title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to convert NumPy array to dictionary in Python? - GeeksforGeeks | 23 Feb, 2022
The following article explains how to convert numpy array to dictionary in Python. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers giving the size of the array along each dimension is known as shape of the array. An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists.
To convert a numpy array to dictionary the following program uses dict(enumerate(array.flatten(), 1)) and this is what it exactly does:
array.flatten: This function is used to get a copy of given array, collapsed into one dimension.
enumerate: Enumerate method comes with an automatic counter/index for each of the items present in the list. The first index value will start from 0
dict: this function is used to convert any object to dictionary.
Example 1:
Python3
# importing required librariesimport numpy as np # creating a numpy arrayarray = np.array([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]) # convert numpy array to dictionaryd = dict(enumerate(array.flatten(), 1)) # print numpy arrayprint(array)print(type(array)) # print dictionaryprint(d)print(type(d))
Output:
[[‘a’ ‘b’ ‘c’]
[‘d’ ‘e’ ‘f’]
[‘g’ ‘h’ ‘i’]]
<class ‘numpy.ndarray’>
{1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’, 5: ‘e’, 6: ‘f’, 7: ‘g’, 8: ‘h’, 9: ‘i’}
<class ‘dict’>
Example 2:
Python3
# importing required librariesimport numpy as np # creating a numpy arrayarray = np.array([['1', '2', '3','4','5'], ['6', '7', '8','9','10'], ['11', '12', '13','14','15']]) # convert numpy array to dictionaryd = dict(enumerate(array.flatten(), 1)) # print numpy arrayprint(array)print(type(array)) # print dictionaryprint(d)print(type(d))
Output:
[[‘1’ ‘2’ ‘3’ ‘4’ ‘5’]
[‘6’ ‘7’ ‘8’ ‘9’ ’10’]
[’11’ ’12’ ’13’ ’14’ ’15’]]
<class ‘numpy.ndarray’>
{1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’, 5: ‘5’, 6: ‘6’, 7: ‘7’, 8: ‘8’, 9: ‘9’, 10: ’10’, 11: ’11’, 12: ’12’, 13: ’13’, 14: ’14’, 15: ’15’}
<class ‘dict’>
kashishsoda
varshagumber28
sumitgumber28
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 24752,
"s": 24212,
"text": "The following article explains how to convert numpy array to dictionary in Python. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers giving the size of the array along each dimension is known as shape of the array. An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists."
},
{
"code": null,
"e": 24889,
"s": 24752,
"text": "To convert a numpy array to dictionary the following program uses dict(enumerate(array.flatten(), 1)) and this is what it exactly does: "
},
{
"code": null,
"e": 24986,
"s": 24889,
"text": "array.flatten: This function is used to get a copy of given array, collapsed into one dimension."
},
{
"code": null,
"e": 25135,
"s": 24986,
"text": "enumerate: Enumerate method comes with an automatic counter/index for each of the items present in the list. The first index value will start from 0"
},
{
"code": null,
"e": 25200,
"s": 25135,
"text": "dict: this function is used to convert any object to dictionary."
},
{
"code": null,
"e": 25211,
"s": 25200,
"text": "Example 1:"
},
{
"code": null,
"e": 25219,
"s": 25211,
"text": "Python3"
},
{
"code": "# importing required librariesimport numpy as np # creating a numpy arrayarray = np.array([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]) # convert numpy array to dictionaryd = dict(enumerate(array.flatten(), 1)) # print numpy arrayprint(array)print(type(array)) # print dictionaryprint(d)print(type(d))",
"e": 25562,
"s": 25219,
"text": null
},
{
"code": null,
"e": 25570,
"s": 25562,
"text": "Output:"
},
{
"code": null,
"e": 25585,
"s": 25570,
"text": "[[‘a’ ‘b’ ‘c’]"
},
{
"code": null,
"e": 25599,
"s": 25585,
"text": "[‘d’ ‘e’ ‘f’]"
},
{
"code": null,
"e": 25614,
"s": 25599,
"text": "[‘g’ ‘h’ ‘i’]]"
},
{
"code": null,
"e": 25638,
"s": 25614,
"text": "<class ‘numpy.ndarray’>"
},
{
"code": null,
"e": 25711,
"s": 25638,
"text": "{1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’, 5: ‘e’, 6: ‘f’, 7: ‘g’, 8: ‘h’, 9: ‘i’}"
},
{
"code": null,
"e": 25726,
"s": 25711,
"text": "<class ‘dict’>"
},
{
"code": null,
"e": 25737,
"s": 25726,
"text": "Example 2:"
},
{
"code": null,
"e": 25745,
"s": 25737,
"text": "Python3"
},
{
"code": "# importing required librariesimport numpy as np # creating a numpy arrayarray = np.array([['1', '2', '3','4','5'], ['6', '7', '8','9','10'], ['11', '12', '13','14','15']]) # convert numpy array to dictionaryd = dict(enumerate(array.flatten(), 1)) # print numpy arrayprint(array)print(type(array)) # print dictionaryprint(d)print(type(d))",
"e": 26118,
"s": 25745,
"text": null
},
{
"code": null,
"e": 26126,
"s": 26118,
"text": "Output:"
},
{
"code": null,
"e": 26149,
"s": 26126,
"text": "[[‘1’ ‘2’ ‘3’ ‘4’ ‘5’]"
},
{
"code": null,
"e": 26172,
"s": 26149,
"text": "[‘6’ ‘7’ ‘8’ ‘9’ ’10’]"
},
{
"code": null,
"e": 26200,
"s": 26172,
"text": "[’11’ ’12’ ’13’ ’14’ ’15’]]"
},
{
"code": null,
"e": 26224,
"s": 26200,
"text": "<class ‘numpy.ndarray’>"
},
{
"code": null,
"e": 26357,
"s": 26224,
"text": "{1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’, 5: ‘5’, 6: ‘6’, 7: ‘7’, 8: ‘8’, 9: ‘9’, 10: ’10’, 11: ’11’, 12: ’12’, 13: ’13’, 14: ’14’, 15: ’15’}"
},
{
"code": null,
"e": 26372,
"s": 26357,
"text": "<class ‘dict’>"
},
{
"code": null,
"e": 26384,
"s": 26372,
"text": "kashishsoda"
},
{
"code": null,
"e": 26399,
"s": 26384,
"text": "varshagumber28"
},
{
"code": null,
"e": 26413,
"s": 26399,
"text": "sumitgumber28"
},
{
"code": null,
"e": 26426,
"s": 26413,
"text": "Python-numpy"
},
{
"code": null,
"e": 26433,
"s": 26426,
"text": "Python"
},
{
"code": null,
"e": 26531,
"s": 26433,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26540,
"s": 26531,
"text": "Comments"
},
{
"code": null,
"e": 26553,
"s": 26540,
"text": "Old Comments"
},
{
"code": null,
"e": 26585,
"s": 26553,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26641,
"s": 26585,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26662,
"s": 26641,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26701,
"s": 26662,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26743,
"s": 26701,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26770,
"s": 26743,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26801,
"s": 26770,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26843,
"s": 26801,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26879,
"s": 26843,
"text": "Python | Pandas dataframe.groupby()"
}
] |
MySQL - TIMESTAMPDIFF() Function | The DATE, DATETIME and TIMESTAMP datatypes in MySQL are used to store the date, date and time, time stamp values respectively. Where a time stamp is a numerical value representing the number of milliseconds from '1970-01-01 00:00:01' UTC (epoch) to the specified time. MySQL provides a set of functions to manipulate these values.
The MYSQL TIMESTAMPDIFF() function accepts two datetime or date expressions as parameters, calculates the difference between them and returns the result. One of the arguments can be date and the other a datetime expression.
Following is the syntax of the above function –
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Where,
unit is the interval type represented by the expr value which can be DAY, WEEK, MONTH, QUARTER, YEAR, HOUR, MINUTE, SECOND, MICROSECOND.
unit is the interval type represented by the expr value which can be DAY, WEEK, MONTH, QUARTER, YEAR, HOUR, MINUTE, SECOND, MICROSECOND.
The unit can be mixed values as: SECOND_MICROSECOND, MINUTE_MICROSECOND, MINUTE_SECOND, HOUR_MICROSECOND, HOUR_SECOND, HOUR_MINUTE, DAY_MICROSECOND, DAY_SECOND, DAY_MINUTE, DAY_HOUR, YEAR_MONTH.
datetime_expr1 and datetime_expr2 are the date or date-time expressions.
datetime_expr1 and datetime_expr2 are the date or date-time expressions.
Following example demonstrates the usage of the TIMESTAMPDIFF() function –
mysql> SELECT TIMESTAMPDIFF(DAY, '1898-03-22', '2019-05-02');
+------------------------------------------------+
| TIMESTAMPDIFF(DAY, '1898-03-22', '2019-05-02') |
+------------------------------------------------+
| 44235 |
+------------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT TIMESTAMPDIFF(MONTH, '1898-03-22', '2019-05-02');
+--------------------------------------------------+
| TIMESTAMPDIFF(MONTH, '1898-03-22', '2019-05-02') |
+--------------------------------------------------+
| 1453 |
+--------------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT TIMESTAMPDIFF(WEEK, '1898-03-22', '2019-05-02');
+-------------------------------------------------+
| TIMESTAMPDIFF(WEEK, '1898-03-22', '2019-05-02') |
+-------------------------------------------------+
| 6319 |
+-------------------------------------------------+
1 row in set (0.00 sec)
Following is another example of this function –
mysql> SELECT TIMESTAMPDIFF(QUARTER, '2021-11-29', '1996-11-22');
+----------------------------------------------------+
| TIMESTAMPDIFF(QUARTER, '2021-11-29', '1996-11-22') |
+----------------------------------------------------+
| -100 |
+----------------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT TIMESTAMPDIFF(YEAR, '2021-11-29', '1996-11-22');
+-------------------------------------------------+
| TIMESTAMPDIFF(YEAR, '2021-11-29', '1996-11-22') |
+-------------------------------------------------+
| -25 |
+-------------------------------------------------+
1 row in set (0.00 sec)
In the following example we are passing DATETIME value for date –
mysql> SELECT TIMESTAMPDIFF(HOUR,'1987-3-12 12:35:58','2018-05-23 20:40:32');
+----------------------------------------------------------------+
| TIMESTAMPDIFF(HOUR,'1987-3-12 12:35:58','2018-05-23 20:40:32') |
+----------------------------------------------------------------+
| 273488 |
+----------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT TIMESTAMPDIFF(MINUTE,'1987-3-12 12:35:58','2018-05-23 20:40:32');
+------------------------------------------------------------------+
| TIMESTAMPDIFF(MINUTE,'1987-3-12 12:35:58','2018-05-23 20:40:32') |
+------------------------------------------------------------------+
| 16409284 |
+------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT TIMESTAMPDIFF(SECOND,'1987-3-12 12:35:58','2018-05-23 20:40:32');
+------------------------------------------------------------------+
| TIMESTAMPDIFF(SECOND,'1987-3-12 12:35:58','2018-05-23 20:40:32') |
+------------------------------------------------------------------+
| 984557074 |
+------------------------------------------------------------------+
1 row in set (0.00 sec)
In the following example we are passing the result of CURDATE() as an argument to the DATEDIFF() function —
mysql> SELECT TIMESTAMPDIFF(DAY, CURDATE(),'2015-09-05');
+--------------------------------------------+
| TIMESTAMPDIFF(DAY, CURDATE(),'2015-09-05') |
+--------------------------------------------+
| -2141 |
+--------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT TIMESTAMPDIFF(MONTH,'1995-11-15', CURDATE());
+----------------------------------------------+
| TIMESTAMPDIFF(MONTH,'1995-11-15', CURDATE()) |
+----------------------------------------------+
| 308 |
+----------------------------------------------+
1 row in set (0.00 sec)
We can also pass current timestamp values as arguments to this function –
mysql> SELECT DATEDIFF(CURRENT_TIMESTAMP(), '2015-09-05 14:58:25');
+------------------------------------------------------+
| DATEDIFF(CURRENT_TIMESTAMP(), '2015-09-05 14:58:25') |
+------------------------------------------------------+
| 2141 |
+------------------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT DATEDIFF('2015-09-05 14:58:25',CURRENT_TIMESTAMP());
+-----------------------------------------------------+
| DATEDIFF('2015-09-05 14:58:25',CURRENT_TIMESTAMP()) |
+-----------------------------------------------------+
| -2141 |
+-----------------------------------------------------+
1 row in set (0.00 sec)
You can also pass the column name as an argument to this function. Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below –
mysql> CREATE TABLE MyPlayers(
ID INT,
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Date_Of_Birth date,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255),
PRIMARY KEY (ID)
);
Now, we will insert 7 records in MyPlayers table using INSERT statements −
mysql> insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
mysql> insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
mysql> insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
mysql> insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
mysql> insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');
mysql> insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');
mysql> insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');
Following query calculates the age of the players in years —
mysql> SELECT First_Name, Last_Name, Date_Of_Birth, Country, TIMESTAMPDIFF(YEAR, Date_Of_Birth, NOW()) FROM MyPlayers;
+------------+------------+---------------+-------------+-------------------------------------------+
| First_Name | Last_Name | Date_Of_Birth | Country | TIMESTAMPDIFF(YEAR, Date_Of_Birth, NOW()) |
+------------+------------+---------------+-------------+-------------------------------------------+
| Shikhar | Dhawan | 1981-12-05 | India | 39 |
| Jonathan | Trott | 1981-04-22 | SouthAfrica | 40 |
| Kumara | Sangakkara | 1977-10-27 | Srilanka | 43 |
| Virat | Kohli | 1988-11-05 | India | 32 |
| Rohit | Sharma | 1987-04-30 | India | 34 |
| Ravindra | Jadeja | 1988-12-06 | India | 32 |
| James | Anderson | 1982-06-30 | England | 39 |
+------------+------------+---------------+-------------+-------------------------------------------+
7 rows in set (0.00 sec)
Suppose we have created a table named dispatches_data with 5 records in it using the following queries –
mysql> CREATE TABLE dispatches_data(
ProductName VARCHAR(255),
CustomerName VARCHAR(255),
DispatchTimeStamp timestamp,
Price INT,
Location VARCHAR(255)
);
insert into dispatches_data values('Key-Board', 'Raja', TIMESTAMP('2019-05-04', '15:02:45'), 7000, 'Hyderabad');
insert into dispatches_data values('Earphones', 'Roja', TIMESTAMP('2019-06-26', '14:13:12'), 2000, 'Vishakhapatnam');
insert into dispatches_data values('Mouse', 'Puja', TIMESTAMP('2019-12-07', '07:50:37'), 3000, 'Vijayawada');
insert into dispatches_data values('Mobile', 'Vanaja' , TIMESTAMP ('2018-03-21', '16:00:45'), 9000, 'Chennai');
insert into dispatches_data values('Headset', 'Jalaja' , TIMESTAMP('2018-12-30', '10:49:27'), 6000, 'Goa');
Following query adds 365 days to the dates of the DispatchTimeStamp column —
mysql> SELECT ProductName, CustomerName, DispatchTimeStamp, Price, TIMESTAMPDIFF(DAY,CURRENT_TIMESTAMP,DispatchTimeStamp) FROM dispatches_data;
+-------------+--------------+---------------------+-------+--------------------------------------------------------+
| ProductName | CustomerName | DispatchTimeStamp | Price | TIMESTAMPDIFF(DAY,CURRENT_TIMESTAMP,DispatchTimeStamp) |
+-------------+--------------+---------------------+-------+--------------------------------------------------------+
| Key-Board | Raja | 2019-05-04 15:02:45 | 7000 | -804 |
| Earphones | Roja | 2019-06-26 14:13:12 | 2000 | -751 |
| Mouse | Puja | 2019-12-07 07:50:37 | 3000 | -587 |
| Mobile | Vanaja | 2018-03-21 16:00:45 | 9000 | -1213 |
| Headset | Jalaja | 2018-12-30 10:49:27 | 6000 | -929 |
+-------------+--------------+---------------------+-------+--------------------------------------------------------+
5 rows in set (0.00 sec)
Suppose we have created a table named Subscribers with 5 records in it using the following queries –
mysql> CREATE TABLE Subscribers(
SubscriberName VARCHAR(255),
PackageName VARCHAR(255),
SubscriptionDate date
);
insert into Subscribers values('Raja', 'Premium', Date('2020-10-21'));
insert into Subscribers values('Roja', 'Basic', Date('2020-11-26'));
insert into Subscribers values('Puja', 'Moderate', Date('2021-03-07'));
insert into Subscribers values('Vanaja', 'Basic', Date('2021-02-21'));
insert into Subscribers values('Jalaja', 'Premium', Date('2021-01-30'));
Following query calculates and displays the remaining number of days for the subscription to complete —
mysql> SELECT SubscriberName, PackageName, SubscriptionDate, TIMESTAMPDIFF(DAY,SubscriptionDate,CURDATE()) as Remaining_Days FROM Subscribers;
+----------------+-------------+------------------+----------------+
| SubscriberName | PackageName | SubscriptionDate | Remaining_Days |
+----------------+-------------+------------------+----------------+
| Raja | Premium | 2020-10-21 | 268 |
| Roja | Basic | 2020-11-26 | 232 |
| Puja | Moderate | 2021-03-07 | 131 |
| Vanaja | Basic | 2021-02-21 | 145 |
| Jalaja | Premium | 2021-01-30 | 167 |
+----------------+-------------+------------------+----------------+
5 rows in set (0.00 sec)
Following example demonstrates the usage WEEK and QUARTER units available in the TIMESTAMPDIFF() function –
mysql> SELECT TIMESTAMPDIFF(WEEK,'1920-07-12','2021-03-22');
+-----------------------------------------------+
| TIMESTAMPDIFF(WEEK,'1920-07-12','2021-03-22') |
+-----------------------------------------------+
| 5254 |
+-----------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT TIMESTAMPDIFF(QUARTER,'1969-10-23','2021-03-22');
+--------------------------------------------------+
| TIMESTAMPDIFF(QUARTER,'1969-10-23','2021-03-22') |
+--------------------------------------------------+
| 205 |
+--------------------------------------------------+
1 row in set (0.00 sec)
31 Lectures
6 hours
Eduonix Learning Solutions
84 Lectures
5.5 hours
Frahaan Hussain
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
60 Lectures
10 hours
Vijay Kumar Parvatha Reddy
10 Lectures
1 hours
Harshit Srivastava
25 Lectures
4 hours
Trevoir Williams
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2664,
"s": 2333,
"text": "The DATE, DATETIME and TIMESTAMP datatypes in MySQL are used to store the date, date and time, time stamp values respectively. Where a time stamp is a numerical value representing the number of milliseconds from '1970-01-01 00:00:01' UTC (epoch) to the specified time. MySQL provides a set of functions to manipulate these values."
},
{
"code": null,
"e": 2888,
"s": 2664,
"text": "The MYSQL TIMESTAMPDIFF() function accepts two datetime or date expressions as parameters, calculates the difference between them and returns the result. One of the arguments can be date and the other a datetime expression."
},
{
"code": null,
"e": 2936,
"s": 2888,
"text": "Following is the syntax of the above function –"
},
{
"code": null,
"e": 2987,
"s": 2936,
"text": "TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)\n"
},
{
"code": null,
"e": 2994,
"s": 2987,
"text": "Where,"
},
{
"code": null,
"e": 3131,
"s": 2994,
"text": "unit is the interval type represented by the expr value which can be DAY, WEEK, MONTH, QUARTER, YEAR, HOUR, MINUTE, SECOND, MICROSECOND."
},
{
"code": null,
"e": 3268,
"s": 3131,
"text": "unit is the interval type represented by the expr value which can be DAY, WEEK, MONTH, QUARTER, YEAR, HOUR, MINUTE, SECOND, MICROSECOND."
},
{
"code": null,
"e": 3463,
"s": 3268,
"text": "The unit can be mixed values as: SECOND_MICROSECOND, MINUTE_MICROSECOND, MINUTE_SECOND, HOUR_MICROSECOND, HOUR_SECOND, HOUR_MINUTE, DAY_MICROSECOND, DAY_SECOND, DAY_MINUTE, DAY_HOUR, YEAR_MONTH."
},
{
"code": null,
"e": 3536,
"s": 3463,
"text": "datetime_expr1 and datetime_expr2 are the date or date-time expressions."
},
{
"code": null,
"e": 3609,
"s": 3536,
"text": "datetime_expr1 and datetime_expr2 are the date or date-time expressions."
},
{
"code": null,
"e": 3684,
"s": 3609,
"text": "Following example demonstrates the usage of the TIMESTAMPDIFF() function –"
},
{
"code": null,
"e": 4725,
"s": 3684,
"text": "mysql> SELECT TIMESTAMPDIFF(DAY, '1898-03-22', '2019-05-02');\n+------------------------------------------------+\n| TIMESTAMPDIFF(DAY, '1898-03-22', '2019-05-02') |\n+------------------------------------------------+\n| 44235 |\n+------------------------------------------------+\n1 row in set (0.00 sec)\nmysql> SELECT TIMESTAMPDIFF(MONTH, '1898-03-22', '2019-05-02');\n+--------------------------------------------------+\n| TIMESTAMPDIFF(MONTH, '1898-03-22', '2019-05-02') |\n+--------------------------------------------------+\n| 1453 |\n+--------------------------------------------------+\n1 row in set (0.00 sec)\nmysql> SELECT TIMESTAMPDIFF(WEEK, '1898-03-22', '2019-05-02');\n+-------------------------------------------------+\n| TIMESTAMPDIFF(WEEK, '1898-03-22', '2019-05-02') |\n+-------------------------------------------------+\n| 6319 |\n+-------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 4773,
"s": 4725,
"text": "Following is another example of this function –"
},
{
"code": null,
"e": 5486,
"s": 4773,
"text": "mysql> SELECT TIMESTAMPDIFF(QUARTER, '2021-11-29', '1996-11-22');\n+----------------------------------------------------+\n| TIMESTAMPDIFF(QUARTER, '2021-11-29', '1996-11-22') |\n+----------------------------------------------------+\n| -100 |\n+----------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT TIMESTAMPDIFF(YEAR, '2021-11-29', '1996-11-22');\n+-------------------------------------------------+\n| TIMESTAMPDIFF(YEAR, '2021-11-29', '1996-11-22') |\n+-------------------------------------------------+\n| -25 |\n+-------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 5552,
"s": 5486,
"text": "In the following example we are passing DATETIME value for date –"
},
{
"code": null,
"e": 6889,
"s": 5552,
"text": "mysql> SELECT TIMESTAMPDIFF(HOUR,'1987-3-12 12:35:58','2018-05-23 20:40:32');\n+----------------------------------------------------------------+\n| TIMESTAMPDIFF(HOUR,'1987-3-12 12:35:58','2018-05-23 20:40:32') |\n+----------------------------------------------------------------+\n| 273488 |\n+----------------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT TIMESTAMPDIFF(MINUTE,'1987-3-12 12:35:58','2018-05-23 20:40:32');\n+------------------------------------------------------------------+\n| TIMESTAMPDIFF(MINUTE,'1987-3-12 12:35:58','2018-05-23 20:40:32') |\n+------------------------------------------------------------------+\n| 16409284 |\n+------------------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT TIMESTAMPDIFF(SECOND,'1987-3-12 12:35:58','2018-05-23 20:40:32');\n+------------------------------------------------------------------+\n| TIMESTAMPDIFF(SECOND,'1987-3-12 12:35:58','2018-05-23 20:40:32') |\n+------------------------------------------------------------------+\n| 984557074 |\n+------------------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 6997,
"s": 6889,
"text": "In the following example we are passing the result of CURDATE() as an argument to the DATEDIFF() function —"
},
{
"code": null,
"e": 7644,
"s": 6997,
"text": "mysql> SELECT TIMESTAMPDIFF(DAY, CURDATE(),'2015-09-05');\n+--------------------------------------------+\n| TIMESTAMPDIFF(DAY, CURDATE(),'2015-09-05') |\n+--------------------------------------------+\n| -2141 |\n+--------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT TIMESTAMPDIFF(MONTH,'1995-11-15', CURDATE());\n+----------------------------------------------+\n| TIMESTAMPDIFF(MONTH,'1995-11-15', CURDATE()) |\n+----------------------------------------------+\n| 308 |\n+----------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 7718,
"s": 7644,
"text": "We can also pass current timestamp values as arguments to this function –"
},
{
"code": null,
"e": 8467,
"s": 7718,
"text": "mysql> SELECT DATEDIFF(CURRENT_TIMESTAMP(), '2015-09-05 14:58:25');\n+------------------------------------------------------+\n| DATEDIFF(CURRENT_TIMESTAMP(), '2015-09-05 14:58:25') |\n+------------------------------------------------------+\n| 2141 |\n+------------------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT DATEDIFF('2015-09-05 14:58:25',CURRENT_TIMESTAMP());\n+-----------------------------------------------------+\n| DATEDIFF('2015-09-05 14:58:25',CURRENT_TIMESTAMP()) |\n+-----------------------------------------------------+\n| -2141 |\n+-----------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 8634,
"s": 8467,
"text": "You can also pass the column name as an argument to this function. Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below –"
},
{
"code": null,
"e": 8820,
"s": 8634,
"text": "mysql> CREATE TABLE MyPlayers(\n\tID INT,\n\tFirst_Name VARCHAR(255),\n\tLast_Name VARCHAR(255),\n\tDate_Of_Birth date,\n\tPlace_Of_Birth VARCHAR(255),\n\tCountry VARCHAR(255),\n\tPRIMARY KEY (ID)\n);"
},
{
"code": null,
"e": 8895,
"s": 8820,
"text": "Now, we will insert 7 records in MyPlayers table using INSERT statements −"
},
{
"code": null,
"e": 9606,
"s": 8895,
"text": "mysql> insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\nmysql> insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\nmysql> insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\nmysql> insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\nmysql> insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\nmysql> insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');\nmysql> insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');"
},
{
"code": null,
"e": 9667,
"s": 9606,
"text": "Following query calculates the age of the players in years —"
},
{
"code": null,
"e": 10933,
"s": 9667,
"text": "mysql> SELECT First_Name, Last_Name, Date_Of_Birth, Country, TIMESTAMPDIFF(YEAR, Date_Of_Birth, NOW()) FROM MyPlayers;\n+------------+------------+---------------+-------------+-------------------------------------------+\n| First_Name | Last_Name | Date_Of_Birth | Country | TIMESTAMPDIFF(YEAR, Date_Of_Birth, NOW()) |\n+------------+------------+---------------+-------------+-------------------------------------------+\n| Shikhar | Dhawan | 1981-12-05 | India | 39 |\n| Jonathan | Trott | 1981-04-22 | SouthAfrica | 40 |\n| Kumara | Sangakkara | 1977-10-27 | Srilanka | 43 |\n| Virat | Kohli | 1988-11-05 | India | 32 |\n| Rohit | Sharma | 1987-04-30 | India | 34 |\n| Ravindra | Jadeja | 1988-12-06 | India | 32 |\n| James | Anderson | 1982-06-30 | England | 39 |\n+------------+------------+---------------+-------------+-------------------------------------------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 11038,
"s": 10933,
"text": "Suppose we have created a table named dispatches_data with 5 records in it using the following queries –"
},
{
"code": null,
"e": 11759,
"s": 11038,
"text": "mysql> CREATE TABLE dispatches_data(\n\tProductName VARCHAR(255),\n\tCustomerName VARCHAR(255),\n\tDispatchTimeStamp timestamp,\n\tPrice INT,\n\tLocation VARCHAR(255)\n);\ninsert into dispatches_data values('Key-Board', 'Raja', TIMESTAMP('2019-05-04', '15:02:45'), 7000, 'Hyderabad');\ninsert into dispatches_data values('Earphones', 'Roja', TIMESTAMP('2019-06-26', '14:13:12'), 2000, 'Vishakhapatnam');\ninsert into dispatches_data values('Mouse', 'Puja', TIMESTAMP('2019-12-07', '07:50:37'), 3000, 'Vijayawada');\ninsert into dispatches_data values('Mobile', 'Vanaja' , TIMESTAMP ('2018-03-21', '16:00:45'), 9000, 'Chennai');\ninsert into dispatches_data values('Headset', 'Jalaja' , TIMESTAMP('2018-12-30', '10:49:27'), 6000, 'Goa');"
},
{
"code": null,
"e": 11836,
"s": 11759,
"text": "Following query adds 365 days to the dates of the DispatchTimeStamp column —"
},
{
"code": null,
"e": 13067,
"s": 11836,
"text": "mysql> SELECT ProductName, CustomerName, DispatchTimeStamp, Price, TIMESTAMPDIFF(DAY,CURRENT_TIMESTAMP,DispatchTimeStamp) FROM dispatches_data;\n+-------------+--------------+---------------------+-------+--------------------------------------------------------+\n| ProductName | CustomerName | DispatchTimeStamp | Price | TIMESTAMPDIFF(DAY,CURRENT_TIMESTAMP,DispatchTimeStamp) |\n+-------------+--------------+---------------------+-------+--------------------------------------------------------+\n| Key-Board | Raja | 2019-05-04 15:02:45 | 7000 | -804 |\n| Earphones | Roja | 2019-06-26 14:13:12 | 2000 | -751 |\n| Mouse | Puja | 2019-12-07 07:50:37 | 3000 | -587 |\n| Mobile | Vanaja | 2018-03-21 16:00:45 | 9000 | -1213 |\n| Headset | Jalaja | 2018-12-30 10:49:27 | 6000 | -929 |\n+-------------+--------------+---------------------+-------+--------------------------------------------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 13168,
"s": 13067,
"text": "Suppose we have created a table named Subscribers with 5 records in it using the following queries –"
},
{
"code": null,
"e": 13640,
"s": 13168,
"text": "mysql> CREATE TABLE Subscribers(\n\tSubscriberName VARCHAR(255),\n\tPackageName VARCHAR(255),\n\tSubscriptionDate date\n);\ninsert into Subscribers values('Raja', 'Premium', Date('2020-10-21'));\ninsert into Subscribers values('Roja', 'Basic', Date('2020-11-26'));\ninsert into Subscribers values('Puja', 'Moderate', Date('2021-03-07'));\ninsert into Subscribers values('Vanaja', 'Basic', Date('2021-02-21'));\ninsert into Subscribers values('Jalaja', 'Premium', Date('2021-01-30'));"
},
{
"code": null,
"e": 13744,
"s": 13640,
"text": "Following query calculates and displays the remaining number of days for the subscription to complete —"
},
{
"code": null,
"e": 14533,
"s": 13744,
"text": "mysql> SELECT SubscriberName, PackageName, SubscriptionDate, TIMESTAMPDIFF(DAY,SubscriptionDate,CURDATE()) as Remaining_Days FROM Subscribers;\n+----------------+-------------+------------------+----------------+\n| SubscriberName | PackageName | SubscriptionDate | Remaining_Days |\n+----------------+-------------+------------------+----------------+\n| Raja | Premium | 2020-10-21 | 268 |\n| Roja | Basic | 2020-11-26 | 232 |\n| Puja | Moderate | 2021-03-07 | 131 |\n| Vanaja | Basic | 2021-02-21 | 145 |\n| Jalaja | Premium | 2021-01-30 | 167 |\n+----------------+-------------+------------------+----------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 14641,
"s": 14533,
"text": "Following example demonstrates the usage WEEK and QUARTER units available in the TIMESTAMPDIFF() function –"
},
{
"code": null,
"e": 15330,
"s": 14641,
"text": "mysql> SELECT TIMESTAMPDIFF(WEEK,'1920-07-12','2021-03-22');\n+-----------------------------------------------+\n| TIMESTAMPDIFF(WEEK,'1920-07-12','2021-03-22') |\n+-----------------------------------------------+\n| 5254 |\n+-----------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> SELECT TIMESTAMPDIFF(QUARTER,'1969-10-23','2021-03-22');\n+--------------------------------------------------+\n| TIMESTAMPDIFF(QUARTER,'1969-10-23','2021-03-22') |\n+--------------------------------------------------+\n| 205 |\n+--------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 15363,
"s": 15330,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 15391,
"s": 15363,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 15426,
"s": 15391,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 15443,
"s": 15426,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 15477,
"s": 15443,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 15512,
"s": 15477,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 15546,
"s": 15512,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 15574,
"s": 15546,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 15607,
"s": 15574,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 15627,
"s": 15607,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 15660,
"s": 15627,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 15678,
"s": 15660,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 15685,
"s": 15678,
"text": " Print"
},
{
"code": null,
"e": 15696,
"s": 15685,
"text": " Add Notes"
}
] |
How to install and configuration ftp server in centos 7 | In this article, we will learn how to configure FTP server on CentOs 7 using ‘vsftpd’. ‘vsftpd’ (Very Secure File Transport Protocol Daemon) is a secure and very fast FTP server on Linux systems.
Below is the command to install the ‘vsftpd’, we needed a root user to run the following command
# yum install vsftp ftp –y
Loaded plugins: fastestmirror, refresh-packagekit, security
Loading mirror speeds from cached hostfile * base: ftp.iitm.ac.in
* extras: ftp.iitm.ac.in
* updates: ftp.iitm.ac.in
Setting up Install Process
No package vsftp available.
Resolving Dependencies
--> Running transaction check
---> Package ftp.x86_64 0:0.17-54.el6 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
=================================================================================================================================================================================
Package Arch Version Repository Size
=================================================================================================================================================================================
Installing:
vsftpd x86_64 2.2.2-21.el6 base 155 k ftp x86_64 0.17-54.el6 base 58 k
Transaction Summary
=================================================================================================================================================================================
Install 2 Package(s)
Total download size: 58 k
Installed size: 95 k
Is this ok [y/N]: y
Downloading Packages:
ftp-0.17-54.el6.x86_64.rpm , vsftpd-2.2.2-21.el6.x86_64.rpm | 58 kB 00:00
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Installing : ftp-0.17-54.el6.x86_64
Installing : vsftpd-2.2.2-21.el6.x86_64
Verifying : vsftpd-2.2.2-21.el6.x86_64
Verifying : ftp-0.17-54.el6.x86_64
Installed:
ftp.x86_64 0:0.17-54.el6, vsftpd.x86_64 0:2.2.2-21.el6
Complete!
We needed to edit the configuration file ‘vsftpd’ for securing the FTP server since, by default it will allow anonymous users to login and use the server.
# vi /etc/vsftpd/vsftpd.conf
We have to disallow anonymous, unidentified users to access files via FTP; change the anonymous_enable setting to NO:
anonymous_enable=NO
Allow local users to login by changing the local_enable setting to YES:
local_enable=YES
If you want to allow the local users to be able to write to a directory, then change the write_enable setting in the configuration file to YES:
write_enable=YES
Local users will be ‘chroot jailed’ and they will be denied access the local users to any other part of the server; change the chroot_local_user setting in the configuration file to YES:
chroot_local_user=YES
Below is the simple configuration file for your reference –
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
chroot_local_user=YES
dirmessage_enable=YES
xferlog_enable=YES
connect_from_port_20=YES
xferlog_std_format=YES
listen=YES
#listen_ipv6=YES
pam_service_name=vsftpd
userlist_enable=YES
tcp_wrappers=YES
Save the file with the command :wq .
We needed to restart the ‘vsftpd’ services so that the configuration changes has applied
# systemctl restart vsftpd
We will set the ‘vsftpd’ service to start at boot time, below is the command to enable the ‘vsftpd’ to start.
# systemctl enable vsftpd
We have to allow the default FTP port, port 21, through firewall.
# firewall-cmd --permanent --add-port=21/tcp
We needed to reload the firewall so that the firewall.
# firewall-cmd –reload
We will create FTP user other than local users and assign the home directory
For this tutorial, I will create a user without a home directory therefore I use –M instead of –m.
# useradd -M user1 –s /sbin/nologin
# passwd user1
We will next set the home directory for “user1” by creating a new directory
# mkdir /var/www/mike
# chmod 755 /var/www/mike
We have to provide access to the “user1” on FTP
# chown -R mike /var/www/user1
We can access the FTP server from the client on your favorite browser using the url ftp://192.168.100.108
By using the above information, we can easily configure and install the FTP server. ‘vsftpd’ is a simple and very secure FTP server, we can use local user and we can also create other users specially to use FTP ‘vsftpd’ server which has many more features too. | [
{
"code": null,
"e": 1258,
"s": 1062,
"text": "In this article, we will learn how to configure FTP server on CentOs 7 using ‘vsftpd’. ‘vsftpd’ (Very Secure File Transport Protocol Daemon) is a secure and very fast FTP server on Linux systems."
},
{
"code": null,
"e": 1355,
"s": 1258,
"text": "Below is the command to install the ‘vsftpd’, we needed a root user to run the following command"
},
{
"code": null,
"e": 2960,
"s": 1355,
"text": "# yum install vsftp ftp –y\nLoaded plugins: fastestmirror, refresh-packagekit, security\nLoading mirror speeds from cached hostfile * base: ftp.iitm.ac.in\n* extras: ftp.iitm.ac.in\n* updates: ftp.iitm.ac.in\nSetting up Install Process\nNo package vsftp available.\nResolving Dependencies\n--> Running transaction check\n---> Package ftp.x86_64 0:0.17-54.el6 will be installed\n--> Finished Dependency Resolution\nDependencies Resolved\n=================================================================================================================================================================================\nPackage Arch Version Repository Size\n=================================================================================================================================================================================\nInstalling:\nvsftpd x86_64 2.2.2-21.el6 base 155 k ftp x86_64 0.17-54.el6 base 58 k\nTransaction Summary\n=================================================================================================================================================================================\nInstall 2 Package(s)\nTotal download size: 58 k\nInstalled size: 95 k\nIs this ok [y/N]: y\nDownloading Packages:\nftp-0.17-54.el6.x86_64.rpm , vsftpd-2.2.2-21.el6.x86_64.rpm | 58 kB 00:00\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\nInstalling : ftp-0.17-54.el6.x86_64\nInstalling : vsftpd-2.2.2-21.el6.x86_64\nVerifying : vsftpd-2.2.2-21.el6.x86_64\nVerifying : ftp-0.17-54.el6.x86_64\nInstalled:\nftp.x86_64 0:0.17-54.el6, vsftpd.x86_64 0:2.2.2-21.el6\nComplete!"
},
{
"code": null,
"e": 3115,
"s": 2960,
"text": "We needed to edit the configuration file ‘vsftpd’ for securing the FTP server since, by default it will allow anonymous users to login and use the server."
},
{
"code": null,
"e": 3144,
"s": 3115,
"text": "# vi /etc/vsftpd/vsftpd.conf"
},
{
"code": null,
"e": 3262,
"s": 3144,
"text": "We have to disallow anonymous, unidentified users to access files via FTP; change the anonymous_enable setting to NO:"
},
{
"code": null,
"e": 3282,
"s": 3262,
"text": "anonymous_enable=NO"
},
{
"code": null,
"e": 3354,
"s": 3282,
"text": "Allow local users to login by changing the local_enable setting to YES:"
},
{
"code": null,
"e": 3371,
"s": 3354,
"text": "local_enable=YES"
},
{
"code": null,
"e": 3515,
"s": 3371,
"text": "If you want to allow the local users to be able to write to a directory, then change the write_enable setting in the configuration file to YES:"
},
{
"code": null,
"e": 3532,
"s": 3515,
"text": "write_enable=YES"
},
{
"code": null,
"e": 3719,
"s": 3532,
"text": "Local users will be ‘chroot jailed’ and they will be denied access the local users to any other part of the server; change the chroot_local_user setting in the configuration file to YES:"
},
{
"code": null,
"e": 3741,
"s": 3719,
"text": "chroot_local_user=YES"
},
{
"code": null,
"e": 3801,
"s": 3741,
"text": "Below is the simple configuration file for your reference –"
},
{
"code": null,
"e": 4108,
"s": 3801,
"text": "anonymous_enable=NO\nlocal_enable=YES\nwrite_enable=YES\nlocal_umask=022\nchroot_local_user=YES\ndirmessage_enable=YES\nxferlog_enable=YES\nconnect_from_port_20=YES\nxferlog_std_format=YES\nlisten=YES\n#listen_ipv6=YES\npam_service_name=vsftpd\nuserlist_enable=YES\ntcp_wrappers=YES\nSave the file with the command :wq ."
},
{
"code": null,
"e": 4197,
"s": 4108,
"text": "We needed to restart the ‘vsftpd’ services so that the configuration changes has applied"
},
{
"code": null,
"e": 4224,
"s": 4197,
"text": "# systemctl restart vsftpd"
},
{
"code": null,
"e": 4334,
"s": 4224,
"text": "We will set the ‘vsftpd’ service to start at boot time, below is the command to enable the ‘vsftpd’ to start."
},
{
"code": null,
"e": 4360,
"s": 4334,
"text": "# systemctl enable vsftpd"
},
{
"code": null,
"e": 4426,
"s": 4360,
"text": "We have to allow the default FTP port, port 21, through firewall."
},
{
"code": null,
"e": 4471,
"s": 4426,
"text": "# firewall-cmd --permanent --add-port=21/tcp"
},
{
"code": null,
"e": 4526,
"s": 4471,
"text": "We needed to reload the firewall so that the firewall."
},
{
"code": null,
"e": 4549,
"s": 4526,
"text": "# firewall-cmd –reload"
},
{
"code": null,
"e": 4626,
"s": 4549,
"text": "We will create FTP user other than local users and assign the home directory"
},
{
"code": null,
"e": 4725,
"s": 4626,
"text": "For this tutorial, I will create a user without a home directory therefore I use –M instead of –m."
},
{
"code": null,
"e": 4776,
"s": 4725,
"text": "# useradd -M user1 –s /sbin/nologin\n# passwd user1"
},
{
"code": null,
"e": 4852,
"s": 4776,
"text": "We will next set the home directory for “user1” by creating a new directory"
},
{
"code": null,
"e": 4900,
"s": 4852,
"text": "# mkdir /var/www/mike\n# chmod 755 /var/www/mike"
},
{
"code": null,
"e": 4948,
"s": 4900,
"text": "We have to provide access to the “user1” on FTP"
},
{
"code": null,
"e": 5085,
"s": 4948,
"text": "# chown -R mike /var/www/user1\nWe can access the FTP server from the client on your favorite browser using the url ftp://192.168.100.108"
},
{
"code": null,
"e": 5346,
"s": 5085,
"text": "By using the above information, we can easily configure and install the FTP server. ‘vsftpd’ is a simple and very secure FTP server, we can use local user and we can also create other users specially to use FTP ‘vsftpd’ server which has many more features too."
}
] |
Dates in Tableau. This post will be useful for those who... | by Amanda Monzon | Towards Data Science | This post will be useful for those who are working with financial data or anyone who is tracking how the business is doing compared to last years numbers.
User wants to track how sales are doing to the previous year on a macro and micro level (YTD, Day YOY).
Switch between date fields — when working with financial data users want to see how sales are doing as orders come in but also want to track when they are booked in an accounting system. Building in the ability for the user to easily switch between these two date fields while only keeping one set of reports and charts.Drill up and down — when using date fields to build a time series chart, Tableau includes the ability to drill date parts up and down. But not all users know to hover over the date axis to view the -/+ or you want to limit the users ability too drill to far up or down.Date Compare — the Relative Date Range filter can be used to select YTD, MTD, and Today but does not allow Year over Year (YOY) or Rolling date range comparison. Build in the most common date range comparison to allow for YOY and Rolling period. Additionally, capability to change the end date to track how far away from previous years sales.
Switch between date fields — when working with financial data users want to see how sales are doing as orders come in but also want to track when they are booked in an accounting system. Building in the ability for the user to easily switch between these two date fields while only keeping one set of reports and charts.
Drill up and down — when using date fields to build a time series chart, Tableau includes the ability to drill date parts up and down. But not all users know to hover over the date axis to view the -/+ or you want to limit the users ability too drill to far up or down.
Date Compare — the Relative Date Range filter can be used to select YTD, MTD, and Today but does not allow Year over Year (YOY) or Rolling date range comparison. Build in the most common date range comparison to allow for YOY and Rolling period. Additionally, capability to change the end date to track how far away from previous years sales.
The workbook below displays the end result of each step with the final tab “Time Series” bringing everything together. I decided to show how to build each component using continuous and discrete because there are use cases for both depending on requirements.
public.tableau.com
WARNING row-level calculations involving parameters such as the ones in this workbook will increase load time. Check out this Interworks post.
Built upon Carl Slifer’s Interworks post on date comparison made easy.
Using parameters can easily change between two or more date fields.
Step 1. Create a parameter field, [Select Date field]. Setting the data type to integer will help performance since integer and boolean data types run faster than date and string data types. Each value can be given a name that is easily recognized.
Step 2. Create the calculation [Select Date field]
CASE [Parameters].[Select Date field]WHEN 1 THEN [Order Date]WHEN 2 THEN [Ship Date]END
Step 3. Place the calculation in a view and show the parameter.
Below I built two charts using the [Select Date field] calculation. Notice the continuous chart has no breaks in the lines and each Month/Year is not labeled while the discrete chart has breaks in the line and each year, quarter and month is labeled.
Build a parameter to switch to different date levels.
Step 1. Create [Date View] parameter
Step 2. Create Date View calculation. Notice that I will be using the [Select Date field] created in the previous step. If you do not need to switch between dates then the desired date field can be used.
Date View_Continuous
CASE [Parameters].[Date View]WHEN 5 THEN DATE(DATETRUNC('year', [Select Date field]))WHEN 1 THEN DATE(DATETRUNC('quarter', [Select Date field]))WHEN 2 THEN DATE(DATETRUNC('month', [Select Date field]))WHEN 3 THEN DATE(DATETRUNC('week', [Select Date field]))WHEN 4 THEN DATE(DATETRUNC('day', [Select Date field]))END
Date View_Discrete
CASE [Parameters].[Date View]WHEN 5 THEN DATENAME('year',[Select Date field])WHEN 1 THEN DATENAME('year',[Select Date field]) + ' Q' + DATENAME('quarter',[Select Date field])WHEN 2 THEN DATENAME('year',[Select Date field]) + '-' + STR(DATEPART('month',[Select Date field]))WHEN 3 THEN DATENAME('year',[Select Date field]) + ' W' + STR(DATEPART('week',[Select Date field]))WHEN 4 THEN DATENAME('year',[Select Date field]) + '-' + STR(DATEPART('month',[Select Date field])) + '-' + STR(DATEPART('day',[Select Date field]))END
Step 3. Place on view
Continuous
On a Mac, hold down “option” key, select [Date View_Continuous] and place on columns. A new Drop Field window will pop up, select the first option “Date View_Continuous (Continuous)” which will not assign a static date part and allow the parameter to work properly.
Discrete
Move the [Date View_Discrete] to columns, by default date parts will not be applied.
Lets compare the two time series. Now we see the discrete time series does not contain breaks. I also prefer the discrete labels since it labels the date based on the date view selected. Where the continuous time series will adjust based on the date view selected, for months it displays the day which can be misleading to users.
Relative dates allow users to select YTD, MTD, and Day but does not allow Year over Year or Rolling period comparison.
For easy Year over Year and Rolling period comparison we will create 2 parameters; the first [End Date Chooser] will determine when the end date will be, the second [Date Compare to] will tell what type of date range to look at. Below are the 7 date comparisons that I typically heard users request. These comparisons can be grouped into three buckets; Year to Date, Rolling period, Year over Year. Each of the end dates will be determined based on the [End Date Chooser]. On the Date Compare dashboard, play with the selections to see how the date ranges change.
Year to Date: begins the first day of the calendar year
1. Year to Date (e.g., 9/15/2018)
2. Year to Day of Week (e.g., Monday, Tuesday)
Rolling period: consecutive days
3. Rolling Year to Date
Year over Year: current results for the same time period in the previous year
4. Quarter to Date
5. Month to Date
6. Date (e.g., 9/15/2018)
7. Day of Week (e.g., Monday, Tuesday)
Building the [End Date Chooser] first create the parameter
Then build the [End Date Chooser] calculation. This can be adjusted depending on how often the data is updated. Most of the time default to Yesterday since in many cases extracts are refreshed once per day. The Month End selections (e.g., Current, Previous, -2 Months, Current Year End) come in handy when users need to track what is happening YTD and MTD.
DATE(Case [Parameters].[End Date Chooser]WHEN 1 THEN TODAY()WHEN 2 THEN DATEADD('day', -1, TODAY())WHEN 3 THEN { MAX([Select Date field]) }WHEN 4 THEN [Custom End Date]WHEN 5 THEN DATEADD('day',-1,DATEADD('month',1,DATETRUNC('month',TODAY())))WHEN 6 THEN DATEADD('day',-1,DATETRUNC('month',TODAY()))WHEN 7 THEN DATEADD('day',-1,DATEADD('month', -1, DATETRUNC('month',TODAY())))WHEN 8 THEN DATEADD('day',-1,DATEADD('month', -2, DATETRUNC('month',TODAY())))WHEN 9 THEN DATEADD('day',-1,DATEADD('month', -3, DATETRUNC('month',TODAY())))WHEN 10 THEN DATEADD('day',-1,DATEADD('month', -4, DATETRUNC('month',TODAY())))WHEN 11 THEN DATEADD('day',-1,DATEADD('month', -5, DATETRUNC('month',TODAY())))WHEN 12 THEN DATEADD('day',-1,DATEADD('month', -6, DATETRUNC('month',TODAY())))WHEN 13 THEN DATEADD('day',-1,DATEADD('month', -7, DATETRUNC('month',TODAY())))WHEN 14 THEN DATEADD('day',-1,DATEADD('month', -8, DATETRUNC('month',TODAY())))WHEN 15 THEN DATEADD('day',-1,DATEADD('month', -9, DATETRUNC('month',TODAY())))WHEN 16 THEN DATEADD('day',-1,DATEADD('month', -10, DATETRUNC('month',TODAY())))WHEN 17 THEN DATEADD('day',-1,DATEADD('year', 1, DATETRUNC('year',TODAY())))END)
Next create the [Date Compare to] parameter.
Create [Date Compare to] calculation
CASE [Parameters].[Date Compare to]//Year To DateWHEN 1 THEN//CurrentIIF( DATEPART('dayofyear',[Select Date field]) <= DATEPART('dayofyear',[End Date Chooser])AND YEAR([Select Date field]) - YEAR([End Date Chooser]) = 0, 0//Previous, IIF( [Select Date field] <=DATEPARSE('MM-dd-yyyy',(STR(MONTH([End Date Chooser]))+'-'+STR(DAY([End Date Chooser]))+'-'+STR(YEAR(DATEADD('year',-1, [End Date Chooser])))))AND YEAR([Select Date field]) - YEAR([End Date Chooser]) = -1, -1, NULL))//Year to WeekdayWHEN 2 THEN//CurrentIIF( DATEPART('dayofyear',[Select Date field]) <= DATEPART('dayofyear',[End Date Chooser])AND YEAR([Select Date field]) - YEAR([End Date Chooser]) = 0, 0//Previous, IIF( YEAR([Select Date field]) - YEAR([End Date Chooser]) = -1AND DATEPART('week', [Select Date field])*10 + DATEPART('weekday', [Select Date field])<= DATEPART('week', [End Date Chooser])*10 + DATEPART('weekday', [End Date Chooser]), -1, NULL))//Rolling Year to DateWHEN 3 THEN//The first statement sets the conditions for a date to be considered the “current period.”//It will check every date to the date we've chosen as our starting point.//It must be based on whatever date we’ve chosen and go back a user chosen number of months, weeks, days, etc.//If the difference between these dates is >=0 and < our Period Length, we consider it to be the “current period.”IIF( DATEDIFF('day',[Select Date field],[End Date Chooser]) >=0AND DATEDIFF('day',[Select Date field],[End Date Chooser])< 365, 0//The second statement sets the conditions for a date to be considered the “previous period.”//It will compare every date to the date we've chosen as our starting point.//It will be based on whatever date we've chosen and it will immediately precede the “current period” and be the same length.//If the difference between the dates is > the Period Length but also < two times the length, it will be the “previous period.”, IIF( DATEDIFF('day',[Select Date field],[End Date Chooser]) >= 365AND DATEDIFF('day',[Select Date field],[End Date Chooser]) < 2*365, -1, NULL))//Quarter to DateWHEN 4 THEN//CurrentIIF( [Select Date field] <= [End Date Chooser]AND DATEDIFF('quarter',[Select Date field],[End Date Chooser])= 0, 0//Previous, IIF( [Select Date field] <=DATEPARSE('MM-dd-yyyy',(STR(MONTH([End Date Chooser]))+'-'+STR(DAY([End Date Chooser]))+'-'+STR(YEAR(DATEADD('year',-1, [End Date Chooser])))))AND DATEDIFF('quarter',[Select Date field],[End Date Chooser]) = 4, -1, NULL))//Month to DateWHEN 5 THEN//CurrentIIF( [Select Date field] <= [End Date Chooser]AND DATEDIFF('month',[Select Date field],[End Date Chooser])= 0, 0//Previous, IIF( DAY([Select Date field]) <= DAY([End Date Chooser])AND DATEDIFF('month',[Select Date field],[End Date Chooser])= 12, -1, NULL))//DateWHEN 6 THEN//CurrentIIF( DATEDIFF('day',[Select Date field],[End Date Chooser])= 0, 0//Previous, IIF( [Select Date field] =DATEPARSE('MM-dd-yyyy',(STR(MONTH([End Date Chooser]))+'-'+STR(DAY([End Date Chooser]))+'-'+STR(YEAR(DATEADD('year',-1, [End Date Chooser]))))), -1, NULL))//WeekdayWHEN 7 THEN//CurrentIIF( DATEDIFF('day',[Select Date field],[End Date Chooser])= 0, 0//Previous, IIF( YEAR([Select Date field]) - YEAR([End Date Chooser]) = -1AND DATEPART('week', [Select Date field])*10 + DATEPART('weekday', [Select Date field])= DATEPART('week', [End Date Chooser])*10 + DATEPART('weekday', [End Date Chooser]), -1, NULL))END
This last step we will create a date field that only uses the current year so we can have the previous and current period displayed on a time series with the month/day matching.
Create a calculation [Date Mth/Day/CY]. This will create a new date field that matches the month and day and uses the [End Date Chooser’] to grab the current period year. Additional logic is added to account for leap years where there is an extra day in February. If this is not added then Feb-29 will end up in March.
DATE(STR(MONTH([Select Date field]))+"/"+IIF(DATEPART('day',[Select Date field]) = 29 AND DATEPART('month',[Select Date field]) = 2,STR(DAY(DATEADD('day', -1, [Select Date field]))),STR(DAY([Select Date field])))+"/"+STR(YEAR([End Date Chooser])))
Then create the [Date View_Continuous] and [Date View_Discrete] based on the logic in the previous section switching the date to [Date Mth/Day/CY].
Now we have the final view that meets the original use case described at the beginning of this post. The final workbook can be viewed here. | [
{
"code": null,
"e": 327,
"s": 172,
"text": "This post will be useful for those who are working with financial data or anyone who is tracking how the business is doing compared to last years numbers."
},
{
"code": null,
"e": 431,
"s": 327,
"text": "User wants to track how sales are doing to the previous year on a macro and micro level (YTD, Day YOY)."
},
{
"code": null,
"e": 1363,
"s": 431,
"text": "Switch between date fields — when working with financial data users want to see how sales are doing as orders come in but also want to track when they are booked in an accounting system. Building in the ability for the user to easily switch between these two date fields while only keeping one set of reports and charts.Drill up and down — when using date fields to build a time series chart, Tableau includes the ability to drill date parts up and down. But not all users know to hover over the date axis to view the -/+ or you want to limit the users ability too drill to far up or down.Date Compare — the Relative Date Range filter can be used to select YTD, MTD, and Today but does not allow Year over Year (YOY) or Rolling date range comparison. Build in the most common date range comparison to allow for YOY and Rolling period. Additionally, capability to change the end date to track how far away from previous years sales."
},
{
"code": null,
"e": 1684,
"s": 1363,
"text": "Switch between date fields — when working with financial data users want to see how sales are doing as orders come in but also want to track when they are booked in an accounting system. Building in the ability for the user to easily switch between these two date fields while only keeping one set of reports and charts."
},
{
"code": null,
"e": 1954,
"s": 1684,
"text": "Drill up and down — when using date fields to build a time series chart, Tableau includes the ability to drill date parts up and down. But not all users know to hover over the date axis to view the -/+ or you want to limit the users ability too drill to far up or down."
},
{
"code": null,
"e": 2297,
"s": 1954,
"text": "Date Compare — the Relative Date Range filter can be used to select YTD, MTD, and Today but does not allow Year over Year (YOY) or Rolling date range comparison. Build in the most common date range comparison to allow for YOY and Rolling period. Additionally, capability to change the end date to track how far away from previous years sales."
},
{
"code": null,
"e": 2556,
"s": 2297,
"text": "The workbook below displays the end result of each step with the final tab “Time Series” bringing everything together. I decided to show how to build each component using continuous and discrete because there are use cases for both depending on requirements."
},
{
"code": null,
"e": 2575,
"s": 2556,
"text": "public.tableau.com"
},
{
"code": null,
"e": 2718,
"s": 2575,
"text": "WARNING row-level calculations involving parameters such as the ones in this workbook will increase load time. Check out this Interworks post."
},
{
"code": null,
"e": 2789,
"s": 2718,
"text": "Built upon Carl Slifer’s Interworks post on date comparison made easy."
},
{
"code": null,
"e": 2857,
"s": 2789,
"text": "Using parameters can easily change between two or more date fields."
},
{
"code": null,
"e": 3106,
"s": 2857,
"text": "Step 1. Create a parameter field, [Select Date field]. Setting the data type to integer will help performance since integer and boolean data types run faster than date and string data types. Each value can be given a name that is easily recognized."
},
{
"code": null,
"e": 3157,
"s": 3106,
"text": "Step 2. Create the calculation [Select Date field]"
},
{
"code": null,
"e": 3245,
"s": 3157,
"text": "CASE [Parameters].[Select Date field]WHEN 1 THEN [Order Date]WHEN 2 THEN [Ship Date]END"
},
{
"code": null,
"e": 3309,
"s": 3245,
"text": "Step 3. Place the calculation in a view and show the parameter."
},
{
"code": null,
"e": 3560,
"s": 3309,
"text": "Below I built two charts using the [Select Date field] calculation. Notice the continuous chart has no breaks in the lines and each Month/Year is not labeled while the discrete chart has breaks in the line and each year, quarter and month is labeled."
},
{
"code": null,
"e": 3614,
"s": 3560,
"text": "Build a parameter to switch to different date levels."
},
{
"code": null,
"e": 3651,
"s": 3614,
"text": "Step 1. Create [Date View] parameter"
},
{
"code": null,
"e": 3855,
"s": 3651,
"text": "Step 2. Create Date View calculation. Notice that I will be using the [Select Date field] created in the previous step. If you do not need to switch between dates then the desired date field can be used."
},
{
"code": null,
"e": 3876,
"s": 3855,
"text": "Date View_Continuous"
},
{
"code": null,
"e": 4192,
"s": 3876,
"text": "CASE [Parameters].[Date View]WHEN 5 THEN DATE(DATETRUNC('year', [Select Date field]))WHEN 1 THEN DATE(DATETRUNC('quarter', [Select Date field]))WHEN 2 THEN DATE(DATETRUNC('month', [Select Date field]))WHEN 3 THEN DATE(DATETRUNC('week', [Select Date field]))WHEN 4 THEN DATE(DATETRUNC('day', [Select Date field]))END"
},
{
"code": null,
"e": 4211,
"s": 4192,
"text": "Date View_Discrete"
},
{
"code": null,
"e": 4735,
"s": 4211,
"text": "CASE [Parameters].[Date View]WHEN 5 THEN DATENAME('year',[Select Date field])WHEN 1 THEN DATENAME('year',[Select Date field]) + ' Q' + DATENAME('quarter',[Select Date field])WHEN 2 THEN DATENAME('year',[Select Date field]) + '-' + STR(DATEPART('month',[Select Date field]))WHEN 3 THEN DATENAME('year',[Select Date field]) + ' W' + STR(DATEPART('week',[Select Date field]))WHEN 4 THEN DATENAME('year',[Select Date field]) + '-' + STR(DATEPART('month',[Select Date field])) + '-' + STR(DATEPART('day',[Select Date field]))END"
},
{
"code": null,
"e": 4757,
"s": 4735,
"text": "Step 3. Place on view"
},
{
"code": null,
"e": 4768,
"s": 4757,
"text": "Continuous"
},
{
"code": null,
"e": 5034,
"s": 4768,
"text": "On a Mac, hold down “option” key, select [Date View_Continuous] and place on columns. A new Drop Field window will pop up, select the first option “Date View_Continuous (Continuous)” which will not assign a static date part and allow the parameter to work properly."
},
{
"code": null,
"e": 5043,
"s": 5034,
"text": "Discrete"
},
{
"code": null,
"e": 5128,
"s": 5043,
"text": "Move the [Date View_Discrete] to columns, by default date parts will not be applied."
},
{
"code": null,
"e": 5458,
"s": 5128,
"text": "Lets compare the two time series. Now we see the discrete time series does not contain breaks. I also prefer the discrete labels since it labels the date based on the date view selected. Where the continuous time series will adjust based on the date view selected, for months it displays the day which can be misleading to users."
},
{
"code": null,
"e": 5577,
"s": 5458,
"text": "Relative dates allow users to select YTD, MTD, and Day but does not allow Year over Year or Rolling period comparison."
},
{
"code": null,
"e": 6141,
"s": 5577,
"text": "For easy Year over Year and Rolling period comparison we will create 2 parameters; the first [End Date Chooser] will determine when the end date will be, the second [Date Compare to] will tell what type of date range to look at. Below are the 7 date comparisons that I typically heard users request. These comparisons can be grouped into three buckets; Year to Date, Rolling period, Year over Year. Each of the end dates will be determined based on the [End Date Chooser]. On the Date Compare dashboard, play with the selections to see how the date ranges change."
},
{
"code": null,
"e": 6197,
"s": 6141,
"text": "Year to Date: begins the first day of the calendar year"
},
{
"code": null,
"e": 6231,
"s": 6197,
"text": "1. Year to Date (e.g., 9/15/2018)"
},
{
"code": null,
"e": 6278,
"s": 6231,
"text": "2. Year to Day of Week (e.g., Monday, Tuesday)"
},
{
"code": null,
"e": 6311,
"s": 6278,
"text": "Rolling period: consecutive days"
},
{
"code": null,
"e": 6335,
"s": 6311,
"text": "3. Rolling Year to Date"
},
{
"code": null,
"e": 6413,
"s": 6335,
"text": "Year over Year: current results for the same time period in the previous year"
},
{
"code": null,
"e": 6432,
"s": 6413,
"text": "4. Quarter to Date"
},
{
"code": null,
"e": 6449,
"s": 6432,
"text": "5. Month to Date"
},
{
"code": null,
"e": 6475,
"s": 6449,
"text": "6. Date (e.g., 9/15/2018)"
},
{
"code": null,
"e": 6514,
"s": 6475,
"text": "7. Day of Week (e.g., Monday, Tuesday)"
},
{
"code": null,
"e": 6573,
"s": 6514,
"text": "Building the [End Date Chooser] first create the parameter"
},
{
"code": null,
"e": 6930,
"s": 6573,
"text": "Then build the [End Date Chooser] calculation. This can be adjusted depending on how often the data is updated. Most of the time default to Yesterday since in many cases extracts are refreshed once per day. The Month End selections (e.g., Current, Previous, -2 Months, Current Year End) come in handy when users need to track what is happening YTD and MTD."
},
{
"code": null,
"e": 8098,
"s": 6930,
"text": "DATE(Case [Parameters].[End Date Chooser]WHEN 1 THEN TODAY()WHEN 2 THEN DATEADD('day', -1, TODAY())WHEN 3 THEN { MAX([Select Date field]) }WHEN 4 THEN [Custom End Date]WHEN 5 THEN DATEADD('day',-1,DATEADD('month',1,DATETRUNC('month',TODAY())))WHEN 6 THEN DATEADD('day',-1,DATETRUNC('month',TODAY()))WHEN 7 THEN DATEADD('day',-1,DATEADD('month', -1, DATETRUNC('month',TODAY())))WHEN 8 THEN DATEADD('day',-1,DATEADD('month', -2, DATETRUNC('month',TODAY())))WHEN 9 THEN DATEADD('day',-1,DATEADD('month', -3, DATETRUNC('month',TODAY())))WHEN 10 THEN DATEADD('day',-1,DATEADD('month', -4, DATETRUNC('month',TODAY())))WHEN 11 THEN DATEADD('day',-1,DATEADD('month', -5, DATETRUNC('month',TODAY())))WHEN 12 THEN DATEADD('day',-1,DATEADD('month', -6, DATETRUNC('month',TODAY())))WHEN 13 THEN DATEADD('day',-1,DATEADD('month', -7, DATETRUNC('month',TODAY())))WHEN 14 THEN DATEADD('day',-1,DATEADD('month', -8, DATETRUNC('month',TODAY())))WHEN 15 THEN DATEADD('day',-1,DATEADD('month', -9, DATETRUNC('month',TODAY())))WHEN 16 THEN DATEADD('day',-1,DATEADD('month', -10, DATETRUNC('month',TODAY())))WHEN 17 THEN DATEADD('day',-1,DATEADD('year', 1, DATETRUNC('year',TODAY())))END)"
},
{
"code": null,
"e": 8143,
"s": 8098,
"text": "Next create the [Date Compare to] parameter."
},
{
"code": null,
"e": 8180,
"s": 8143,
"text": "Create [Date Compare to] calculation"
},
{
"code": null,
"e": 11566,
"s": 8180,
"text": "CASE [Parameters].[Date Compare to]//Year To DateWHEN 1 THEN//CurrentIIF( DATEPART('dayofyear',[Select Date field]) <= DATEPART('dayofyear',[End Date Chooser])AND YEAR([Select Date field]) - YEAR([End Date Chooser]) = 0, 0//Previous, IIF( [Select Date field] <=DATEPARSE('MM-dd-yyyy',(STR(MONTH([End Date Chooser]))+'-'+STR(DAY([End Date Chooser]))+'-'+STR(YEAR(DATEADD('year',-1, [End Date Chooser])))))AND YEAR([Select Date field]) - YEAR([End Date Chooser]) = -1, -1, NULL))//Year to WeekdayWHEN 2 THEN//CurrentIIF( DATEPART('dayofyear',[Select Date field]) <= DATEPART('dayofyear',[End Date Chooser])AND YEAR([Select Date field]) - YEAR([End Date Chooser]) = 0, 0//Previous, IIF( YEAR([Select Date field]) - YEAR([End Date Chooser]) = -1AND DATEPART('week', [Select Date field])*10 + DATEPART('weekday', [Select Date field])<= DATEPART('week', [End Date Chooser])*10 + DATEPART('weekday', [End Date Chooser]), -1, NULL))//Rolling Year to DateWHEN 3 THEN//The first statement sets the conditions for a date to be considered the “current period.”//It will check every date to the date we've chosen as our starting point.//It must be based on whatever date we’ve chosen and go back a user chosen number of months, weeks, days, etc.//If the difference between these dates is >=0 and < our Period Length, we consider it to be the “current period.”IIF( DATEDIFF('day',[Select Date field],[End Date Chooser]) >=0AND DATEDIFF('day',[Select Date field],[End Date Chooser])< 365, 0//The second statement sets the conditions for a date to be considered the “previous period.”//It will compare every date to the date we've chosen as our starting point.//It will be based on whatever date we've chosen and it will immediately precede the “current period” and be the same length.//If the difference between the dates is > the Period Length but also < two times the length, it will be the “previous period.”, IIF( DATEDIFF('day',[Select Date field],[End Date Chooser]) >= 365AND DATEDIFF('day',[Select Date field],[End Date Chooser]) < 2*365, -1, NULL))//Quarter to DateWHEN 4 THEN//CurrentIIF( [Select Date field] <= [End Date Chooser]AND DATEDIFF('quarter',[Select Date field],[End Date Chooser])= 0, 0//Previous, IIF( [Select Date field] <=DATEPARSE('MM-dd-yyyy',(STR(MONTH([End Date Chooser]))+'-'+STR(DAY([End Date Chooser]))+'-'+STR(YEAR(DATEADD('year',-1, [End Date Chooser])))))AND DATEDIFF('quarter',[Select Date field],[End Date Chooser]) = 4, -1, NULL))//Month to DateWHEN 5 THEN//CurrentIIF( [Select Date field] <= [End Date Chooser]AND DATEDIFF('month',[Select Date field],[End Date Chooser])= 0, 0//Previous, IIF( DAY([Select Date field]) <= DAY([End Date Chooser])AND DATEDIFF('month',[Select Date field],[End Date Chooser])= 12, -1, NULL))//DateWHEN 6 THEN//CurrentIIF( DATEDIFF('day',[Select Date field],[End Date Chooser])= 0, 0//Previous, IIF( [Select Date field] =DATEPARSE('MM-dd-yyyy',(STR(MONTH([End Date Chooser]))+'-'+STR(DAY([End Date Chooser]))+'-'+STR(YEAR(DATEADD('year',-1, [End Date Chooser]))))), -1, NULL))//WeekdayWHEN 7 THEN//CurrentIIF( DATEDIFF('day',[Select Date field],[End Date Chooser])= 0, 0//Previous, IIF( YEAR([Select Date field]) - YEAR([End Date Chooser]) = -1AND DATEPART('week', [Select Date field])*10 + DATEPART('weekday', [Select Date field])= DATEPART('week', [End Date Chooser])*10 + DATEPART('weekday', [End Date Chooser]), -1, NULL))END"
},
{
"code": null,
"e": 11744,
"s": 11566,
"text": "This last step we will create a date field that only uses the current year so we can have the previous and current period displayed on a time series with the month/day matching."
},
{
"code": null,
"e": 12063,
"s": 11744,
"text": "Create a calculation [Date Mth/Day/CY]. This will create a new date field that matches the month and day and uses the [End Date Chooser’] to grab the current period year. Additional logic is added to account for leap years where there is an extra day in February. If this is not added then Feb-29 will end up in March."
},
{
"code": null,
"e": 12311,
"s": 12063,
"text": "DATE(STR(MONTH([Select Date field]))+\"/\"+IIF(DATEPART('day',[Select Date field]) = 29 AND DATEPART('month',[Select Date field]) = 2,STR(DAY(DATEADD('day', -1, [Select Date field]))),STR(DAY([Select Date field])))+\"/\"+STR(YEAR([End Date Chooser])))"
},
{
"code": null,
"e": 12459,
"s": 12311,
"text": "Then create the [Date View_Continuous] and [Date View_Discrete] based on the logic in the previous section switching the date to [Date Mth/Day/CY]."
}
] |
JUnit - Executing Tests | The test cases are executed using JUnitCore class. JUnitCore is a facade for running tests. It supports running JUnit 4 tests, JUnit 3.8.x tests, and mixtures. To run tests from the command line, run java org.junit.runner.JUnitCore <TestClass>. For one-shot test runs, use the static method runClasses(Class[]).
Following is the declaration for org.junit.runner.JUnitCore class:
public class JUnitCore extends java.lang.Object
Here we will see how to execute the tests with the help of JUnitCore.
Create a java class to be tested, say, MessageUtil.java, in C:\>JUNIT_WORKSPACE.
/*
* This class prints the given message on console.
*/
public class MessageUtil {
private String message;
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
// prints the message
public String printMessage(){
System.out.println(message);
return message;
}
}
Create a java test class, say, TestJunit.java.
Create a java test class, say, TestJunit.java.
Add a test method testPrintMessage() to your test class.
Add a test method testPrintMessage() to your test class.
Add an Annotaion @Test to the method testPrintMessage().
Add an Annotaion @Test to the method testPrintMessage().
Implement the test condition and check the condition using assertEquals API of JUnit.
Implement the test condition and check the condition using assertEquals API of JUnit.
Create a java class file named TestJunit.java in C:\>JUNIT_WORKSPACE.
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
String message = "Hello World";
MessageUtil messageUtil = new MessageUtil(message);
@Test
public void testPrintMessage() {
assertEquals(message,messageUtil.printMessage());
}
}
Now create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s). It imports the JUnitCore class and uses the runClasses() method that takes the test class name as its parameter.
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java
Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.
Hello World
true
24 Lectures
2.5 hours
Nishita Bhatt
56 Lectures
7.5 hours
Dinesh Varyani
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2284,
"s": 1972,
"text": "The test cases are executed using JUnitCore class. JUnitCore is a facade for running tests. It supports running JUnit 4 tests, JUnit 3.8.x tests, and mixtures. To run tests from the command line, run java org.junit.runner.JUnitCore <TestClass>. For one-shot test runs, use the static method runClasses(Class[])."
},
{
"code": null,
"e": 2351,
"s": 2284,
"text": "Following is the declaration for org.junit.runner.JUnitCore class:"
},
{
"code": null,
"e": 2400,
"s": 2351,
"text": "public class JUnitCore extends java.lang.Object\n"
},
{
"code": null,
"e": 2470,
"s": 2400,
"text": "Here we will see how to execute the tests with the help of JUnitCore."
},
{
"code": null,
"e": 2551,
"s": 2470,
"text": "Create a java class to be tested, say, MessageUtil.java, in C:\\>JUNIT_WORKSPACE."
},
{
"code": null,
"e": 2925,
"s": 2551,
"text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message){\n this.message = message;\n }\n \n // prints the message\n public String printMessage(){\n System.out.println(message);\n return message;\n } \n\t\n} "
},
{
"code": null,
"e": 2972,
"s": 2925,
"text": "Create a java test class, say, TestJunit.java."
},
{
"code": null,
"e": 3019,
"s": 2972,
"text": "Create a java test class, say, TestJunit.java."
},
{
"code": null,
"e": 3076,
"s": 3019,
"text": "Add a test method testPrintMessage() to your test class."
},
{
"code": null,
"e": 3133,
"s": 3076,
"text": "Add a test method testPrintMessage() to your test class."
},
{
"code": null,
"e": 3190,
"s": 3133,
"text": "Add an Annotaion @Test to the method testPrintMessage()."
},
{
"code": null,
"e": 3247,
"s": 3190,
"text": "Add an Annotaion @Test to the method testPrintMessage()."
},
{
"code": null,
"e": 3333,
"s": 3247,
"text": "Implement the test condition and check the condition using assertEquals API of JUnit."
},
{
"code": null,
"e": 3419,
"s": 3333,
"text": "Implement the test condition and check the condition using assertEquals API of JUnit."
},
{
"code": null,
"e": 3489,
"s": 3419,
"text": "Create a java class file named TestJunit.java in C:\\>JUNIT_WORKSPACE."
},
{
"code": null,
"e": 3785,
"s": 3489,
"text": "import org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit {\n\t\n String message = \"Hello World\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n\n @Test\n public void testPrintMessage() {\n assertEquals(message,messageUtil.printMessage());\n }\n}"
},
{
"code": null,
"e": 3997,
"s": 3785,
"text": "Now create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s). It imports the JUnitCore class and uses the runClasses() method that takes the test class name as its parameter."
},
{
"code": null,
"e": 4418,
"s": 3997,
"text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t"
},
{
"code": null,
"e": 4477,
"s": 4418,
"text": "Compile the Test case and Test Runner classes using javac."
},
{
"code": null,
"e": 4551,
"s": 4477,
"text": "C:\\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java\n"
},
{
"code": null,
"e": 4646,
"s": 4551,
"text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class."
},
{
"code": null,
"e": 4682,
"s": 4646,
"text": "C:\\JUNIT_WORKSPACE>java TestRunner\n"
},
{
"code": null,
"e": 4701,
"s": 4682,
"text": "Verify the output."
},
{
"code": null,
"e": 4719,
"s": 4701,
"text": "Hello World\ntrue\n"
},
{
"code": null,
"e": 4754,
"s": 4719,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4769,
"s": 4754,
"text": " Nishita Bhatt"
},
{
"code": null,
"e": 4804,
"s": 4769,
"text": "\n 56 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4820,
"s": 4804,
"text": " Dinesh Varyani"
},
{
"code": null,
"e": 4827,
"s": 4820,
"text": " Print"
},
{
"code": null,
"e": 4838,
"s": 4827,
"text": " Add Notes"
}
] |
What is Docker Images? | 09 Jun, 2022
Docker Image is an executable package of software that includes everything needed to run an application. This image informs how a container should instantiate, determining which software components will run and how. Docker Container is a virtual environment that bundles application code with all the dependencies required to run the application. The application runs quickly and reliably from one computing environment to another.
Running Instances from DockerFile
Follow the below steps to create a Docker Image and run a Container:
Step 1: Create a Dockerfile.
Step 2: Run the following command in the terminal and it will create a docker image of the application and download all the necessary dependencies needed for the application to run successfully.
docker build -t <name to give to your image>
This will start building the image.
Step 3: We have successfully created a Dockerfile and a respective Docker image for the same.
Step 4: Run the following command in the terminal and it will create a running container with all the needed dependencies and start the application.
docker run -p 9000:80 <image-name>
The 9000 is the port we want to access our application on. 80 is the port the container is exposing for the host to access.
List images:
docker ls
Pull an image from a registry:
docker image pull <image-name>
Remove an Image from Docker:
docker rmi <id-of-image>
khushb99
docker
Picked
TrueGeek-2021
Docker
TrueGeek
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
Naming Convention in C++
Floyd’s Cycle Finding Algorithm
How to redirect to another page in ReactJS ?
How to remove duplicate elements from JavaScript Array ?
How to Convert Char to String in Java?
Basics of API Testing Using Postman
Types of Internet Protocols | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 485,
"s": 53,
"text": "Docker Image is an executable package of software that includes everything needed to run an application. This image informs how a container should instantiate, determining which software components will run and how. Docker Container is a virtual environment that bundles application code with all the dependencies required to run the application. The application runs quickly and reliably from one computing environment to another."
},
{
"code": null,
"e": 519,
"s": 485,
"text": "Running Instances from DockerFile"
},
{
"code": null,
"e": 588,
"s": 519,
"text": "Follow the below steps to create a Docker Image and run a Container:"
},
{
"code": null,
"e": 617,
"s": 588,
"text": "Step 1: Create a Dockerfile."
},
{
"code": null,
"e": 812,
"s": 617,
"text": "Step 2: Run the following command in the terminal and it will create a docker image of the application and download all the necessary dependencies needed for the application to run successfully."
},
{
"code": null,
"e": 857,
"s": 812,
"text": "docker build -t <name to give to your image>"
},
{
"code": null,
"e": 893,
"s": 857,
"text": "This will start building the image."
},
{
"code": null,
"e": 988,
"s": 893,
"text": "Step 3: We have successfully created a Dockerfile and a respective Docker image for the same."
},
{
"code": null,
"e": 1137,
"s": 988,
"text": "Step 4: Run the following command in the terminal and it will create a running container with all the needed dependencies and start the application."
},
{
"code": null,
"e": 1172,
"s": 1137,
"text": "docker run -p 9000:80 <image-name>"
},
{
"code": null,
"e": 1296,
"s": 1172,
"text": "The 9000 is the port we want to access our application on. 80 is the port the container is exposing for the host to access."
},
{
"code": null,
"e": 1310,
"s": 1296,
"text": " List images:"
},
{
"code": null,
"e": 1320,
"s": 1310,
"text": "docker ls"
},
{
"code": null,
"e": 1351,
"s": 1320,
"text": "Pull an image from a registry:"
},
{
"code": null,
"e": 1382,
"s": 1351,
"text": "docker image pull <image-name>"
},
{
"code": null,
"e": 1411,
"s": 1382,
"text": "Remove an Image from Docker:"
},
{
"code": null,
"e": 1436,
"s": 1411,
"text": "docker rmi <id-of-image>"
},
{
"code": null,
"e": 1445,
"s": 1436,
"text": "khushb99"
},
{
"code": null,
"e": 1452,
"s": 1445,
"text": "docker"
},
{
"code": null,
"e": 1459,
"s": 1452,
"text": "Picked"
},
{
"code": null,
"e": 1473,
"s": 1459,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 1480,
"s": 1473,
"text": "Docker"
},
{
"code": null,
"e": 1489,
"s": 1480,
"text": "TrueGeek"
},
{
"code": null,
"e": 1587,
"s": 1489,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1661,
"s": 1587,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 1714,
"s": 1661,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 1780,
"s": 1714,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 1805,
"s": 1780,
"text": "Naming Convention in C++"
},
{
"code": null,
"e": 1837,
"s": 1805,
"text": "Floyd’s Cycle Finding Algorithm"
},
{
"code": null,
"e": 1882,
"s": 1837,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 1939,
"s": 1882,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 1978,
"s": 1939,
"text": "How to Convert Char to String in Java?"
},
{
"code": null,
"e": 2014,
"s": 1978,
"text": "Basics of API Testing Using Postman"
}
] |
Can a try block have multiple catch blocks in Java? | Yes, you can have multiple catch blocks for a single try block.
The following Java program contains an array of numbers (which is displayed). from user it accepts two positions from this array and, divides the number in first position with the number in second position.
While entering values −
If you choose a position which is not in the displayed array an ArrayIndexOutOfBoundsException is thrown
If you choose a position which is not in the displayed array an ArrayIndexOutOfBoundsException is thrown
If you choose 0 as denominator and ArithmeticException is thrown.
If you choose 0 as denominator and ArithmeticException is thrown.
In this program we have handled all the possible exceptions using two different catch blocks.
Live Demo
import java.util.Arrays;
import java.util.Scanner;
public class MultipleCatchBlocks {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Enter 3 integer values one by one: ");
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
int a = sc.nextInt();
int b = sc.nextInt();
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Warning: You have chosen a position which is not in the array");
}
catch(ArithmeticException e) {
System.out.println("Warning: You cannot divide an number with 0");
}
}
}
Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator (not 0) from this array (enter positions 0 to 5)
2
8
Warning: You have chosen a position which is not in the array
Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
1
4
Warning: You cannot divide an number with 0 | [
{
"code": null,
"e": 1251,
"s": 1187,
"text": "Yes, you can have multiple catch blocks for a single try block."
},
{
"code": null,
"e": 1458,
"s": 1251,
"text": "The following Java program contains an array of numbers (which is displayed). from user it accepts two positions from this array and, divides the number in first position with the number in second position."
},
{
"code": null,
"e": 1482,
"s": 1458,
"text": "While entering values −"
},
{
"code": null,
"e": 1587,
"s": 1482,
"text": "If you choose a position which is not in the displayed array an ArrayIndexOutOfBoundsException is thrown"
},
{
"code": null,
"e": 1692,
"s": 1587,
"text": "If you choose a position which is not in the displayed array an ArrayIndexOutOfBoundsException is thrown"
},
{
"code": null,
"e": 1758,
"s": 1692,
"text": "If you choose 0 as denominator and ArithmeticException is thrown."
},
{
"code": null,
"e": 1824,
"s": 1758,
"text": "If you choose 0 as denominator and ArithmeticException is thrown."
},
{
"code": null,
"e": 1918,
"s": 1824,
"text": "In this program we have handled all the possible exceptions using two different catch blocks."
},
{
"code": null,
"e": 1929,
"s": 1918,
"text": " Live Demo"
},
{
"code": null,
"e": 2845,
"s": 1929,
"text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class MultipleCatchBlocks {\n public static void main(String [] args) {\n Scanner sc = new Scanner(System.in);\n int[] arr = {10, 20, 30, 2, 0, 8};\n System.out.println(\"Enter 3 integer values one by one: \");\n System.out.println(\"Array: \"+Arrays.toString(arr));\n System.out.println(\"Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)\");\n int a = sc.nextInt();\n int b = sc.nextInt();\n try {\n int result = (arr[a])/(arr[b]);\n System.out.println(\"Result of \"+arr[a]+\"/\"+arr[b]+\": \"+result);\n }\n catch(ArrayIndexOutOfBoundsException e) {\n System.out.println(\"Warning: You have chosen a position which is not in the array\");\n }\n catch(ArithmeticException e) {\n System.out.println(\"Warning: You cannot divide an number with 0\");\n }\n }\n}"
},
{
"code": null,
"e": 3057,
"s": 2845,
"text": "Enter 3 integer values one by one:\nArray: [10, 20, 30, 2, 0, 8]\nChoose numerator and denominator (not 0) from this array (enter positions 0 to 5)\n2\n8\nWarning: You have chosen a position which is not in the array"
},
{
"code": null,
"e": 3250,
"s": 3057,
"text": "Enter 3 integer values one by one:\nArray: [10, 20, 30, 2, 0, 8]\nChoose numerator and denominator(not 0) from this array (enter positions 0 to 5)\n1\n4\nWarning: You cannot divide an number with 0"
}
] |
turtle.degrees() function in Python | 01 Aug, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to set angle measurement units to degrees. By default the angle measurement unit is “degrees”.
Syntax: turtle.degrees(fullcircle=360.0)
Parameter:
fullcircle(optional): a number. Set angle measurement units, i.e. set number of ‘degrees’ for a full circle. Default value is 360 degrees.
Below is the implementation of the above method with an example :
Python3
# importing packageimport turtle # set turtle speedturtle.speed(1) # forward turtle by 100turtle.forward(100) # turn the turtle (degrees)turtle.left(90) # print headingprint(turtle.heading()) # move forward by 100turtle.forward(100) # set to radiansturtle.radians() # turn to left by 90 (radians)turtle.left(1.57079633) # print headingprint(turtle.heading()) # move forward by 100turtle.forward(100) # set to radiansturtle.degrees() # turn to left by 90 (degrees)turtle.left(90) # print headingprint(turtle.heading())
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 360,
"s": 245,
"text": "This method is used to set angle measurement units to degrees. By default the angle measurement unit is “degrees”."
},
{
"code": null,
"e": 401,
"s": 360,
"text": "Syntax: turtle.degrees(fullcircle=360.0)"
},
{
"code": null,
"e": 412,
"s": 401,
"text": "Parameter:"
},
{
"code": null,
"e": 551,
"s": 412,
"text": "fullcircle(optional): a number. Set angle measurement units, i.e. set number of ‘degrees’ for a full circle. Default value is 360 degrees."
},
{
"code": null,
"e": 617,
"s": 551,
"text": "Below is the implementation of the above method with an example :"
},
{
"code": null,
"e": 625,
"s": 617,
"text": "Python3"
},
{
"code": "# importing packageimport turtle # set turtle speedturtle.speed(1) # forward turtle by 100turtle.forward(100) # turn the turtle (degrees)turtle.left(90) # print headingprint(turtle.heading()) # move forward by 100turtle.forward(100) # set to radiansturtle.radians() # turn to left by 90 (radians)turtle.left(1.57079633) # print headingprint(turtle.heading()) # move forward by 100turtle.forward(100) # set to radiansturtle.degrees() # turn to left by 90 (degrees)turtle.left(90) # print headingprint(turtle.heading())",
"e": 1155,
"s": 625,
"text": null
},
{
"code": null,
"e": 1164,
"s": 1155,
"text": "Output :"
},
{
"code": null,
"e": 1178,
"s": 1164,
"text": "Python-turtle"
},
{
"code": null,
"e": 1185,
"s": 1178,
"text": "Python"
},
{
"code": null,
"e": 1283,
"s": 1185,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1315,
"s": 1283,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1342,
"s": 1315,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1373,
"s": 1342,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1396,
"s": 1373,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1417,
"s": 1396,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1473,
"s": 1417,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1515,
"s": 1473,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1557,
"s": 1515,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1596,
"s": 1557,
"text": "Python | Get unique values from a list"
}
] |
Create a Quiz App using ReactJS | 08 Oct, 2020
React is a JavaScript library used to develop interactive user interfaces. It is managed by Facebook and a community of individual developers and companies. react mainly focus on developing single-page web or mobile applications. here, we will create a quiz app to understand the basics of reactjs.
Modules required:
npm
React
React Bootstrapnpm install react-bootstrap bootstrap
npm install react-bootstrap bootstrap
Basic setup:
Start a project by the following command –
npx create-react-app quiz
NPX is a package runner tool that comes with npm 5.2+, npx is easy to use CLI tools. npx is used for executing Node packages. It greatly simplifies a number of things one of which is checked/run a node package quickly without installing it locally or globally.
now, goto the folder create
cd quiz
Start the server- Start the server by typing following command in terminal –
npm start
open http://localhost:3000/
Change directory to src –
cd src
Delete every thing inside the directory
rm *
Now create index.js files
touch index.js
This file will render our app to html file which is in public folder now, create a folder name components with files src/components/QuestionBox.js and src/components/ResultBox.js to hold our app components and a folder question with file src/question/index.js to hold our questions.
mkdir components && cd components && touch app.js
mkdir question && cd question && index.js
Edit src/index.js fileThis file contains our app logic.
import React, {Component} from "react";import ReactDOM from "react-dom";import "./style.css";import questionAPI from './question';import QuestionBox from './components/QuestionBox';import Result from './components/ResultBox'; class Quiz extends Component { constructor() { super(); this.state = { questionBank: [], score: 0, responses: 0 }; } // Function to get question from ./question getQuestions = () => { questionAPI().then(question => { this.setState({questionBank: question}); }); }; // Set state back to default and call function playAgain = () => { this.getQuestions(); this.setState({score: 0, responses: 0}); }; // Function to compute scores computeAnswer = (answer, correctAns) => { if (answer === correctAns) { this.setState({ score: this.state.score + 1 }); } this.setState({ responses: this.state.responses < 5 ? this.state.responses + 1 : 5 }); }; // componentDidMount function to get question componentDidMount() { this.getQuestions(); } render() { return (<div className="container"> <div className="title"> QuizOn </div> {this.state.questionBank.length > 0 && this.state.responses < 5 && this.state.questionBank.map(({question, answers, correct, questionId}) => <QuestionBox question= {question} options={answers} key={questionId} selected={answer => this.computeAnswer(answer, correct)}/>)} { this.state.responses === 5 ? (<Result score={this.state.score} playAgain={this.playAgain}/>) : null } </div>) }} ReactDOM.render(<Quiz/>, document.getElementById("root"));
Edit src/question/index.js file: This file contains all question which will be displayed.
const qBank = [ { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "099099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "093909" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "009039" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "090089" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "01010101" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "092299" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "099099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "222099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "2222099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "09922099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "222292099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "0998999099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "099099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "099099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "099099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "09459099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "0912219099" }, ]; // n = 5 to export 5 questionexport default (n = 5) => Promise.resolve(qBank.sort(() => 0.5 - Math.random()).slice(0, n));
Edit src/components/QuestionBox.js file: This file makes question box with buttons.
import React, {useState} from "react";import "../style.css"; // Function to question inside our appconst QuestionBox = ({ question, options, selected}) => { const [answer, setAnswer] = useState(options); return ( <div className="questionBox"> <div className="question">{question}</div> {answer.map((text, index) => ( <button key={index} className="answerBtn" onClick={()=>{ setAnswer(); selected(text); }}> {text} </button> ))} </div> )}; export default QuestionBox;
Edit src/components/ResultBox.js file: This file displays the result.
import React from 'react';import "../style.css"; const Result = ({score, playAgain}) => ( <div className="score-board"> <div className="score"> Your score is {score} / 5 correct answer ! ! ! </div> <button className="playBtn" onClick={playAgain} > Play Again </button> </div>) export default Result;
Save all files and start the server:
npm start
open http://localhost:3000/ URL in the browser. It will display the result.
react-js
Web Technologies
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Oct, 2020"
},
{
"code": null,
"e": 351,
"s": 52,
"text": "React is a JavaScript library used to develop interactive user interfaces. It is managed by Facebook and a community of individual developers and companies. react mainly focus on developing single-page web or mobile applications. here, we will create a quiz app to understand the basics of reactjs."
},
{
"code": null,
"e": 369,
"s": 351,
"text": "Modules required:"
},
{
"code": null,
"e": 373,
"s": 369,
"text": "npm"
},
{
"code": null,
"e": 379,
"s": 373,
"text": "React"
},
{
"code": null,
"e": 432,
"s": 379,
"text": "React Bootstrapnpm install react-bootstrap bootstrap"
},
{
"code": null,
"e": 470,
"s": 432,
"text": "npm install react-bootstrap bootstrap"
},
{
"code": null,
"e": 483,
"s": 470,
"text": "Basic setup:"
},
{
"code": null,
"e": 526,
"s": 483,
"text": "Start a project by the following command –"
},
{
"code": null,
"e": 552,
"s": 526,
"text": "npx create-react-app quiz"
},
{
"code": null,
"e": 813,
"s": 552,
"text": "NPX is a package runner tool that comes with npm 5.2+, npx is easy to use CLI tools. npx is used for executing Node packages. It greatly simplifies a number of things one of which is checked/run a node package quickly without installing it locally or globally."
},
{
"code": null,
"e": 841,
"s": 813,
"text": "now, goto the folder create"
},
{
"code": null,
"e": 849,
"s": 841,
"text": "cd quiz"
},
{
"code": null,
"e": 926,
"s": 849,
"text": "Start the server- Start the server by typing following command in terminal –"
},
{
"code": null,
"e": 936,
"s": 926,
"text": "npm start"
},
{
"code": null,
"e": 964,
"s": 936,
"text": "open http://localhost:3000/"
},
{
"code": null,
"e": 990,
"s": 964,
"text": "Change directory to src –"
},
{
"code": null,
"e": 997,
"s": 990,
"text": "cd src"
},
{
"code": null,
"e": 1037,
"s": 997,
"text": "Delete every thing inside the directory"
},
{
"code": null,
"e": 1042,
"s": 1037,
"text": "rm *"
},
{
"code": null,
"e": 1068,
"s": 1042,
"text": "Now create index.js files"
},
{
"code": null,
"e": 1084,
"s": 1068,
"text": "touch index.js "
},
{
"code": null,
"e": 1367,
"s": 1084,
"text": "This file will render our app to html file which is in public folder now, create a folder name components with files src/components/QuestionBox.js and src/components/ResultBox.js to hold our app components and a folder question with file src/question/index.js to hold our questions."
},
{
"code": null,
"e": 1417,
"s": 1367,
"text": "mkdir components && cd components && touch app.js"
},
{
"code": null,
"e": 1459,
"s": 1417,
"text": "mkdir question && cd question && index.js"
},
{
"code": null,
"e": 1515,
"s": 1459,
"text": "Edit src/index.js fileThis file contains our app logic."
},
{
"code": "import React, {Component} from \"react\";import ReactDOM from \"react-dom\";import \"./style.css\";import questionAPI from './question';import QuestionBox from './components/QuestionBox';import Result from './components/ResultBox'; class Quiz extends Component { constructor() { super(); this.state = { questionBank: [], score: 0, responses: 0 }; } // Function to get question from ./question getQuestions = () => { questionAPI().then(question => { this.setState({questionBank: question}); }); }; // Set state back to default and call function playAgain = () => { this.getQuestions(); this.setState({score: 0, responses: 0}); }; // Function to compute scores computeAnswer = (answer, correctAns) => { if (answer === correctAns) { this.setState({ score: this.state.score + 1 }); } this.setState({ responses: this.state.responses < 5 ? this.state.responses + 1 : 5 }); }; // componentDidMount function to get question componentDidMount() { this.getQuestions(); } render() { return (<div className=\"container\"> <div className=\"title\"> QuizOn </div> {this.state.questionBank.length > 0 && this.state.responses < 5 && this.state.questionBank.map(({question, answers, correct, questionId}) => <QuestionBox question= {question} options={answers} key={questionId} selected={answer => this.computeAnswer(answer, correct)}/>)} { this.state.responses === 5 ? (<Result score={this.state.score} playAgain={this.playAgain}/>) : null } </div>) }} ReactDOM.render(<Quiz/>, document.getElementById(\"root\"));",
"e": 3232,
"s": 1515,
"text": null
},
{
"code": null,
"e": 3322,
"s": 3232,
"text": "Edit src/question/index.js file: This file contains all question which will be displayed."
},
{
"code": "const qBank = [ { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"099099\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"093909\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"009039\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"090089\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"01010101\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"092299\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"099099\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"222099\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"2222099\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"09922099\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"222292099\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"0998999099\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"099099\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"099099\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"099099\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"09459099\" }, { question: \"how build the app ?\", answers: [\"vinayak\", \"sarthak\", \"somil\", \"devesh\"], correct: \"vinayak\", questionId: \"0912219099\" }, ]; // n = 5 to export 5 questionexport default (n = 5) => Promise.resolve(qBank.sort(() => 0.5 - Math.random()).slice(0, n));",
"e": 6035,
"s": 3322,
"text": null
},
{
"code": null,
"e": 6119,
"s": 6035,
"text": "Edit src/components/QuestionBox.js file: This file makes question box with buttons."
},
{
"code": "import React, {useState} from \"react\";import \"../style.css\"; // Function to question inside our appconst QuestionBox = ({ question, options, selected}) => { const [answer, setAnswer] = useState(options); return ( <div className=\"questionBox\"> <div className=\"question\">{question}</div> {answer.map((text, index) => ( <button key={index} className=\"answerBtn\" onClick={()=>{ setAnswer(); selected(text); }}> {text} </button> ))} </div> )}; export default QuestionBox;",
"e": 6729,
"s": 6119,
"text": null
},
{
"code": null,
"e": 6799,
"s": 6729,
"text": "Edit src/components/ResultBox.js file: This file displays the result."
},
{
"code": "import React from 'react';import \"../style.css\"; const Result = ({score, playAgain}) => ( <div className=\"score-board\"> <div className=\"score\"> Your score is {score} / 5 correct answer ! ! ! </div> <button className=\"playBtn\" onClick={playAgain} > Play Again </button> </div>) export default Result;",
"e": 7109,
"s": 6799,
"text": null
},
{
"code": null,
"e": 7146,
"s": 7109,
"text": "Save all files and start the server:"
},
{
"code": null,
"e": 7156,
"s": 7146,
"text": "npm start"
},
{
"code": null,
"e": 7232,
"s": 7156,
"text": "open http://localhost:3000/ URL in the browser. It will display the result."
},
{
"code": null,
"e": 7241,
"s": 7232,
"text": "react-js"
},
{
"code": null,
"e": 7258,
"s": 7241,
"text": "Web Technologies"
},
{
"code": null,
"e": 7274,
"s": 7258,
"text": "Write From Home"
}
] |
HTTP headers | X-Content-Type-Options | 14 Sep, 2021
The HTTP headers X-Content-Type-Options acts as a marker that indicates the MIME-types headers in the content types headers should not be changed to the server. This header was introduced in the Internet Explorer 8 of Microsoft. This header block the content sniffing (non-executable MIME type into executable MIME type). After that, all the other browsers also introduce the X-Content-Type-Options, and their MIME sniffing algorithms were less aggressive.
Syntax:
x-content-type-options: nosniff
Directives: There is a single directive accepted by X-Content-Type-Options header.
nosniff: It blocks all request if there “style” MIME-type is not text/css and JavaScript MIME-type. Plus it enables the cross origin if there MIME-Type text/html, text/plain, text/jason, application/jason and any type of xml extension.
Example:
x-content-type-options: nosniff
To check the X-Content-Type-Options in action go to Inspect Element -> Network check the request header for x-content-type-options like below.
Supported Browsers: The browsers compatible with x-content-type-options header are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
singghakshay
HTTP-headers
Picked
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": "\n14 Sep, 2021"
},
{
"code": null,
"e": 486,
"s": 28,
"text": "The HTTP headers X-Content-Type-Options acts as a marker that indicates the MIME-types headers in the content types headers should not be changed to the server. This header was introduced in the Internet Explorer 8 of Microsoft. This header block the content sniffing (non-executable MIME type into executable MIME type). After that, all the other browsers also introduce the X-Content-Type-Options, and their MIME sniffing algorithms were less aggressive. "
},
{
"code": null,
"e": 496,
"s": 486,
"text": "Syntax: "
},
{
"code": null,
"e": 528,
"s": 496,
"text": "x-content-type-options: nosniff"
},
{
"code": null,
"e": 613,
"s": 528,
"text": "Directives: There is a single directive accepted by X-Content-Type-Options header. "
},
{
"code": null,
"e": 849,
"s": 613,
"text": "nosniff: It blocks all request if there “style” MIME-type is not text/css and JavaScript MIME-type. Plus it enables the cross origin if there MIME-Type text/html, text/plain, text/jason, application/jason and any type of xml extension."
},
{
"code": null,
"e": 860,
"s": 849,
"text": "Example: "
},
{
"code": null,
"e": 892,
"s": 860,
"text": "x-content-type-options: nosniff"
},
{
"code": null,
"e": 1036,
"s": 892,
"text": "To check the X-Content-Type-Options in action go to Inspect Element -> Network check the request header for x-content-type-options like below. "
},
{
"code": null,
"e": 1134,
"s": 1036,
"text": "Supported Browsers: The browsers compatible with x-content-type-options header are listed below: "
},
{
"code": null,
"e": 1148,
"s": 1134,
"text": "Google Chrome"
},
{
"code": null,
"e": 1166,
"s": 1148,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1174,
"s": 1166,
"text": "Firefox"
},
{
"code": null,
"e": 1180,
"s": 1174,
"text": "Opera"
},
{
"code": null,
"e": 1193,
"s": 1180,
"text": "singghakshay"
},
{
"code": null,
"e": 1206,
"s": 1193,
"text": "HTTP-headers"
},
{
"code": null,
"e": 1213,
"s": 1206,
"text": "Picked"
},
{
"code": null,
"e": 1230,
"s": 1213,
"text": "Web Technologies"
}
] |
How to add a column in an R data frame with consecutive numbers? | Addition of a column with consecutive might have different objectives such as getting the sequence of numbers, representing serial numbers, representing ids, identification of each row, or a variable. We can use the sequence starting from any number up to the number of rows if we know the number of rows for this purpose.
Consider the below data frame:
Live Demo
> x1<-rnorm(20,5,1.12)
> x2<-rnorm(20,5,0.34)
> df1<-data.frame(x1,x2)
> df1
x1 x2
1 6.137898 5.203712
2 5.283467 5.057344
3 5.873749 4.907388
4 7.628762 5.012650
5 4.134700 4.988379
6 5.340686 4.684900
7 5.126999 4.821752
8 3.722762 4.974044
9 4.097969 5.284176
10 4.249122 4.503324
11 5.511502 5.355315
12 5.826045 4.853419
13 4.947602 5.512752
14 7.174369 5.320503
15 4.671888 5.100163
16 3.777945 4.893680
17 3.591266 4.715214
18 4.270032 4.776928
19 6.913433 4.828765
20 4.619279 5.138295
Adding a column of consecutive numbers:
> df1$consecutive_numbers<-1:nrow(df1)
> df1
x1 x2 consecutive numbers
1 6.137898 5.203712 1
2 5.283467 5.057344 2
3 5.873749 4.907388 3
4 7.628762 5.012650 4
5 4.134700 4.988379 5
6 5.340686 4.684900 6
7 5.126999 4.821752 7
8 3.722762 4.974044 8
9 4.097969 5.284176 9
10 4.249122 4.503324 10
11 5.511502 5.355315 11
12 5.826045 4.853419 12
13 4.947602 5.512752 13
14 7.174369 5.320503 14
15 4.671888 5.100163 15
16 3.777945 4.893680 16
17 3.591266 4.715214 17
18 4.270032 4.776928 18
19 6.913433 4.828765 19
20 4.619279 5.138295 20
Live Demo
> y1<-rpois(20,5)
> y2<-rpois(20,8)
> df2<-data.frame(y1,y2)
> df2
y1 y2
1 4 7
2 11 7
3 5 5
4 3 8
5 6 5
6 4 8
7 6 6
8 2 10
9 1 8
10 6 6
11 6 5
12 2 10
13 4 3
14 1 12
15 5 9
16 4 8
17 5 8
18 4 2
19 6 10
20 4 8
Adding a column of consecutive numbers:
> df2$consecutive_numbers<-101:120
> df2
y1 y2 consecutive numbers
1 4 7 101
2 11 7 102
3 5 5 103
4 3 8 104
5 6 5 105
6 4 8 106
7 6 6 107
8 2 10 108
9 1 8 109
10 6 6 110
11 6 5 111
12 2 10 112
13 4 3 113
14 1 12 114
15 5 9 115
16 4 8 116
17 5 8 117
18 4 2 118
19 6 10 119
20 4 8 120 | [
{
"code": null,
"e": 1510,
"s": 1187,
"text": "Addition of a column with consecutive might have different objectives such as getting the sequence of numbers, representing serial numbers, representing ids, identification of each row, or a variable. We can use the sequence starting from any number up to the number of rows if we know the number of rows for this purpose."
},
{
"code": null,
"e": 1541,
"s": 1510,
"text": "Consider the below data frame:"
},
{
"code": null,
"e": 1551,
"s": 1541,
"text": "Live Demo"
},
{
"code": null,
"e": 1628,
"s": 1551,
"text": "> x1<-rnorm(20,5,1.12)\n> x2<-rnorm(20,5,0.34)\n> df1<-data.frame(x1,x2)\n> df1"
},
{
"code": null,
"e": 2056,
"s": 1628,
"text": " x1 x2\n1 6.137898 5.203712\n2 5.283467 5.057344\n3 5.873749 4.907388\n4 7.628762 5.012650\n5 4.134700 4.988379\n6 5.340686 4.684900\n7 5.126999 4.821752\n8 3.722762 4.974044\n9 4.097969 5.284176\n10 4.249122 4.503324\n11 5.511502 5.355315\n12 5.826045 4.853419\n13 4.947602 5.512752\n14 7.174369 5.320503\n15 4.671888 5.100163\n16 3.777945 4.893680\n17 3.591266 4.715214\n18 4.270032 4.776928\n19 6.913433 4.828765\n20 4.619279 5.138295"
},
{
"code": null,
"e": 2096,
"s": 2056,
"text": "Adding a column of consecutive numbers:"
},
{
"code": null,
"e": 2141,
"s": 2096,
"text": "> df1$consecutive_numbers<-1:nrow(df1)\n> df1"
},
{
"code": null,
"e": 2669,
"s": 2141,
"text": " x1 x2 consecutive numbers\n1 6.137898 5.203712 1\n2 5.283467 5.057344 2\n3 5.873749 4.907388 3\n4 7.628762 5.012650 4\n5 4.134700 4.988379 5\n6 5.340686 4.684900 6\n7 5.126999 4.821752 7\n8 3.722762 4.974044 8\n9 4.097969 5.284176 9\n10 4.249122 4.503324 10\n11 5.511502 5.355315 11\n12 5.826045 4.853419 12\n13 4.947602 5.512752 13\n14 7.174369 5.320503 14\n15 4.671888 5.100163 15\n16 3.777945 4.893680 16\n17 3.591266 4.715214 17\n18 4.270032 4.776928 18\n19 6.913433 4.828765 19\n20 4.619279 5.138295 20"
},
{
"code": null,
"e": 2679,
"s": 2669,
"text": "Live Demo"
},
{
"code": null,
"e": 2746,
"s": 2679,
"text": "> y1<-rpois(20,5)\n> y2<-rpois(20,8)\n> df2<-data.frame(y1,y2)\n> df2"
},
{
"code": null,
"e": 2889,
"s": 2746,
"text": " y1 y2\n1 4 7\n2 11 7\n3 5 5\n4 3 8\n5 6 5\n6 4 8\n7 6 6\n8 2 10\n9 1 8\n10 6 6\n11 6 5\n12 2 10\n13 4 3\n14 1 12\n15 5 9\n16 4 8\n17 5 8\n18 4 2\n19 6 10\n20 4 8"
},
{
"code": null,
"e": 2929,
"s": 2889,
"text": "Adding a column of consecutive numbers:"
},
{
"code": null,
"e": 2970,
"s": 2929,
"text": "> df2$consecutive_numbers<-101:120\n> df2"
},
{
"code": null,
"e": 3278,
"s": 2970,
"text": " y1 y2 consecutive numbers\n1 4 7 101\n2 11 7 102\n3 5 5 103\n4 3 8 104\n5 6 5 105\n6 4 8 106\n7 6 6 107\n8 2 10 108\n9 1 8 109\n10 6 6 110\n11 6 5 111 \n12 2 10 112\n13 4 3 113\n14 1 12 114\n15 5 9 115\n16 4 8 116\n17 5 8 117\n18 4 2 118\n19 6 10 119\n20 4 8 120"
}
] |
Python String lstrip() Method | Python string method lstrip() returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters).
Following is the syntax for lstrip() method −
str.lstrip([chars])
chars − You can supply what chars have to be trimmed.
chars − You can supply what chars have to be trimmed.
This method returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters).
The following example shows the usage of lstrip() method.
#!/usr/bin/python
str = " this is string example....wow!!! ";
print str.lstrip()
str = "88888888this is string example....wow!!!8888888";
print str.lstrip('8')
When we run above program, it produces following result −
this is string example....wow!!!
this is string example....wow!!!8888888 | [
{
"code": null,
"e": 2542,
"s": 2378,
"text": "Python string method lstrip() returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters)."
},
{
"code": null,
"e": 2588,
"s": 2542,
"text": "Following is the syntax for lstrip() method −"
},
{
"code": null,
"e": 2609,
"s": 2588,
"text": "str.lstrip([chars])\n"
},
{
"code": null,
"e": 2663,
"s": 2609,
"text": "chars − You can supply what chars have to be trimmed."
},
{
"code": null,
"e": 2717,
"s": 2663,
"text": "chars − You can supply what chars have to be trimmed."
},
{
"code": null,
"e": 2862,
"s": 2717,
"text": "This method returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters)."
},
{
"code": null,
"e": 2920,
"s": 2862,
"text": "The following example shows the usage of lstrip() method."
},
{
"code": null,
"e": 3089,
"s": 2920,
"text": "#!/usr/bin/python\n\nstr = \" this is string example....wow!!! \";\nprint str.lstrip()\nstr = \"88888888this is string example....wow!!!8888888\";\nprint str.lstrip('8')"
},
{
"code": null,
"e": 3147,
"s": 3089,
"text": "When we run above program, it produces following result −"
}
] |
Software Testing | Static Testing | 13 May, 2019
Static Testing is a type of a Software Testing method which is performed to check the defects in software without actually executing the code of the software application. Whereas in Dynamic Testing checks the code is executed to detect the defects.
Static testing is performed in early stage of development to avoid errors as it is easier to find sources of failures and it can be fixed easily. The errors that can’t not be found using Dynamic Testing, can be easily found by Static Testing.
Static Testing Techniques:There are mainly two type techniques used in Static Testing:
1. Review:In static testing review is a process or technique that is performed to find the potential defects in the design of the software. It is process to detect and remove errors and defects in the different supporting documents like software requirements specifications. People examine the documents and sorted out errors, redundancies and ambiguities.Review is of four types:
Informal:In informal review the creator of the documents put the contents in front of audience and everyone gives their opinion and thus defects are identified in the early stage.
Walkthrough:It is basically performed by experienced person or expert to check the defects so that there might not be problem further in the development or testing phase.
Peer review:Peer review means checking documents of one-another to detect and fix the defects. It is basically done in a team of colleagues.
Inspection:Inspection is basically the verification of document the higher authority like the verification of software requirement specifications (SRS).
2. Static Analysis:Static Analysis includes the evaluation of the code quality that is written by developers. Different tools are used to do the analysis of the code and comparison of the same with the standard.It also helps in following identification of following defects:
(a) Unused variables
(b) Dead code
(c) Infinite loops
(d) Variable with undefined value
(e) Wrong syntax
Static Analysis is of three types:
Data Flow:Data flow is related to the stream processing.
Control Flow:Control flow is basically how the statements or instructions are executed.
Cyclomatic Complexity:Cyclomatic complexity is the measurement of the complexity of the program that is basically related to the number of independent paths in the control flow graph of the program.
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 May, 2019"
},
{
"code": null,
"e": 302,
"s": 53,
"text": "Static Testing is a type of a Software Testing method which is performed to check the defects in software without actually executing the code of the software application. Whereas in Dynamic Testing checks the code is executed to detect the defects."
},
{
"code": null,
"e": 545,
"s": 302,
"text": "Static testing is performed in early stage of development to avoid errors as it is easier to find sources of failures and it can be fixed easily. The errors that can’t not be found using Dynamic Testing, can be easily found by Static Testing."
},
{
"code": null,
"e": 632,
"s": 545,
"text": "Static Testing Techniques:There are mainly two type techniques used in Static Testing:"
},
{
"code": null,
"e": 1013,
"s": 632,
"text": "1. Review:In static testing review is a process or technique that is performed to find the potential defects in the design of the software. It is process to detect and remove errors and defects in the different supporting documents like software requirements specifications. People examine the documents and sorted out errors, redundancies and ambiguities.Review is of four types:"
},
{
"code": null,
"e": 1193,
"s": 1013,
"text": "Informal:In informal review the creator of the documents put the contents in front of audience and everyone gives their opinion and thus defects are identified in the early stage."
},
{
"code": null,
"e": 1364,
"s": 1193,
"text": "Walkthrough:It is basically performed by experienced person or expert to check the defects so that there might not be problem further in the development or testing phase."
},
{
"code": null,
"e": 1505,
"s": 1364,
"text": "Peer review:Peer review means checking documents of one-another to detect and fix the defects. It is basically done in a team of colleagues."
},
{
"code": null,
"e": 1658,
"s": 1505,
"text": "Inspection:Inspection is basically the verification of document the higher authority like the verification of software requirement specifications (SRS)."
},
{
"code": null,
"e": 1933,
"s": 1658,
"text": "2. Static Analysis:Static Analysis includes the evaluation of the code quality that is written by developers. Different tools are used to do the analysis of the code and comparison of the same with the standard.It also helps in following identification of following defects:"
},
{
"code": null,
"e": 2039,
"s": 1933,
"text": "(a) Unused variables\n(b) Dead code\n(c) Infinite loops\n(d) Variable with undefined value\n(e) Wrong syntax "
},
{
"code": null,
"e": 2074,
"s": 2039,
"text": "Static Analysis is of three types:"
},
{
"code": null,
"e": 2131,
"s": 2074,
"text": "Data Flow:Data flow is related to the stream processing."
},
{
"code": null,
"e": 2219,
"s": 2131,
"text": "Control Flow:Control flow is basically how the statements or instructions are executed."
},
{
"code": null,
"e": 2418,
"s": 2219,
"text": "Cyclomatic Complexity:Cyclomatic complexity is the measurement of the complexity of the program that is basically related to the number of independent paths in the control flow graph of the program."
},
{
"code": null,
"e": 2435,
"s": 2418,
"text": "Software Testing"
},
{
"code": null,
"e": 2456,
"s": 2435,
"text": "Software Engineering"
}
] |
What are the differences between compareTo() and compare() methods in Java?
| The Comparable interface provides a compareTo() method for the ordering of objects. This ordering is called the class’s natural ordering and the compareTo() method is called its natural comparison method. The Comparator interface provides the methods for performing sorting operations. By using the Comparator interface we can do multiple sorting sequences. We can sort the objects with respect to multiple data members.
compareTo() method compares this object with an o1 object and returns an integer.
public int compareTo(Object o1)
It returns –ve number if & only if this object is less than o1.
It returns +ve number if & only if this object is greater than o1.
It returns 0 if & only if this object is equal to o1.
Live Demo
import java.util.*;
class Employee implements Comparable {
String name;
int age;
Employee(String name, int age) {
this.name = name;
this.age = age;
}
//overridden compareTo method
@Override
public int compareTo(Object o) {
return this.age - ((Employee) o).age;
}
}
public class ComparableDemo {
public static void main(String[] args) {
// CREATION
List list = new ArrayList<>();
//INSERTION
list.add(new Employee("Krishna", 30));
list.add(new Employee("Archana", 28));
list.add(new Employee("Vineet", 25));
list.add(new Employee("Ramesh", 38));
list.add(new Employee("Alok", 28));
System.out.println("Before sorting: ");
for (Employee e : list) {
System.out.print("[ EMP : age = " + e.age + " ] ");
}
//SORTING
Collections.sort(list);
System.out.println("After sorting: ");
for (Employee e : list) {
System.out.print("[ EMP : age = " + e.age + " ] ");
}
}
}
Before sorting:
[ EMP : age = 2 ] [ EMP : age = 33 ] [ EMP : age = 11 ] [ EMP : age = 34 ] [ EMP : age = 7 ]
After sorting:
[ EMP : age = 2 ] [ EMP : age = 7 ] [ EMP : age = 11 ] [ EMP : age = 33 ] [ EMP : age = 34 ]
compare() method compares the first object with the second object and returns an integer
public int compare (Object o1,Object o2)
It returns –ve number if & only if o1 is less than o2
It returns +ve number if & only if o1 is greater than o2
It returns 0 if & only if o1 is equal to o2
Live Demo
import java.util.*;
class Student {
String name;
int age, roll;
Student(String name, int age, int roll) {
this.name = name;
this.age = age;
this.roll = roll;
}
}
class AgeComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
return ((Student) o1).age - ((Student) o2).age;
}
}
class RollComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
return ((Student) o1).roll - ((Student) o2).roll;
}
}
public class ComparatorDemo {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(new Student("Ramesh", 30, 20));
list.add(new Student("Adithya", 7, 10));
list.add(new Student("Krishna", 25, 5));
list.add(new Student("Vineet", 24, 15));
System.out.println("BEFORE SORTING");
for (Student e : list) {
System.out.println("[ STU : name = " + e.name + " age = " + e.age + " roll = " + e.roll + "]");
}
Collections.sort(list,new AgeComparator());
System.out.println("AFTER SORTING WITH AGE");
for (Student e : list) {
System.out.println("[ STU : name = " + e.name + " age = " + e.age + " ]");
}
Collections.sort(list,new RollComparator());
System.out.println("AFTER SORTING WITH ROLL");
for (Student e : list) {
System.out.println("[ STU : name = " + e.name + " roll = " + e.roll + " ]");
}
}
}
BEFORE SORTING
[ STU : name = Ramesh age = 30 roll = 20 ]
[ STU : name = Adithya age = 7 roll = 10 ]
[ STU : name = Krishna age = 25 roll = 5 ]
[ STU : name = Vineet age = 24 roll = 15 ]
AFTER SORTING WITH AGE
[ STU : name = Adithya age = 7 ]
[ STU : name = Vineet age = 24 ]
[ STU : name = Krishna age = 25 ]
[ STU : name = Ramesh age = 30 ]
AFTER SORTING WITH ROLL
[ STU : name = Krishna roll = 5 ]
[ STU : name = Adithya roll = 10 ]
[ STU : name = Vineet roll = 15 ]
[ STU : name = Ramesh roll = 20 ] | [
{
"code": null,
"e": 1608,
"s": 1187,
"text": "The Comparable interface provides a compareTo() method for the ordering of objects. This ordering is called the class’s natural ordering and the compareTo() method is called its natural comparison method. The Comparator interface provides the methods for performing sorting operations. By using the Comparator interface we can do multiple sorting sequences. We can sort the objects with respect to multiple data members."
},
{
"code": null,
"e": 1690,
"s": 1608,
"text": "compareTo() method compares this object with an o1 object and returns an integer."
},
{
"code": null,
"e": 1722,
"s": 1690,
"text": "public int compareTo(Object o1)"
},
{
"code": null,
"e": 1786,
"s": 1722,
"text": "It returns –ve number if & only if this object is less than o1."
},
{
"code": null,
"e": 1853,
"s": 1786,
"text": "It returns +ve number if & only if this object is greater than o1."
},
{
"code": null,
"e": 1907,
"s": 1853,
"text": "It returns 0 if & only if this object is equal to o1."
},
{
"code": null,
"e": 1917,
"s": 1907,
"text": "Live Demo"
},
{
"code": null,
"e": 2937,
"s": 1917,
"text": "import java.util.*;\nclass Employee implements Comparable {\n String name;\n int age;\n Employee(String name, int age) {\n this.name = name;\n this.age = age;\n }\n //overridden compareTo method\n @Override\n public int compareTo(Object o) {\n return this.age - ((Employee) o).age;\n }\n}\npublic class ComparableDemo {\n public static void main(String[] args) {\n // CREATION\n List list = new ArrayList<>();\n //INSERTION\n list.add(new Employee(\"Krishna\", 30));\n list.add(new Employee(\"Archana\", 28));\n list.add(new Employee(\"Vineet\", 25));\n list.add(new Employee(\"Ramesh\", 38));\n list.add(new Employee(\"Alok\", 28));\n System.out.println(\"Before sorting: \");\n for (Employee e : list) {\n System.out.print(\"[ EMP : age = \" + e.age + \" ] \");\n }\n //SORTING\n Collections.sort(list);\n System.out.println(\"After sorting: \");\n for (Employee e : list) {\n System.out.print(\"[ EMP : age = \" + e.age + \" ] \");\n }\n }\n}"
},
{
"code": null,
"e": 3154,
"s": 2937,
"text": "Before sorting:\n[ EMP : age = 2 ] [ EMP : age = 33 ] [ EMP : age = 11 ] [ EMP : age = 34 ] [ EMP : age = 7 ]\nAfter sorting:\n[ EMP : age = 2 ] [ EMP : age = 7 ] [ EMP : age = 11 ] [ EMP : age = 33 ] [ EMP : age = 34 ]"
},
{
"code": null,
"e": 3243,
"s": 3154,
"text": "compare() method compares the first object with the second object and returns an integer"
},
{
"code": null,
"e": 3284,
"s": 3243,
"text": "public int compare (Object o1,Object o2)"
},
{
"code": null,
"e": 3338,
"s": 3284,
"text": "It returns –ve number if & only if o1 is less than o2"
},
{
"code": null,
"e": 3395,
"s": 3338,
"text": "It returns +ve number if & only if o1 is greater than o2"
},
{
"code": null,
"e": 3439,
"s": 3395,
"text": "It returns 0 if & only if o1 is equal to o2"
},
{
"code": null,
"e": 3449,
"s": 3439,
"text": "Live Demo"
},
{
"code": null,
"e": 4920,
"s": 3449,
"text": "import java.util.*;\nclass Student {\n String name;\n int age, roll;\n Student(String name, int age, int roll) {\n this.name = name;\n this.age = age;\n this.roll = roll;\n }\n}\nclass AgeComparator implements Comparator {\n @Override\n public int compare(Object o1, Object o2) {\n return ((Student) o1).age - ((Student) o2).age;\n }\n}\nclass RollComparator implements Comparator {\n @Override\n public int compare(Object o1, Object o2) {\n return ((Student) o1).roll - ((Student) o2).roll;\n }\n}\npublic class ComparatorDemo {\n public static void main(String[] args) {\n List list = new ArrayList<>();\n list.add(new Student(\"Ramesh\", 30, 20));\n list.add(new Student(\"Adithya\", 7, 10));\n list.add(new Student(\"Krishna\", 25, 5));\n list.add(new Student(\"Vineet\", 24, 15));\n System.out.println(\"BEFORE SORTING\");\n for (Student e : list) {\n System.out.println(\"[ STU : name = \" + e.name + \" age = \" + e.age + \" roll = \" + e.roll + \"]\");\n }\n Collections.sort(list,new AgeComparator());\n System.out.println(\"AFTER SORTING WITH AGE\");\n for (Student e : list) {\n System.out.println(\"[ STU : name = \" + e.name + \" age = \" + e.age + \" ]\");\n }\n Collections.sort(list,new RollComparator());\n System.out.println(\"AFTER SORTING WITH ROLL\");\n for (Student e : list) {\n System.out.println(\"[ STU : name = \" + e.name + \" roll = \" + e.roll + \" ]\");\n }\n }\n}"
},
{
"code": null,
"e": 5424,
"s": 4920,
"text": "BEFORE SORTING\n[ STU : name = Ramesh age = 30 roll = 20 ]\n[ STU : name = Adithya age = 7 roll = 10 ]\n[ STU : name = Krishna age = 25 roll = 5 ]\n[ STU : name = Vineet age = 24 roll = 15 ]\nAFTER SORTING WITH AGE\n[ STU : name = Adithya age = 7 ]\n[ STU : name = Vineet age = 24 ]\n[ STU : name = Krishna age = 25 ]\n[ STU : name = Ramesh age = 30 ]\nAFTER SORTING WITH ROLL\n[ STU : name = Krishna roll = 5 ]\n[ STU : name = Adithya roll = 10 ]\n[ STU : name = Vineet roll = 15 ]\n[ STU : name = Ramesh roll = 20 ]"
}
] |
Java Program to Print Left Triangle Star Pattern | 06 Jun, 2022
In this article, we will learn about printing Left Triangle Star Pattern.
Examples:
Input : n = 5
Output:
*
* *
* * *
* * * *
* * * * *
Left Triangle Star Pattern:
Java
import java.io.*; // java program for left trianglepublic class GFG { // Function to demonstrate printing pattern public static void StarleftTriangle(int k) { int a, b; // 1st loop for (a = 0; a < k; a++) { // nested 2nd loop for (b = 2 * (k - a); b >= 0; b--) { // printing spaces System.out.print(" "); } // nested 3rd loop for (b = 0; b <= a; b++) { // printing stars System.out.print("* "); } // end-line System.out.println(); } } // Driver Function public static void main(String args[]) { int k = 5; StarleftTriangle(k); }}
*
* *
* * *
* * * *
* * * * *
Time Complexity: O(k2), where k represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant.
tamanna17122007
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 126,
"s": 52,
"text": "In this article, we will learn about printing Left Triangle Star Pattern."
},
{
"code": null,
"e": 136,
"s": 126,
"text": "Examples:"
},
{
"code": null,
"e": 229,
"s": 136,
"text": "Input : n = 5\nOutput: \n * \n * * \n * * * \n * * * * \n * * * * * "
},
{
"code": null,
"e": 257,
"s": 229,
"text": "Left Triangle Star Pattern:"
},
{
"code": null,
"e": 262,
"s": 257,
"text": "Java"
},
{
"code": "import java.io.*; // java program for left trianglepublic class GFG { // Function to demonstrate printing pattern public static void StarleftTriangle(int k) { int a, b; // 1st loop for (a = 0; a < k; a++) { // nested 2nd loop for (b = 2 * (k - a); b >= 0; b--) { // printing spaces System.out.print(\" \"); } // nested 3rd loop for (b = 0; b <= a; b++) { // printing stars System.out.print(\"* \"); } // end-line System.out.println(); } } // Driver Function public static void main(String args[]) { int k = 5; StarleftTriangle(k); }}",
"e": 1011,
"s": 262,
"text": null
},
{
"code": null,
"e": 1081,
"s": 1011,
"text": " * \n * * \n * * * \n * * * * \n * * * * * "
},
{
"code": null,
"e": 1212,
"s": 1081,
"text": "Time Complexity: O(k2), where k represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 1228,
"s": 1212,
"text": "tamanna17122007"
},
{
"code": null,
"e": 1235,
"s": 1228,
"text": "Picked"
},
{
"code": null,
"e": 1240,
"s": 1235,
"text": "Java"
},
{
"code": null,
"e": 1254,
"s": 1240,
"text": "Java Programs"
},
{
"code": null,
"e": 1259,
"s": 1254,
"text": "Java"
}
] |
Negative transformation of an image using Python and OpenCV | 11 Mar, 2020
Image is also known as a set of pixels. When we store an image in computers or digitally, it’s corresponding pixel values are stored. So, when we read an image to a variable using OpenCV in Python, the variable stores the pixel values of the image. When we try to negatively transform an image, the brightest areas are transformed into the darkest and the darkest areas are transformed into the brightest.
As we know, a color image stores 3 different channels. They are red, green and blue. That’s why color images are also known as RGB images. So, if we need a negative transformation of an image then we need to invert these 3 channels.
Let’s see 3 channels of a color image by plotting it in the histogram.
Input Image –
# We need cv2 module for image # reading and matplotlib module# for plottingimport cv2import matplotlib.pyplot as plt img_bgr = cv2.imread('scenary.jpg', 1) color = ('b', 'g', 'r') for i, col in enumerate(color): histr = cv2.calcHist([img_bgr], [i], None, [256], [0, 256]) plt.plot(histr, color = col) plt.xlim([0, 256]) plt.show()
Output:
Here, the 3 channels (Red, Green, Blue) are overlapped and create a single histogram. If you have studied about pixels and RGB before, you may know that each color contains 256 values. If RGB value of a color is (255, 255, 255) then that color is shown as white and If RGB value of a color is (0, 0, 0) then that color is shown as black. Like that, the above 3 channels also contain 256 numbers of pixels.
So, X-axis shows a total of 256 values (0 – 255) and Y-axis shows the total frequencies of each channel. As you can see in the histogram, the blue channel has the highest frequency and you can easily mark the amount of blue color present in the image by looking at it.
Let’s create a negative transformation of the image. There 2 different ways to transform an image to negative using the OpenCV module. The first method explains negative transformation step by step and the second method explains negative transformation of an image in single line.
First method: Steps for negative transformation
Read an imageGet height and width of the imageEach pixel contains 3 channels. So, take a pixel value and collect 3 channels in 3 different variables.Negate 3 pixels values from 255 and store them again in pixel used before.Do it for all pixel values present in image.
Read an image
Get height and width of the image
Each pixel contains 3 channels. So, take a pixel value and collect 3 channels in 3 different variables.
Negate 3 pixels values from 255 and store them again in pixel used before.
Do it for all pixel values present in image.
Python code for 1st method: –
import cv2import matplotlib.pyplot as plt # Read an imageimg_bgr = cv2.imread('scenary.jpg', 1)plt.imshow(img_bgr)plt.show() # Histogram plotting of the imagecolor = ('b', 'g', 'r') for i, col in enumerate(color): histr = cv2.calcHist([img_bgr], [i], None, [256], [0, 256]) plt.plot(histr, color = col) # Limit X - axis to 256 plt.xlim([0, 256]) plt.show() # get height and width of the imageheight, width, _ = img_bgr.shape for i in range(0, height - 1): for j in range(0, width - 1): # Get the pixel value pixel = img_bgr[i, j] # Negate each channel by # subtracting it from 255 # 1st index contains red pixel pixel[0] = 255 - pixel[0] # 2nd index contains green pixel pixel[1] = 255 - pixel[1] # 3rd index contains blue pixel pixel[2] = 255 - pixel[2] # Store new values in the pixel img_bgr[i, j] = pixel # Display the negative transformed imageplt.imshow(img_bgr)plt.show() # Histogram plotting of the# negative transformed imagecolor = ('b', 'g', 'r') for i, col in enumerate(color): histr = cv2.calcHist([img_bgr], [i], None, [256], [0, 256]) plt.plot(histr, color = col) plt.xlim([0, 256]) plt.show()
Output :
(Original image and it’s histogram)
(Negative image and it’s histogram)
2nd method: Steps for negative transformation
Read an image and store it in a variable.Subtract the variable from 1 and store the value in another variable.All done. You successfully done the negative transformation.
Read an image and store it in a variable.
Subtract the variable from 1 and store the value in another variable.
All done. You successfully done the negative transformation.
Python code for 2nd method: –
import cv2import matplotlib.pyplot as plt # Read an imageimg_bgr = cv2.imread('scenary.jpg', 1) plt.imshow(img_bgr)plt.show() # Histogram plotting of original imagecolor = ('b', 'g', 'r') for i, col in enumerate(color): histr = cv2.calcHist([img_bgr], [i], None, [256], [0, 256]) plt.plot(histr, color = col) # Limit X - axis to 256 plt.xlim([0, 256]) plt.show() # Negate the original imageimg_neg = 1 - img_bgr plt.imshow(img_neg)plt.show() # Histogram plotting of# negative transformed imagecolor = ('b', 'g', 'r') for i, col in enumerate(color): histr = cv2.calcHist([img_neg], [i], None, [256], [0, 256]) plt.plot(histr, color = col) plt.xlim([0, 256]) plt.show()
Output :
(Original image and it’s histogram)
(Negative image and it’s histogram)
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Mar, 2020"
},
{
"code": null,
"e": 434,
"s": 28,
"text": "Image is also known as a set of pixels. When we store an image in computers or digitally, it’s corresponding pixel values are stored. So, when we read an image to a variable using OpenCV in Python, the variable stores the pixel values of the image. When we try to negatively transform an image, the brightest areas are transformed into the darkest and the darkest areas are transformed into the brightest."
},
{
"code": null,
"e": 667,
"s": 434,
"text": "As we know, a color image stores 3 different channels. They are red, green and blue. That’s why color images are also known as RGB images. So, if we need a negative transformation of an image then we need to invert these 3 channels."
},
{
"code": null,
"e": 738,
"s": 667,
"text": "Let’s see 3 channels of a color image by plotting it in the histogram."
},
{
"code": null,
"e": 752,
"s": 738,
"text": "Input Image –"
},
{
"code": "# We need cv2 module for image # reading and matplotlib module# for plottingimport cv2import matplotlib.pyplot as plt img_bgr = cv2.imread('scenary.jpg', 1) color = ('b', 'g', 'r') for i, col in enumerate(color): histr = cv2.calcHist([img_bgr], [i], None, [256], [0, 256]) plt.plot(histr, color = col) plt.xlim([0, 256]) plt.show()",
"e": 1103,
"s": 752,
"text": null
},
{
"code": null,
"e": 1111,
"s": 1103,
"text": "Output:"
},
{
"code": null,
"e": 1517,
"s": 1111,
"text": "Here, the 3 channels (Red, Green, Blue) are overlapped and create a single histogram. If you have studied about pixels and RGB before, you may know that each color contains 256 values. If RGB value of a color is (255, 255, 255) then that color is shown as white and If RGB value of a color is (0, 0, 0) then that color is shown as black. Like that, the above 3 channels also contain 256 numbers of pixels."
},
{
"code": null,
"e": 1786,
"s": 1517,
"text": "So, X-axis shows a total of 256 values (0 – 255) and Y-axis shows the total frequencies of each channel. As you can see in the histogram, the blue channel has the highest frequency and you can easily mark the amount of blue color present in the image by looking at it."
},
{
"code": null,
"e": 2067,
"s": 1786,
"text": "Let’s create a negative transformation of the image. There 2 different ways to transform an image to negative using the OpenCV module. The first method explains negative transformation step by step and the second method explains negative transformation of an image in single line."
},
{
"code": null,
"e": 2115,
"s": 2067,
"text": "First method: Steps for negative transformation"
},
{
"code": null,
"e": 2383,
"s": 2115,
"text": "Read an imageGet height and width of the imageEach pixel contains 3 channels. So, take a pixel value and collect 3 channels in 3 different variables.Negate 3 pixels values from 255 and store them again in pixel used before.Do it for all pixel values present in image."
},
{
"code": null,
"e": 2397,
"s": 2383,
"text": "Read an image"
},
{
"code": null,
"e": 2431,
"s": 2397,
"text": "Get height and width of the image"
},
{
"code": null,
"e": 2535,
"s": 2431,
"text": "Each pixel contains 3 channels. So, take a pixel value and collect 3 channels in 3 different variables."
},
{
"code": null,
"e": 2610,
"s": 2535,
"text": "Negate 3 pixels values from 255 and store them again in pixel used before."
},
{
"code": null,
"e": 2655,
"s": 2610,
"text": "Do it for all pixel values present in image."
},
{
"code": null,
"e": 2685,
"s": 2655,
"text": "Python code for 1st method: –"
},
{
"code": "import cv2import matplotlib.pyplot as plt # Read an imageimg_bgr = cv2.imread('scenary.jpg', 1)plt.imshow(img_bgr)plt.show() # Histogram plotting of the imagecolor = ('b', 'g', 'r') for i, col in enumerate(color): histr = cv2.calcHist([img_bgr], [i], None, [256], [0, 256]) plt.plot(histr, color = col) # Limit X - axis to 256 plt.xlim([0, 256]) plt.show() # get height and width of the imageheight, width, _ = img_bgr.shape for i in range(0, height - 1): for j in range(0, width - 1): # Get the pixel value pixel = img_bgr[i, j] # Negate each channel by # subtracting it from 255 # 1st index contains red pixel pixel[0] = 255 - pixel[0] # 2nd index contains green pixel pixel[1] = 255 - pixel[1] # 3rd index contains blue pixel pixel[2] = 255 - pixel[2] # Store new values in the pixel img_bgr[i, j] = pixel # Display the negative transformed imageplt.imshow(img_bgr)plt.show() # Histogram plotting of the# negative transformed imagecolor = ('b', 'g', 'r') for i, col in enumerate(color): histr = cv2.calcHist([img_bgr], [i], None, [256], [0, 256]) plt.plot(histr, color = col) plt.xlim([0, 256]) plt.show()",
"e": 4160,
"s": 2685,
"text": null
},
{
"code": null,
"e": 4169,
"s": 4160,
"text": "Output :"
},
{
"code": null,
"e": 4205,
"s": 4169,
"text": "(Original image and it’s histogram)"
},
{
"code": null,
"e": 4241,
"s": 4205,
"text": "(Negative image and it’s histogram)"
},
{
"code": null,
"e": 4287,
"s": 4241,
"text": "2nd method: Steps for negative transformation"
},
{
"code": null,
"e": 4458,
"s": 4287,
"text": "Read an image and store it in a variable.Subtract the variable from 1 and store the value in another variable.All done. You successfully done the negative transformation."
},
{
"code": null,
"e": 4500,
"s": 4458,
"text": "Read an image and store it in a variable."
},
{
"code": null,
"e": 4570,
"s": 4500,
"text": "Subtract the variable from 1 and store the value in another variable."
},
{
"code": null,
"e": 4631,
"s": 4570,
"text": "All done. You successfully done the negative transformation."
},
{
"code": null,
"e": 4661,
"s": 4631,
"text": "Python code for 2nd method: –"
},
{
"code": "import cv2import matplotlib.pyplot as plt # Read an imageimg_bgr = cv2.imread('scenary.jpg', 1) plt.imshow(img_bgr)plt.show() # Histogram plotting of original imagecolor = ('b', 'g', 'r') for i, col in enumerate(color): histr = cv2.calcHist([img_bgr], [i], None, [256], [0, 256]) plt.plot(histr, color = col) # Limit X - axis to 256 plt.xlim([0, 256]) plt.show() # Negate the original imageimg_neg = 1 - img_bgr plt.imshow(img_neg)plt.show() # Histogram plotting of# negative transformed imagecolor = ('b', 'g', 'r') for i, col in enumerate(color): histr = cv2.calcHist([img_neg], [i], None, [256], [0, 256]) plt.plot(histr, color = col) plt.xlim([0, 256]) plt.show()",
"e": 5545,
"s": 4661,
"text": null
},
{
"code": null,
"e": 5554,
"s": 5545,
"text": "Output :"
},
{
"code": null,
"e": 5590,
"s": 5554,
"text": "(Original image and it’s histogram)"
},
{
"code": null,
"e": 5626,
"s": 5590,
"text": "(Negative image and it’s histogram)"
},
{
"code": null,
"e": 5640,
"s": 5626,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 5647,
"s": 5640,
"text": "Python"
}
] |
Minimum Platforms | Practice | GeeksforGeeks | Given arrival and departure times of all trains that reach a railway station. Find the minimum number of platforms required for the railway station so that no train is kept waiting.
Consider that all the trains arrive on the same day and leave on the same day. Arrival and departure time can never be the same for a train but we can have arrival time of one train equal to departure time of the other. At any given instance of time, same platform can not be used for both departure of a train and arrival of another train. In such cases, we need different platforms.
Example 1:
Input: n = 6
arr[] = {0900, 0940, 0950, 1100, 1500, 1800}
dep[] = {0910, 1200, 1120, 1130, 1900, 2000}
Output: 3
Explanation:
Minimum 3 platforms are required to
safely arrive and depart all trains.
Example 2:
Input: n = 3
arr[] = {0900, 1100, 1235}
dep[] = {1000, 1200, 1240}
Output: 1
Explanation: Only 1 platform is required to
safely manage the arrival and departure
of all trains.
Your Task:
You don't need to read input or print anything. Your task is to complete the function findPlatform() which takes the array arr[] (denoting the arrival times), array dep[] (denoting the departure times) and the size of the array as inputs and returns the minimum number of platforms required at the railway station such that no train waits.
Note: Time intervals are in the 24-hour format(HHMM) , where the first two characters represent hour (between 00 to 23 ) and the last two characters represent minutes (this may be > 59).
Expected Time Complexity: O(nLogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 50000
0000 ≤ A[i] ≤ D[i] ≤ 2359
+3
abhiraj643110 hours ago
C++ | priority queue | easy explained ||
Approach : let's think little practically here what we need is priority wise arranging trains, such that we use least platforms.
say we have an intelligent data structure whose size represents the total platforms and maintains a pointer to a train of lowest departure time among present trains on all platforms.
when new train comes (consider we have only one platform initially with only one train's departure data maintanded)
based on new train's arrival time we can
compare the lowest daparture time of existing trains with the arrival time of this new train.if there exists such train on platforms whose departure is less than arrival time of this new train , then we will just add this new train to that platform and now data structure will maintain info of new train''s departure time and will remove the old train's data from that particular platformif arrival time is greater than the existing train's lowest departure time time we will just add new platform for the train
compare the lowest daparture time of existing trains with the arrival time of this new train.
if there exists such train on platforms whose departure is less than arrival time of this new train , then we will just add this new train to that platform and now data structure will maintain info of new train''s departure time and will remove the old train's data from that particular platform
if arrival time is greater than the existing train's lowest departure time time we will just add new platform for the train
( eventually platforms will dynamically change in the end the the required platforms will be equal to the size of data structure)
we need priority queue which shows minimum element in the queue.
priority_queue<int, vector<int> , greater<int>> pq;
Solution :
store pair of arrival and departure into vector pairsort vector pair as per the arrival time of trainsget min heapif lowest departure time in existing platform queue is less than arrival time of new train then pop that train and add new train's departure timeelse add new trains departure time to queue : assigning new platform to new train.return size of platform queue.
store pair of arrival and departure into vector pair
sort vector pair as per the arrival time of trains
get min heap
if lowest departure time in existing platform queue is less than arrival time of new train then pop that train and add new train's departure time
else add new trains departure time to queue : assigning new platform to new train.
return size of platform queue.
class Solution{
public:
//Function to find the minimum number of platforms required at the
//railway station such that no train waits.
int findPlatform(int arr[], int dep[], int n)
{
vector<pair<int,int>> vp;
for(int i=0;i<n;i++){
vp.push_back({arr[i],dep[i]});
}
sort(vp.begin(),vp.end());
priority_queue<int, vector<int> , greater<int>> pq;
for(int i=0;i<n;i++){
pq.push(vp[i].second);
if(pq.top()<vp[i].first) {pq.pop();}
}
return pq.size();
}
};
0
bibhore0215 hours ago
using pq...all test case passed
int findPlatform(int arr[], int dep[], int n) { vector<pair<int,int>> itvls; for(int i=0;i<n;i++) itvls.push_back({arr[i],dep[i]}); sort(itvls.begin(),itvls.end()); priority_queue <int, vector<int>, greater<int> > pq; pq.push(itvls[0].second); for(int i=1;i<n;i++) { if(pq.top()>=itvls[i].first) { pq.push(itvls[i].second); } else { pq.pop(); pq.push(itvls[i].second); } } return pq.size(); }};
0
abhinayabhi1412 days ago
sort(arr,arr+n);
sort(dep,dep+n);
int count=1,ans=1;
int j=0,i=1;
while(i<n && j<n){
if(arr[i]<=dep[j]){
count++;
i++;
}
else{
count--;
j++;
}
if(count>ans)ans=count;
}
return ans;
0
yogya25singhal3 days ago
sort(arr,arr+n);
sort(dep,dep+n);
int count=1,ans=1;
int j=0,i=1;
while(i<n && j<n){
if(arr[i]<=dep[j]){
count++;
i++;
}
else{
count--;
j++;
}
if(count>ans)ans=count;
}
return ans;
+1
jaydhurat3 days ago
class Solution
{
//Function to find the minimum number of platforms required at the
//railway station such that no train waits.
static int findPlatform(int a[], int dep[], int n)
{
// add your code here
Arrays.sort(a);
Arrays.sort(dep);
int pf = 1;
int max =1;
int i = 1;
int j=0;
while(i<n && j<n)
{
if(a[i]<=dep[j])
{
pf++;
i++;
}
else if( a[i]>dep[j])
{
pf--;
j++;
}
if(pf>max)
{
max=pf;
}
}
return max;
}
}
0
sanjeevranjan12094 days ago
Python full solution:
class Solution:
#Function to find the minimum number of platforms required at the
#railway station such that no train waits.
def minimumPlatform(self,n,arr,dep):
dep.sort()
arr.sort()
i,j=1,0
result,platform = 1,1
while (i<n and j<n):
if arr[i]<=dep[j]:
i+=1
platform+=1
elif arr[i]>dep[j]:
j+=1
platform-=1
if result<platform:
result = platform
return result
0
sanskritisrivastava201914 days ago
Java Solution:
static int findPlatform(int arr[], int dep[], int n)
{
Arrays.sort(arr);//sorting arrival and departure time
Arrays.sort(dep);//to know till when platforms will be busy
int platform_needed=1,res=1;
int i=1,j=0;
while(i<n && j<n){
if(arr[i]<=dep[j]){ //platform is busy w former arrival
platform_needed++;
i++;
}else if(arr[i]>dep[j]){
platform_needed--; //current platform_needed will reduce
j++; //checking for next departure
}
res = Math.max(platform_needed,res); //max platform needed overall
}
return res;
}
0
hum_toh_ram_bharose4 days ago
c++ short and crisp
int findPlatform(int arr[], int dep[], int n) { int need=1; int j=0; int max=1; sort(arr,arr+n); sort(dep,dep+n); for(int i=1;i<n;i++){ if(arr[i]>dep[j]){ j++; } else need++; if(need>max) max=need; } return max; }
-1
ashivamsahu144 days ago
CPP Solution
sort(arr,arr+n);
sort(dep,dep+n);
int mx=1;
int platform=1;
int start=1;
int end=0;
while(start<n && end<n){
if(arr[start] > dep[end]){
end++;
platform--;
}
else if(arr[start] <= dep[end]){
platform++;
start++;
}
mx=max(platform,mx);
}
return mx;
0
iamsamrat165 days ago
Simple Implementation of LineSweeping Algorithm:
static int findPlatform(int arr[], int dep[], int n)
{
int lmax = 0,gmax=0;
Arrays.sort(arr);
Arrays.sort(dep);
int i =0,j=0;
while(i<arr.length && j<dep.length) {
if(arr[i]<=dep[j])
{
lmax++;
i++;
}
else{
j++;
lmax--;
}
gmax = Math.max(lmax, gmax);
}
return gmax;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints. | [
{
"code": null,
"e": 805,
"s": 238,
"text": "Given arrival and departure times of all trains that reach a railway station. Find the minimum number of platforms required for the railway station so that no train is kept waiting.\nConsider that all the trains arrive on the same day and leave on the same day. Arrival and departure time can never be the same for a train but we can have arrival time of one train equal to departure time of the other. At any given instance of time, same platform can not be used for both departure of a train and arrival of another train. In such cases, we need different platforms."
},
{
"code": null,
"e": 817,
"s": 805,
"text": "\nExample 1:"
},
{
"code": null,
"e": 1019,
"s": 817,
"text": "Input: n = 6 \narr[] = {0900, 0940, 0950, 1100, 1500, 1800}\ndep[] = {0910, 1200, 1120, 1130, 1900, 2000}\nOutput: 3\nExplanation: \nMinimum 3 platforms are required to \nsafely arrive and depart all trains."
},
{
"code": null,
"e": 1030,
"s": 1019,
"text": "Example 2:"
},
{
"code": null,
"e": 1210,
"s": 1030,
"text": "Input: n = 3\narr[] = {0900, 1100, 1235}\ndep[] = {1000, 1200, 1240}\nOutput: 1\nExplanation: Only 1 platform is required to \nsafely manage the arrival and departure \nof all trains. \n"
},
{
"code": null,
"e": 1562,
"s": 1210,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function findPlatform() which takes the array arr[] (denoting the arrival times), array dep[] (denoting the departure times) and the size of the array as inputs and returns the minimum number of platforms required at the railway station such that no train waits."
},
{
"code": null,
"e": 1749,
"s": 1562,
"text": "Note: Time intervals are in the 24-hour format(HHMM) , where the first two characters represent hour (between 00 to 23 ) and the last two characters represent minutes (this may be > 59)."
},
{
"code": null,
"e": 1816,
"s": 1749,
"text": "\nExpected Time Complexity: O(nLogn)\nExpected Auxiliary Space: O(n)"
},
{
"code": null,
"e": 1870,
"s": 1816,
"text": "\nConstraints:\n1 ≤ n ≤ 50000\n0000 ≤ A[i] ≤ D[i] ≤ 2359"
},
{
"code": null,
"e": 1873,
"s": 1870,
"text": "+3"
},
{
"code": null,
"e": 1897,
"s": 1873,
"text": "abhiraj643110 hours ago"
},
{
"code": null,
"e": 1939,
"s": 1897,
"text": "C++ | priority queue | easy explained || "
},
{
"code": null,
"e": 2069,
"s": 1939,
"text": "Approach : let's think little practically here what we need is priority wise arranging trains, such that we use least platforms."
},
{
"code": null,
"e": 2257,
"s": 2069,
"text": "say we have an intelligent data structure whose size represents the total platforms and maintains a pointer to a train of lowest departure time among present trains on all platforms. "
},
{
"code": null,
"e": 2373,
"s": 2257,
"text": "when new train comes (consider we have only one platform initially with only one train's departure data maintanded)"
},
{
"code": null,
"e": 2415,
"s": 2373,
"text": "based on new train's arrival time we can "
},
{
"code": null,
"e": 2927,
"s": 2415,
"text": "compare the lowest daparture time of existing trains with the arrival time of this new train.if there exists such train on platforms whose departure is less than arrival time of this new train , then we will just add this new train to that platform and now data structure will maintain info of new train''s departure time and will remove the old train's data from that particular platformif arrival time is greater than the existing train's lowest departure time time we will just add new platform for the train"
},
{
"code": null,
"e": 3021,
"s": 2927,
"text": "compare the lowest daparture time of existing trains with the arrival time of this new train."
},
{
"code": null,
"e": 3317,
"s": 3021,
"text": "if there exists such train on platforms whose departure is less than arrival time of this new train , then we will just add this new train to that platform and now data structure will maintain info of new train''s departure time and will remove the old train's data from that particular platform"
},
{
"code": null,
"e": 3441,
"s": 3317,
"text": "if arrival time is greater than the existing train's lowest departure time time we will just add new platform for the train"
},
{
"code": null,
"e": 3574,
"s": 3441,
"text": " ( eventually platforms will dynamically change in the end the the required platforms will be equal to the size of data structure) "
},
{
"code": null,
"e": 3641,
"s": 3576,
"text": "we need priority queue which shows minimum element in the queue."
},
{
"code": null,
"e": 3696,
"s": 3643,
"text": "\tpriority_queue<int, vector<int> , greater<int>> pq;"
},
{
"code": null,
"e": 3707,
"s": 3696,
"text": "Solution :"
},
{
"code": null,
"e": 4084,
"s": 3707,
"text": "store pair of arrival and departure into vector pairsort vector pair as per the arrival time of trainsget min heapif lowest departure time in existing platform queue is less than arrival time of new train then pop that train and add new train's departure timeelse add new trains departure time to queue : assigning new platform to new train.return size of platform queue. "
},
{
"code": null,
"e": 4137,
"s": 4084,
"text": "store pair of arrival and departure into vector pair"
},
{
"code": null,
"e": 4188,
"s": 4137,
"text": "sort vector pair as per the arrival time of trains"
},
{
"code": null,
"e": 4201,
"s": 4188,
"text": "get min heap"
},
{
"code": null,
"e": 4351,
"s": 4201,
"text": "if lowest departure time in existing platform queue is less than arrival time of new train then pop that train and add new train's departure time"
},
{
"code": null,
"e": 4434,
"s": 4351,
"text": "else add new trains departure time to queue : assigning new platform to new train."
},
{
"code": null,
"e": 4466,
"s": 4434,
"text": "return size of platform queue. "
},
{
"code": null,
"e": 5037,
"s": 4466,
"text": "class Solution{\n public:\n //Function to find the minimum number of platforms required at the\n //railway station such that no train waits.\n int findPlatform(int arr[], int dep[], int n)\n {\n \t\n \tvector<pair<int,int>> vp;\n \tfor(int i=0;i<n;i++){\n \t vp.push_back({arr[i],dep[i]});\n \t}\n \t\n \tsort(vp.begin(),vp.end());\n\n \tpriority_queue<int, vector<int> , greater<int>> pq;\n \t\n \t\n \tfor(int i=0;i<n;i++){\n \t pq.push(vp[i].second);\n \t if(pq.top()<vp[i].first) {pq.pop();}\n \t}\n \treturn pq.size();\n \n }\n};"
},
{
"code": null,
"e": 5041,
"s": 5039,
"text": "0"
},
{
"code": null,
"e": 5063,
"s": 5041,
"text": "bibhore0215 hours ago"
},
{
"code": null,
"e": 5095,
"s": 5063,
"text": "using pq...all test case passed"
},
{
"code": null,
"e": 5721,
"s": 5095,
"text": "int findPlatform(int arr[], int dep[], int n) { vector<pair<int,int>> itvls; for(int i=0;i<n;i++) itvls.push_back({arr[i],dep[i]}); sort(itvls.begin(),itvls.end()); priority_queue <int, vector<int>, greater<int> > pq; pq.push(itvls[0].second); for(int i=1;i<n;i++) { if(pq.top()>=itvls[i].first) { pq.push(itvls[i].second); } else { pq.pop(); pq.push(itvls[i].second); } } return pq.size(); }};"
},
{
"code": null,
"e": 5723,
"s": 5721,
"text": "0"
},
{
"code": null,
"e": 5748,
"s": 5723,
"text": "abhinayabhi1412 days ago"
},
{
"code": null,
"e": 6042,
"s": 5748,
"text": " sort(arr,arr+n);\n sort(dep,dep+n);\n int count=1,ans=1;\n int j=0,i=1;\n while(i<n && j<n){\n if(arr[i]<=dep[j]){\n count++;\n i++;\n }\n else{\n count--;\n j++;\n }\n if(count>ans)ans=count;\n }\n return ans;"
},
{
"code": null,
"e": 6044,
"s": 6042,
"text": "0"
},
{
"code": null,
"e": 6069,
"s": 6044,
"text": "yogya25singhal3 days ago"
},
{
"code": null,
"e": 6368,
"s": 6069,
"text": " sort(arr,arr+n);\n sort(dep,dep+n);\n int count=1,ans=1;\n int j=0,i=1;\n while(i<n && j<n){\n if(arr[i]<=dep[j]){\n count++;\n i++;\n }\n else{\n count--;\n j++;\n }\n if(count>ans)ans=count;\n }\n return ans;\n "
},
{
"code": null,
"e": 6371,
"s": 6368,
"text": "+1"
},
{
"code": null,
"e": 6391,
"s": 6371,
"text": "jaydhurat3 days ago"
},
{
"code": null,
"e": 7115,
"s": 6391,
"text": "class Solution\n{\n //Function to find the minimum number of platforms required at the\n //railway station such that no train waits.\n static int findPlatform(int a[], int dep[], int n)\n {\n // add your code here\n Arrays.sort(a);\n Arrays.sort(dep);\n int pf = 1;\n int max =1;\n \n int i = 1;\n int j=0;\n \n while(i<n && j<n)\n {\n if(a[i]<=dep[j])\n {\n pf++;\n \n i++;\n }\n else if( a[i]>dep[j])\n {\n pf--;\n j++;\n \n }\n if(pf>max)\n {\n max=pf;\n }\n }\n return max;\n }\n}"
},
{
"code": null,
"e": 7117,
"s": 7115,
"text": "0"
},
{
"code": null,
"e": 7145,
"s": 7117,
"text": "sanjeevranjan12094 days ago"
},
{
"code": null,
"e": 7725,
"s": 7145,
"text": "Python full solution:\n\nclass Solution: \n #Function to find the minimum number of platforms required at the\n #railway station such that no train waits.\n def minimumPlatform(self,n,arr,dep):\n dep.sort()\n arr.sort()\n i,j=1,0\n result,platform = 1,1\n while (i<n and j<n):\n if arr[i]<=dep[j]:\n i+=1\n platform+=1\n elif arr[i]>dep[j]:\n j+=1\n platform-=1\n if result<platform:\n result = platform\n \n return result"
},
{
"code": null,
"e": 7727,
"s": 7725,
"text": "0"
},
{
"code": null,
"e": 7762,
"s": 7727,
"text": "sanskritisrivastava201914 days ago"
},
{
"code": null,
"e": 7777,
"s": 7762,
"text": "Java Solution:"
},
{
"code": null,
"e": 8462,
"s": 7777,
"text": "static int findPlatform(int arr[], int dep[], int n)\n {\n Arrays.sort(arr);//sorting arrival and departure time\n Arrays.sort(dep);//to know till when platforms will be busy\n int platform_needed=1,res=1;\n int i=1,j=0;\n while(i<n && j<n){\n if(arr[i]<=dep[j]){ //platform is busy w former arrival\n platform_needed++;\n i++;\n }else if(arr[i]>dep[j]){\n platform_needed--; //current platform_needed will reduce\n j++; //checking for next departure\n }\n res = Math.max(platform_needed,res); //max platform needed overall\n }\n return res;\n }"
},
{
"code": null,
"e": 8464,
"s": 8462,
"text": "0"
},
{
"code": null,
"e": 8494,
"s": 8464,
"text": "hum_toh_ram_bharose4 days ago"
},
{
"code": null,
"e": 8514,
"s": 8494,
"text": "c++ short and crisp"
},
{
"code": null,
"e": 8784,
"s": 8514,
"text": " int findPlatform(int arr[], int dep[], int n) { int need=1; int j=0; int max=1; sort(arr,arr+n); sort(dep,dep+n); for(int i=1;i<n;i++){ if(arr[i]>dep[j]){ j++; } else need++; if(need>max) max=need; } return max; }"
},
{
"code": null,
"e": 8787,
"s": 8784,
"text": "-1"
},
{
"code": null,
"e": 8811,
"s": 8787,
"text": "ashivamsahu144 days ago"
},
{
"code": null,
"e": 8825,
"s": 8811,
"text": "CPP Solution "
},
{
"code": null,
"e": 9225,
"s": 8825,
"text": "sort(arr,arr+n);\n \tsort(dep,dep+n);\n \tint mx=1;\n \tint platform=1;\n \tint start=1;\n \tint end=0;\n \twhile(start<n && end<n){\n \t \n \t if(arr[start] > dep[end]){\n \t end++;\n \t platform--;\n \t }\n \t else if(arr[start] <= dep[end]){\n \t platform++;\n \t start++;\n \t }\n \t mx=max(platform,mx);\n \t}\n \t\n \treturn mx;"
},
{
"code": null,
"e": 9227,
"s": 9225,
"text": "0"
},
{
"code": null,
"e": 9249,
"s": 9227,
"text": "iamsamrat165 days ago"
},
{
"code": null,
"e": 9298,
"s": 9249,
"text": "Simple Implementation of LineSweeping Algorithm:"
},
{
"code": null,
"e": 9765,
"s": 9298,
"text": "static int findPlatform(int arr[], int dep[], int n)\n {\n int lmax = 0,gmax=0;\n Arrays.sort(arr);\n Arrays.sort(dep);\n int i =0,j=0;\n while(i<arr.length && j<dep.length) {\n if(arr[i]<=dep[j])\n {\n lmax++;\n i++;\n }\n else{\n j++;\n lmax--;\n }\n gmax = Math.max(lmax, gmax);\n }\n return gmax;\n }"
},
{
"code": null,
"e": 9911,
"s": 9765,
"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": 9947,
"s": 9911,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 9957,
"s": 9947,
"text": "\nProblem\n"
},
{
"code": null,
"e": 9967,
"s": 9957,
"text": "\nContest\n"
},
{
"code": null,
"e": 10030,
"s": 9967,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 10215,
"s": 10030,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 10499,
"s": 10215,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 10645,
"s": 10499,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 10722,
"s": 10645,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 10763,
"s": 10722,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 10791,
"s": 10763,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 10862,
"s": 10791,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 11049,
"s": 10862,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Moment.js moment().diff() Function | 29 Jul, 2020
The moment().diff() function is used to get the difference in milliseconds of given dates which are passed as parameter to this function.
Syntax:
moment().diff(Moment|String|Number|Date|Array, String, Boolean);
Parameters: This function has two parameters, first one is the date of type Moment|String|Number|Date|Array and second parameter is an optional parameter of boolean type which is used to get floating numbers as result instead of integer.
Return Value: This function returns the date in milliseconds.
Installation of moment module:
You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js as shown below.
You can visit the link to Install moment module. You can install this package by using this command.npm install moment
npm install moment
After installing the moment module, you can check your moment version in command prompt using the command.npm version moment
npm version moment
After that, you can just create a folder and add a file for example, index.js as shown below.
Example 1: Filename: index.js
// Requiring the moduleconst moment = require('moment'); var dateOne = moment([2019, 03, 17]);var dateTwo = moment([2001, 10, 28]); // Function callvar result = dateOne.diff(dateTwo, 'days') console.log("No of Days:", result)
Steps to run the program:
The project structure will look like this:Run index.js file using below command:node index.jsOutput:No of Days: 6349
The project structure will look like this:
Run index.js file using below command:node index.jsOutput:No of Days: 6349
node index.js
Output:
No of Days: 6349
Example 2: Filename: index.js
// Requiring the moduleconst moment = require('moment'); function getYearDiff(dateOne, dateTwo) { return dateOne.diff(dateTwo, 'years', true);} // Function callvar result = getYearDiff(moment([2019, 11, 30]), moment([2001, 2, 17])); console.log("No of years difference:", result)
Steps to run the program:
The project structure will look like this:Run index.js file using below command:node index.jsOutput:No of years difference: 18.78611111111111
The project structure will look like this:
Run index.js file using below command:node index.jsOutput:No of years difference: 18.78611111111111
node index.js
Output:
No of years difference: 18.78611111111111
Reference: https://momentjs.com/docs/#/displaying/difference/
Moment.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
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 ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jul, 2020"
},
{
"code": null,
"e": 166,
"s": 28,
"text": "The moment().diff() function is used to get the difference in milliseconds of given dates which are passed as parameter to this function."
},
{
"code": null,
"e": 174,
"s": 166,
"text": "Syntax:"
},
{
"code": null,
"e": 239,
"s": 174,
"text": "moment().diff(Moment|String|Number|Date|Array, String, Boolean);"
},
{
"code": null,
"e": 477,
"s": 239,
"text": "Parameters: This function has two parameters, first one is the date of type Moment|String|Number|Date|Array and second parameter is an optional parameter of boolean type which is used to get floating numbers as result instead of integer."
},
{
"code": null,
"e": 539,
"s": 477,
"text": "Return Value: This function returns the date in milliseconds."
},
{
"code": null,
"e": 570,
"s": 539,
"text": "Installation of moment module:"
},
{
"code": null,
"e": 906,
"s": 570,
"text": "You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js as shown below."
},
{
"code": null,
"e": 1025,
"s": 906,
"text": "You can visit the link to Install moment module. You can install this package by using this command.npm install moment"
},
{
"code": null,
"e": 1044,
"s": 1025,
"text": "npm install moment"
},
{
"code": null,
"e": 1169,
"s": 1044,
"text": "After installing the moment module, you can check your moment version in command prompt using the command.npm version moment"
},
{
"code": null,
"e": 1188,
"s": 1169,
"text": "npm version moment"
},
{
"code": null,
"e": 1282,
"s": 1188,
"text": "After that, you can just create a folder and add a file for example, index.js as shown below."
},
{
"code": null,
"e": 1312,
"s": 1282,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Requiring the moduleconst moment = require('moment'); var dateOne = moment([2019, 03, 17]);var dateTwo = moment([2001, 10, 28]); // Function callvar result = dateOne.diff(dateTwo, 'days') console.log(\"No of Days:\", result)",
"e": 1542,
"s": 1312,
"text": null
},
{
"code": null,
"e": 1568,
"s": 1542,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 1686,
"s": 1568,
"text": "The project structure will look like this:Run index.js file using below command:node index.jsOutput:No of Days: 6349\n"
},
{
"code": null,
"e": 1729,
"s": 1686,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 1805,
"s": 1729,
"text": "Run index.js file using below command:node index.jsOutput:No of Days: 6349\n"
},
{
"code": null,
"e": 1819,
"s": 1805,
"text": "node index.js"
},
{
"code": null,
"e": 1827,
"s": 1819,
"text": "Output:"
},
{
"code": null,
"e": 1845,
"s": 1827,
"text": "No of Days: 6349\n"
},
{
"code": null,
"e": 1875,
"s": 1845,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Requiring the moduleconst moment = require('moment'); function getYearDiff(dateOne, dateTwo) { return dateOne.diff(dateTwo, 'years', true);} // Function callvar result = getYearDiff(moment([2019, 11, 30]), moment([2001, 2, 17])); console.log(\"No of years difference:\", result)",
"e": 2166,
"s": 1875,
"text": null
},
{
"code": null,
"e": 2192,
"s": 2166,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 2335,
"s": 2192,
"text": "The project structure will look like this:Run index.js file using below command:node index.jsOutput:No of years difference: 18.78611111111111\n"
},
{
"code": null,
"e": 2378,
"s": 2335,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 2479,
"s": 2378,
"text": "Run index.js file using below command:node index.jsOutput:No of years difference: 18.78611111111111\n"
},
{
"code": null,
"e": 2493,
"s": 2479,
"text": "node index.js"
},
{
"code": null,
"e": 2501,
"s": 2493,
"text": "Output:"
},
{
"code": null,
"e": 2544,
"s": 2501,
"text": "No of years difference: 18.78611111111111\n"
},
{
"code": null,
"e": 2606,
"s": 2544,
"text": "Reference: https://momentjs.com/docs/#/displaying/difference/"
},
{
"code": null,
"e": 2616,
"s": 2606,
"text": "Moment.js"
},
{
"code": null,
"e": 2624,
"s": 2616,
"text": "Node.js"
},
{
"code": null,
"e": 2641,
"s": 2624,
"text": "Web Technologies"
},
{
"code": null,
"e": 2739,
"s": 2641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2769,
"s": 2739,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 2826,
"s": 2769,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 2880,
"s": 2826,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 2920,
"s": 2880,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 2955,
"s": 2920,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 3017,
"s": 2955,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3078,
"s": 3017,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3128,
"s": 3078,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3171,
"s": 3128,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python | Split a list having single integer | 28 Feb, 2019
Given a list containing single integer, the task is to split each value in the list.
Examples:
Input: Input = [23]
Output: Output = [2, 3]
Input: Input = [15478]
Output: Output = [1, 5, 4, 7, 8]
Method #1 : Using Map
# Python code to split list containing single integer # List initializationinput = [200] # Using mapoutput = list(map(int, str(input[0]))) # Printing outputprint(output)
[2, 0, 0]
Method #2 : Using list comprehension
# Python code to split list containing single integer # List initializationinput = [231] # Using list comprehensionoutput = [int(x) if x.isdigit() else x for z in input for x in str(z)] # Printing outputprint(output)
[2, 3, 1]
Method #3 : Using Loops
# Python code to split list containing single integer # List initializationinput = [987] # Converting to intinput = int(input[0]) # Output list initializationoutput = [] while input>0: rem = input % 10 input = int(input / 10) output.append(rem) # Printing outputprint(output)
[7, 8, 9]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Feb, 2019"
},
{
"code": null,
"e": 113,
"s": 28,
"text": "Given a list containing single integer, the task is to split each value in the list."
},
{
"code": null,
"e": 123,
"s": 113,
"text": "Examples:"
},
{
"code": null,
"e": 227,
"s": 123,
"text": "Input: Input = [23]\nOutput: Output = [2, 3]\n\nInput: Input = [15478]\nOutput: Output = [1, 5, 4, 7, 8]\n"
},
{
"code": null,
"e": 249,
"s": 227,
"text": "Method #1 : Using Map"
},
{
"code": "# Python code to split list containing single integer # List initializationinput = [200] # Using mapoutput = list(map(int, str(input[0]))) # Printing outputprint(output)",
"e": 422,
"s": 249,
"text": null
},
{
"code": null,
"e": 433,
"s": 422,
"text": "[2, 0, 0]\n"
},
{
"code": null,
"e": 472,
"s": 435,
"text": "Method #2 : Using list comprehension"
},
{
"code": "# Python code to split list containing single integer # List initializationinput = [231] # Using list comprehensionoutput = [int(x) if x.isdigit() else x for z in input for x in str(z)] # Printing outputprint(output)",
"e": 702,
"s": 472,
"text": null
},
{
"code": null,
"e": 713,
"s": 702,
"text": "[2, 3, 1]\n"
},
{
"code": null,
"e": 738,
"s": 713,
"text": " Method #3 : Using Loops"
},
{
"code": "# Python code to split list containing single integer # List initializationinput = [987] # Converting to intinput = int(input[0]) # Output list initializationoutput = [] while input>0: rem = input % 10 input = int(input / 10) output.append(rem) # Printing outputprint(output)",
"e": 1028,
"s": 738,
"text": null
},
{
"code": null,
"e": 1039,
"s": 1028,
"text": "[7, 8, 9]\n"
},
{
"code": null,
"e": 1060,
"s": 1039,
"text": "Python list-programs"
},
{
"code": null,
"e": 1067,
"s": 1060,
"text": "Python"
},
{
"code": null,
"e": 1083,
"s": 1067,
"text": "Python Programs"
},
{
"code": null,
"e": 1181,
"s": 1083,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1199,
"s": 1181,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1241,
"s": 1199,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1263,
"s": 1241,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1298,
"s": 1263,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1330,
"s": 1298,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1373,
"s": 1330,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1395,
"s": 1373,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1434,
"s": 1395,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1472,
"s": 1434,
"text": "Python | Convert a list to dictionary"
}
] |
Virtual Functions in Derived Classes in C++ | 16 May, 2022
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class’s version of the function.
In C++, once a member function is declared as a virtual function in a base class, it becomes virtual in every class derived from that base class. In other words, it is not necessary to use the keyword virtual in the derived class while declaring redefined versions of the virtual base class function.
For example, the following program prints “C::fun() called“ as “B::fun()“ becomes virtual automatically.
CPP
// C++ Program to demonstrate Virtual// functions in derived classes#include <iostream>using namespace std; class A {public: virtual void fun() { cout << "\n A::fun() called "; }}; class B : public A {public: void fun() { cout << "\n B::fun() called "; }}; class C : public B {public: void fun() { cout << "\n C::fun() called "; }}; int main(){ // An object of class C C c; // A pointer of class B pointing // to memory location of c B* b = &c; // this line prints "C::fun() called" b->fun(); getchar(); // to get the next character return 0;}
C::fun() called
Note: Never call a virtual function from a CONSTRUCTOR or DESTRUCTOR
anshikajain26
harsh_shokeen
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
unordered_map in C++ STL
vector erase() and clear() in C++
Substring in C++
C++ Classes and Objects
Object Oriented Programming in C++
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
2D Vector In C++ With User Defined Size
C++ Data Types | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 May, 2022"
},
{
"code": null,
"e": 348,
"s": 52,
"text": "A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class’s version of the function."
},
{
"code": null,
"e": 649,
"s": 348,
"text": "In C++, once a member function is declared as a virtual function in a base class, it becomes virtual in every class derived from that base class. In other words, it is not necessary to use the keyword virtual in the derived class while declaring redefined versions of the virtual base class function."
},
{
"code": null,
"e": 754,
"s": 649,
"text": "For example, the following program prints “C::fun() called“ as “B::fun()“ becomes virtual automatically."
},
{
"code": null,
"e": 758,
"s": 754,
"text": "CPP"
},
{
"code": "// C++ Program to demonstrate Virtual// functions in derived classes#include <iostream>using namespace std; class A {public: virtual void fun() { cout << \"\\n A::fun() called \"; }}; class B : public A {public: void fun() { cout << \"\\n B::fun() called \"; }}; class C : public B {public: void fun() { cout << \"\\n C::fun() called \"; }}; int main(){ // An object of class C C c; // A pointer of class B pointing // to memory location of c B* b = &c; // this line prints \"C::fun() called\" b->fun(); getchar(); // to get the next character return 0;}",
"e": 1347,
"s": 758,
"text": null
},
{
"code": null,
"e": 1365,
"s": 1347,
"text": " C::fun() called "
},
{
"code": null,
"e": 1434,
"s": 1365,
"text": "Note: Never call a virtual function from a CONSTRUCTOR or DESTRUCTOR"
},
{
"code": null,
"e": 1448,
"s": 1434,
"text": "anshikajain26"
},
{
"code": null,
"e": 1462,
"s": 1448,
"text": "harsh_shokeen"
},
{
"code": null,
"e": 1466,
"s": 1462,
"text": "C++"
},
{
"code": null,
"e": 1470,
"s": 1466,
"text": "CPP"
},
{
"code": null,
"e": 1568,
"s": 1470,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1611,
"s": 1568,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1636,
"s": 1611,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 1670,
"s": 1636,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 1687,
"s": 1670,
"text": "Substring in C++"
},
{
"code": null,
"e": 1711,
"s": 1687,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 1746,
"s": 1711,
"text": "Object Oriented Programming in C++"
},
{
"code": null,
"e": 1800,
"s": 1746,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1824,
"s": 1800,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1864,
"s": 1824,
"text": "2D Vector In C++ With User Defined Size"
}
] |
Program to implement t-test | 03 May, 2021
The t test (also called Student’s T Test) compares two averages (means) and tells if they are different from each other. The t-test also tells how significant the differences are. In other words it lets you know if those differences could have happened by chance. t-test can be calculated by using formula :
where, x̄1 is the mean of first data set x̄2 is the mean of second data set S12 is the standard deviation of first data set S22 is the standard deviation of second data set N1 is the number of elements in the first data set N2 is the number of elements in the second data set
Examples :
Input : arr1[] = {10, 20, 30, 40, 50}
arr2[] = {1, 29, 46, 78, 99}
Output : -1.09789
Input : arr1[] = {5, 20, 40, 80, 100, 120}
arr2[] = {1, 29, 46, 78, 99}
Output : 0.399518
Explanation : In example 1, x̄1 = 30, x̄2 = 50.6, S12 = 15.8114, S12 = 38.8626 using the formula, t-test = -1.09789
Below is the implementation of t-test.
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to implement t-test.#include <bits/stdc++.h>using namespace std; // Function to find mean.float Mean(float arr[], int n){ float sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n;} // Function to find standard// deviation of given array.float standardDeviation(float arr[], int n){ float sum = 0; for (int i = 0; i < n; i++) sum = sum + (arr[i] - Mean(arr, n)) * (arr[i] - Mean(arr, n)); return sqrt(sum / (n - 1));} // Function to find t-test of// two set of statistical data.float tTest(float arr1[], int n, float arr2[], int m){ float mean1 = Mean(arr1, n); float mean2 = Mean(arr2, m); float sd1 = standardDeviation(arr1, n); float sd2 = standardDeviation(arr2, m); // Formula to find t-test // of two set of data. float t_test = (mean1 - mean2) / sqrt((sd1 * sd1) / n + (sd2 * sd2) / m); return t_test;} // Driver function.int main(){ float arr1[] = { 10, 20, 30, 40, 50 }; // Calculate size of first array. int n = sizeof(arr1) / sizeof(arr1[0]); float arr2[] = { 1, 29, 46, 78, 99 }; // Calculate size of second array. int m = sizeof(arr2) / sizeof(arr2[0]); // Function call. cout << tTest(arr1, n, arr2, m); return 0;}
// Java Program to implement t-test.import java.util.*;import java.io.*; class GFG{ // Function to find mean. static float Mean(float arr[], int n) { float sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n; } // Function to find standard // deviation of given array. static float standardDeviation(float arr[], int n) { float sum = 0; for (int i = 0; i < n; i++) sum = sum + (arr[i] - Mean(arr, n)) * (arr[i] - Mean(arr, n)); return (float)Math.sqrt(sum / (n - 1)); } // Function to find t-test of // two set of statistical data. static float tTest(float arr1[], int n, float arr2[], int m) { float mean1 = Mean(arr1, n); float mean2 = Mean(arr2, m); float sd1 = standardDeviation(arr1, n); float sd2 = standardDeviation(arr2, m); // Formula to find t-test // of two set of data. float t_test = (mean1 - mean2) / (float)Math.sqrt((sd1 * sd1) / n + (sd2 * sd2) / m); return t_test; } // Driver code public static void main(String args[]) { float arr1[] = { 10, 20, 30, 40, 50 }; // Calculate size of first array. int n = arr1.length; float arr2[] = { 1, 29, 46, 78, 99 }; // Calculate size of second array. int m = arr2.length; // Function call. System.out.print(tTest(arr1, n, arr2, m)); }} // This code is contributed by Sahil_Bansall
# Python 3 Program to implement t-test.from math import sqrt # Function to find mean.def Mean(arr, n): sum = 0 for i in range(0, n, 1): sum = sum + arr[i] return sum / n # Function to find standard# deviation of given array.def standardDeviation(arr, n): sum = 0 for i in range(0, n, 1): sum = (sum + (arr[i] - Mean(arr, n)) * (arr[i] - Mean(arr, n))) return sqrt(sum / (n - 1)) # Function to find t-test of# two set of statistical data.def tTest(arr1, n, arr2, m): mean1 = Mean(arr1, n) mean2 = Mean(arr2, m) sd1 = standardDeviation(arr1, n) sd2 = standardDeviation(arr2, m) # Formula to find t-test # of two set of data. t_test = (mean1 - mean2) / sqrt((sd1 * sd1) / n + (sd2 * sd2) / m) return t_test # Driver Codeif __name__ == '__main__': arr1 = [10, 20, 30, 40, 50] # Calculate size of first array. n = len(arr1) arr2 = [1, 29, 46, 78, 99] # Calculate size of second array. m = len(arr2) # Function call. print('{0:.6}'.format(tTest(arr1, n, arr2, m))) # This code is contributed by# Surendra_Gangwar
// C# Program to implement t-test.using System; class GFG { // Function to find mean. static float Mean(float[] arr, int n) { float sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n; } // Function to find standard // deviation of given array. static float standardDeviation(float[] arr, int n) { float sum = 0; for (int i = 0; i < n; i++) sum = sum + (arr[i] - Mean(arr, n)) * (arr[i] - Mean(arr, n)); return (float)Math.Sqrt(sum / (n - 1)); } // Function to find t-test of // two set of statistical data. static float tTest(float[] arr1, int n, float[] arr2, int m) { float mean1 = Mean(arr1, n); float mean2 = Mean(arr2, m); float sd1 = standardDeviation(arr1, n); float sd2 = standardDeviation(arr2, m); // Formula to find t-test // of two set of data. float t_test = (mean1 - mean2) / (float)Math.Sqrt((sd1 * sd1) / n + (sd2 * sd2) / m); return t_test; } // Driver code static public void Main () { float[] arr1 = {10, 20, 30, 40, 50}; // Calculate size of first array int n = arr1.Length; float[] arr2 = { 1, 29, 46, 78, 99 }; // Calculate size of second array int m = arr2.Length; // Function calling Console.Write(tTest(arr1, n, arr2, m)); }} // This code is contributed by Ajit.
<?php// PHP Program to implement t-test. // Function to find mean.function Mean($arr, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum = $sum + $arr[$i]; return $sum / $n;} // Function to find standard// deviation of given array.function standardDeviation($arr,$n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum = $sum + ($arr[$i] - Mean($arr, $n)) * ($arr[$i] - Mean($arr, $n)); return sqrt($sum / ($n - 1));} // Function to find t-test of// two set of statistical data.function tTest($arr1, $n, $arr2, $m){ $mean1 = Mean($arr1, $n); $mean2 = Mean($arr2, $m); $sd1 = standardDeviation($arr1, $n); $sd2 = standardDeviation($arr2, $m); // Formula to find t-test // of two set of data. $t_test = ($mean1 - $mean2) / sqrt(($sd1 * $sd1) / $n + ($sd2 * $sd2) / $m); return $t_test;} // Driver Code{ $arr1 = array(10, 20, 30, 40, 50); // Calculate size of first array. $n = sizeof($arr1) / sizeof($arr1[0]); $arr2 = array( 1, 29, 46, 78, 99 ); // Calculate size of second array. $m = sizeof($arr2) / sizeof($arr2[0]); // Function call. echo tTest($arr1, $n, $arr2, $m); return 0;} // This code is contributed by nitin mittal.?>
<script> // Javascript program to implement t-test. // Function to find mean.function Mean(arr, n){ let sum = 0; for(let i = 0; i < n; i++) sum = sum + arr[i]; return sum / n;} // Function to find standard// deviation of given array.function standardDeviation(arr, n){ let sum = 0; for(let i = 0; i < n; i++) sum = sum + (arr[i] - Mean(arr, n)) * (arr[i] - Mean(arr, n)); return Math.sqrt(sum / (n - 1));} // Function to find t-test of// two set of statistical data.function tTest(arr1, n, arr2, m){ let mean1 = Mean(arr1, n); let mean2 = Mean(arr2, m); let sd1 = standardDeviation(arr1, n); let sd2 = standardDeviation(arr2, m); // Formula to find t-test // of two set of data. let t_test = (mean1 - mean2) / Math.sqrt((sd1 * sd1) / n + (sd2 * sd2) / m); return t_test.toFixed(5);} // Driver codelet arr1 = [ 10, 20, 30, 40, 50 ]; // Calculate size of first arraylet n = arr1.length;let arr2 = [ 1, 29, 46, 78, 99 ]; // Calculate size of second arraylet m = arr2.length; // Function callingdocument.write(tTest(arr1, n, arr2, m)); // This code is contributed by decode2207 </script>
Output:
-1.09789
jit_t
nitin mittal
SURENDRA_GANGWAR
decode2207
statistical-algorithms
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Introduction to Arrays
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Introduction to Data Structures | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 May, 2021"
},
{
"code": null,
"e": 363,
"s": 54,
"text": "The t test (also called Student’s T Test) compares two averages (means) and tells if they are different from each other. The t-test also tells how significant the differences are. In other words it lets you know if those differences could have happened by chance. t-test can be calculated by using formula : "
},
{
"code": null,
"e": 639,
"s": 363,
"text": "where, x̄1 is the mean of first data set x̄2 is the mean of second data set S12 is the standard deviation of first data set S22 is the standard deviation of second data set N1 is the number of elements in the first data set N2 is the number of elements in the second data set"
},
{
"code": null,
"e": 652,
"s": 639,
"text": "Examples : "
},
{
"code": null,
"e": 844,
"s": 652,
"text": "Input : arr1[] = {10, 20, 30, 40, 50}\n arr2[] = {1, 29, 46, 78, 99}\nOutput : -1.09789\n\nInput : arr1[] = {5, 20, 40, 80, 100, 120}\n arr2[] = {1, 29, 46, 78, 99}\nOutput : 0.399518"
},
{
"code": null,
"e": 960,
"s": 844,
"text": "Explanation : In example 1, x̄1 = 30, x̄2 = 50.6, S12 = 15.8114, S12 = 38.8626 using the formula, t-test = -1.09789"
},
{
"code": null,
"e": 1000,
"s": 960,
"text": "Below is the implementation of t-test. "
},
{
"code": null,
"e": 1004,
"s": 1000,
"text": "C++"
},
{
"code": null,
"e": 1009,
"s": 1004,
"text": "Java"
},
{
"code": null,
"e": 1017,
"s": 1009,
"text": "Python3"
},
{
"code": null,
"e": 1020,
"s": 1017,
"text": "C#"
},
{
"code": null,
"e": 1024,
"s": 1020,
"text": "PHP"
},
{
"code": null,
"e": 1035,
"s": 1024,
"text": "Javascript"
},
{
"code": "// CPP Program to implement t-test.#include <bits/stdc++.h>using namespace std; // Function to find mean.float Mean(float arr[], int n){ float sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n;} // Function to find standard// deviation of given array.float standardDeviation(float arr[], int n){ float sum = 0; for (int i = 0; i < n; i++) sum = sum + (arr[i] - Mean(arr, n)) * (arr[i] - Mean(arr, n)); return sqrt(sum / (n - 1));} // Function to find t-test of// two set of statistical data.float tTest(float arr1[], int n, float arr2[], int m){ float mean1 = Mean(arr1, n); float mean2 = Mean(arr2, m); float sd1 = standardDeviation(arr1, n); float sd2 = standardDeviation(arr2, m); // Formula to find t-test // of two set of data. float t_test = (mean1 - mean2) / sqrt((sd1 * sd1) / n + (sd2 * sd2) / m); return t_test;} // Driver function.int main(){ float arr1[] = { 10, 20, 30, 40, 50 }; // Calculate size of first array. int n = sizeof(arr1) / sizeof(arr1[0]); float arr2[] = { 1, 29, 46, 78, 99 }; // Calculate size of second array. int m = sizeof(arr2) / sizeof(arr2[0]); // Function call. cout << tTest(arr1, n, arr2, m); return 0;}",
"e": 2347,
"s": 1035,
"text": null
},
{
"code": "// Java Program to implement t-test.import java.util.*;import java.io.*; class GFG{ // Function to find mean. static float Mean(float arr[], int n) { float sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n; } // Function to find standard // deviation of given array. static float standardDeviation(float arr[], int n) { float sum = 0; for (int i = 0; i < n; i++) sum = sum + (arr[i] - Mean(arr, n)) * (arr[i] - Mean(arr, n)); return (float)Math.sqrt(sum / (n - 1)); } // Function to find t-test of // two set of statistical data. static float tTest(float arr1[], int n, float arr2[], int m) { float mean1 = Mean(arr1, n); float mean2 = Mean(arr2, m); float sd1 = standardDeviation(arr1, n); float sd2 = standardDeviation(arr2, m); // Formula to find t-test // of two set of data. float t_test = (mean1 - mean2) / (float)Math.sqrt((sd1 * sd1) / n + (sd2 * sd2) / m); return t_test; } // Driver code public static void main(String args[]) { float arr1[] = { 10, 20, 30, 40, 50 }; // Calculate size of first array. int n = arr1.length; float arr2[] = { 1, 29, 46, 78, 99 }; // Calculate size of second array. int m = arr2.length; // Function call. System.out.print(tTest(arr1, n, arr2, m)); }} // This code is contributed by Sahil_Bansall",
"e": 3928,
"s": 2347,
"text": null
},
{
"code": "# Python 3 Program to implement t-test.from math import sqrt # Function to find mean.def Mean(arr, n): sum = 0 for i in range(0, n, 1): sum = sum + arr[i] return sum / n # Function to find standard# deviation of given array.def standardDeviation(arr, n): sum = 0 for i in range(0, n, 1): sum = (sum + (arr[i] - Mean(arr, n)) * (arr[i] - Mean(arr, n))) return sqrt(sum / (n - 1)) # Function to find t-test of# two set of statistical data.def tTest(arr1, n, arr2, m): mean1 = Mean(arr1, n) mean2 = Mean(arr2, m) sd1 = standardDeviation(arr1, n) sd2 = standardDeviation(arr2, m) # Formula to find t-test # of two set of data. t_test = (mean1 - mean2) / sqrt((sd1 * sd1) / n + (sd2 * sd2) / m) return t_test # Driver Codeif __name__ == '__main__': arr1 = [10, 20, 30, 40, 50] # Calculate size of first array. n = len(arr1) arr2 = [1, 29, 46, 78, 99] # Calculate size of second array. m = len(arr2) # Function call. print('{0:.6}'.format(tTest(arr1, n, arr2, m))) # This code is contributed by# Surendra_Gangwar",
"e": 5075,
"s": 3928,
"text": null
},
{
"code": "// C# Program to implement t-test.using System; class GFG { // Function to find mean. static float Mean(float[] arr, int n) { float sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n; } // Function to find standard // deviation of given array. static float standardDeviation(float[] arr, int n) { float sum = 0; for (int i = 0; i < n; i++) sum = sum + (arr[i] - Mean(arr, n)) * (arr[i] - Mean(arr, n)); return (float)Math.Sqrt(sum / (n - 1)); } // Function to find t-test of // two set of statistical data. static float tTest(float[] arr1, int n, float[] arr2, int m) { float mean1 = Mean(arr1, n); float mean2 = Mean(arr2, m); float sd1 = standardDeviation(arr1, n); float sd2 = standardDeviation(arr2, m); // Formula to find t-test // of two set of data. float t_test = (mean1 - mean2) / (float)Math.Sqrt((sd1 * sd1) / n + (sd2 * sd2) / m); return t_test; } // Driver code static public void Main () { float[] arr1 = {10, 20, 30, 40, 50}; // Calculate size of first array int n = arr1.Length; float[] arr2 = { 1, 29, 46, 78, 99 }; // Calculate size of second array int m = arr2.Length; // Function calling Console.Write(tTest(arr1, n, arr2, m)); }} // This code is contributed by Ajit.",
"e": 6620,
"s": 5075,
"text": null
},
{
"code": "<?php// PHP Program to implement t-test. // Function to find mean.function Mean($arr, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum = $sum + $arr[$i]; return $sum / $n;} // Function to find standard// deviation of given array.function standardDeviation($arr,$n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum = $sum + ($arr[$i] - Mean($arr, $n)) * ($arr[$i] - Mean($arr, $n)); return sqrt($sum / ($n - 1));} // Function to find t-test of// two set of statistical data.function tTest($arr1, $n, $arr2, $m){ $mean1 = Mean($arr1, $n); $mean2 = Mean($arr2, $m); $sd1 = standardDeviation($arr1, $n); $sd2 = standardDeviation($arr2, $m); // Formula to find t-test // of two set of data. $t_test = ($mean1 - $mean2) / sqrt(($sd1 * $sd1) / $n + ($sd2 * $sd2) / $m); return $t_test;} // Driver Code{ $arr1 = array(10, 20, 30, 40, 50); // Calculate size of first array. $n = sizeof($arr1) / sizeof($arr1[0]); $arr2 = array( 1, 29, 46, 78, 99 ); // Calculate size of second array. $m = sizeof($arr2) / sizeof($arr2[0]); // Function call. echo tTest($arr1, $n, $arr2, $m); return 0;} // This code is contributed by nitin mittal.?>",
"e": 7895,
"s": 6620,
"text": null
},
{
"code": "<script> // Javascript program to implement t-test. // Function to find mean.function Mean(arr, n){ let sum = 0; for(let i = 0; i < n; i++) sum = sum + arr[i]; return sum / n;} // Function to find standard// deviation of given array.function standardDeviation(arr, n){ let sum = 0; for(let i = 0; i < n; i++) sum = sum + (arr[i] - Mean(arr, n)) * (arr[i] - Mean(arr, n)); return Math.sqrt(sum / (n - 1));} // Function to find t-test of// two set of statistical data.function tTest(arr1, n, arr2, m){ let mean1 = Mean(arr1, n); let mean2 = Mean(arr2, m); let sd1 = standardDeviation(arr1, n); let sd2 = standardDeviation(arr2, m); // Formula to find t-test // of two set of data. let t_test = (mean1 - mean2) / Math.sqrt((sd1 * sd1) / n + (sd2 * sd2) / m); return t_test.toFixed(5);} // Driver codelet arr1 = [ 10, 20, 30, 40, 50 ]; // Calculate size of first arraylet n = arr1.length;let arr2 = [ 1, 29, 46, 78, 99 ]; // Calculate size of second arraylet m = arr2.length; // Function callingdocument.write(tTest(arr1, n, arr2, m)); // This code is contributed by decode2207 </script>",
"e": 9087,
"s": 7895,
"text": null
},
{
"code": null,
"e": 9096,
"s": 9087,
"text": "Output: "
},
{
"code": null,
"e": 9105,
"s": 9096,
"text": "-1.09789"
},
{
"code": null,
"e": 9113,
"s": 9107,
"text": "jit_t"
},
{
"code": null,
"e": 9126,
"s": 9113,
"text": "nitin mittal"
},
{
"code": null,
"e": 9143,
"s": 9126,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 9154,
"s": 9143,
"text": "decode2207"
},
{
"code": null,
"e": 9177,
"s": 9154,
"text": "statistical-algorithms"
},
{
"code": null,
"e": 9184,
"s": 9177,
"text": "Arrays"
},
{
"code": null,
"e": 9191,
"s": 9184,
"text": "Arrays"
},
{
"code": null,
"e": 9289,
"s": 9191,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9357,
"s": 9289,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 9401,
"s": 9357,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 9433,
"s": 9401,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 9481,
"s": 9433,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 9495,
"s": 9481,
"text": "Linear Search"
},
{
"code": null,
"e": 9518,
"s": 9495,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 9603,
"s": 9518,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 9659,
"s": 9603,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 9686,
"s": 9659,
"text": "Subset Sum Problem | DP-25"
}
] |
Pytest - Run Tests in Parallel | By default, pytest runs tests in sequential order. In a real scenario, a test suite will have a number of test files and each file will have a bunch of tests. This will lead to a large execution time. To overcome this, pytest provides us with an option to run tests in parallel.
For this, we need to first install the pytest-xdist plugin.
Install pytest-xdist by running the following command −
pip install pytest-xdist
Now, we can run tests by using the syntax pytest -n <num>
pytest -n 3
-n <num> runs the tests by using multiple workers, here it is 3.
We will not be having much time difference when there is only a few tests to run. However,
it matters when the test suite is large. | [
{
"code": null,
"e": 2455,
"s": 2176,
"text": "By default, pytest runs tests in sequential order. In a real scenario, a test suite will have a number of test files and each file will have a bunch of tests. This will lead to a large execution time. To overcome this, pytest provides us with an option to run tests in parallel."
},
{
"code": null,
"e": 2515,
"s": 2455,
"text": "For this, we need to first install the pytest-xdist plugin."
},
{
"code": null,
"e": 2571,
"s": 2515,
"text": "Install pytest-xdist by running the following command −"
},
{
"code": null,
"e": 2597,
"s": 2571,
"text": "pip install pytest-xdist\n"
},
{
"code": null,
"e": 2655,
"s": 2597,
"text": "Now, we can run tests by using the syntax pytest -n <num>"
},
{
"code": null,
"e": 2668,
"s": 2655,
"text": "pytest -n 3\n"
},
{
"code": null,
"e": 2733,
"s": 2668,
"text": "-n <num> runs the tests by using multiple workers, here it is 3."
}
] |
Kali Linux – Command Line Essentials | 26 May, 2022
Command-line plays a vital role while working with Kali Linux as most of its tools don’t have a Graphical User Interface and if you are performing ethical hacking or penetration testing then most of the time you will have to work with command Line Interface itself. While executing a command in Kali Linux we enter a command on the terminal emulator and it gives us the appropriate output after the execution of the command.
There are some commands in Kali Linux which we use too frequently. So we should be aware of those commands as it could increase our productivity.
1. To display present working directory
pwd
This command will display the current directory you are in.
2. To list the directories and files in the current directory.
ls
This command will display the list of files and directories in the current directory.
3. To change the current working directory
cd
This command will change the directory you are currently working on.
4. To find a word in a file.
grep keyword filename
This command will list all the lines containing the keyword in them.
5. To create a new directory
mkdir directory_name
This command will create a new directory in the current folder with the name directory_name.
6. To remove a directory
rmdir directory_name
This command will remove the directory with the name directory_name from the current directory.
7. To move a file
mv source destination
This command is used to move a file from one location to another.
8. To copy a file
cp source destination
This command will copy the file from the source to the destination.
9. To create a new file
touch filename
This command will create a new file with the name “filename”
10. To display manual of a command
man ls
This command will display a manual or a user guide for the command.
11. To check the internet connection or to check whether the host is active or not.
ping google.com
This command will send some packets to the mentioned host and will give us output about the details of what is the status of the packet. This command could be used to check the internet connection.
12. To display network interface details.
ifconfig
This command is used to display the details of the network interfaces connected to the system.
13. To download a file
wget link_to_file
This command will download the file from the link entered in the command.
14. To install a package
sudo apt install package_name
This command is used to install the mentioned package in the system.
15. To remove a package
sudo apt remove package_namme
This command will remove the mentioned package from the system.
16. To upgrade packages in the system
sudo apt upgrade
This command will upgrade all the packages in the system.
17. To fetch the packages updates
sudo apt update
This command will check for updates of all the packages and will add the updates in the list to upgrade.
18. To get the current username
whoami
This command is used to print the username of the current user.
19. To change the current user to superuser or root
sudo su
This command will ask for a password and will change the current user to root.
20. To print in terminal
echo " To print something on terminal"
The command will print the mentioned text on the terminal.
surindertarika1234
shivanshsinghx365
Kali-Linux
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
'crontab' in Linux with Examples
TCP Server-Client implementation in C
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2022"
},
{
"code": null,
"e": 454,
"s": 28,
"text": "Command-line plays a vital role while working with Kali Linux as most of its tools don’t have a Graphical User Interface and if you are performing ethical hacking or penetration testing then most of the time you will have to work with command Line Interface itself. While executing a command in Kali Linux we enter a command on the terminal emulator and it gives us the appropriate output after the execution of the command. "
},
{
"code": null,
"e": 601,
"s": 454,
"text": "There are some commands in Kali Linux which we use too frequently. So we should be aware of those commands as it could increase our productivity. "
},
{
"code": null,
"e": 642,
"s": 601,
"text": "1. To display present working directory "
},
{
"code": null,
"e": 646,
"s": 642,
"text": "pwd"
},
{
"code": null,
"e": 707,
"s": 646,
"text": "This command will display the current directory you are in. "
},
{
"code": null,
"e": 772,
"s": 707,
"text": "2. To list the directories and files in the current directory. "
},
{
"code": null,
"e": 775,
"s": 772,
"text": "ls"
},
{
"code": null,
"e": 862,
"s": 775,
"text": "This command will display the list of files and directories in the current directory. "
},
{
"code": null,
"e": 907,
"s": 862,
"text": "3. To change the current working directory "
},
{
"code": null,
"e": 910,
"s": 907,
"text": "cd"
},
{
"code": null,
"e": 980,
"s": 910,
"text": "This command will change the directory you are currently working on. "
},
{
"code": null,
"e": 1011,
"s": 980,
"text": "4. To find a word in a file. "
},
{
"code": null,
"e": 1033,
"s": 1011,
"text": "grep keyword filename"
},
{
"code": null,
"e": 1103,
"s": 1033,
"text": "This command will list all the lines containing the keyword in them. "
},
{
"code": null,
"e": 1134,
"s": 1103,
"text": "5. To create a new directory "
},
{
"code": null,
"e": 1155,
"s": 1134,
"text": "mkdir directory_name"
},
{
"code": null,
"e": 1249,
"s": 1155,
"text": "This command will create a new directory in the current folder with the name directory_name. "
},
{
"code": null,
"e": 1276,
"s": 1249,
"text": "6. To remove a directory "
},
{
"code": null,
"e": 1297,
"s": 1276,
"text": "rmdir directory_name"
},
{
"code": null,
"e": 1394,
"s": 1297,
"text": "This command will remove the directory with the name directory_name from the current directory. "
},
{
"code": null,
"e": 1414,
"s": 1394,
"text": "7. To move a file "
},
{
"code": null,
"e": 1436,
"s": 1414,
"text": "mv source destination"
},
{
"code": null,
"e": 1503,
"s": 1436,
"text": "This command is used to move a file from one location to another. "
},
{
"code": null,
"e": 1523,
"s": 1503,
"text": "8. To copy a file "
},
{
"code": null,
"e": 1545,
"s": 1523,
"text": "cp source destination"
},
{
"code": null,
"e": 1614,
"s": 1545,
"text": "This command will copy the file from the source to the destination. "
},
{
"code": null,
"e": 1640,
"s": 1614,
"text": "9. To create a new file "
},
{
"code": null,
"e": 1656,
"s": 1640,
"text": "touch filename "
},
{
"code": null,
"e": 1718,
"s": 1656,
"text": "This command will create a new file with the name “filename” "
},
{
"code": null,
"e": 1755,
"s": 1718,
"text": "10. To display manual of a command "
},
{
"code": null,
"e": 1762,
"s": 1755,
"text": "man ls"
},
{
"code": null,
"e": 1831,
"s": 1762,
"text": "This command will display a manual or a user guide for the command. "
},
{
"code": null,
"e": 1917,
"s": 1831,
"text": "11. To check the internet connection or to check whether the host is active or not. "
},
{
"code": null,
"e": 1933,
"s": 1917,
"text": "ping google.com"
},
{
"code": null,
"e": 2132,
"s": 1933,
"text": "This command will send some packets to the mentioned host and will give us output about the details of what is the status of the packet. This command could be used to check the internet connection. "
},
{
"code": null,
"e": 2176,
"s": 2132,
"text": "12. To display network interface details. "
},
{
"code": null,
"e": 2186,
"s": 2176,
"text": "ifconfig "
},
{
"code": null,
"e": 2282,
"s": 2186,
"text": "This command is used to display the details of the network interfaces connected to the system. "
},
{
"code": null,
"e": 2307,
"s": 2282,
"text": "13. To download a file "
},
{
"code": null,
"e": 2326,
"s": 2307,
"text": "wget link_to_file "
},
{
"code": null,
"e": 2401,
"s": 2326,
"text": "This command will download the file from the link entered in the command. "
},
{
"code": null,
"e": 2428,
"s": 2401,
"text": "14. To install a package "
},
{
"code": null,
"e": 2458,
"s": 2428,
"text": "sudo apt install package_name"
},
{
"code": null,
"e": 2528,
"s": 2458,
"text": "This command is used to install the mentioned package in the system. "
},
{
"code": null,
"e": 2554,
"s": 2528,
"text": "15. To remove a package "
},
{
"code": null,
"e": 2584,
"s": 2554,
"text": "sudo apt remove package_namme"
},
{
"code": null,
"e": 2649,
"s": 2584,
"text": "This command will remove the mentioned package from the system. "
},
{
"code": null,
"e": 2689,
"s": 2649,
"text": "16. To upgrade packages in the system "
},
{
"code": null,
"e": 2706,
"s": 2689,
"text": "sudo apt upgrade"
},
{
"code": null,
"e": 2765,
"s": 2706,
"text": "This command will upgrade all the packages in the system. "
},
{
"code": null,
"e": 2801,
"s": 2765,
"text": "17. To fetch the packages updates "
},
{
"code": null,
"e": 2818,
"s": 2801,
"text": "sudo apt update "
},
{
"code": null,
"e": 2924,
"s": 2818,
"text": "This command will check for updates of all the packages and will add the updates in the list to upgrade. "
},
{
"code": null,
"e": 2958,
"s": 2924,
"text": "18. To get the current username "
},
{
"code": null,
"e": 2966,
"s": 2958,
"text": "whoami "
},
{
"code": null,
"e": 3031,
"s": 2966,
"text": "This command is used to print the username of the current user. "
},
{
"code": null,
"e": 3085,
"s": 3031,
"text": "19. To change the current user to superuser or root "
},
{
"code": null,
"e": 3093,
"s": 3085,
"text": "sudo su"
},
{
"code": null,
"e": 3173,
"s": 3093,
"text": "This command will ask for a password and will change the current user to root. "
},
{
"code": null,
"e": 3200,
"s": 3173,
"text": "20. To print in terminal "
},
{
"code": null,
"e": 3239,
"s": 3200,
"text": "echo \" To print something on terminal\""
},
{
"code": null,
"e": 3299,
"s": 3239,
"text": "The command will print the mentioned text on the terminal. "
},
{
"code": null,
"e": 3318,
"s": 3299,
"text": "surindertarika1234"
},
{
"code": null,
"e": 3336,
"s": 3318,
"text": "shivanshsinghx365"
},
{
"code": null,
"e": 3347,
"s": 3336,
"text": "Kali-Linux"
},
{
"code": null,
"e": 3358,
"s": 3347,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3456,
"s": 3358,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3491,
"s": 3456,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 3526,
"s": 3491,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 3562,
"s": 3526,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 3603,
"s": 3562,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 3636,
"s": 3603,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 3674,
"s": 3636,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 3710,
"s": 3674,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 3736,
"s": 3710,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3771,
"s": 3736,
"text": "scp command in Linux with Examples"
}
] |
How to get integer values from a string in Python? | You can use regular expressions to get all integer values in order of their occurance in an array. You can use the following code to get those values -
import re
s = "12 hello 52 19 some random 15 number"
# Extract numbers and cast them to int
list_of_nums = map(int, re.findall('\d+', s))
print list_of_nums
[12, 52, 19, 15]
If you want to concatenate all numbers in one number and output that, then you can use str.isdigit method to filter them. For example,
>>> s = "12 hello 52 19 some random 15 number"
>>> print int(filter(str.isdigit, s))
12521915 | [
{
"code": null,
"e": 1339,
"s": 1187,
"text": "You can use regular expressions to get all integer values in order of their occurance in an array. You can use the following code to get those values -"
},
{
"code": null,
"e": 1496,
"s": 1339,
"text": "import re\ns = \"12 hello 52 19 some random 15 number\"\n# Extract numbers and cast them to int\nlist_of_nums = map(int, re.findall('\\d+', s))\nprint list_of_nums"
},
{
"code": null,
"e": 1513,
"s": 1496,
"text": "[12, 52, 19, 15]"
},
{
"code": null,
"e": 1648,
"s": 1513,
"text": "If you want to concatenate all numbers in one number and output that, then you can use str.isdigit method to filter them. For example,"
},
{
"code": null,
"e": 1742,
"s": 1648,
"text": ">>> s = \"12 hello 52 19 some random 15 number\"\n>>> print int(filter(str.isdigit, s))\n12521915"
}
] |
Flexbox - Justifying Contents | Often you can observe an extra space left in the container after arranging the flex items as shown below.
Using the property justify-content, you can align the contents along the main axis by distributing the extra space as intended. You can also adjust the alignment of the flexitems, in case they overflow the line.
usage −
justify-content: flex-start | flex-end | center | space-between | space-around| space-evenly;
This property accepts the following values −
flex-start − The flex-items are placed at the start of the container.
flex-start − The flex-items are placed at the start of the container.
flex-end − The flex-items are placed at the end of the container.
flex-end − The flex-items are placed at the end of the container.
center − The flex-items are placed at the center of the container, where the extra space is equally distributed at the start and at the end of the flex-items.
center − The flex-items are placed at the center of the container, where the extra space is equally distributed at the start and at the end of the flex-items.
space-between − The extra space is equally distributed between the flex-items.
space-between − The extra space is equally distributed between the flex-items.
space-around − The extra space is equally distributed between the flex items such that the space between the edges of the container and its contents is half as the space between the flex-items.
space-around − The extra space is equally distributed between the flex items such that the space between the edges of the container and its contents is half as the space between the flex-items.
Now, we will see how to use the justify-content property, with examples.
On passing this value to the property justify-content, the flex-items are placed at the start of the container.
The following example demonstrates the result of passing the value flex-start to the justify-content property.
<!doctype html>
<html lang = "en">
<style>
.box1{background:green;}
.box2{background:blue;}
.box3{background:red;}
.box4{background:magenta;}
.box5{background:yellow;}
.box6{background:pink;}
.box{
font-size:35px;
padding:15px;
}
.container{
display:flex;
border:3px solid black;
justify-content:flex-start;
}
</style>
<body>
<div class = "container">
<div class = "box box1">One</div>
<div class = "box box2">two</div>
<div class = "box box3">three</div>
<div class = "box box4">four</div>
<div class = "box box5">five</div>
<div class = "box box6">six</div>
</div>
</body>
</html>
It will produce the following result −
On passing this value to the property justify-content, the flex-items are placed at the end of the container.
The following example demonstrates the result of passing the value flex-end to the justify-content property.
<!doctype html>
<html lang = "en">
<style>
.box1{background:green;}
.box2{background:blue;}
.box3{background:red;}
.box4{background:magenta;}
.box5{background:yellow;}
.box6{background:pink;}
.box{
font-size:35px;
padding:15px;
}
.container{
display:flex;
border:3px solid black;
justify-content:flex-end;
}
</style>
<body>
<div class = "container">
<div class = "box box1">One</div>
<div class = "box box2">two</div>
<div class = "box box3">three</div>
<div class = "box box4">four</div>
<div class = "box box5">five</div>
<div class = "box box6">six</div>
</div>
</body>
</html>
It will produce the following result −
On passing this value to the property justify-content, the flex-items are placed at the center of the container, where the extra space is equally distributed at the start and at the end of the flex-items.
The following example demonstrates the result of passing the value center to the justify-content property.
<!doctype html>
<html lang = "en">
<style>
.box1{background:green;}
.box2{background:blue;}
.box3{background:red;}
.box4{background:magenta;}
.box5{background:yellow;}
.box6{background:pink;}
.box{
font-size:35px;
padding:15px;
}
.container{
display:flex;
border:3px solid black;
justify-content:center;
}
</style>
<body>
<div class = "container">
<div class = "box box1">One</div>
<div class = "box box2">two</div>
<div class = "box box3">three</div>
<div class = "box box4">four</div>
<div class = "box box5">five</div>
<div class = "box box6">six</div>
</div>
</body>
</html>
It will produce the following result −
On passing this value to the property justify-content, the extra space is equally distributed between the flex items such that the space between any two flex-items is the same and the start and end of the flex-items touch the edges of the container.
The following example demonstrates the result of passing the value space-between to the justify-content property.
<!doctype html>
<html lang = "en">
<style>
.box1{background:green;}
.box2{background:blue;}
.box3{background:red;}
.box4{background:magenta;}
.box5{background:yellow;}
.box6{background:pink;}
.box{
font-size:35px;
padding:15px;
}
.container{
display:flex;
border:3px solid black;
justify-content:space-between;
}
</style>
<body>
<div class = "container">
<div class = "box box1">One</div>
<div class = "box box2">two</div>
<div class = "box box3">three</div>
<div class = "box box4">four</div>
<div class = "box box5">five</div>
<div class = "box box6">six</div>
</div>
</body>
</html>
It will produce the following result −
On passing this value to the property justify-content, the extra space is equally distributed between the flex-items such that the space between any two flex-items is the same. However, the space between the edges of the container and its contents (the start and end of the flex-items) is half as the space between the flex items.
The following example demonstrates the result of passing the value space-around to the justify-content property.
<!doctype html>
<html lang = "en">
<style>
.box1{background:green;}
.box2{background:blue;}
.box3{background:red;}
.box4{background:magenta;}
.box5{background:yellow;}
.box6{background:pink;}
.box{
font-size:35px;
padding:15px;
}
.container{
display:flex;
border:3px solid black;
justify-content:space-around;
}
</style>
<body>
<div class = "container">
<div class = "box box1">One</div>
<div class = "box box2">two</div>
<div class = "box box3">three</div>
<div class = "box box4">four</div>
<div class = "box box5">five</div>
<div class = "box box6">six</div>
</div>
</body>
</html>
It will produce the following result −
On passing this value to the property justify-content, the extra space is equally distributed between the flex-items such that the space between any two flex-items is the same (including the space to the edges).
The following example demonstrates the result of passing the value space-evenly to the justify-content property.
<!doctype html>
<html lang = "en">
<style>
.box1{background:green;}
.box2{background:blue;}
.box3{background:red;}
.box4{background:magenta;}
.box5{background:yellow;}
.box6{background:pink;}
.box{
font-size:35px;
padding:15px;
}
.container{
display:flex;
border:3px solid black;
justify-content:space-evenly;
}
</style>
<body>
<div class = "container">
<div class = "box box1">One</div>
<div class = "box box2">two</div>
<div class = "box box3">three</div>
<div class = "box box4">four</div>
<div class = "box box5">five</div>
<div class = "box box6">six</div>
</div>
</body>
</html>
It will produce the following result − | [
{
"code": null,
"e": 2051,
"s": 1945,
"text": "Often you can observe an extra space left in the container after arranging the flex items as shown below."
},
{
"code": null,
"e": 2263,
"s": 2051,
"text": "Using the property justify-content, you can align the contents along the main axis by distributing the extra space as intended. You can also adjust the alignment of the flexitems, in case they overflow the line."
},
{
"code": null,
"e": 2271,
"s": 2263,
"text": "usage −"
},
{
"code": null,
"e": 2366,
"s": 2271,
"text": "justify-content: flex-start | flex-end | center | space-between | space-around| space-evenly;\n"
},
{
"code": null,
"e": 2411,
"s": 2366,
"text": "This property accepts the following values −"
},
{
"code": null,
"e": 2481,
"s": 2411,
"text": "flex-start − The flex-items are placed at the start of the container."
},
{
"code": null,
"e": 2551,
"s": 2481,
"text": "flex-start − The flex-items are placed at the start of the container."
},
{
"code": null,
"e": 2617,
"s": 2551,
"text": "flex-end − The flex-items are placed at the end of the container."
},
{
"code": null,
"e": 2683,
"s": 2617,
"text": "flex-end − The flex-items are placed at the end of the container."
},
{
"code": null,
"e": 2842,
"s": 2683,
"text": "center − The flex-items are placed at the center of the container, where the extra space is equally distributed at the start and at the end of the flex-items."
},
{
"code": null,
"e": 3001,
"s": 2842,
"text": "center − The flex-items are placed at the center of the container, where the extra space is equally distributed at the start and at the end of the flex-items."
},
{
"code": null,
"e": 3080,
"s": 3001,
"text": "space-between − The extra space is equally distributed between the flex-items."
},
{
"code": null,
"e": 3159,
"s": 3080,
"text": "space-between − The extra space is equally distributed between the flex-items."
},
{
"code": null,
"e": 3353,
"s": 3159,
"text": "space-around − The extra space is equally distributed between the flex items such that the space between the edges of the container and its contents is half as the space between the flex-items."
},
{
"code": null,
"e": 3547,
"s": 3353,
"text": "space-around − The extra space is equally distributed between the flex items such that the space between the edges of the container and its contents is half as the space between the flex-items."
},
{
"code": null,
"e": 3620,
"s": 3547,
"text": "Now, we will see how to use the justify-content property, with examples."
},
{
"code": null,
"e": 3732,
"s": 3620,
"text": "On passing this value to the property justify-content, the flex-items are placed at the start of the container."
},
{
"code": null,
"e": 3843,
"s": 3732,
"text": "The following example demonstrates the result of passing the value flex-start to the justify-content property."
},
{
"code": null,
"e": 4620,
"s": 3843,
"text": "<!doctype html>\n<html lang = \"en\">\n <style>\n .box1{background:green;}\n .box2{background:blue;}\n .box3{background:red;}\n .box4{background:magenta;}\n .box5{background:yellow;}\n .box6{background:pink;}\n \n .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:flex;\n border:3px solid black;\n justify-content:flex-start;\n }\n </style>\n \n <body>\n <div class = \"container\">\n <div class = \"box box1\">One</div>\n <div class = \"box box2\">two</div>\n <div class = \"box box3\">three</div>\n <div class = \"box box4\">four</div>\n <div class = \"box box5\">five</div>\n <div class = \"box box6\">six</div>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 4659,
"s": 4620,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4769,
"s": 4659,
"text": "On passing this value to the property justify-content, the flex-items are placed at the end of the container."
},
{
"code": null,
"e": 4878,
"s": 4769,
"text": "The following example demonstrates the result of passing the value flex-end to the justify-content property."
},
{
"code": null,
"e": 5653,
"s": 4878,
"text": "<!doctype html>\n<html lang = \"en\">\n <style>\n .box1{background:green;}\n .box2{background:blue;}\n .box3{background:red;}\n .box4{background:magenta;}\n .box5{background:yellow;}\n .box6{background:pink;}\n \n .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:flex;\n border:3px solid black;\n justify-content:flex-end;\n }\n </style>\n \n <body>\n <div class = \"container\">\n <div class = \"box box1\">One</div>\n <div class = \"box box2\">two</div>\n <div class = \"box box3\">three</div>\n <div class = \"box box4\">four</div>\n <div class = \"box box5\">five</div>\n <div class = \"box box6\">six</div>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 5692,
"s": 5653,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5897,
"s": 5692,
"text": "On passing this value to the property justify-content, the flex-items are placed at the center of the container, where the extra space is equally distributed at the start and at the end of the flex-items."
},
{
"code": null,
"e": 6004,
"s": 5897,
"text": "The following example demonstrates the result of passing the value center to the justify-content property."
},
{
"code": null,
"e": 6777,
"s": 6004,
"text": "<!doctype html>\n<html lang = \"en\">\n <style>\n .box1{background:green;}\n .box2{background:blue;}\n .box3{background:red;}\n .box4{background:magenta;}\n .box5{background:yellow;}\n .box6{background:pink;}\n \n .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:flex;\n border:3px solid black;\n justify-content:center;\n }\n </style>\n \n <body>\n <div class = \"container\">\n <div class = \"box box1\">One</div>\n <div class = \"box box2\">two</div>\n <div class = \"box box3\">three</div>\n <div class = \"box box4\">four</div>\n <div class = \"box box5\">five</div>\n <div class = \"box box6\">six</div>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 6816,
"s": 6777,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 7066,
"s": 6816,
"text": "On passing this value to the property justify-content, the extra space is equally distributed between the flex items such that the space between any two flex-items is the same and the start and end of the flex-items touch the edges of the container."
},
{
"code": null,
"e": 7180,
"s": 7066,
"text": "The following example demonstrates the result of passing the value space-between to the justify-content property."
},
{
"code": null,
"e": 7960,
"s": 7180,
"text": "<!doctype html>\n<html lang = \"en\">\n <style>\n .box1{background:green;}\n .box2{background:blue;}\n .box3{background:red;}\n .box4{background:magenta;}\n .box5{background:yellow;}\n .box6{background:pink;}\n \n .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:flex;\n border:3px solid black;\n justify-content:space-between;\n }\n </style>\n \n <body>\n <div class = \"container\">\n <div class = \"box box1\">One</div>\n <div class = \"box box2\">two</div>\n <div class = \"box box3\">three</div>\n <div class = \"box box4\">four</div>\n <div class = \"box box5\">five</div>\n <div class = \"box box6\">six</div>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 7999,
"s": 7960,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 8330,
"s": 7999,
"text": "On passing this value to the property justify-content, the extra space is equally distributed between the flex-items such that the space between any two flex-items is the same. However, the space between the edges of the container and its contents (the start and end of the flex-items) is half as the space between the flex items."
},
{
"code": null,
"e": 8443,
"s": 8330,
"text": "The following example demonstrates the result of passing the value space-around to the justify-content property."
},
{
"code": null,
"e": 9222,
"s": 8443,
"text": "<!doctype html>\n<html lang = \"en\">\n <style>\n .box1{background:green;}\n .box2{background:blue;}\n .box3{background:red;}\n .box4{background:magenta;}\n .box5{background:yellow;}\n .box6{background:pink;}\n \n .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:flex;\n border:3px solid black;\n justify-content:space-around;\n }\n </style>\n \n <body>\n <div class = \"container\">\n <div class = \"box box1\">One</div>\n <div class = \"box box2\">two</div>\n <div class = \"box box3\">three</div>\n <div class = \"box box4\">four</div>\n <div class = \"box box5\">five</div>\n <div class = \"box box6\">six</div>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 9261,
"s": 9222,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 9473,
"s": 9261,
"text": "On passing this value to the property justify-content, the extra space is equally distributed between the flex-items such that the space between any two flex-items is the same (including the space to the edges)."
},
{
"code": null,
"e": 9586,
"s": 9473,
"text": "The following example demonstrates the result of passing the value space-evenly to the justify-content property."
},
{
"code": null,
"e": 10365,
"s": 9586,
"text": "<!doctype html>\n<html lang = \"en\">\n <style>\n .box1{background:green;}\n .box2{background:blue;}\n .box3{background:red;}\n .box4{background:magenta;}\n .box5{background:yellow;}\n .box6{background:pink;}\n \n .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:flex;\n border:3px solid black;\n justify-content:space-evenly;\n }\n </style>\n \n <body>\n <div class = \"container\">\n <div class = \"box box1\">One</div>\n <div class = \"box box2\">two</div>\n <div class = \"box box3\">three</div>\n <div class = \"box box4\">four</div>\n <div class = \"box box5\">five</div>\n <div class = \"box box6\">six</div>\n </div>\n </body>\n</html>"
}
] |
D3.js - Geographies | Geospatial coordinates are often used for weather or population data. D3.js gives us three tools for geographic data −
Paths − They produce the final pixels.
Paths − They produce the final pixels.
Projections − They turn sphere coordinates into Cartesian coordinates and
Projections − They turn sphere coordinates into Cartesian coordinates and
Streams − They speed things up.
Streams − They speed things up.
Before learning what geographies in D3.js are, we should understand the following two terms −
D3 Geo Path and
Projections
Let us discuss these two terms in detail.
It is a geographic path generator. GeoJSON generates SVG path data string or renders the path to a Canvas. A Canvas is recommended for dynamic or interactive projections to improve performance. To generate a D3 Geo Path Data Generator, you can call the following function.
d3.geo.path()
Here, the d3.geo.path() path generator function allows us to select which Map Projection we want to use for the translation from Geo Coordinates to Cartesian Coordinates.
For example, if we want to show the map details of India, we can define a path as shown below.
var path = d3.geo.path()
svg.append("path")
.attr("d", path(states))
Projections transform spherical polygonal geometry to planar polygonal geometry. D3 provides the following projection implementations.
Azimuthal − Azimuthal projections project the sphere directly onto a plane.
Azimuthal − Azimuthal projections project the sphere directly onto a plane.
Composite − Composite consists of several projections that are composed into a single display.
Composite − Composite consists of several projections that are composed into a single display.
Conic − Projects the sphere onto a cone and then unroll the cone onto the plane.
Conic − Projects the sphere onto a cone and then unroll the cone onto the plane.
Cylindrical − Cylindrical projections project the sphere onto a containing cylinder, and then unroll the cylinder onto the plane.
Cylindrical − Cylindrical projections project the sphere onto a containing cylinder, and then unroll the cylinder onto the plane.
To create a new projection, you can use the following function.
d3.geoProjection(project)
It constructs a new projection from the specified raw projection project. The project function takes the longitude and latitude of a given point in radians. You can apply the following projection in your code.
var width = 400
var height = 400
var projection = d3.geo.orthographic()
var projections = d3.geo.equirectangular()
var project = d3.geo.gnomonic()
var p = d3.geo.mercator()
var pro = d3.geo.transverseMercator()
.scale(100)
.rotate([100,0,0])
.translate([width/2, height/2])
.clipAngle(45);
Here, we can apply any one of the above projections. Let us discuss each of these projections in brief.
d3.geo.orthographic() − The orthographic projection is an azimuthal projection suitable for displaying a single hemisphere; the point of perspective is at infinity.
d3.geo.orthographic() − The orthographic projection is an azimuthal projection suitable for displaying a single hemisphere; the point of perspective is at infinity.
d3.geo.gnomonic() − The gnomonic projection is an azimuthal projection that projects great circles as straight lines.
d3.geo.gnomonic() − The gnomonic projection is an azimuthal projection that projects great circles as straight lines.
d3.geo.equirectangular() − The equirectangular is the simplest possible geographic projection. The identity function. It is neither equal-area nor conformal, but is sometimes used for raster data.
d3.geo.equirectangular() − The equirectangular is the simplest possible geographic projection. The identity function. It is neither equal-area nor conformal, but is sometimes used for raster data.
d3.geo.mercator() − The Spherical Mercator projection is commonly used by tiled mapping libraries.
d3.geo.mercator() − The Spherical Mercator projection is commonly used by tiled mapping libraries.
d3.geo.transverseMercator() − The Transverse Mercator projection.
d3.geo.transverseMercator() − The Transverse Mercator projection.
Let us create the map of India in this example. To do this, we should adhere to the following steps.
Step 1 − Apply styles − Let us add styles in map using the code below.
<style>
path {
stroke: white;
stroke-width: 0.5px;
fill: grey;
}
.stateTN { fill: red; }
.stateAP { fill: blue; }
.stateMP{ fill: green; }
</style>
Here, we have applied particular colors for state TN, AP and MP.
Step 2 − Include topojson script − TopoJSON is an extension of GeoJSON that encodes topology, which is defined below.
<script src = "http://d3js.org/topojson.v0.min.js"></script>
We can include this script in our coding.
Step 3 − Define variables − Add variables in your script, using the code below.
var width = 600;
var height = 400;
var projection = d3.geo.mercator()
.center([78, 22])
.scale(680)
.translate([width / 2, height / 2]);
Here, SVG width is 600 and height is 400. The screen is a two-dimensional space and we are trying to present a three-dimensional object. So, we can grievously distort the land size / shape using the d3.geo.mercator() function.
The center is specified [78, 22], this sets the projection’s center to the specified location as a two-element array of longitude and latitude in degrees and returns the projection.
Here, the map has been centered on 78 degrees West and 22 degrees North.
The Scale is specified as 680, this sets the projection’s scale factor to the specified value. If the scale is not specified, it returns the current scale factor, which defaults to 150. It is important to note that scale factors are not consistent across projections.
Step 4 − Append SVG − Now, append the SVG attributes.
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
Step 5 − Create path − The following portion of code creates a new geographic path generator.
var path = d3.geo.path()
.projection(projection);
Here, the path generator (d3.geo.path()) is used to specify a projection type (.projection), which was defined earlier as a Mercator projection using the variable projection.
Step 6 − Generate data − indiatopo.json – This file contains so many records, which we can easily download from the following attachment.
Download indiatopo.json file
After the file has been downloaded, we can add it our D3 location. The sample format is shown below.
{"type":"Topology","transform":{"scale":[0.002923182318231823,0.0027427542754275428],
"translate":[68.1862,8.0765]},"objects":
{"states":{"type":"GeometryCollection",
"geometries":[{"type":"MultiPolygon","id":"AP","arcs":
[[[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
25,26,27,28,29,30,31,32,33,34]],[[35,36,37,38,39,40,41]],[[42]],
[[43,44,45]],[[46]],[[47]],[[48]],[[49]],[[50]],[[51]],[[52,53]],
[[54]],[[55]],[[56]],[[57,58]],[[59]],[[60]],[[61,62,63]],[[64]],
[[65]],[[66]],[[67]],[[68]],[[69]],[[-41,70]],
[[71]],[[72]],[[73]],[[74]],[[75]]],
"properties":{"name":"Andhra Pradesh"}},{"type":"MultiPolygon",
"id":"AR","arcs":[[[76,77,78,79,80,81,82]]],
"properties":{"name":"Arunachal Pradesh"}},{"type":"MultiPolygon",
"id":"AS","arcs":[[[83,84,85,86,87,88,89,90,
91,92,93,94,95,96,97,98,99,100,101,102,103]],
[[104,105,106,107]],[[108,109]]], ......
........................................
Step 7 − Draw map − Now, read the data from the indiatopo.json file and draw the map.
d3.json("indiatopo.json", function(error, topology) {
g.selectAll("path")
.data(topojson.object(topology, topology.objects.states)
.geometries)
.enter()
.append("path")
.attr("class", function(d) { return "state" + d.id; })
.attr("d", path)
});
Here, we will load the TopoJSON file with the coordinates for the India map (indiatopo.json). Then we declare that we are going to act on all the path elements in the graphic. It is defined as, g.selectAll(“path”). We will then pull the data that defines the countries from the TopoJSON file.
.data(topojson.object(topology, topology.objects.states)
.geometries)
Finally, we will add it to the data that we are going to display using the .enter() method and then we append that data as path elements using the .append(“path”) method. | [
{
"code": null,
"e": 2383,
"s": 2264,
"text": "Geospatial coordinates are often used for weather or population data. D3.js gives us three tools for geographic data −"
},
{
"code": null,
"e": 2422,
"s": 2383,
"text": "Paths − They produce the final pixels."
},
{
"code": null,
"e": 2461,
"s": 2422,
"text": "Paths − They produce the final pixels."
},
{
"code": null,
"e": 2536,
"s": 2461,
"text": "Projections − They turn sphere coordinates into Cartesian coordinates and "
},
{
"code": null,
"e": 2611,
"s": 2536,
"text": "Projections − They turn sphere coordinates into Cartesian coordinates and "
},
{
"code": null,
"e": 2643,
"s": 2611,
"text": "Streams − They speed things up."
},
{
"code": null,
"e": 2675,
"s": 2643,
"text": "Streams − They speed things up."
},
{
"code": null,
"e": 2769,
"s": 2675,
"text": "Before learning what geographies in D3.js are, we should understand the following two terms −"
},
{
"code": null,
"e": 2785,
"s": 2769,
"text": "D3 Geo Path and"
},
{
"code": null,
"e": 2797,
"s": 2785,
"text": "Projections"
},
{
"code": null,
"e": 2839,
"s": 2797,
"text": "Let us discuss these two terms in detail."
},
{
"code": null,
"e": 3112,
"s": 2839,
"text": "It is a geographic path generator. GeoJSON generates SVG path data string or renders the path to a Canvas. A Canvas is recommended for dynamic or interactive projections to improve performance. To generate a D3 Geo Path Data Generator, you can call the following function."
},
{
"code": null,
"e": 3126,
"s": 3112,
"text": "d3.geo.path()"
},
{
"code": null,
"e": 3297,
"s": 3126,
"text": "Here, the d3.geo.path() path generator function allows us to select which Map Projection we want to use for the translation from Geo Coordinates to Cartesian Coordinates."
},
{
"code": null,
"e": 3392,
"s": 3297,
"text": "For example, if we want to show the map details of India, we can define a path as shown below."
},
{
"code": null,
"e": 3464,
"s": 3392,
"text": "var path = d3.geo.path()\nsvg.append(\"path\")\n .attr(\"d\", path(states))"
},
{
"code": null,
"e": 3599,
"s": 3464,
"text": "Projections transform spherical polygonal geometry to planar polygonal geometry. D3 provides the following projection implementations."
},
{
"code": null,
"e": 3675,
"s": 3599,
"text": "Azimuthal − Azimuthal projections project the sphere directly onto a plane."
},
{
"code": null,
"e": 3751,
"s": 3675,
"text": "Azimuthal − Azimuthal projections project the sphere directly onto a plane."
},
{
"code": null,
"e": 3846,
"s": 3751,
"text": "Composite − Composite consists of several projections that are composed into a single display."
},
{
"code": null,
"e": 3941,
"s": 3846,
"text": "Composite − Composite consists of several projections that are composed into a single display."
},
{
"code": null,
"e": 4022,
"s": 3941,
"text": "Conic − Projects the sphere onto a cone and then unroll the cone onto the plane."
},
{
"code": null,
"e": 4103,
"s": 4022,
"text": "Conic − Projects the sphere onto a cone and then unroll the cone onto the plane."
},
{
"code": null,
"e": 4233,
"s": 4103,
"text": "Cylindrical − Cylindrical projections project the sphere onto a containing cylinder, and then unroll the cylinder onto the plane."
},
{
"code": null,
"e": 4363,
"s": 4233,
"text": "Cylindrical − Cylindrical projections project the sphere onto a containing cylinder, and then unroll the cylinder onto the plane."
},
{
"code": null,
"e": 4427,
"s": 4363,
"text": "To create a new projection, you can use the following function."
},
{
"code": null,
"e": 4453,
"s": 4427,
"text": "d3.geoProjection(project)"
},
{
"code": null,
"e": 4663,
"s": 4453,
"text": "It constructs a new projection from the specified raw projection project. The project function takes the longitude and latitude of a given point in radians. You can apply the following projection in your code."
},
{
"code": null,
"e": 4966,
"s": 4663,
"text": "var width = 400\nvar height = 400\nvar projection = d3.geo.orthographic() \nvar projections = d3.geo.equirectangular()\nvar project = d3.geo.gnomonic()\nvar p = d3.geo.mercator()\nvar pro = d3.geo.transverseMercator()\n .scale(100)\n .rotate([100,0,0])\n .translate([width/2, height/2])\n .clipAngle(45);"
},
{
"code": null,
"e": 5070,
"s": 4966,
"text": "Here, we can apply any one of the above projections. Let us discuss each of these projections in brief."
},
{
"code": null,
"e": 5235,
"s": 5070,
"text": "d3.geo.orthographic() − The orthographic projection is an azimuthal projection suitable for displaying a single hemisphere; the point of perspective is at infinity."
},
{
"code": null,
"e": 5400,
"s": 5235,
"text": "d3.geo.orthographic() − The orthographic projection is an azimuthal projection suitable for displaying a single hemisphere; the point of perspective is at infinity."
},
{
"code": null,
"e": 5518,
"s": 5400,
"text": "d3.geo.gnomonic() − The gnomonic projection is an azimuthal projection that projects great circles as straight lines."
},
{
"code": null,
"e": 5636,
"s": 5518,
"text": "d3.geo.gnomonic() − The gnomonic projection is an azimuthal projection that projects great circles as straight lines."
},
{
"code": null,
"e": 5833,
"s": 5636,
"text": "d3.geo.equirectangular() − The equirectangular is the simplest possible geographic projection. The identity function. It is neither equal-area nor conformal, but is sometimes used for raster data."
},
{
"code": null,
"e": 6030,
"s": 5833,
"text": "d3.geo.equirectangular() − The equirectangular is the simplest possible geographic projection. The identity function. It is neither equal-area nor conformal, but is sometimes used for raster data."
},
{
"code": null,
"e": 6129,
"s": 6030,
"text": "d3.geo.mercator() − The Spherical Mercator projection is commonly used by tiled mapping libraries."
},
{
"code": null,
"e": 6228,
"s": 6129,
"text": "d3.geo.mercator() − The Spherical Mercator projection is commonly used by tiled mapping libraries."
},
{
"code": null,
"e": 6294,
"s": 6228,
"text": "d3.geo.transverseMercator() − The Transverse Mercator projection."
},
{
"code": null,
"e": 6360,
"s": 6294,
"text": "d3.geo.transverseMercator() − The Transverse Mercator projection."
},
{
"code": null,
"e": 6461,
"s": 6360,
"text": "Let us create the map of India in this example. To do this, we should adhere to the following steps."
},
{
"code": null,
"e": 6532,
"s": 6461,
"text": "Step 1 − Apply styles − Let us add styles in map using the code below."
},
{
"code": null,
"e": 6717,
"s": 6532,
"text": "<style>\n path {\n stroke: white;\n stroke-width: 0.5px;\n fill: grey;\n }\n \n .stateTN { fill: red; }\n .stateAP { fill: blue; }\n .stateMP{ fill: green; }\n</style>"
},
{
"code": null,
"e": 6782,
"s": 6717,
"text": "Here, we have applied particular colors for state TN, AP and MP."
},
{
"code": null,
"e": 6900,
"s": 6782,
"text": "Step 2 − Include topojson script − TopoJSON is an extension of GeoJSON that encodes topology, which is defined below."
},
{
"code": null,
"e": 6961,
"s": 6900,
"text": "<script src = \"http://d3js.org/topojson.v0.min.js\"></script>"
},
{
"code": null,
"e": 7003,
"s": 6961,
"text": "We can include this script in our coding."
},
{
"code": null,
"e": 7083,
"s": 7003,
"text": "Step 3 − Define variables − Add variables in your script, using the code below."
},
{
"code": null,
"e": 7229,
"s": 7083,
"text": "var width = 600;\nvar height = 400;\nvar projection = d3.geo.mercator()\n .center([78, 22])\n .scale(680)\n .translate([width / 2, height / 2]);"
},
{
"code": null,
"e": 7456,
"s": 7229,
"text": "Here, SVG width is 600 and height is 400. The screen is a two-dimensional space and we are trying to present a three-dimensional object. So, we can grievously distort the land size / shape using the d3.geo.mercator() function."
},
{
"code": null,
"e": 7638,
"s": 7456,
"text": "The center is specified [78, 22], this sets the projection’s center to the specified location as a two-element array of longitude and latitude in degrees and returns the projection."
},
{
"code": null,
"e": 7711,
"s": 7638,
"text": "Here, the map has been centered on 78 degrees West and 22 degrees North."
},
{
"code": null,
"e": 7979,
"s": 7711,
"text": "The Scale is specified as 680, this sets the projection’s scale factor to the specified value. If the scale is not specified, it returns the current scale factor, which defaults to 150. It is important to note that scale factors are not consistent across projections."
},
{
"code": null,
"e": 8033,
"s": 7979,
"text": "Step 4 − Append SVG − Now, append the SVG attributes."
},
{
"code": null,
"e": 8128,
"s": 8033,
"text": "var svg = d3.select(\"body\").append(\"svg\")\n .attr(\"width\", width)\n .attr(\"height\", height);"
},
{
"code": null,
"e": 8222,
"s": 8128,
"text": "Step 5 − Create path − The following portion of code creates a new geographic path generator."
},
{
"code": null,
"e": 8275,
"s": 8222,
"text": "var path = d3.geo.path()\n .projection(projection);"
},
{
"code": null,
"e": 8450,
"s": 8275,
"text": "Here, the path generator (d3.geo.path()) is used to specify a projection type (.projection), which was defined earlier as a Mercator projection using the variable projection."
},
{
"code": null,
"e": 8588,
"s": 8450,
"text": "Step 6 − Generate data − indiatopo.json – This file contains so many records, which we can easily download from the following attachment."
},
{
"code": null,
"e": 8617,
"s": 8588,
"text": "Download indiatopo.json file"
},
{
"code": null,
"e": 8718,
"s": 8617,
"text": "After the file has been downloaded, we can add it our D3 location. The sample format is shown below."
},
{
"code": null,
"e": 9640,
"s": 8718,
"text": "{\"type\":\"Topology\",\"transform\":{\"scale\":[0.002923182318231823,0.0027427542754275428],\n\"translate\":[68.1862,8.0765]},\"objects\":\n{\"states\":{\"type\":\"GeometryCollection\",\n\"geometries\":[{\"type\":\"MultiPolygon\",\"id\":\"AP\",\"arcs\":\n[[[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,\n25,26,27,28,29,30,31,32,33,34]],[[35,36,37,38,39,40,41]],[[42]],\n[[43,44,45]],[[46]],[[47]],[[48]],[[49]],[[50]],[[51]],[[52,53]],\n[[54]],[[55]],[[56]],[[57,58]],[[59]],[[60]],[[61,62,63]],[[64]],\n[[65]],[[66]],[[67]],[[68]],[[69]],[[-41,70]],\n[[71]],[[72]],[[73]],[[74]],[[75]]],\n\"properties\":{\"name\":\"Andhra Pradesh\"}},{\"type\":\"MultiPolygon\",\n\"id\":\"AR\",\"arcs\":[[[76,77,78,79,80,81,82]]],\n\"properties\":{\"name\":\"Arunachal Pradesh\"}},{\"type\":\"MultiPolygon\",\n\"id\":\"AS\",\"arcs\":[[[83,84,85,86,87,88,89,90,\n91,92,93,94,95,96,97,98,99,100,101,102,103]],\n[[104,105,106,107]],[[108,109]]], ......\n\n........................................"
},
{
"code": null,
"e": 9726,
"s": 9640,
"text": "Step 7 − Draw map − Now, read the data from the indiatopo.json file and draw the map."
},
{
"code": null,
"e": 9992,
"s": 9726,
"text": "d3.json(\"indiatopo.json\", function(error, topology) {\n g.selectAll(\"path\")\n .data(topojson.object(topology, topology.objects.states)\n .geometries)\n .enter()\n .append(\"path\")\n .attr(\"class\", function(d) { return \"state\" + d.id; })\n .attr(\"d\", path)\n});"
},
{
"code": null,
"e": 10285,
"s": 9992,
"text": "Here, we will load the TopoJSON file with the coordinates for the India map (indiatopo.json). Then we declare that we are going to act on all the path elements in the graphic. It is defined as, g.selectAll(“path”). We will then pull the data that defines the countries from the TopoJSON file."
},
{
"code": null,
"e": 10358,
"s": 10285,
"text": ".data(topojson.object(topology, topology.objects.states)\n .geometries)"
}
] |
C# | FlowLayoutPanel Class | 15 Nov, 2021
In Windows Forms, FlowLayoutPanel control is used to arrange its child controls in a horizontal or vertical flow direction. Or in other words, FlowLayoutPanel is a container which is used to organize different or same types of controls in it either horizontally or vertically. The FlowLayoutPanel class is used to represent windows flow layout panel and also provide different types of properties, methods, and events. It is defined under System.Windows.Forms namespace. In C#, you can create a FlowLayoutPanel in the windows form by using two different ways:
1. Design-Time: It is the easiest way to create a FlowLayoutPanel control as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Next, drag and drop the FlowLayoutPanel control from the toolbox to the form as shown in the below image:
Step 3: After drag and drop you will go to the properties of the FlowLayoutPanel to modify FlowLayoutPanel according to your requirement.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a FlowLayoutPanel programmatically with the help of syntax provided by the FlowLayoutPanel class. The following steps show how to set the create FlowLayoutPanel dynamically:
Step 1: Create a FlowLayoutPanel using the FlowLayoutPanel() constructor is provided by the FlowLayoutPanel class.// Creating a FlowLayoutPanel
FlowLayoutPanel fl = new FlowLayoutPanel();
// Creating a FlowLayoutPanel
FlowLayoutPanel fl = new FlowLayoutPanel();
Step 2: After creating a FlowLayoutPanel, set the property of the FlowLayoutPanel provided by the FlowLayoutPanel class.// Setting the location of the FlowLayoutPanel
fl.Location = new Point(380, 124);
// Setting the size of the FlowLayoutPanel
fl.Size = new Size(216, 57);
// Setting the name of the FlowLayoutPanel
fl.Name = "Mycontainer";
// Setting the font of the FlowLayoutPanel
fl.Font = new Font("Calibri", 12);
// Setting the flow direction of the FlowLayoutPanel
fl.FlowDirection = FlowDirection.RightToLeft;
// Setting the border style of the FlowLayoutPanel
fl.BorderStyle = BorderStyle.Fixed3D;
// Setting the foreground color of the FlowLayoutPanel
fl.ForeColor = Color.BlueViolet;
// Setting the visibility of the FlowLayoutPanel
fl.Visible = true;
// Setting the location of the FlowLayoutPanel
fl.Location = new Point(380, 124);
// Setting the size of the FlowLayoutPanel
fl.Size = new Size(216, 57);
// Setting the name of the FlowLayoutPanel
fl.Name = "Mycontainer";
// Setting the font of the FlowLayoutPanel
fl.Font = new Font("Calibri", 12);
// Setting the flow direction of the FlowLayoutPanel
fl.FlowDirection = FlowDirection.RightToLeft;
// Setting the border style of the FlowLayoutPanel
fl.BorderStyle = BorderStyle.Fixed3D;
// Setting the foreground color of the FlowLayoutPanel
fl.ForeColor = Color.BlueViolet;
// Setting the visibility of the FlowLayoutPanel
fl.Visible = true;
Step 3: And last add this FlowLayoutPanel control to the form and also add other controls on the FlowLayoutPanel using the following statements:// Adding a FlowLayoutPanel
// control to the form
this.Controls.Add(fl);
and
// Adding child controls
// to the FlowLayoutPanel
fl.Controls.Add(f1);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp50 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of FlowLayoutPanel FlowLayoutPanel fl = new FlowLayoutPanel(); fl.Location = new Point(380, 124); fl.Size = new Size(216, 57); fl.Name = "Myflowpanel"; fl.Font = new Font("Calibri", 12); fl.FlowDirection = FlowDirection.RightToLeft; fl.BorderStyle = BorderStyle.Fixed3D; fl.ForeColor = Color.BlueViolet; fl.Visible = true; // Adding this control to the form this.Controls.Add(fl); // Creating and setting the // properties of radio buttons RadioButton f1 = new RadioButton(); f1.Location = new Point(3, 3); f1.Size = new Size(95, 20); f1.Text = "R1"; // Adding this control // to the FlowLayoutPanel fl.Controls.Add(f1); RadioButton f2 = new RadioButton(); f2.Location = new Point(94, 3); f2.Size = new Size(95, 20); f2.Text = "R2"; // Adding this control // to the FlowLayoutPanel fl.Controls.Add(f2); RadioButton f3 = new RadioButton(); f3.Location = new Point(3, 26); f3.Size = new Size(95, 20); f3.Text = "R3"; // Adding this control // to the FlowLayoutPanel fl.Controls.Add(f3); }}}Output:
// Adding a FlowLayoutPanel
// control to the form
this.Controls.Add(fl);
and
// Adding child controls
// to the FlowLayoutPanel
fl.Controls.Add(f1);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp50 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of FlowLayoutPanel FlowLayoutPanel fl = new FlowLayoutPanel(); fl.Location = new Point(380, 124); fl.Size = new Size(216, 57); fl.Name = "Myflowpanel"; fl.Font = new Font("Calibri", 12); fl.FlowDirection = FlowDirection.RightToLeft; fl.BorderStyle = BorderStyle.Fixed3D; fl.ForeColor = Color.BlueViolet; fl.Visible = true; // Adding this control to the form this.Controls.Add(fl); // Creating and setting the // properties of radio buttons RadioButton f1 = new RadioButton(); f1.Location = new Point(3, 3); f1.Size = new Size(95, 20); f1.Text = "R1"; // Adding this control // to the FlowLayoutPanel fl.Controls.Add(f1); RadioButton f2 = new RadioButton(); f2.Location = new Point(94, 3); f2.Size = new Size(95, 20); f2.Text = "R2"; // Adding this control // to the FlowLayoutPanel fl.Controls.Add(f2); RadioButton f3 = new RadioButton(); f3.Location = new Point(3, 26); f3.Size = new Size(95, 20); f3.Text = "R3"; // Adding this control // to the FlowLayoutPanel fl.Controls.Add(f3); }}}
Output:
CSharp-Windows-Forms-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 588,
"s": 28,
"text": "In Windows Forms, FlowLayoutPanel control is used to arrange its child controls in a horizontal or vertical flow direction. Or in other words, FlowLayoutPanel is a container which is used to organize different or same types of controls in it either horizontally or vertically. The FlowLayoutPanel class is used to represent windows flow layout panel and also provide different types of properties, methods, and events. It is defined under System.Windows.Forms namespace. In C#, you can create a FlowLayoutPanel in the windows form by using two different ways:"
},
{
"code": null,
"e": 695,
"s": 588,
"text": "1. Design-Time: It is the easiest way to create a FlowLayoutPanel control as shown in the following steps:"
},
{
"code": null,
"e": 811,
"s": 695,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 925,
"s": 811,
"text": "Step 2: Next, drag and drop the FlowLayoutPanel control from the toolbox to the form as shown in the below image:"
},
{
"code": null,
"e": 1070,
"s": 925,
"text": "Step 3: After drag and drop you will go to the properties of the FlowLayoutPanel to modify FlowLayoutPanel according to your requirement.Output:"
},
{
"code": null,
"e": 1078,
"s": 1070,
"text": "Output:"
},
{
"code": null,
"e": 1347,
"s": 1078,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a FlowLayoutPanel programmatically with the help of syntax provided by the FlowLayoutPanel class. The following steps show how to set the create FlowLayoutPanel dynamically:"
},
{
"code": null,
"e": 1537,
"s": 1347,
"text": "Step 1: Create a FlowLayoutPanel using the FlowLayoutPanel() constructor is provided by the FlowLayoutPanel class.// Creating a FlowLayoutPanel\nFlowLayoutPanel fl = new FlowLayoutPanel(); \n"
},
{
"code": null,
"e": 1613,
"s": 1537,
"text": "// Creating a FlowLayoutPanel\nFlowLayoutPanel fl = new FlowLayoutPanel(); \n"
},
{
"code": null,
"e": 2450,
"s": 1613,
"text": "Step 2: After creating a FlowLayoutPanel, set the property of the FlowLayoutPanel provided by the FlowLayoutPanel class.// Setting the location of the FlowLayoutPanel\n fl.Location = new Point(380, 124); \n\n// Setting the size of the FlowLayoutPanel\n fl.Size = new Size(216, 57); \n\n// Setting the name of the FlowLayoutPanel\n fl.Name = \"Mycontainer\"; \n\n// Setting the font of the FlowLayoutPanel\n fl.Font = new Font(\"Calibri\", 12); \n\n// Setting the flow direction of the FlowLayoutPanel\n fl.FlowDirection = FlowDirection.RightToLeft; \n\n// Setting the border style of the FlowLayoutPanel\n fl.BorderStyle = BorderStyle.Fixed3D; \n\n// Setting the foreground color of the FlowLayoutPanel\n fl.ForeColor = Color.BlueViolet; \n\n// Setting the visibility of the FlowLayoutPanel\n fl.Visible = true; \n"
},
{
"code": null,
"e": 3167,
"s": 2450,
"text": "// Setting the location of the FlowLayoutPanel\n fl.Location = new Point(380, 124); \n\n// Setting the size of the FlowLayoutPanel\n fl.Size = new Size(216, 57); \n\n// Setting the name of the FlowLayoutPanel\n fl.Name = \"Mycontainer\"; \n\n// Setting the font of the FlowLayoutPanel\n fl.Font = new Font(\"Calibri\", 12); \n\n// Setting the flow direction of the FlowLayoutPanel\n fl.FlowDirection = FlowDirection.RightToLeft; \n\n// Setting the border style of the FlowLayoutPanel\n fl.BorderStyle = BorderStyle.Fixed3D; \n\n// Setting the foreground color of the FlowLayoutPanel\n fl.ForeColor = Color.BlueViolet; \n\n// Setting the visibility of the FlowLayoutPanel\n fl.Visible = true; \n"
},
{
"code": null,
"e": 5175,
"s": 3167,
"text": "Step 3: And last add this FlowLayoutPanel control to the form and also add other controls on the FlowLayoutPanel using the following statements:// Adding a FlowLayoutPanel\n// control to the form\nthis.Controls.Add(fl);\nand \n\n// Adding child controls \n// to the FlowLayoutPanel\nfl.Controls.Add(f1);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp50 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of FlowLayoutPanel FlowLayoutPanel fl = new FlowLayoutPanel(); fl.Location = new Point(380, 124); fl.Size = new Size(216, 57); fl.Name = \"Myflowpanel\"; fl.Font = new Font(\"Calibri\", 12); fl.FlowDirection = FlowDirection.RightToLeft; fl.BorderStyle = BorderStyle.Fixed3D; fl.ForeColor = Color.BlueViolet; fl.Visible = true; // Adding this control to the form this.Controls.Add(fl); // Creating and setting the // properties of radio buttons RadioButton f1 = new RadioButton(); f1.Location = new Point(3, 3); f1.Size = new Size(95, 20); f1.Text = \"R1\"; // Adding this control // to the FlowLayoutPanel fl.Controls.Add(f1); RadioButton f2 = new RadioButton(); f2.Location = new Point(94, 3); f2.Size = new Size(95, 20); f2.Text = \"R2\"; // Adding this control // to the FlowLayoutPanel fl.Controls.Add(f2); RadioButton f3 = new RadioButton(); f3.Location = new Point(3, 26); f3.Size = new Size(95, 20); f3.Text = \"R3\"; // Adding this control // to the FlowLayoutPanel fl.Controls.Add(f3); }}}Output:"
},
{
"code": null,
"e": 5329,
"s": 5175,
"text": "// Adding a FlowLayoutPanel\n// control to the form\nthis.Controls.Add(fl);\nand \n\n// Adding child controls \n// to the FlowLayoutPanel\nfl.Controls.Add(f1);\n"
},
{
"code": null,
"e": 5338,
"s": 5329,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp50 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of FlowLayoutPanel FlowLayoutPanel fl = new FlowLayoutPanel(); fl.Location = new Point(380, 124); fl.Size = new Size(216, 57); fl.Name = \"Myflowpanel\"; fl.Font = new Font(\"Calibri\", 12); fl.FlowDirection = FlowDirection.RightToLeft; fl.BorderStyle = BorderStyle.Fixed3D; fl.ForeColor = Color.BlueViolet; fl.Visible = true; // Adding this control to the form this.Controls.Add(fl); // Creating and setting the // properties of radio buttons RadioButton f1 = new RadioButton(); f1.Location = new Point(3, 3); f1.Size = new Size(95, 20); f1.Text = \"R1\"; // Adding this control // to the FlowLayoutPanel fl.Controls.Add(f1); RadioButton f2 = new RadioButton(); f2.Location = new Point(94, 3); f2.Size = new Size(95, 20); f2.Text = \"R2\"; // Adding this control // to the FlowLayoutPanel fl.Controls.Add(f2); RadioButton f3 = new RadioButton(); f3.Location = new Point(3, 26); f3.Size = new Size(95, 20); f3.Text = \"R3\"; // Adding this control // to the FlowLayoutPanel fl.Controls.Add(f3); }}}",
"e": 7034,
"s": 5338,
"text": null
},
{
"code": null,
"e": 7042,
"s": 7034,
"text": "Output:"
},
{
"code": null,
"e": 7073,
"s": 7042,
"text": "CSharp-Windows-Forms-Namespace"
},
{
"code": null,
"e": 7076,
"s": 7073,
"text": "C#"
}
] |
Tree of Space – Locking and Unlocking N-Ary Tree | 21 Nov, 2021
Given a world map in the form of Generic M-ary Tree consisting of N nodes and an array queries[], the task is to implement the functions Lock, Unlock and Upgrade for the given tree. For each query in queries[], the functions return true when the operation is performed successfully, otherwise it returns false. The functions are defined as:
X: Name of the node in the tree and will be uniqueuid: User Id for the person who accesses node X
1. Lock(X, uid): Lock takes exclusive access to the subtree rooted.
Once Lock(X, uid) succeeds, then lock(A, any user) should fail, where A is a descendant of X.
Lock(B. any user) should fail where X is a descendant of B.
Lock operation cannot be performed on a node that is already locked.
2. Unlock(X, uid): To unlock the locked node.
The unlock reverts what was done by the Lock operation.
It can only be called on same and unlocked by same uid.
3. UpgradeLock(X, uid): The user uid can upgrade their lock to an ancestor node.
It is only possible if any ancestor node is only locked by the same user uid.
The Upgrade should fail if there is any node that is locked by some other uid Y below.
Examples:
Input: N = 7, M = 2, nodes = [‘World’, ‘Asia’, ‘Africa’, ‘China’, ‘India’, ‘SouthAfrica’, ‘Egypt’], queries = [‘1 China 9’, ‘1 India 9’, ‘3 Asia 9’, ‘2 India 9’, ‘2 Asia 9’]Output: true true true false true
Input: N = 3, M = 2, nodes = [‘World’, ‘China’, ‘India’], queries = [‘3 India 1’, ‘1 World 9’]Output: false true
Below is the implementation of the above approach:
Python3
# Python Implementation # Locking functiondef lock(name): ind = nodes.index(name)+1 c1 = ind * 2 c2 = ind * 2 + 1 if status[name] == 'lock' \ or status[name] == 'fail': return 'false' else: p = ind//2 status[nodes[p-1]] = 'fail' status[name] = 'lock' return 'true' # Unlocking functiondef unlock(name): if status[name] == 'lock': status[name] = 'unlock' return 'true' else: return 'false' # Upgrade functiondef upgrade(name): ind = nodes.index(name)+1 # left child of ind c1 = ind * 2 # right child of ind c2 = ind * 2 + 1 if c1 in range(1, n) and c2 in range(1, n): if status[nodes[c1-1]] == 'lock' \ and status[nodes[c2-1]] == 'lock': status[nodes[c1-1]] = 'unlock' status[nodes[c2-1]] = 'unlock' status[nodes[ind-1]] = 'lock' return 'true' else: return 'false' # Precomputationdef precompute(queries): d = [] # Traversing the queries for j in queries: i = j.split() d.append(i[1]) d.append(int(i[0])) status = {} for j in range(0, len(d)-1, 2): status[d[j]] = 0 return status, d # Function to perform operationsdef operation(name, code): result = 'false' # Choose operation to perform if code == 1: result = lock(name) elif code == 2: result = unlock(name) elif code == 3: result = upgrade(name) return result # Driver Codeif __name__ == '__main__': # Given Input n = 7;m = 2 apis = 5 nodes = ['World', 'Asia', \ 'Africa', 'China', \ 'India', 'SouthAfrica', 'Egypt'] queries = ['1 China 9', '1 India 9', \ '3 Asia 9', '2 India 9', '2 Asia 9'] # Precomputation status, d = precompute(queries) # Function Call for j in range(0, len(d) - 1, 2): print(operation(d[j], d[j + 1]), end = ' ')
true true true false true
Time Complexity: O(LogN)Auxiliary Space: O(N)
chakkritip
kalrap615
Juspay
Binary Search Tree
Tree
Binary Search Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Merge Two Balanced Binary Search Trees
Inorder Successor in Binary Search Tree
Convert a normal BST to Balanced BST
Floor and Ceil from a BST
Print Right View of a Binary Tree
Binary Tree | Set 1 (Introduction)
Introduction to Data Structures
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 3 (Types of Binary Tree) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Nov, 2021"
},
{
"code": null,
"e": 394,
"s": 52,
"text": "Given a world map in the form of Generic M-ary Tree consisting of N nodes and an array queries[], the task is to implement the functions Lock, Unlock and Upgrade for the given tree. For each query in queries[], the functions return true when the operation is performed successfully, otherwise it returns false. The functions are defined as: "
},
{
"code": null,
"e": 492,
"s": 394,
"text": "X: Name of the node in the tree and will be uniqueuid: User Id for the person who accesses node X"
},
{
"code": null,
"e": 560,
"s": 492,
"text": "1. Lock(X, uid): Lock takes exclusive access to the subtree rooted."
},
{
"code": null,
"e": 654,
"s": 560,
"text": "Once Lock(X, uid) succeeds, then lock(A, any user) should fail, where A is a descendant of X."
},
{
"code": null,
"e": 714,
"s": 654,
"text": "Lock(B. any user) should fail where X is a descendant of B."
},
{
"code": null,
"e": 783,
"s": 714,
"text": "Lock operation cannot be performed on a node that is already locked."
},
{
"code": null,
"e": 829,
"s": 783,
"text": "2. Unlock(X, uid): To unlock the locked node."
},
{
"code": null,
"e": 885,
"s": 829,
"text": "The unlock reverts what was done by the Lock operation."
},
{
"code": null,
"e": 941,
"s": 885,
"text": "It can only be called on same and unlocked by same uid."
},
{
"code": null,
"e": 1022,
"s": 941,
"text": "3. UpgradeLock(X, uid): The user uid can upgrade their lock to an ancestor node."
},
{
"code": null,
"e": 1100,
"s": 1022,
"text": "It is only possible if any ancestor node is only locked by the same user uid."
},
{
"code": null,
"e": 1187,
"s": 1100,
"text": "The Upgrade should fail if there is any node that is locked by some other uid Y below."
},
{
"code": null,
"e": 1197,
"s": 1187,
"text": "Examples:"
},
{
"code": null,
"e": 1406,
"s": 1197,
"text": "Input: N = 7, M = 2, nodes = [‘World’, ‘Asia’, ‘Africa’, ‘China’, ‘India’, ‘SouthAfrica’, ‘Egypt’], queries = [‘1 China 9’, ‘1 India 9’, ‘3 Asia 9’, ‘2 India 9’, ‘2 Asia 9’]Output: true true true false true"
},
{
"code": null,
"e": 1521,
"s": 1406,
"text": "Input: N = 3, M = 2, nodes = [‘World’, ‘China’, ‘India’], queries = [‘3 India 1’, ‘1 World 9’]Output: false true"
},
{
"code": null,
"e": 1572,
"s": 1521,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1580,
"s": 1572,
"text": "Python3"
},
{
"code": "# Python Implementation # Locking functiondef lock(name): ind = nodes.index(name)+1 c1 = ind * 2 c2 = ind * 2 + 1 if status[name] == 'lock' \\ or status[name] == 'fail': return 'false' else: p = ind//2 status[nodes[p-1]] = 'fail' status[name] = 'lock' return 'true' # Unlocking functiondef unlock(name): if status[name] == 'lock': status[name] = 'unlock' return 'true' else: return 'false' # Upgrade functiondef upgrade(name): ind = nodes.index(name)+1 # left child of ind c1 = ind * 2 # right child of ind c2 = ind * 2 + 1 if c1 in range(1, n) and c2 in range(1, n): if status[nodes[c1-1]] == 'lock' \\ and status[nodes[c2-1]] == 'lock': status[nodes[c1-1]] = 'unlock' status[nodes[c2-1]] = 'unlock' status[nodes[ind-1]] = 'lock' return 'true' else: return 'false' # Precomputationdef precompute(queries): d = [] # Traversing the queries for j in queries: i = j.split() d.append(i[1]) d.append(int(i[0])) status = {} for j in range(0, len(d)-1, 2): status[d[j]] = 0 return status, d # Function to perform operationsdef operation(name, code): result = 'false' # Choose operation to perform if code == 1: result = lock(name) elif code == 2: result = unlock(name) elif code == 3: result = upgrade(name) return result # Driver Codeif __name__ == '__main__': # Given Input n = 7;m = 2 apis = 5 nodes = ['World', 'Asia', \\ 'Africa', 'China', \\ 'India', 'SouthAfrica', 'Egypt'] queries = ['1 China 9', '1 India 9', \\ '3 Asia 9', '2 India 9', '2 Asia 9'] # Precomputation status, d = precompute(queries) # Function Call for j in range(0, len(d) - 1, 2): print(operation(d[j], d[j + 1]), end = ' ')",
"e": 3515,
"s": 1580,
"text": null
},
{
"code": null,
"e": 3541,
"s": 3515,
"text": "true true true false true"
},
{
"code": null,
"e": 3589,
"s": 3543,
"text": "Time Complexity: O(LogN)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 3600,
"s": 3589,
"text": "chakkritip"
},
{
"code": null,
"e": 3610,
"s": 3600,
"text": "kalrap615"
},
{
"code": null,
"e": 3617,
"s": 3610,
"text": "Juspay"
},
{
"code": null,
"e": 3636,
"s": 3617,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 3641,
"s": 3636,
"text": "Tree"
},
{
"code": null,
"e": 3660,
"s": 3641,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 3665,
"s": 3660,
"text": "Tree"
},
{
"code": null,
"e": 3763,
"s": 3665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3833,
"s": 3763,
"text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"
},
{
"code": null,
"e": 3872,
"s": 3833,
"text": "Merge Two Balanced Binary Search Trees"
},
{
"code": null,
"e": 3912,
"s": 3872,
"text": "Inorder Successor in Binary Search Tree"
},
{
"code": null,
"e": 3949,
"s": 3912,
"text": "Convert a normal BST to Balanced BST"
},
{
"code": null,
"e": 3975,
"s": 3949,
"text": "Floor and Ceil from a BST"
},
{
"code": null,
"e": 4009,
"s": 3975,
"text": "Print Right View of a Binary Tree"
},
{
"code": null,
"e": 4044,
"s": 4009,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 4076,
"s": 4044,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 4138,
"s": 4076,
"text": "Write a Program to Find the Maximum Depth or Height of a Tree"
}
] |
Multiple regression as a machine learning algorithm | by Mahbubul Alam | Towards Data Science | Previously I wrote a couple of pieces on multivariate modeling but they both focused on time series forecasting. If curious, go ahead and check out the posts on vector autoregression and panel data modeling. Writing on multivariate regression (i.e. multiple linear regression) was always on my list but something else was on its way — I started a series on anomaly detection techniques! Once started that series, I could not stop until I wrote 11 consecutive posts.
Today I’m back with multiple regression and here’s the plan — first I’ll define in broad terms what a multiple regression is, and then list some real-world use cases as examples. The second part is going to be a rapid implementation of multiple regression in Python, just to give a broad intuition. In the third part, I’ll dive a bit deeper following the typical machine learning workflow. I’ll end with some additional points to keep in mind while implementing linear regression
Before talking multiple regression let’s talk about simple linear regression.
Simple linear regression is one that has one dependent variable and only one independent variable. If “income” is explained by the “education” of an individual then the regression is expressed in terms of simple linear regression as follows:
Income= b0+ b1*Education+ e
Multiple regression goes one step further, and instead of one, there will be two or more independent variables. If we have an additional variable (let’s say “experience”) in the equation above then it becomes a multiple regression:
Income= b0+ b1*Education+ b2*Experience+ e
So why is multiple regression useful and how are they used in real-world data science?
Regression-based machine learning applications can be grouped into (at least) three different problem domains:
1) Quantifying relationships: We know that through correlation we can find the strength (expressed in terms of a number between 0–1) and direction (positive or negative) of the relationship between two variables. But multiple regression goes a step further and actually quantifies that relationship.
2) Prediction: Machine learning is all about prediction. Since regression has the capacity to quantify relationships, we can turn this capability into solving prediction problems. That means, if we know the level of education and years of experience of an individual, we should be able to predict what the level of salary should be for that individual using a regression equation (as the equation above).
3) Forecasting: The third problem domain for multiple regression is forecasting with time series analysis. Vector autoregression and panel data regression are two powerful forecasting techniques that use the principles of multiple regression.
Now here are some real-world application cases of multiple regression:
prediction of used-car prices based on make, model, year, shift, mpg and color
[make, model, year, shift, mpg] → car prices
prediction of the price for a house in the market based on location, lot size, number of beds, number of baths, neighborhood characteristics etc.
[location, lot size, # beds, # bath, crime rate, school ratings] → house prices
forecasting future revenue based on historical data such as expenditure on ads, marketing, customer characteristics etc.
[past ads expenditure $, marketing $, subscription rate] → revenue at time T
Now it’s time to show how multiple regression works in data scientists’ notebooks. First I will give an intuition with a fire-drill and then will dive a bit deeper. If you want to follow along, you can do so by downloading the automobile dataset from the UCI Machine Learning Repository.
The machine learning objective here is to predict the price of used cars based on their features.
import pandas as pdimport numpy as npfrom sklearn import linear_model
# import datadf = pd.read_csv("../automobile.csv")# select features X = df[["horsepower", "highway-mpg"]]y = df["price"]
# instantiate modelmodel = linear_model.LinearRegression()# fit modelmodel.fit(X, y)
# predicting price based 90 horsepower and 30 mpgmodel.predict([[90, 30]])# predicted price>> 11454.03
You’ve got the intuition with a simplified example of how multiple regression makes prediction of the price of a used car based on two features: horsepower and high-way mpg.
But the world we live in is complex and messy. Each of the steps I’ve shown above will need to be branched out further. For example, in Step 2 we imported data and assigned features to X, y variables, without doing any further analysis. But who doesn’t know that data wrangling alone can take upwards of 80% of all tasks in any machine learning project?
I’m not going to go into every situation you’ll encounter as a data scientist in the real-world but I’ll talk about some fundamental issues which are unavoidable.
I’m going to use a few libraries and modules to do some mandatory tasks.
data wrangling: pandas and numpy
multiple regression model: linear_model from sklearn
splitting training and testing data: train_test_split
model evaluation: r2_score
import pandas as pdimport numpy as npfrom sklearn import linear_modelfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import r2_score
First I’m reading the dataset in my environment (I’m using Jupyter notebook, by the way) and as a ritual, taking a peek at the first few rows.
# import datadata = pd.read_csv("../automobile.csv")data.head(2)
As you can see, there are many columns that barely fit in the window. So I’m going to get a list of all columns.
# all column namedata.columns>> 'symboling', 'normalized-losses', 'make', 'fuel-type', 'aspiration', 'num-of-doors', 'body-style', 'drive-wheels', 'engine-location', 'wheel-base', 'length', 'width', 'height', 'curb-weight', 'engine-type', 'num-of-cylinders', 'engine-size', 'fuel-system', 'bore', 'stroke', 'compression-ratio', 'horsepower', 'peak-rpm', 'city-mpg', 'highway-mpg', 'price'
(I’m not a car expert so I really don’t know what some of those columns represent, but in real-world data science, this is not a good excuse, some domain knowledge is essential).
I did few other things as part of data exploration and preparation which I’m skipping here (such as checking and converting data types, removing a couple of rows that had symbols like ‘?’ etc.), but suffice to reiterate my previous point that getting the data in the right format can be a real pain in the neck.
We want to predict price, so the dependent variable is already set. Now comes which features to use for prediction. Ideally I’d include all of the features in the initial model, but for this demo I’m choosing 1 categorical feature (i.e. make) and two numeric features (i.e. horsepower and highway-mpg) which I think most people would care about while choosing a car.
Following the ML convention, I’m designating the independent variables as X and the dependent variable as y.
# select data subsetdf = data[["make", "horsepower", "highway-mpg", "price"]]# select data for modelingX = df[["make", "horsepower", "highway-mpg"]]y = df["price"]
I’ve purposefully chosen a categorical variable (i.e. make) to highlight that you need to do some extra work to convert it into a machine-readable format (a.k.a. numbers!). There are several ways to do that such as with Label Encoder or One Hot Encoder — both available in sklearn module. But I’m going with the classical “dummy variable” approach, which converts categorical features into numerical dichotomous variables (0s and 1s).
At this stage, I’m also splitting data into training and testing set for model evaluation.
# create dummy variablesmake_dummy = pd.get_dummies(X["make"], drop_first = True)X = X.drop("make", axis = 1)X = pd.concat([X, make_dummy], axis = 1)# split data into train and testX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)
It’s always amazing to think that within the whole complex machine learning pipeline the easiest part is (in my opinion of course!) actually specifying the model. It’s just three easy steps of instantiate — fit — predict as in most ML algorithms. Of course, you have to parameterize the model and iterate it several times until you get the one that satisfies your criteria, but still, this step of the model building process gives me the least headache.
# instantiate model = LinearRegression()# fitmodel.fit(X_train, y_train)# predicty_pred = model.predict(X_test)
Now comes the moment of truth — how well does the model perform? There are many ways to evaluate model performance but in classical statistics, the performance of linear regression models is evaluated with R2 — which gives a value between 0 and 1, and the higher the R2 the better the model.
# model evaluationscore = r2_score(y_test, y_pred)print(score)# score>> 0.8135478081839133
In our demonstration we are getting a R2 value of 0.81, meaning 81% of the variation in the dependent variable (i.e. used car price) can be explained by the three independent variables (i.e. make, horsepower and highway-mpg). Of course, this metric can be improved by including more variables and trying with different combinations of them and by tuning model parameters — the topic of a separate discussion.
I felt like I could write forever on multiple regression, there are so many areas to cover but I have to stop somewhere. Here are few additional things to keep in mind while building a linear regression model for real-world application development:
while selecting features check for correlation between dependent and each independent variable separately. If they are not correlated, remove the feature from the model;
check for multicollinearity, the relationship between independent variables. Remove correlated features to avoid model overfitting;
there are a few ways to choose variables for the model. Forward selection and backward elimination are two of them. As the names suggest, in this process you add or remove one variable at a time and check mode performance;
I used R2 for model performance evaluation, but some people choose other metrics such as AIC, BIC, p-value etc.
To recap:
Multiple regression is a machine learning algorithm to predict a dependent variable with two or more predictors.
Multiple regression has numerous real-world applications in three problem domains: examining relationships between variables, making numerical predictions and time series forecasting.
If you have everything ready for model building, its implementation can be as simple as 4 easy steps as demonstrated in the “Fire Drill”. However, real hard work is wrangling with data and finding the right model through an iterative process.
I hope this was a useful post. If you have comments feel free to write them down below. You can follow me on Medium, Twitter or LinkedIn. | [
{
"code": null,
"e": 638,
"s": 172,
"text": "Previously I wrote a couple of pieces on multivariate modeling but they both focused on time series forecasting. If curious, go ahead and check out the posts on vector autoregression and panel data modeling. Writing on multivariate regression (i.e. multiple linear regression) was always on my list but something else was on its way — I started a series on anomaly detection techniques! Once started that series, I could not stop until I wrote 11 consecutive posts."
},
{
"code": null,
"e": 1118,
"s": 638,
"text": "Today I’m back with multiple regression and here’s the plan — first I’ll define in broad terms what a multiple regression is, and then list some real-world use cases as examples. The second part is going to be a rapid implementation of multiple regression in Python, just to give a broad intuition. In the third part, I’ll dive a bit deeper following the typical machine learning workflow. I’ll end with some additional points to keep in mind while implementing linear regression"
},
{
"code": null,
"e": 1196,
"s": 1118,
"text": "Before talking multiple regression let’s talk about simple linear regression."
},
{
"code": null,
"e": 1438,
"s": 1196,
"text": "Simple linear regression is one that has one dependent variable and only one independent variable. If “income” is explained by the “education” of an individual then the regression is expressed in terms of simple linear regression as follows:"
},
{
"code": null,
"e": 1466,
"s": 1438,
"text": "Income= b0+ b1*Education+ e"
},
{
"code": null,
"e": 1698,
"s": 1466,
"text": "Multiple regression goes one step further, and instead of one, there will be two or more independent variables. If we have an additional variable (let’s say “experience”) in the equation above then it becomes a multiple regression:"
},
{
"code": null,
"e": 1741,
"s": 1698,
"text": "Income= b0+ b1*Education+ b2*Experience+ e"
},
{
"code": null,
"e": 1828,
"s": 1741,
"text": "So why is multiple regression useful and how are they used in real-world data science?"
},
{
"code": null,
"e": 1939,
"s": 1828,
"text": "Regression-based machine learning applications can be grouped into (at least) three different problem domains:"
},
{
"code": null,
"e": 2239,
"s": 1939,
"text": "1) Quantifying relationships: We know that through correlation we can find the strength (expressed in terms of a number between 0–1) and direction (positive or negative) of the relationship between two variables. But multiple regression goes a step further and actually quantifies that relationship."
},
{
"code": null,
"e": 2644,
"s": 2239,
"text": "2) Prediction: Machine learning is all about prediction. Since regression has the capacity to quantify relationships, we can turn this capability into solving prediction problems. That means, if we know the level of education and years of experience of an individual, we should be able to predict what the level of salary should be for that individual using a regression equation (as the equation above)."
},
{
"code": null,
"e": 2887,
"s": 2644,
"text": "3) Forecasting: The third problem domain for multiple regression is forecasting with time series analysis. Vector autoregression and panel data regression are two powerful forecasting techniques that use the principles of multiple regression."
},
{
"code": null,
"e": 2958,
"s": 2887,
"text": "Now here are some real-world application cases of multiple regression:"
},
{
"code": null,
"e": 3037,
"s": 2958,
"text": "prediction of used-car prices based on make, model, year, shift, mpg and color"
},
{
"code": null,
"e": 3082,
"s": 3037,
"text": "[make, model, year, shift, mpg] → car prices"
},
{
"code": null,
"e": 3228,
"s": 3082,
"text": "prediction of the price for a house in the market based on location, lot size, number of beds, number of baths, neighborhood characteristics etc."
},
{
"code": null,
"e": 3308,
"s": 3228,
"text": "[location, lot size, # beds, # bath, crime rate, school ratings] → house prices"
},
{
"code": null,
"e": 3429,
"s": 3308,
"text": "forecasting future revenue based on historical data such as expenditure on ads, marketing, customer characteristics etc."
},
{
"code": null,
"e": 3506,
"s": 3429,
"text": "[past ads expenditure $, marketing $, subscription rate] → revenue at time T"
},
{
"code": null,
"e": 3794,
"s": 3506,
"text": "Now it’s time to show how multiple regression works in data scientists’ notebooks. First I will give an intuition with a fire-drill and then will dive a bit deeper. If you want to follow along, you can do so by downloading the automobile dataset from the UCI Machine Learning Repository."
},
{
"code": null,
"e": 3892,
"s": 3794,
"text": "The machine learning objective here is to predict the price of used cars based on their features."
},
{
"code": null,
"e": 3962,
"s": 3892,
"text": "import pandas as pdimport numpy as npfrom sklearn import linear_model"
},
{
"code": null,
"e": 4083,
"s": 3962,
"text": "# import datadf = pd.read_csv(\"../automobile.csv\")# select features X = df[[\"horsepower\", \"highway-mpg\"]]y = df[\"price\"]"
},
{
"code": null,
"e": 4168,
"s": 4083,
"text": "# instantiate modelmodel = linear_model.LinearRegression()# fit modelmodel.fit(X, y)"
},
{
"code": null,
"e": 4271,
"s": 4168,
"text": "# predicting price based 90 horsepower and 30 mpgmodel.predict([[90, 30]])# predicted price>> 11454.03"
},
{
"code": null,
"e": 4445,
"s": 4271,
"text": "You’ve got the intuition with a simplified example of how multiple regression makes prediction of the price of a used car based on two features: horsepower and high-way mpg."
},
{
"code": null,
"e": 4799,
"s": 4445,
"text": "But the world we live in is complex and messy. Each of the steps I’ve shown above will need to be branched out further. For example, in Step 2 we imported data and assigned features to X, y variables, without doing any further analysis. But who doesn’t know that data wrangling alone can take upwards of 80% of all tasks in any machine learning project?"
},
{
"code": null,
"e": 4962,
"s": 4799,
"text": "I’m not going to go into every situation you’ll encounter as a data scientist in the real-world but I’ll talk about some fundamental issues which are unavoidable."
},
{
"code": null,
"e": 5035,
"s": 4962,
"text": "I’m going to use a few libraries and modules to do some mandatory tasks."
},
{
"code": null,
"e": 5068,
"s": 5035,
"text": "data wrangling: pandas and numpy"
},
{
"code": null,
"e": 5121,
"s": 5068,
"text": "multiple regression model: linear_model from sklearn"
},
{
"code": null,
"e": 5175,
"s": 5121,
"text": "splitting training and testing data: train_test_split"
},
{
"code": null,
"e": 5202,
"s": 5175,
"text": "model evaluation: r2_score"
},
{
"code": null,
"e": 5360,
"s": 5202,
"text": "import pandas as pdimport numpy as npfrom sklearn import linear_modelfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import r2_score"
},
{
"code": null,
"e": 5503,
"s": 5360,
"text": "First I’m reading the dataset in my environment (I’m using Jupyter notebook, by the way) and as a ritual, taking a peek at the first few rows."
},
{
"code": null,
"e": 5568,
"s": 5503,
"text": "# import datadata = pd.read_csv(\"../automobile.csv\")data.head(2)"
},
{
"code": null,
"e": 5681,
"s": 5568,
"text": "As you can see, there are many columns that barely fit in the window. So I’m going to get a list of all columns."
},
{
"code": null,
"e": 6070,
"s": 5681,
"text": "# all column namedata.columns>> 'symboling', 'normalized-losses', 'make', 'fuel-type', 'aspiration', 'num-of-doors', 'body-style', 'drive-wheels', 'engine-location', 'wheel-base', 'length', 'width', 'height', 'curb-weight', 'engine-type', 'num-of-cylinders', 'engine-size', 'fuel-system', 'bore', 'stroke', 'compression-ratio', 'horsepower', 'peak-rpm', 'city-mpg', 'highway-mpg', 'price'"
},
{
"code": null,
"e": 6249,
"s": 6070,
"text": "(I’m not a car expert so I really don’t know what some of those columns represent, but in real-world data science, this is not a good excuse, some domain knowledge is essential)."
},
{
"code": null,
"e": 6561,
"s": 6249,
"text": "I did few other things as part of data exploration and preparation which I’m skipping here (such as checking and converting data types, removing a couple of rows that had symbols like ‘?’ etc.), but suffice to reiterate my previous point that getting the data in the right format can be a real pain in the neck."
},
{
"code": null,
"e": 6928,
"s": 6561,
"text": "We want to predict price, so the dependent variable is already set. Now comes which features to use for prediction. Ideally I’d include all of the features in the initial model, but for this demo I’m choosing 1 categorical feature (i.e. make) and two numeric features (i.e. horsepower and highway-mpg) which I think most people would care about while choosing a car."
},
{
"code": null,
"e": 7037,
"s": 6928,
"text": "Following the ML convention, I’m designating the independent variables as X and the dependent variable as y."
},
{
"code": null,
"e": 7201,
"s": 7037,
"text": "# select data subsetdf = data[[\"make\", \"horsepower\", \"highway-mpg\", \"price\"]]# select data for modelingX = df[[\"make\", \"horsepower\", \"highway-mpg\"]]y = df[\"price\"]"
},
{
"code": null,
"e": 7636,
"s": 7201,
"text": "I’ve purposefully chosen a categorical variable (i.e. make) to highlight that you need to do some extra work to convert it into a machine-readable format (a.k.a. numbers!). There are several ways to do that such as with Label Encoder or One Hot Encoder — both available in sklearn module. But I’m going with the classical “dummy variable” approach, which converts categorical features into numerical dichotomous variables (0s and 1s)."
},
{
"code": null,
"e": 7727,
"s": 7636,
"text": "At this stage, I’m also splitting data into training and testing set for model evaluation."
},
{
"code": null,
"e": 8001,
"s": 7727,
"text": "# create dummy variablesmake_dummy = pd.get_dummies(X[\"make\"], drop_first = True)X = X.drop(\"make\", axis = 1)X = pd.concat([X, make_dummy], axis = 1)# split data into train and testX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)"
},
{
"code": null,
"e": 8455,
"s": 8001,
"text": "It’s always amazing to think that within the whole complex machine learning pipeline the easiest part is (in my opinion of course!) actually specifying the model. It’s just three easy steps of instantiate — fit — predict as in most ML algorithms. Of course, you have to parameterize the model and iterate it several times until you get the one that satisfies your criteria, but still, this step of the model building process gives me the least headache."
},
{
"code": null,
"e": 8567,
"s": 8455,
"text": "# instantiate model = LinearRegression()# fitmodel.fit(X_train, y_train)# predicty_pred = model.predict(X_test)"
},
{
"code": null,
"e": 8859,
"s": 8567,
"text": "Now comes the moment of truth — how well does the model perform? There are many ways to evaluate model performance but in classical statistics, the performance of linear regression models is evaluated with R2 — which gives a value between 0 and 1, and the higher the R2 the better the model."
},
{
"code": null,
"e": 8950,
"s": 8859,
"text": "# model evaluationscore = r2_score(y_test, y_pred)print(score)# score>> 0.8135478081839133"
},
{
"code": null,
"e": 9359,
"s": 8950,
"text": "In our demonstration we are getting a R2 value of 0.81, meaning 81% of the variation in the dependent variable (i.e. used car price) can be explained by the three independent variables (i.e. make, horsepower and highway-mpg). Of course, this metric can be improved by including more variables and trying with different combinations of them and by tuning model parameters — the topic of a separate discussion."
},
{
"code": null,
"e": 9608,
"s": 9359,
"text": "I felt like I could write forever on multiple regression, there are so many areas to cover but I have to stop somewhere. Here are few additional things to keep in mind while building a linear regression model for real-world application development:"
},
{
"code": null,
"e": 9778,
"s": 9608,
"text": "while selecting features check for correlation between dependent and each independent variable separately. If they are not correlated, remove the feature from the model;"
},
{
"code": null,
"e": 9910,
"s": 9778,
"text": "check for multicollinearity, the relationship between independent variables. Remove correlated features to avoid model overfitting;"
},
{
"code": null,
"e": 10133,
"s": 9910,
"text": "there are a few ways to choose variables for the model. Forward selection and backward elimination are two of them. As the names suggest, in this process you add or remove one variable at a time and check mode performance;"
},
{
"code": null,
"e": 10245,
"s": 10133,
"text": "I used R2 for model performance evaluation, but some people choose other metrics such as AIC, BIC, p-value etc."
},
{
"code": null,
"e": 10255,
"s": 10245,
"text": "To recap:"
},
{
"code": null,
"e": 10368,
"s": 10255,
"text": "Multiple regression is a machine learning algorithm to predict a dependent variable with two or more predictors."
},
{
"code": null,
"e": 10552,
"s": 10368,
"text": "Multiple regression has numerous real-world applications in three problem domains: examining relationships between variables, making numerical predictions and time series forecasting."
},
{
"code": null,
"e": 10795,
"s": 10552,
"text": "If you have everything ready for model building, its implementation can be as simple as 4 easy steps as demonstrated in the “Fire Drill”. However, real hard work is wrangling with data and finding the right model through an iterative process."
}
] |
What is an object in Python? Explain with examples | A python is an object-oriented programming language. Almost everything in Python is considered as an object. An object has its own properties(attributes) and behavior(methods).
A class is a blueprint of the objects or can be termed as object constructor for creating objects.
One class can have many objects and value of properties for different objects can be different.
Let’s take the example of car as an object. Its properties will include its color, company name, year of manufacture , price , mileage etc. The behavior of the car will include the functions it can perform, this will include increase speed, decrease speed, apply brakes etc. Object basically related everything with real life objects. Everything we find around us in real life has some properties and some functions.
Different objects belonging to same class can have different properties. For example, Person(Human) can be treated as a class which has properties such as name, age,gender etc. Every individual can be treated as an object of the class human or Person. Each individual will have different values of the properties of class Person.Everyone will have different names, age and gender.
An object is also called an instance of a class. Thus, the process of creating object of a class is known as instantiation.
As the function in Python is defined using the keyword ‘def’. The keyword ‘class’ is used to define a class in Python. Since the class is a blueprint of the object, all the common attributes and methods will be declared and defined in the class. Different objects which are created from the class can access those properties and functions. Different objects can hold their own values for properties defined inside the class.
Creating object of a class is simple. The name of the class must be known and object can be created as follows −
Object_name= class_name()
Live Demo
class Person:
name=""
age=0
city=""
def display(self):
print("Name : ",self.name)
print("Age : ",self.age)
print("City : ",self.city)
p1=Person()
p1.name="Rahul"
p1.age=20
p1.city="Kolkata"
p1.display()
print()
p2=Person()
p2.name="Karan"
p2.age=22
p2.city="Bangalore"
p2.display()
print()
p1.display()
In the above implementation, p1=Person() is the object instantiation. p1 is the name of the object . We accessed the properties of the class through object p1 and gave them different values and later called the display function to display values of this object.Later,we do the same for second object p2 and display properties of p2.
At the end, we again call display() for object p1 to show that each object holds its own value of properties and those are independent of the other objects.
Name : Rahul
Age : 20
City : Kolkata
Name : Karan
Age : 22
City : Bangalore
Name : Rahul
Age : 20
City : Kolkata | [
{
"code": null,
"e": 1239,
"s": 1062,
"text": "A python is an object-oriented programming language. Almost everything in Python is considered as an object. An object has its own properties(attributes) and behavior(methods)."
},
{
"code": null,
"e": 1338,
"s": 1239,
"text": "A class is a blueprint of the objects or can be termed as object constructor for creating objects."
},
{
"code": null,
"e": 1434,
"s": 1338,
"text": "One class can have many objects and value of properties for different objects can be different."
},
{
"code": null,
"e": 1851,
"s": 1434,
"text": "Let’s take the example of car as an object. Its properties will include its color, company name, year of manufacture , price , mileage etc. The behavior of the car will include the functions it can perform, this will include increase speed, decrease speed, apply brakes etc. Object basically related everything with real life objects. Everything we find around us in real life has some properties and some functions."
},
{
"code": null,
"e": 2232,
"s": 1851,
"text": "Different objects belonging to same class can have different properties. For example, Person(Human) can be treated as a class which has properties such as name, age,gender etc. Every individual can be treated as an object of the class human or Person. Each individual will have different values of the properties of class Person.Everyone will have different names, age and gender."
},
{
"code": null,
"e": 2356,
"s": 2232,
"text": "An object is also called an instance of a class. Thus, the process of creating object of a class is known as instantiation."
},
{
"code": null,
"e": 2781,
"s": 2356,
"text": "As the function in Python is defined using the keyword ‘def’. The keyword ‘class’ is used to define a class in Python. Since the class is a blueprint of the object, all the common attributes and methods will be declared and defined in the class. Different objects which are created from the class can access those properties and functions. Different objects can hold their own values for properties defined inside the class."
},
{
"code": null,
"e": 2894,
"s": 2781,
"text": "Creating object of a class is simple. The name of the class must be known and object can be created as follows −"
},
{
"code": null,
"e": 2920,
"s": 2894,
"text": "Object_name= class_name()"
},
{
"code": null,
"e": 2931,
"s": 2920,
"text": " Live Demo"
},
{
"code": null,
"e": 3268,
"s": 2931,
"text": "class Person:\n name=\"\"\n age=0\n city=\"\"\n def display(self):\n print(\"Name : \",self.name)\n print(\"Age : \",self.age)\n print(\"City : \",self.city)\n\np1=Person()\np1.name=\"Rahul\"\np1.age=20\np1.city=\"Kolkata\"\np1.display()\n\nprint()\n\np2=Person()\np2.name=\"Karan\"\np2.age=22\np2.city=\"Bangalore\"\np2.display()\n\nprint()\np1.display()"
},
{
"code": null,
"e": 3601,
"s": 3268,
"text": "In the above implementation, p1=Person() is the object instantiation. p1 is the name of the object . We accessed the properties of the class through object p1 and gave them different values and later called the display function to display values of this object.Later,we do the same for second object p2 and display properties of p2."
},
{
"code": null,
"e": 3758,
"s": 3601,
"text": "At the end, we again call display() for object p1 to show that each object holds its own value of properties and those are independent of the other objects."
},
{
"code": null,
"e": 3871,
"s": 3758,
"text": "Name : Rahul\nAge : 20\nCity : Kolkata\nName : Karan\nAge : 22\nCity : Bangalore\nName : Rahul\nAge : 20\nCity : Kolkata"
}
] |
ReactJS | Keys | 11 May, 2022
In the previous article on ReactJS | Lists, we had discussed Keys and also told why they are needed while creating lists. We will continue the discussion further in this article.
A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used to React to identify which items in the list are changed, updated, or deleted. In other words, we can say that keys are used to give an identity to the elements in the lists. The next thing that comes to mind is that what should be good to be chosen as key for the items in lists. It is recommended to use a string as a key that uniquely identifies the items in the list. Below example shows a list with string keys:
Javascript
const numbers = [ 1, 2, 3, 4, 5 ]; const updatedNums = numbers.map((number)=>{return <li key={index}>{number} </li>;});
You can also assign the array indexes as keys to the list items. The below example assigns array indexes as key to the elements.
Javascript
const numbers = [ 1, 2, 3, 4, 5 ]; const updatedNums = numbers.map((number, index)=><li key = {index}>{number} </li>);
Assigning indexes as keys are highly discouraged because if the elements of the arrays get reordered in the future then it will get confusing for the developer as the keys for the elements will also change.
Using Keys with Components
Consider a situation where you have created a separate component for list items and you are extracting list items from that component. In that case, you will have to assign keys to the component you are returning from the iterator and not to the list items. That is you should assign keys to <Component /> and not to <li> A good practice to avoid mistakes is to keep in mind that anything you are returning from inside of the map() function is needed to be assigned key.
Below code shows incorrect usage of keys:
Javascript
import React from 'react';import ReactDOM from 'react-dom';// Component to be extractedfunction MenuItems(props){const item = props.item;return(<li key = {item.toString()}>{item}</li> );} // Component that will return an// unordered listfunction Navmenu(props){const list = props.menuitems;const updatedList = list.map((listItems)=>{return (<MenuItems item = { listItems } /> ); }); return(<ul>{updatedList}</ul>);} const menuItems = [1, 2, 3, 4, 5]; ReactDOM.render(<Navmenu menuitems = {menuItems} />, document.getElementById('root'));
Output:
You can see in the above output that the list is rendered successfully but a warning is thrown to the console that the elements inside the iterator are not assigned keys. This is because we had not assigned key to the elements we are returning to the map() iterator.
Below example shows correct usage of keys:
Javascript
import React from "react";import ReactDOM from "react-dom";// Component to be extractedfunction MenuItems(props) { const item = props.item; return <li>{item}</li>;} // Component that will return an// unordered listfunction Navmenu(props) { const list = props.menuitems; const updatedList = list.map((listItems) => { return <MenuItems key={listItems.toString()} item={listItems} />; }); return <ul>{updatedList}</ul>;} const menuItems = [1, 2, 3, 4, 5]; ReactDOM.render( <Navmenu menuitems={menuItems} />, document.getElementById("root"));
The above code will run successfully without any warning message.
Uniqueness of Keys
We have told many times while discussing about keys that keys assigned to the array elements must be unique. By this, we did not mean that the keys should be globally unique. All the elements in a particular array should have unique keys. That is, two different arrays can have the same set of keys.In the below code we have created two different arrays menuItems1 and menuItems2. You can see in the below code that the keys for the first 5 items for both arrays are the same still the code runs successfully without any warning.
Javascript
import React from "react";import ReactDOM from "react-dom";// Component to be extractedfunction MenuItems(props) { const item = props.item; return <li>{item}</li>;} // Component that will return an// unordered listfunction Navmenu(props) { const list = props.menuitems; const updatedList = list.map((listItems) => { return <MenuItems key={listItems.toString()} item={listItems} />; }); return <ul>{updatedList}</ul>;} const menuItems1 = [1, 2, 3, 4, 5];const menuItems2 = [1, 2, 3, 4, 5, 6]; ReactDOM.render( <div> <Navmenu menuitems={menuItems1} /> <Navmenu menuitems={menuItems2} /> </div>, document.getElementById("root"));
Output:
Note: Keys are not the same as props, only the method of assigning “key” to a component is the same as that of props. Keys are internal to React and can not be accessed from inside of the component like props. Therefore, we can use the same value we have assigned to the Key for any other prop we are passing to the Component.
nidhi_biet
shubhamyadav4
9om0sk493pl0h8zi519ok9azwd0grd2zvp1pe1ez
react-js
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS setState()
How to pass data from one component to other component in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 231,
"s": 52,
"text": "In the previous article on ReactJS | Lists, we had discussed Keys and also told why they are needed while creating lists. We will continue the discussion further in this article."
},
{
"code": null,
"e": 764,
"s": 231,
"text": "A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used to React to identify which items in the list are changed, updated, or deleted. In other words, we can say that keys are used to give an identity to the elements in the lists. The next thing that comes to mind is that what should be good to be chosen as key for the items in lists. It is recommended to use a string as a key that uniquely identifies the items in the list. Below example shows a list with string keys: "
},
{
"code": null,
"e": 775,
"s": 764,
"text": "Javascript"
},
{
"code": "const numbers = [ 1, 2, 3, 4, 5 ]; const updatedNums = numbers.map((number)=>{return <li key={index}>{number} </li>;});",
"e": 896,
"s": 775,
"text": null
},
{
"code": null,
"e": 1026,
"s": 896,
"text": "You can also assign the array indexes as keys to the list items. The below example assigns array indexes as key to the elements. "
},
{
"code": null,
"e": 1037,
"s": 1026,
"text": "Javascript"
},
{
"code": "const numbers = [ 1, 2, 3, 4, 5 ]; const updatedNums = numbers.map((number, index)=><li key = {index}>{number} </li>);",
"e": 1157,
"s": 1037,
"text": null
},
{
"code": null,
"e": 1365,
"s": 1157,
"text": "Assigning indexes as keys are highly discouraged because if the elements of the arrays get reordered in the future then it will get confusing for the developer as the keys for the elements will also change. "
},
{
"code": null,
"e": 1392,
"s": 1365,
"text": "Using Keys with Components"
},
{
"code": null,
"e": 1864,
"s": 1392,
"text": "Consider a situation where you have created a separate component for list items and you are extracting list items from that component. In that case, you will have to assign keys to the component you are returning from the iterator and not to the list items. That is you should assign keys to <Component /> and not to <li> A good practice to avoid mistakes is to keep in mind that anything you are returning from inside of the map() function is needed to be assigned key. "
},
{
"code": null,
"e": 1907,
"s": 1864,
"text": "Below code shows incorrect usage of keys: "
},
{
"code": null,
"e": 1918,
"s": 1907,
"text": "Javascript"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom';// Component to be extractedfunction MenuItems(props){const item = props.item;return(<li key = {item.toString()}>{item}</li> );} // Component that will return an// unordered listfunction Navmenu(props){const list = props.menuitems;const updatedList = list.map((listItems)=>{return (<MenuItems item = { listItems } /> ); }); return(<ul>{updatedList}</ul>);} const menuItems = [1, 2, 3, 4, 5]; ReactDOM.render(<Navmenu menuitems = {menuItems} />, document.getElementById('root')); ",
"e": 2485,
"s": 1918,
"text": null
},
{
"code": null,
"e": 2494,
"s": 2485,
"text": "Output: "
},
{
"code": null,
"e": 2761,
"s": 2494,
"text": "You can see in the above output that the list is rendered successfully but a warning is thrown to the console that the elements inside the iterator are not assigned keys. This is because we had not assigned key to the elements we are returning to the map() iterator."
},
{
"code": null,
"e": 2805,
"s": 2761,
"text": "Below example shows correct usage of keys: "
},
{
"code": null,
"e": 2816,
"s": 2805,
"text": "Javascript"
},
{
"code": "import React from \"react\";import ReactDOM from \"react-dom\";// Component to be extractedfunction MenuItems(props) { const item = props.item; return <li>{item}</li>;} // Component that will return an// unordered listfunction Navmenu(props) { const list = props.menuitems; const updatedList = list.map((listItems) => { return <MenuItems key={listItems.toString()} item={listItems} />; }); return <ul>{updatedList}</ul>;} const menuItems = [1, 2, 3, 4, 5]; ReactDOM.render( <Navmenu menuitems={menuItems} />, document.getElementById(\"root\"));",
"e": 3391,
"s": 2816,
"text": null
},
{
"code": null,
"e": 3458,
"s": 3391,
"text": "The above code will run successfully without any warning message. "
},
{
"code": null,
"e": 3477,
"s": 3458,
"text": "Uniqueness of Keys"
},
{
"code": null,
"e": 4008,
"s": 3477,
"text": "We have told many times while discussing about keys that keys assigned to the array elements must be unique. By this, we did not mean that the keys should be globally unique. All the elements in a particular array should have unique keys. That is, two different arrays can have the same set of keys.In the below code we have created two different arrays menuItems1 and menuItems2. You can see in the below code that the keys for the first 5 items for both arrays are the same still the code runs successfully without any warning. "
},
{
"code": null,
"e": 4019,
"s": 4008,
"text": "Javascript"
},
{
"code": "import React from \"react\";import ReactDOM from \"react-dom\";// Component to be extractedfunction MenuItems(props) { const item = props.item; return <li>{item}</li>;} // Component that will return an// unordered listfunction Navmenu(props) { const list = props.menuitems; const updatedList = list.map((listItems) => { return <MenuItems key={listItems.toString()} item={listItems} />; }); return <ul>{updatedList}</ul>;} const menuItems1 = [1, 2, 3, 4, 5];const menuItems2 = [1, 2, 3, 4, 5, 6]; ReactDOM.render( <div> <Navmenu menuitems={menuItems1} /> <Navmenu menuitems={menuItems2} /> </div>, document.getElementById(\"root\"));",
"e": 4699,
"s": 4019,
"text": null
},
{
"code": null,
"e": 4707,
"s": 4699,
"text": "Output:"
},
{
"code": null,
"e": 5035,
"s": 4707,
"text": "Note: Keys are not the same as props, only the method of assigning “key” to a component is the same as that of props. Keys are internal to React and can not be accessed from inside of the component like props. Therefore, we can use the same value we have assigned to the Key for any other prop we are passing to the Component. "
},
{
"code": null,
"e": 5046,
"s": 5035,
"text": "nidhi_biet"
},
{
"code": null,
"e": 5060,
"s": 5046,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 5101,
"s": 5060,
"text": "9om0sk493pl0h8zi519ok9azwd0grd2zvp1pe1ez"
},
{
"code": null,
"e": 5110,
"s": 5101,
"text": "react-js"
},
{
"code": null,
"e": 5118,
"s": 5110,
"text": "ReactJS"
},
{
"code": null,
"e": 5135,
"s": 5118,
"text": "Web Technologies"
},
{
"code": null,
"e": 5233,
"s": 5135,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5276,
"s": 5233,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 5321,
"s": 5276,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 5359,
"s": 5321,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 5378,
"s": 5359,
"text": "ReactJS setState()"
},
{
"code": null,
"e": 5446,
"s": 5378,
"text": "How to pass data from one component to other component in ReactJS ?"
},
{
"code": null,
"e": 5508,
"s": 5446,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5541,
"s": 5508,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5602,
"s": 5541,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5652,
"s": 5602,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Number of words in a camelcase sequence | 03 May, 2021
CamelCase is the sequence of one or more than one words having the following properties:
It is a concatenation of one or more words consisting of English letters.All letters in the first word are lowercase.For each of the subsequent words, the first letter is uppercase and rest of the letters are lowercase.
It is a concatenation of one or more words consisting of English letters.
All letters in the first word are lowercase.
For each of the subsequent words, the first letter is uppercase and rest of the letters are lowercase.
Given a CamelCase sequence represented as a string. The task is to find the number of words in the CamelCase sequence. Examples:
Input : str = "geeksForGeeks"
Output : 3
Input : str = "iGotAnInternInGeeksForGeeks"
Output : 8
Approach: As it is already known that the sequence is CamelCase, so it can be said that the number of words in the sequence will be one more than the number of uppercase letters.
Iterate the sequence from the 2nd letter to the end of the sequence.
No. of words will be equal to uppercase letters+1 during the 1st step iteration.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// CPP code to find the count of words// in a CamelCase sequence#include <bits/stdc++.h>using namespace std; // Function to find the count of words// in a CamelCase sequenceint countWords(string str){ int count = 1; for (int i = 1; i < str.length() - 1; i++) { if (isupper(str[i])) count++; } return count;} // Driver codeint main(){ string str = "geeksForGeeks"; cout << countWords(str); return 0;}
// Java code to find the count of words// in a CamelCase sequenceclass solution{ // Function to find the count of words// in a CamelCase sequencestatic int countWords(String str){ int count = 1; for (int i = 1; i < str.length() - 1; i++) { if (str.charAt(i)>=65&&str.charAt(i)<=90) count++; } return count;} // Driver codepublic static void main(String args[]){ String str = "geeksForGeeks"; System.out.print( countWords(str)); }}//contributed by Arnab Kundu
# Python code to find the count of words# in a CamelCase sequence # Function to find the count of words# in a CamelCase sequencedef countWords(str): count = 1 for i in range(1, len(str) - 1): if (str[i].isupper()): count += 1 return count # Driver codestr = "geeksForGeeks";print(countWords(str)) # This code is contributed# by sahishelangia
// C# code to find the count of words// in a CamelCase sequenceusing System; class GFG{ // Function to find the count of words// in a CamelCase sequencestatic int countWords(String str){ int count = 1; for (int i = 1; i < str.Length - 1; i++) { if (str[i] >= 65 && str[i] <= 90) count++; } return count;} // Driver codepublic static void Main(String []args){ String str = "geeksForGeeks"; Console.Write(countWords(str)); }} // This code contributed by Rajput-Ji
<script> // Javascript code to find the count of words// in a CamelCase sequence // Function to find the count of words// in a CamelCase sequencefunction countWords(str){ let count = 1; for (let i = 1; i < str.length - 1; i++) { if (str[i]>= 'A' && str[i]<= 'Z') count++; } return count;} // driver program let str = "geeksForGeeks"; document.write( countWords(str)); </script>
3
andrew1234
sahilshelangia
Rajput-Ji
susmitakundugoaldanga
Constructive Algorithms
math
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Length of the longest substring without repeating characters
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
Convert string to char array in C++
Reverse words in a given string
What is Data Structure: Types, Classifications and Applications
Print all the duplicates in the input string
Reverse string in Python (6 different ways)
Remove duplicates from a given string
Array of Strings in C++ - 5 Different Ways to Create | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 May, 2021"
},
{
"code": null,
"e": 143,
"s": 52,
"text": "CamelCase is the sequence of one or more than one words having the following properties: "
},
{
"code": null,
"e": 363,
"s": 143,
"text": "It is a concatenation of one or more words consisting of English letters.All letters in the first word are lowercase.For each of the subsequent words, the first letter is uppercase and rest of the letters are lowercase."
},
{
"code": null,
"e": 437,
"s": 363,
"text": "It is a concatenation of one or more words consisting of English letters."
},
{
"code": null,
"e": 482,
"s": 437,
"text": "All letters in the first word are lowercase."
},
{
"code": null,
"e": 585,
"s": 482,
"text": "For each of the subsequent words, the first letter is uppercase and rest of the letters are lowercase."
},
{
"code": null,
"e": 716,
"s": 585,
"text": "Given a CamelCase sequence represented as a string. The task is to find the number of words in the CamelCase sequence. Examples: "
},
{
"code": null,
"e": 813,
"s": 716,
"text": "Input : str = \"geeksForGeeks\"\nOutput : 3\n\nInput : str = \"iGotAnInternInGeeksForGeeks\"\nOutput : 8"
},
{
"code": null,
"e": 996,
"s": 815,
"text": "Approach: As it is already known that the sequence is CamelCase, so it can be said that the number of words in the sequence will be one more than the number of uppercase letters. "
},
{
"code": null,
"e": 1065,
"s": 996,
"text": "Iterate the sequence from the 2nd letter to the end of the sequence."
},
{
"code": null,
"e": 1146,
"s": 1065,
"text": "No. of words will be equal to uppercase letters+1 during the 1st step iteration."
},
{
"code": null,
"e": 1199,
"s": 1146,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1203,
"s": 1199,
"text": "C++"
},
{
"code": null,
"e": 1208,
"s": 1203,
"text": "Java"
},
{
"code": null,
"e": 1216,
"s": 1208,
"text": "Python3"
},
{
"code": null,
"e": 1219,
"s": 1216,
"text": "C#"
},
{
"code": null,
"e": 1230,
"s": 1219,
"text": "Javascript"
},
{
"code": "// CPP code to find the count of words// in a CamelCase sequence#include <bits/stdc++.h>using namespace std; // Function to find the count of words// in a CamelCase sequenceint countWords(string str){ int count = 1; for (int i = 1; i < str.length() - 1; i++) { if (isupper(str[i])) count++; } return count;} // Driver codeint main(){ string str = \"geeksForGeeks\"; cout << countWords(str); return 0;}",
"e": 1673,
"s": 1230,
"text": null
},
{
"code": "// Java code to find the count of words// in a CamelCase sequenceclass solution{ // Function to find the count of words// in a CamelCase sequencestatic int countWords(String str){ int count = 1; for (int i = 1; i < str.length() - 1; i++) { if (str.charAt(i)>=65&&str.charAt(i)<=90) count++; } return count;} // Driver codepublic static void main(String args[]){ String str = \"geeksForGeeks\"; System.out.print( countWords(str)); }}//contributed by Arnab Kundu",
"e": 2171,
"s": 1673,
"text": null
},
{
"code": "# Python code to find the count of words# in a CamelCase sequence # Function to find the count of words# in a CamelCase sequencedef countWords(str): count = 1 for i in range(1, len(str) - 1): if (str[i].isupper()): count += 1 return count # Driver codestr = \"geeksForGeeks\";print(countWords(str)) # This code is contributed# by sahishelangia",
"e": 2541,
"s": 2171,
"text": null
},
{
"code": "// C# code to find the count of words// in a CamelCase sequenceusing System; class GFG{ // Function to find the count of words// in a CamelCase sequencestatic int countWords(String str){ int count = 1; for (int i = 1; i < str.Length - 1; i++) { if (str[i] >= 65 && str[i] <= 90) count++; } return count;} // Driver codepublic static void Main(String []args){ String str = \"geeksForGeeks\"; Console.Write(countWords(str)); }} // This code contributed by Rajput-Ji",
"e": 3049,
"s": 2541,
"text": null
},
{
"code": "<script> // Javascript code to find the count of words// in a CamelCase sequence // Function to find the count of words// in a CamelCase sequencefunction countWords(str){ let count = 1; for (let i = 1; i < str.length - 1; i++) { if (str[i]>= 'A' && str[i]<= 'Z') count++; } return count;} // driver program let str = \"geeksForGeeks\"; document.write( countWords(str)); </script>",
"e": 3475,
"s": 3049,
"text": null
},
{
"code": null,
"e": 3477,
"s": 3475,
"text": "3"
},
{
"code": null,
"e": 3490,
"s": 3479,
"text": "andrew1234"
},
{
"code": null,
"e": 3505,
"s": 3490,
"text": "sahilshelangia"
},
{
"code": null,
"e": 3515,
"s": 3505,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 3537,
"s": 3515,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 3561,
"s": 3537,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 3566,
"s": 3561,
"text": "math"
},
{
"code": null,
"e": 3574,
"s": 3566,
"text": "Strings"
},
{
"code": null,
"e": 3582,
"s": 3574,
"text": "Strings"
},
{
"code": null,
"e": 3680,
"s": 3582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3741,
"s": 3680,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 3793,
"s": 3741,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 3838,
"s": 3793,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 3874,
"s": 3838,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 3906,
"s": 3874,
"text": "Reverse words in a given string"
},
{
"code": null,
"e": 3970,
"s": 3906,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 4015,
"s": 3970,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 4059,
"s": 4015,
"text": "Reverse string in Python (6 different ways)"
},
{
"code": null,
"e": 4097,
"s": 4059,
"text": "Remove duplicates from a given string"
}
] |
Program for triangular pattern (mirror image around 0) | 18 Jun, 2022
Given the value of n, print the pattern.Examples :
Input : n = 5
Output :
0
101
21012
3210123
432101234
Input : n = 7
Output :
0
101
21012
3210123
432101234
54321012345
6543210123456
Below is the program to print the above pattern
C++
Java
Python3
C#
PHP
Javascript
// C++ Implementation to print the pattern#include <bits/stdc++.h>using namespace std; // Function definitionvoid print(int n){ int var1 = 1, var2 = 1; // Outer for loop to keep // track of number of lines for (int i = 0; i < n; i++) { // for loop to keep track // of spaces for (int j = n - 1; j > i; j--) { cout << " "; } // for loop to print the // digits in pattern for (int k = 1; k <= var1; k++) { cout << abs(k - var2); } var1 += 2; var2++; cout << "\n"; }} // Driver codeint main(){ // taking size from the user int n = 5; // function calling print(n); return 0;}
// Java Implementation to print the pattern class GFG{ // Function definition static void print(int n) { int var1 = 1, var2 = 1; // Outer for loop to keep // track of number of lines for (int i = 0; i < n; i++) { // for loop to keep track // of spaces for (int j = n - 1; j > i; j--) { System.out.print(" "); } // for loop to print the // digits in pattern for (int k = 1; k <= var1; k++) { System.out.print(Math.abs(k - var2)); } var1 += 2; var2++; System.out.println(); } } // Driver code public static void main (String[] args) { // taking size from the user int n = 5; // function calling print(n); }} // This code is contributed by Anant Agarwal.
# Python Implementation to# print the pattern # Function definitiondef printt(n): var1 = 1 var2 = 1 # Outer for loop to keep # track of number of lines for i in range(n): # for loop to keep track # of spaces for j in range(n - 1,i,-1): print(" ", end = "") # for loop to print the # digits in pattern for k in range(1, var1 + 1): print(abs(k - var2), end="") var1 += 2 var2 += 1 print() # Driver code# taking size from the usern = 5 # function callingprintt(n) # This code is contributed# by Anant Agarwal.
//C# Implementation to print the patternusing System;class GFG{ // Function definition static void print(int n) { int var1 = 1, var2 = 1; // Outer for loop to keep // track of number of lines for (int i = 0; i < n; i++) { // for loop to keep track // of spaces for (int j = n - 1; j > i; j--) { Console.Write(" "); } // for loop to print the // digits in pattern for (int k = 1; k <= var1; k++) { Console.Write(Math.Abs(k - var2)); } var1 += 2; var2++; Console.WriteLine(); } } // Driver code public static void Main () { // taking size from the user int n = 5; // function calling print(n); }} // This code is contributed by vt_m.
<?php// PHP Implementation to// print the pattern // Function definitionfunction print1($n){ $var1 = 1; $var2 = 1; // Outer for loop to keep // track of number of lines for ($i = 0; $i < $n; $i++) { // for loop to keep track // of spaces for ($j = $n - 1; $j > $i; $j--) { echo " "; } // for loop to print the // digits in pattern for ($k = 1; $k <= $var1; $k++) { echo abs($k - $var2); } $var1 += 2; $var2++; echo "\n"; }} // Driver code$n = 5;print1($n); // This code is contributed by mits?>
<script>// javascript Implementation to print the pattern // Function definitionfunction print( n){ let var1 = 1, var2 = 1; // Outer for loop to keep // track of number of lines for (let i = 0; i < n; i++) { // for loop to keep track // of spaces for (let j = n - 1; j > i; j--) { document.write(" "); } // for loop to print the // digits in pattern for (let k = 1; k <= var1; k++) { document.write(Math.abs(k - var2)); } var1 += 2; var2++; document.write("<br/>"); }} // Driver code // taking size from the user let n = 5; // function calling print(n); // This code is contributed by aashish1995 </script>
Output :
0
101
21012
3210123
432101234
Time Complexity : O(n*n) ,where n is the number of rows in pattern
Auxiliary Space : O(1)
Mithun Kumar
aashish1995
adityapatil12
pattern-printing
triangle
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction To PYTHON
Constructors in Java
Exceptions in Java
Friend class and function in C++
Classes and Objects in Java
Python Exception Handling
Programs for printing pyramid patterns in Python
Python Try Except
Python program to check whether a number is Prime or not
Inline Functions in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Jun, 2022"
},
{
"code": null,
"e": 105,
"s": 52,
"text": "Given the value of n, print the pattern.Examples : "
},
{
"code": null,
"e": 271,
"s": 105,
"text": "Input : n = 5\nOutput : \n 0\n 101\n 21012\n 3210123\n432101234\n\nInput : n = 7\nOutput : \n 0\n 101\n 21012\n 3210123\n 432101234\n 54321012345\n6543210123456"
},
{
"code": null,
"e": 323,
"s": 273,
"text": "Below is the program to print the above pattern "
},
{
"code": null,
"e": 327,
"s": 323,
"text": "C++"
},
{
"code": null,
"e": 332,
"s": 327,
"text": "Java"
},
{
"code": null,
"e": 340,
"s": 332,
"text": "Python3"
},
{
"code": null,
"e": 343,
"s": 340,
"text": "C#"
},
{
"code": null,
"e": 347,
"s": 343,
"text": "PHP"
},
{
"code": null,
"e": 358,
"s": 347,
"text": "Javascript"
},
{
"code": "// C++ Implementation to print the pattern#include <bits/stdc++.h>using namespace std; // Function definitionvoid print(int n){ int var1 = 1, var2 = 1; // Outer for loop to keep // track of number of lines for (int i = 0; i < n; i++) { // for loop to keep track // of spaces for (int j = n - 1; j > i; j--) { cout << \" \"; } // for loop to print the // digits in pattern for (int k = 1; k <= var1; k++) { cout << abs(k - var2); } var1 += 2; var2++; cout << \"\\n\"; }} // Driver codeint main(){ // taking size from the user int n = 5; // function calling print(n); return 0;}",
"e": 1068,
"s": 358,
"text": null
},
{
"code": "// Java Implementation to print the pattern class GFG{ // Function definition static void print(int n) { int var1 = 1, var2 = 1; // Outer for loop to keep // track of number of lines for (int i = 0; i < n; i++) { // for loop to keep track // of spaces for (int j = n - 1; j > i; j--) { System.out.print(\" \"); } // for loop to print the // digits in pattern for (int k = 1; k <= var1; k++) { System.out.print(Math.abs(k - var2)); } var1 += 2; var2++; System.out.println(); } } // Driver code public static void main (String[] args) { // taking size from the user int n = 5; // function calling print(n); }} // This code is contributed by Anant Agarwal.",
"e": 2012,
"s": 1068,
"text": null
},
{
"code": "# Python Implementation to# print the pattern # Function definitiondef printt(n): var1 = 1 var2 = 1 # Outer for loop to keep # track of number of lines for i in range(n): # for loop to keep track # of spaces for j in range(n - 1,i,-1): print(\" \", end = \"\") # for loop to print the # digits in pattern for k in range(1, var1 + 1): print(abs(k - var2), end=\"\") var1 += 2 var2 += 1 print() # Driver code# taking size from the usern = 5 # function callingprintt(n) # This code is contributed# by Anant Agarwal.",
"e": 2634,
"s": 2012,
"text": null
},
{
"code": "//C# Implementation to print the patternusing System;class GFG{ // Function definition static void print(int n) { int var1 = 1, var2 = 1; // Outer for loop to keep // track of number of lines for (int i = 0; i < n; i++) { // for loop to keep track // of spaces for (int j = n - 1; j > i; j--) { Console.Write(\" \"); } // for loop to print the // digits in pattern for (int k = 1; k <= var1; k++) { Console.Write(Math.Abs(k - var2)); } var1 += 2; var2++; Console.WriteLine(); } } // Driver code public static void Main () { // taking size from the user int n = 5; // function calling print(n); }} // This code is contributed by vt_m.",
"e": 3554,
"s": 2634,
"text": null
},
{
"code": "<?php// PHP Implementation to// print the pattern // Function definitionfunction print1($n){ $var1 = 1; $var2 = 1; // Outer for loop to keep // track of number of lines for ($i = 0; $i < $n; $i++) { // for loop to keep track // of spaces for ($j = $n - 1; $j > $i; $j--) { echo \" \"; } // for loop to print the // digits in pattern for ($k = 1; $k <= $var1; $k++) { echo abs($k - $var2); } $var1 += 2; $var2++; echo \"\\n\"; }} // Driver code$n = 5;print1($n); // This code is contributed by mits?>",
"e": 4186,
"s": 3554,
"text": null
},
{
"code": "<script>// javascript Implementation to print the pattern // Function definitionfunction print( n){ let var1 = 1, var2 = 1; // Outer for loop to keep // track of number of lines for (let i = 0; i < n; i++) { // for loop to keep track // of spaces for (let j = n - 1; j > i; j--) { document.write(\" \"); } // for loop to print the // digits in pattern for (let k = 1; k <= var1; k++) { document.write(Math.abs(k - var2)); } var1 += 2; var2++; document.write(\"<br/>\"); }} // Driver code // taking size from the user let n = 5; // function calling print(n); // This code is contributed by aashish1995 </script>",
"e": 4939,
"s": 4186,
"text": null
},
{
"code": null,
"e": 4950,
"s": 4939,
"text": "Output : "
},
{
"code": null,
"e": 4990,
"s": 4950,
"text": " 0\n 101\n 21012\n 3210123\n432101234"
},
{
"code": null,
"e": 5057,
"s": 4990,
"text": "Time Complexity : O(n*n) ,where n is the number of rows in pattern"
},
{
"code": null,
"e": 5080,
"s": 5057,
"text": "Auxiliary Space : O(1)"
},
{
"code": null,
"e": 5095,
"s": 5082,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 5107,
"s": 5095,
"text": "aashish1995"
},
{
"code": null,
"e": 5121,
"s": 5107,
"text": "adityapatil12"
},
{
"code": null,
"e": 5138,
"s": 5121,
"text": "pattern-printing"
},
{
"code": null,
"e": 5147,
"s": 5138,
"text": "triangle"
},
{
"code": null,
"e": 5166,
"s": 5147,
"text": "School Programming"
},
{
"code": null,
"e": 5183,
"s": 5166,
"text": "pattern-printing"
},
{
"code": null,
"e": 5281,
"s": 5183,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5304,
"s": 5281,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5325,
"s": 5304,
"text": "Constructors in Java"
},
{
"code": null,
"e": 5344,
"s": 5325,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 5377,
"s": 5344,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 5405,
"s": 5377,
"text": "Classes and Objects in Java"
},
{
"code": null,
"e": 5431,
"s": 5405,
"text": "Python Exception Handling"
},
{
"code": null,
"e": 5480,
"s": 5431,
"text": "Programs for printing pyramid patterns in Python"
},
{
"code": null,
"e": 5498,
"s": 5480,
"text": "Python Try Except"
},
{
"code": null,
"e": 5555,
"s": 5498,
"text": "Python program to check whether a number is Prime or not"
}
] |
How to set the Background Color of the RadioButton in C#? | 30 Jun, 2019
In Windows Forms, RadioButton control is used to select a single option among the group of the options. For example, select your gender from the given list, so you will choose only one option among three options like Male or Female or Transgender. In Windows Forms, you are allowed to adjust the background color of the RadioButton using the BackColor Property of the RadioButton which makes your RadioButton more attractive. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set the background color of the RadioButton as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the RadioButton control from the ToolBox and drop it on the windows form. You are allowed to place a RadioButton control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the RadioButton control to set the background color of the RadioButton.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the RadioButton control programmatically with the help of given syntax:
public override System.Drawing.Color BackColor { get; set; }
Here, Color indicates the background color of the RadioButton. The following steps show how to set the background color of the RadioButton dynamically:
Step 1: Create a radio button using the RadioButton() constructor is provided by the RadioButton class.// Creating radio button
RadioButton r1 = new RadioButton();
// Creating radio button
RadioButton r1 = new RadioButton();
Step 2: After creating RadioButton, set the BackColor property of the RadioButton provided by the RadioButton class.// Setting the background color of the radio button
r1.BackColor = Color.LightSalmon;
// Setting the background color of the radio button
r1.BackColor = Color.LightSalmon;
Step 3: And last add this RadioButton control to the form using Add() method.// Add this radio button to the form
this.Controls.Add(r1);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp20 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void RadioButton2_CheckedChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = "Select Your Branch"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = "CSE"; r1.Location = new Point(286, 40); r1.BackColor = Color.LightSalmon; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = "ECE"; r2.Location = new Point(356, 40); r2.BackColor = Color.LightSalmon; // Adding this label to the form this.Controls.Add(r2); }}}Output:
// Add this radio button to the form
this.Controls.Add(r1);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp20 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void RadioButton2_CheckedChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = "Select Your Branch"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = "CSE"; r1.Location = new Point(286, 40); r1.BackColor = Color.LightSalmon; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = "ECE"; r2.Location = new Point(356, 40); r2.BackColor = Color.LightSalmon; // Adding this label to the form this.Controls.Add(r2); }}}
Output:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2019"
},
{
"code": null,
"e": 503,
"s": 28,
"text": "In Windows Forms, RadioButton control is used to select a single option among the group of the options. For example, select your gender from the given list, so you will choose only one option among three options like Male or Female or Transgender. In Windows Forms, you are allowed to adjust the background color of the RadioButton using the BackColor Property of the RadioButton which makes your RadioButton more attractive. You can set this property in two different ways:"
},
{
"code": null,
"e": 621,
"s": 503,
"text": "1. Design-Time: It is the easiest way to set the background color of the RadioButton as shown in the following steps:"
},
{
"code": null,
"e": 737,
"s": 621,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 924,
"s": 737,
"text": "Step 2: Drag the RadioButton control from the ToolBox and drop it on the windows form. You are allowed to place a RadioButton control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 1064,
"s": 924,
"text": "Step 3: After drag and drop you will go to the properties of the RadioButton control to set the background color of the RadioButton.Output:"
},
{
"code": null,
"e": 1072,
"s": 1064,
"text": "Output:"
},
{
"code": null,
"e": 1260,
"s": 1072,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the RadioButton control programmatically with the help of given syntax:"
},
{
"code": null,
"e": 1321,
"s": 1260,
"text": "public override System.Drawing.Color BackColor { get; set; }"
},
{
"code": null,
"e": 1473,
"s": 1321,
"text": "Here, Color indicates the background color of the RadioButton. The following steps show how to set the background color of the RadioButton dynamically:"
},
{
"code": null,
"e": 1638,
"s": 1473,
"text": "Step 1: Create a radio button using the RadioButton() constructor is provided by the RadioButton class.// Creating radio button\nRadioButton r1 = new RadioButton();\n"
},
{
"code": null,
"e": 1700,
"s": 1638,
"text": "// Creating radio button\nRadioButton r1 = new RadioButton();\n"
},
{
"code": null,
"e": 1903,
"s": 1700,
"text": "Step 2: After creating RadioButton, set the BackColor property of the RadioButton provided by the RadioButton class.// Setting the background color of the radio button\nr1.BackColor = Color.LightSalmon;\n"
},
{
"code": null,
"e": 1990,
"s": 1903,
"text": "// Setting the background color of the radio button\nr1.BackColor = Color.LightSalmon;\n"
},
{
"code": null,
"e": 3598,
"s": 1990,
"text": "Step 3: And last add this RadioButton control to the form using Add() method.// Add this radio button to the form\nthis.Controls.Add(r1);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp20 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void RadioButton2_CheckedChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = \"Select Your Branch\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = \"CSE\"; r1.Location = new Point(286, 40); r1.BackColor = Color.LightSalmon; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = \"ECE\"; r2.Location = new Point(356, 40); r2.BackColor = Color.LightSalmon; // Adding this label to the form this.Controls.Add(r2); }}}Output:"
},
{
"code": null,
"e": 3659,
"s": 3598,
"text": "// Add this radio button to the form\nthis.Controls.Add(r1);\n"
},
{
"code": null,
"e": 3668,
"s": 3659,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp20 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void RadioButton2_CheckedChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = \"Select Your Branch\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = \"CSE\"; r1.Location = new Point(286, 40); r1.BackColor = Color.LightSalmon; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = \"ECE\"; r2.Location = new Point(356, 40); r2.BackColor = Color.LightSalmon; // Adding this label to the form this.Controls.Add(r2); }}}",
"e": 5124,
"s": 3668,
"text": null
},
{
"code": null,
"e": 5132,
"s": 5124,
"text": "Output:"
},
{
"code": null,
"e": 5135,
"s": 5132,
"text": "C#"
}
] |
SQL – Logical Operators | 18 Oct, 2021
SQL logical operators are used to test for the truth of the condition. A logical operator like the Comparison operator returns a boolean value of TRUE, FALSE, or UNKNOWN.
Given below is the list of logical operators available in SQL.
In the below example, we will see how this logical operator works.
Step 1: Creating a Database
In order to create a database, we need to use the CREATE operator.
Query:
CREATE DATABASE xstream_db;
Step 2: Create table employee
In this step, we will create the table employee inside the xstream_db database.
Query:
CREATE TABLE employee (emp_id INT, emp_name VARCHAR(255),
emp_city VARCHAR(255),
emp_country VARCHAR(255),
PRIMARY KEY (emp_id));
In order to insert the data inside the database, we need to use the INSERT operator.
Query:
INSERT INTO employee VALUES (101, 'Utkarsh Tripathi', 'Varanasi', 'India'),
(102, 'Abhinav Singh', 'Varanasi', 'India'),
(103, 'Utkarsh Raghuvanshi', 'Varanasi', 'India'),
(104, 'Utkarsh Singh', 'Allahabad', 'India'),
(105, 'Sudhanshu Yadav', 'Allahabad', 'India'),
(106, 'Ashutosh Kumar', 'Patna', 'India');
Output:
Now the given below is an example of the logical operators.
Query :
SELECT * FROM employee WHERE emp_city = 'Allahabad' AND emp_country = 'India';
Output:
Query:
SELECT * FROM employee WHERE emp_city IN ('Allahabad', 'Patna');
Output:
Query:
SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';
Output:
Query:
SELECT * FROM employee WHERE emp_city = 'Varanasi' OR emp_country = 'India';
Output:
Query:
SELECT * FROM employee WHERE emp_city LIKE 'P%';
Output:
Query:
SELECT * FROM employee WHERE emp_id BETWEEN 101 AND 104;
Output:
Query:
SELECT * FROM employee WHERE emp_id = ALL
(SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');
Output:
Query:
SELECT * FROM employee WHERE emp_id = ANY
(SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');
Output:
Query:
SELECT emp_name FROM employee WHERE EXISTS
(SELECT emp_id FROM employee WHERE emp_city = 'Patna');
Output:
Query:
SELECT * FROM employee WHERE emp_id < SOME
(SELECT emp_id FROM employee WHERE emp_city = 'Patna');
Output:
Picked
sql-operators
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time? | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 224,
"s": 53,
"text": "SQL logical operators are used to test for the truth of the condition. A logical operator like the Comparison operator returns a boolean value of TRUE, FALSE, or UNKNOWN."
},
{
"code": null,
"e": 287,
"s": 224,
"text": "Given below is the list of logical operators available in SQL."
},
{
"code": null,
"e": 354,
"s": 287,
"text": "In the below example, we will see how this logical operator works."
},
{
"code": null,
"e": 383,
"s": 354,
"text": "Step 1: Creating a Database "
},
{
"code": null,
"e": 450,
"s": 383,
"text": "In order to create a database, we need to use the CREATE operator."
},
{
"code": null,
"e": 457,
"s": 450,
"text": "Query:"
},
{
"code": null,
"e": 485,
"s": 457,
"text": "CREATE DATABASE xstream_db;"
},
{
"code": null,
"e": 516,
"s": 485,
"text": "Step 2: Create table employee "
},
{
"code": null,
"e": 596,
"s": 516,
"text": "In this step, we will create the table employee inside the xstream_db database."
},
{
"code": null,
"e": 603,
"s": 596,
"text": "Query:"
},
{
"code": null,
"e": 836,
"s": 603,
"text": "CREATE TABLE employee (emp_id INT, emp_name VARCHAR(255), \n emp_city VARCHAR(255),\n emp_country VARCHAR(255),\n PRIMARY KEY (emp_id));"
},
{
"code": null,
"e": 921,
"s": 836,
"text": "In order to insert the data inside the database, we need to use the INSERT operator."
},
{
"code": null,
"e": 928,
"s": 921,
"text": "Query:"
},
{
"code": null,
"e": 1378,
"s": 928,
"text": "INSERT INTO employee VALUES (101, 'Utkarsh Tripathi', 'Varanasi', 'India'),\n (102, 'Abhinav Singh', 'Varanasi', 'India'), \n (103, 'Utkarsh Raghuvanshi', 'Varanasi', 'India'),\n (104, 'Utkarsh Singh', 'Allahabad', 'India'),\n (105, 'Sudhanshu Yadav', 'Allahabad', 'India'),\n (106, 'Ashutosh Kumar', 'Patna', 'India');"
},
{
"code": null,
"e": 1387,
"s": 1378,
"text": "Output: "
},
{
"code": null,
"e": 1447,
"s": 1387,
"text": "Now the given below is an example of the logical operators."
},
{
"code": null,
"e": 1456,
"s": 1447,
"text": "Query : "
},
{
"code": null,
"e": 1535,
"s": 1456,
"text": "SELECT * FROM employee WHERE emp_city = 'Allahabad' AND emp_country = 'India';"
},
{
"code": null,
"e": 1544,
"s": 1535,
"text": "Output: "
},
{
"code": null,
"e": 1551,
"s": 1544,
"text": "Query:"
},
{
"code": null,
"e": 1616,
"s": 1551,
"text": "SELECT * FROM employee WHERE emp_city IN ('Allahabad', 'Patna');"
},
{
"code": null,
"e": 1625,
"s": 1616,
"text": "Output: "
},
{
"code": null,
"e": 1632,
"s": 1625,
"text": "Query:"
},
{
"code": null,
"e": 1685,
"s": 1632,
"text": "SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';"
},
{
"code": null,
"e": 1693,
"s": 1685,
"text": "Output:"
},
{
"code": null,
"e": 1700,
"s": 1693,
"text": "Query:"
},
{
"code": null,
"e": 1777,
"s": 1700,
"text": "SELECT * FROM employee WHERE emp_city = 'Varanasi' OR emp_country = 'India';"
},
{
"code": null,
"e": 1785,
"s": 1777,
"text": "Output:"
},
{
"code": null,
"e": 1792,
"s": 1785,
"text": "Query:"
},
{
"code": null,
"e": 1841,
"s": 1792,
"text": "SELECT * FROM employee WHERE emp_city LIKE 'P%';"
},
{
"code": null,
"e": 1849,
"s": 1841,
"text": "Output:"
},
{
"code": null,
"e": 1856,
"s": 1849,
"text": "Query:"
},
{
"code": null,
"e": 1913,
"s": 1856,
"text": "SELECT * FROM employee WHERE emp_id BETWEEN 101 AND 104;"
},
{
"code": null,
"e": 1921,
"s": 1913,
"text": "Output:"
},
{
"code": null,
"e": 1928,
"s": 1921,
"text": "Query:"
},
{
"code": null,
"e": 2046,
"s": 1928,
"text": "SELECT * FROM employee WHERE emp_id = ALL \n (SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');"
},
{
"code": null,
"e": 2054,
"s": 2046,
"text": "Output:"
},
{
"code": null,
"e": 2061,
"s": 2054,
"text": "Query:"
},
{
"code": null,
"e": 2178,
"s": 2061,
"text": "SELECT * FROM employee WHERE emp_id = ANY\n (SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');"
},
{
"code": null,
"e": 2186,
"s": 2178,
"text": "Output:"
},
{
"code": null,
"e": 2193,
"s": 2186,
"text": "Query:"
},
{
"code": null,
"e": 2308,
"s": 2193,
"text": "SELECT emp_name FROM employee WHERE EXISTS\n (SELECT emp_id FROM employee WHERE emp_city = 'Patna');"
},
{
"code": null,
"e": 2316,
"s": 2308,
"text": "Output:"
},
{
"code": null,
"e": 2323,
"s": 2316,
"text": "Query:"
},
{
"code": null,
"e": 2439,
"s": 2323,
"text": "SELECT * FROM employee WHERE emp_id < SOME \n (SELECT emp_id FROM employee WHERE emp_city = 'Patna');"
},
{
"code": null,
"e": 2447,
"s": 2439,
"text": "Output:"
},
{
"code": null,
"e": 2454,
"s": 2447,
"text": "Picked"
},
{
"code": null,
"e": 2468,
"s": 2454,
"text": "sql-operators"
},
{
"code": null,
"e": 2479,
"s": 2468,
"text": "SQL-Server"
},
{
"code": null,
"e": 2483,
"s": 2479,
"text": "SQL"
},
{
"code": null,
"e": 2487,
"s": 2483,
"text": "SQL"
},
{
"code": null,
"e": 2585,
"s": 2487,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2651,
"s": 2585,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2675,
"s": 2651,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2707,
"s": 2675,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2740,
"s": 2707,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2757,
"s": 2740,
"text": "SQL using Python"
},
{
"code": null,
"e": 2787,
"s": 2757,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2865,
"s": 2787,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2901,
"s": 2865,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2932,
"s": 2901,
"text": "SQL Query to Compare Two Dates"
}
] |
Composite Design Pattern | 01 Sep, 2021
Composite pattern is a partitioning design pattern and describes a group of objects that is treated the same way as a single instance of the same type of object. The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies. It allows you to have a tree structure and ask each node in the tree structure to perform a task.
As described by Gof, “Compose objects into tree structure to represent part-whole hierarchies. Composite lets client treat individual objects and compositions of objects uniformly”.
When dealing with Tree-structured data, programmers often have to discriminate between a leaf-node and a branch. This makes code more complex, and therefore, error prone. The solution is an interface that allows treating complex and primitive objects uniformly.
In object-oriented programming, a composite is an object designed as a composition of one-or-more similar objects, all exhibiting similar functionality. This is known as a “has-a” relationship between objects.
The key concept is that you can manipulate a single instance of the object just as you would manipulate a group of them. The operations you can perform on all the composite objects often have a least common denominator relationship.The Composite Pattern has four participants:
Component – Component declares the interface for objects in the composition and for accessing and managing its child components. It also implements default behavior for the interface common to all classes as appropriate.Leaf – Leaf defines behavior for primitive objects in the composition. It represents leaf objects in the composition.Composite – Composite stores child components and implements child related operations in the component interface.Client – Client manipulates the objects in the composition through the component interface.
Component – Component declares the interface for objects in the composition and for accessing and managing its child components. It also implements default behavior for the interface common to all classes as appropriate.
Leaf – Leaf defines behavior for primitive objects in the composition. It represents leaf objects in the composition.
Composite – Composite stores child components and implements child related operations in the component interface.
Client – Client manipulates the objects in the composition through the component interface.
Client use the component class interface to interact with objects in the composition structure. If recipient is a leaf then request is handled directly. If recipient is a composite, then it usually forwards request to its child components, possibly performing additional operations before and after forwarding.
Real Life example
In an organization, It have general managers and under general managers, there can be managers and under managers there can be developers. Now you can set a tree structure and ask each node to perform common operation like getSalary().Composite design pattern treats each node in two ways:1) Composite – Composite means it can have other objects below it.2) leaf – leaf means it has no objects below it.
Tree structure:
The above figure shows a typical Composite object structure. As you can see, there can be many children to a single parent i.e. Composite, but only one parent per child.
Interface Component.java
public interface Employee{ public void showEmployeeDetails();}
Leaf.java
public class Developer implements Employee{ private String name; private long empId; private String position; public Developer(long empId, String name, String position) { this.empId = empId; this.name = name; this.position = position; } @Override public void showEmployeeDetails() { System.out.println(empId+" " +name+); }}
Leaf.java
public class Manager implements Employee{ private String name; private long empId; private String position; public Manager(long empId, String name, String position) { this.empId = empId; this.name = name; this.position = position; } @Override public void showEmployeeDetails() { System.out.println(empId+" " +name); }}
Composite.java
import java.util.ArrayList;import java.util.List; public class CompanyDirectory implements Employee{ private List<Employee> employeeList = new ArrayList<Employee>(); @Override public void showEmployeeDetails() { for(Employee emp:employeeList) { emp.showEmployeeDetails(); } } public void addEmployee(Employee emp) { employeeList.add(emp); } public void removeEmployee(Employee emp) { employeeList.remove(emp); }}
Client.java
public class Company{ public static void main (String[] args) { Developer dev1 = new Developer(100, "Lokesh Sharma", "Pro Developer"); Developer dev2 = new Developer(101, "Vinay Sharma", "Developer"); CompanyDirectory engDirectory = new CompanyDirectory(); engDirectory.addEmployee(dev1); engDirectory.addEmployee(dev2); Manager man1 = new Manager(200, "Kushagra Garg", "SEO Manager"); Manager man2 = new Manager(201, "Vikram Sharma ", "Kushagra's Manager"); CompanyDirectory accDirectory = new CompanyDirectory(); accDirectory.addEmployee(man1); accDirectory.addEmployee(man2); CompanyDirectory directory = new CompanyDirectory(); directory.addEmployee(engDirectory); directory.addEmployee(accDirectory); directory.showEmployeeDetails(); }}
UML Diagram for the Composite Design Pattern :
Full Running Code for the above example :
// A Java program to demonstrate working of// Composite Design Pattern with example // of a company with different// employee details import java.util.ArrayList;import java.util.List; // A common interface for all employeeinterface Employee{ public void showEmployeeDetails();} class Developer implements Employee{ private String name; private long empId; private String position; public Developer(long empId, String name, String position) { // Assign the Employee id, // name and the position this.empId = empId; this.name = name; this.position = position; } @Override public void showEmployeeDetails() { System.out.println(empId+" " +name+ " " + position ); }} class Manager implements Employee{ private String name; private long empId; private String position; public Manager(long empId, String name, String position) { this.empId = empId; this.name = name; this.position = position; } @Override public void showEmployeeDetails() { System.out.println(empId+" " +name+ " " + position ); }} // Class used to get Employee List// and do the opertions like // add or remove Employee class CompanyDirectory implements Employee{ private List<Employee> employeeList = new ArrayList<Employee>(); @Override public void showEmployeeDetails() { for(Employee emp:employeeList) { emp.showEmployeeDetails(); } } public void addEmployee(Employee emp) { employeeList.add(emp); } public void removeEmployee(Employee emp) { employeeList.remove(emp); }} // Driver classpublic class Company{ public static void main (String[] args) { Developer dev1 = new Developer(100, "Lokesh Sharma", "Pro Developer"); Developer dev2 = new Developer(101, "Vinay Sharma", "Developer"); CompanyDirectory engDirectory = new CompanyDirectory(); engDirectory.addEmployee(dev1); engDirectory.addEmployee(dev2); Manager man1 = new Manager(200, "Kushagra Garg", "SEO Manager"); Manager man2 = new Manager(201, "Vikram Sharma ", "Kushagra's Manager"); CompanyDirectory accDirectory = new CompanyDirectory(); accDirectory.addEmployee(man1); accDirectory.addEmployee(man2); CompanyDirectory directory = new CompanyDirectory(); directory.addEmployee(engDirectory); directory.addEmployee(accDirectory); directory.showEmployeeDetails(); }}
Output :
100 Lokesh Sharma Pro Developer
101 Vinay Sharma Developer
200 Kushagra Garg SEO Manager
201 Vikram Sharma Kushagra's Manager
When to use Composite Design Pattern?
Composite Pattern should be used when clients need to ignore the difference between compositions of objects and individual objects. If programmers find that they are using multiple objects in the same way, and often have nearly identical code to handle each of them, then composite is a good choice, it is less complex in this situation to treat primitives and composites as homogeneous.
Less number of objects reduces the memory usage, and it manages to keep us away from errors related to memory like java.lang.OutOfMemoryError.Although creating an object in Java is really fast, we can still reduce the execution time of our program by sharing objects.
Less number of objects reduces the memory usage, and it manages to keep us away from errors related to memory like java.lang.OutOfMemoryError.
Although creating an object in Java is really fast, we can still reduce the execution time of our program by sharing objects.
When not to use Composite Design Pattern?
Composite Design Pattern makes it harder to restrict the type of components of a composite. So it should not be used when you don’t want to represent a full or partial hierarchy of objects.Composite Design Pattern can make the design overly general. It makes harder to restrict the components of a composite. Sometimes you want a composite to have only certain components. With Composite, you can’t rely on the type system to enforce those constraints for you. Instead you’ll have to use run-time checks.
Composite Design Pattern makes it harder to restrict the type of components of a composite. So it should not be used when you don’t want to represent a full or partial hierarchy of objects.
Composite Design Pattern can make the design overly general. It makes harder to restrict the components of a composite. Sometimes you want a composite to have only certain components. With Composite, you can’t rely on the type system to enforce those constraints for you. Instead you’ll have to use run-time checks.
Further Read: Composite Method in Python
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Unified Modeling Language (UML) | An Introduction
Introduction of Programming Paradigms
Builder Design Pattern
MVC Design Pattern
State Design Pattern
An introduction to Flowcharts
Unified Modeling Language (UML) | Sequence Diagrams
How to design a parking lot using object-oriented principles?
Design an online book reader system | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 420,
"s": 52,
"text": "Composite pattern is a partitioning design pattern and describes a group of objects that is treated the same way as a single instance of the same type of object. The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies. It allows you to have a tree structure and ask each node in the tree structure to perform a task."
},
{
"code": null,
"e": 602,
"s": 420,
"text": "As described by Gof, “Compose objects into tree structure to represent part-whole hierarchies. Composite lets client treat individual objects and compositions of objects uniformly”."
},
{
"code": null,
"e": 864,
"s": 602,
"text": "When dealing with Tree-structured data, programmers often have to discriminate between a leaf-node and a branch. This makes code more complex, and therefore, error prone. The solution is an interface that allows treating complex and primitive objects uniformly."
},
{
"code": null,
"e": 1074,
"s": 864,
"text": "In object-oriented programming, a composite is an object designed as a composition of one-or-more similar objects, all exhibiting similar functionality. This is known as a “has-a” relationship between objects."
},
{
"code": null,
"e": 1351,
"s": 1074,
"text": "The key concept is that you can manipulate a single instance of the object just as you would manipulate a group of them. The operations you can perform on all the composite objects often have a least common denominator relationship.The Composite Pattern has four participants:"
},
{
"code": null,
"e": 1893,
"s": 1351,
"text": "Component – Component declares the interface for objects in the composition and for accessing and managing its child components. It also implements default behavior for the interface common to all classes as appropriate.Leaf – Leaf defines behavior for primitive objects in the composition. It represents leaf objects in the composition.Composite – Composite stores child components and implements child related operations in the component interface.Client – Client manipulates the objects in the composition through the component interface."
},
{
"code": null,
"e": 2114,
"s": 1893,
"text": "Component – Component declares the interface for objects in the composition and for accessing and managing its child components. It also implements default behavior for the interface common to all classes as appropriate."
},
{
"code": null,
"e": 2232,
"s": 2114,
"text": "Leaf – Leaf defines behavior for primitive objects in the composition. It represents leaf objects in the composition."
},
{
"code": null,
"e": 2346,
"s": 2232,
"text": "Composite – Composite stores child components and implements child related operations in the component interface."
},
{
"code": null,
"e": 2438,
"s": 2346,
"text": "Client – Client manipulates the objects in the composition through the component interface."
},
{
"code": null,
"e": 2749,
"s": 2438,
"text": "Client use the component class interface to interact with objects in the composition structure. If recipient is a leaf then request is handled directly. If recipient is a composite, then it usually forwards request to its child components, possibly performing additional operations before and after forwarding."
},
{
"code": null,
"e": 2767,
"s": 2749,
"text": "Real Life example"
},
{
"code": null,
"e": 3171,
"s": 2767,
"text": "In an organization, It have general managers and under general managers, there can be managers and under managers there can be developers. Now you can set a tree structure and ask each node to perform common operation like getSalary().Composite design pattern treats each node in two ways:1) Composite – Composite means it can have other objects below it.2) leaf – leaf means it has no objects below it."
},
{
"code": null,
"e": 3187,
"s": 3171,
"text": "Tree structure:"
},
{
"code": null,
"e": 3357,
"s": 3187,
"text": "The above figure shows a typical Composite object structure. As you can see, there can be many children to a single parent i.e. Composite, but only one parent per child."
},
{
"code": null,
"e": 3382,
"s": 3357,
"text": "Interface Component.java"
},
{
"code": "public interface Employee{ public void showEmployeeDetails();}",
"e": 3448,
"s": 3382,
"text": null
},
{
"code": null,
"e": 3458,
"s": 3448,
"text": "Leaf.java"
},
{
"code": "public class Developer implements Employee{ private String name; private long empId; private String position; public Developer(long empId, String name, String position) { this.empId = empId; this.name = name; this.position = position; } @Override public void showEmployeeDetails() { System.out.println(empId+\" \" +name+); }}",
"e": 3857,
"s": 3458,
"text": null
},
{
"code": null,
"e": 3867,
"s": 3857,
"text": "Leaf.java"
},
{
"code": "public class Manager implements Employee{ private String name; private long empId; private String position; public Manager(long empId, String name, String position) { this.empId = empId; this.name = name; this.position = position; } @Override public void showEmployeeDetails() { System.out.println(empId+\" \" +name); }}",
"e": 4265,
"s": 3867,
"text": null
},
{
"code": null,
"e": 4280,
"s": 4265,
"text": "Composite.java"
},
{
"code": "import java.util.ArrayList;import java.util.List; public class CompanyDirectory implements Employee{ private List<Employee> employeeList = new ArrayList<Employee>(); @Override public void showEmployeeDetails() { for(Employee emp:employeeList) { emp.showEmployeeDetails(); } } public void addEmployee(Employee emp) { employeeList.add(emp); } public void removeEmployee(Employee emp) { employeeList.remove(emp); }}",
"e": 4795,
"s": 4280,
"text": null
},
{
"code": null,
"e": 4807,
"s": 4795,
"text": "Client.java"
},
{
"code": "public class Company{ public static void main (String[] args) { Developer dev1 = new Developer(100, \"Lokesh Sharma\", \"Pro Developer\"); Developer dev2 = new Developer(101, \"Vinay Sharma\", \"Developer\"); CompanyDirectory engDirectory = new CompanyDirectory(); engDirectory.addEmployee(dev1); engDirectory.addEmployee(dev2); Manager man1 = new Manager(200, \"Kushagra Garg\", \"SEO Manager\"); Manager man2 = new Manager(201, \"Vikram Sharma \", \"Kushagra's Manager\"); CompanyDirectory accDirectory = new CompanyDirectory(); accDirectory.addEmployee(man1); accDirectory.addEmployee(man2); CompanyDirectory directory = new CompanyDirectory(); directory.addEmployee(engDirectory); directory.addEmployee(accDirectory); directory.showEmployeeDetails(); }}",
"e": 5682,
"s": 4807,
"text": null
},
{
"code": null,
"e": 5729,
"s": 5682,
"text": "UML Diagram for the Composite Design Pattern :"
},
{
"code": null,
"e": 5771,
"s": 5729,
"text": "Full Running Code for the above example :"
},
{
"code": "// A Java program to demonstrate working of// Composite Design Pattern with example // of a company with different// employee details import java.util.ArrayList;import java.util.List; // A common interface for all employeeinterface Employee{ public void showEmployeeDetails();} class Developer implements Employee{ private String name; private long empId; private String position; public Developer(long empId, String name, String position) { // Assign the Employee id, // name and the position this.empId = empId; this.name = name; this.position = position; } @Override public void showEmployeeDetails() { System.out.println(empId+\" \" +name+ \" \" + position ); }} class Manager implements Employee{ private String name; private long empId; private String position; public Manager(long empId, String name, String position) { this.empId = empId; this.name = name; this.position = position; } @Override public void showEmployeeDetails() { System.out.println(empId+\" \" +name+ \" \" + position ); }} // Class used to get Employee List// and do the opertions like // add or remove Employee class CompanyDirectory implements Employee{ private List<Employee> employeeList = new ArrayList<Employee>(); @Override public void showEmployeeDetails() { for(Employee emp:employeeList) { emp.showEmployeeDetails(); } } public void addEmployee(Employee emp) { employeeList.add(emp); } public void removeEmployee(Employee emp) { employeeList.remove(emp); }} // Driver classpublic class Company{ public static void main (String[] args) { Developer dev1 = new Developer(100, \"Lokesh Sharma\", \"Pro Developer\"); Developer dev2 = new Developer(101, \"Vinay Sharma\", \"Developer\"); CompanyDirectory engDirectory = new CompanyDirectory(); engDirectory.addEmployee(dev1); engDirectory.addEmployee(dev2); Manager man1 = new Manager(200, \"Kushagra Garg\", \"SEO Manager\"); Manager man2 = new Manager(201, \"Vikram Sharma \", \"Kushagra's Manager\"); CompanyDirectory accDirectory = new CompanyDirectory(); accDirectory.addEmployee(man1); accDirectory.addEmployee(man2); CompanyDirectory directory = new CompanyDirectory(); directory.addEmployee(engDirectory); directory.addEmployee(accDirectory); directory.showEmployeeDetails(); }}",
"e": 8374,
"s": 5771,
"text": null
},
{
"code": null,
"e": 8383,
"s": 8374,
"text": "Output :"
},
{
"code": null,
"e": 8511,
"s": 8383,
"text": "100 Lokesh Sharma Pro Developer\n101 Vinay Sharma Developer\n200 Kushagra Garg SEO Manager\n201 Vikram Sharma Kushagra's Manager\n"
},
{
"code": null,
"e": 8549,
"s": 8511,
"text": "When to use Composite Design Pattern?"
},
{
"code": null,
"e": 8937,
"s": 8549,
"text": "Composite Pattern should be used when clients need to ignore the difference between compositions of objects and individual objects. If programmers find that they are using multiple objects in the same way, and often have nearly identical code to handle each of them, then composite is a good choice, it is less complex in this situation to treat primitives and composites as homogeneous."
},
{
"code": null,
"e": 9205,
"s": 8937,
"text": "Less number of objects reduces the memory usage, and it manages to keep us away from errors related to memory like java.lang.OutOfMemoryError.Although creating an object in Java is really fast, we can still reduce the execution time of our program by sharing objects."
},
{
"code": null,
"e": 9348,
"s": 9205,
"text": "Less number of objects reduces the memory usage, and it manages to keep us away from errors related to memory like java.lang.OutOfMemoryError."
},
{
"code": null,
"e": 9474,
"s": 9348,
"text": "Although creating an object in Java is really fast, we can still reduce the execution time of our program by sharing objects."
},
{
"code": null,
"e": 9516,
"s": 9474,
"text": "When not to use Composite Design Pattern?"
},
{
"code": null,
"e": 10021,
"s": 9516,
"text": "Composite Design Pattern makes it harder to restrict the type of components of a composite. So it should not be used when you don’t want to represent a full or partial hierarchy of objects.Composite Design Pattern can make the design overly general. It makes harder to restrict the components of a composite. Sometimes you want a composite to have only certain components. With Composite, you can’t rely on the type system to enforce those constraints for you. Instead you’ll have to use run-time checks."
},
{
"code": null,
"e": 10211,
"s": 10021,
"text": "Composite Design Pattern makes it harder to restrict the type of components of a composite. So it should not be used when you don’t want to represent a full or partial hierarchy of objects."
},
{
"code": null,
"e": 10527,
"s": 10211,
"text": "Composite Design Pattern can make the design overly general. It makes harder to restrict the components of a composite. Sometimes you want a composite to have only certain components. With Composite, you can’t rely on the type system to enforce those constraints for you. Instead you’ll have to use run-time checks."
},
{
"code": null,
"e": 10568,
"s": 10527,
"text": "Further Read: Composite Method in Python"
},
{
"code": null,
"e": 10863,
"s": 10568,
"text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 10988,
"s": 10863,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 11003,
"s": 10988,
"text": "Design Pattern"
},
{
"code": null,
"e": 11101,
"s": 11003,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11139,
"s": 11101,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 11189,
"s": 11139,
"text": "Unified Modeling Language (UML) | An Introduction"
},
{
"code": null,
"e": 11227,
"s": 11189,
"text": "Introduction of Programming Paradigms"
},
{
"code": null,
"e": 11250,
"s": 11227,
"text": "Builder Design Pattern"
},
{
"code": null,
"e": 11269,
"s": 11250,
"text": "MVC Design Pattern"
},
{
"code": null,
"e": 11290,
"s": 11269,
"text": "State Design Pattern"
},
{
"code": null,
"e": 11320,
"s": 11290,
"text": "An introduction to Flowcharts"
},
{
"code": null,
"e": 11372,
"s": 11320,
"text": "Unified Modeling Language (UML) | Sequence Diagrams"
},
{
"code": null,
"e": 11434,
"s": 11372,
"text": "How to design a parking lot using object-oriented principles?"
}
] |
Move first element to end of a given Linked List | 24 Jun, 2021
Write a C function that moves first element to end in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 2->3->4->5->1.
Algorithm:
Traverse the list till last node. Use two pointers: one to store the address of last node(last) and other for address of first node(first). After the end of loop do following operations. i) Make head as second node (*head_ref = first->next). ii) Set next of first as NULL (first->next = NULL). iii) Set next of last as first ( last->next = first)
C++
Java
Python3
C#
Javascript
/* C++ Program to move first element to end in a given linked list */#include <stdio.h>#include <stdlib.h> /* A linked list node */struct Node { int data; struct Node* next;}; /* We are using a double pointer head_ref here because we change head of the linked list inside this function.*/void moveToEnd(struct Node** head_ref){ /* If linked list is empty, or it contains only one node, then nothing needs to be done, simply return */ if (*head_ref == NULL || (*head_ref)->next == NULL) return; /* Initialize first and last pointers */ struct Node* first = *head_ref; struct Node* last = *head_ref; /*After this loop last contains address of last node in Linked List */ while (last->next != NULL) { last = last->next; } /* Change the head pointer to point to second node now */ *head_ref = first->next; /* Set the next of first as NULL */ first->next = NULL; /* Set the next of last as first */ last->next = first;} /* UTILITY FUNCTIONS *//* Function to add a node at the beginning of Linked List */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above function */int main(){ struct Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5 */ push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); printf("\n Linked list before moving first to end\n"); printList(start); moveToEnd(&start); printf("\n Linked list after moving first to end\n"); printList(start); return 0;}
/* Java Program to move first element to endin a given linked list */class Sol{ /* A linked list node */static class Node{ int data; Node next;}; /* We are using a double pointer head_refhere because we change head of the linkedlist inside this function.*/static Node moveToEnd( Node head_ref){ /* If linked list is empty, or it contains only one node, then nothing needs to be done, simply return */ if (head_ref == null || (head_ref).next == null) return null; /* Initialize first and last pointers */ Node first = head_ref; Node last = head_ref; /*After this loop last contains address of last node in Linked List */ while (last.next != null) { last = last.next; } /* Change the head pointer to point to second node now */ head_ref = first.next; /* Set the next of first as null */ first.next = null; /* Set the next of last as first */ last.next = first; return head_ref;} /* UTILITY FUNCTIONS *//* Function to add a node at the beginningof Linked List */static Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} /* Function to print nodes in a given linked list */static void printList( Node node){ while (node != null) { System.out.printf("%d ", node.data); node = node.next; }} /* Driver code */public static void main(String args[]){ Node start = null; /* The constructed linked list is: 1.2.3.4.5 */ start = push(start, 5); start = push(start, 4); start = push(start, 3); start = push(start, 2); start = push(start, 1); System.out.printf("\n Linked list before moving first to end\n"); printList(start); start = moveToEnd(start); System.out.printf("\n Linked list after moving first to end\n"); printList(start);}} // This code is contributed by Arnab Kundu
# Python3 Program to move first element to end# in a given linked list # A linked list nodeclass Node: def __init__(self): self.data = 0 self.next = None # We are using a double pointer head_ref# here because we change head of the linked# list inside this function.def moveToEnd( head_ref) : # If linked list is empty, or it contains # only one node, then nothing needs to be # done, simply return if (head_ref == None or (head_ref).next == None) : return None # Initialize first and last pointers first = head_ref last = head_ref # After this loop last contains address # of last node in Linked List while (last.next != None) : last = last.next # Change the head pointer to point # to second node now head_ref = first.next # Set the next of first as None first.next = None # Set the next of last as first last.next = first return head_ref # UTILITY FUNCTIONS# Function to add a node at the beginning# of Linked Listdef push( head_ref, new_data) : new_node = Node() new_node.data = new_data new_node.next = (head_ref) (head_ref) = new_node return head_ref # Function to print nodes in a given linked listdef printList(node) : while (node != None): print(node.data, end = " ") node = node.next # Driver code start = None # The constructed linked list is:#1.2.3.4.5start = push(start, 5)start = push(start, 4)start = push(start, 3)start = push(start, 2)start = push(start, 1) print("\n Linked list before moving first to end")printList(start) start = moveToEnd(start) print("\n Linked list after moving first to end")printList(start) # This code is contributed by Arnab Kundu
/* C# Program to move first element to endin a given linked list */using System; class GFG{ /* A linked list node */public class Node{ public int data; public Node next;}; /* We are using a double pointer head_refhere because we change head of the linkedlist inside this function.*/static Node moveToEnd( Node head_ref){ /* If linked list is empty, or it contains only one node, then nothing needs to be done, simply return */ if (head_ref == null || (head_ref).next == null) return null; /* Initialize first and last pointers */ Node first = head_ref; Node last = head_ref; /*After this loop last contains address of last node in Linked List */ while (last.next != null) { last = last.next; } /* Change the head pointer to point to second node now */ head_ref = first.next; /* Set the next of first as null */ first.next = null; /* Set the next of last as first */ last.next = first; return head_ref;} /* UTILITY FUNCTIONS *//* Function to add a node at the beginningof Linked List */static Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} /* Function to print nodes in a given linked list */static void printList( Node node){ while (node != null) { Console.Write("{0} ", node.data); node = node.next; }} /* Driver code */public static void Main(String []args){ Node start = null; /* The constructed linked list is: 1.2.3.4.5 */ start = push(start, 5); start = push(start, 4); start = push(start, 3); start = push(start, 2); start = push(start, 1); Console.Write("\n Linked list before moving first to end\n"); printList(start); start = moveToEnd(start); Console.Write("\n Linked list after moving first to end\n"); printList(start);}} // This code is contributed by 29AjayKumar
<script> // JavaScript program to move first element// to end in a given linked list /* A linked list node */class Node{ constructor() { this.data = 0; this.next = null; }} /* We are using a double pointer head_refhere because we change head of the linkedlist inside this function.*/function moveToEnd(head_ref){ /* If linked list is empty, or it contains only one node, then nothing needs to be done, simply return */ if (head_ref == null || head_ref.next == null) return null; /* Initialize first and last pointers */ var first = head_ref; var last = head_ref; /*After this loop last contains address of last node in Linked List */ while (last.next != null) { last = last.next; } /* Change the head pointer to point to second node now */ head_ref = first.next; /* Set the next of first as null */ first.next = null; /* Set the next of last as first */ last.next = first; return head_ref;} /* UTILITY FUNCTIONS *//* Function to add a node at the beginningof Linked List */function push(head_ref, new_data){ var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref;} // Function to print nodes in// a given linked listfunction printList(node){ while (node != null) { document.write(node.data + " "); node = node.next; }} // Driver codevar start = null; // The constructed linked list is:// 1.2.3.4.5start = push(start, 5);start = push(start, 4);start = push(start, 3);start = push(start, 2);start = push(start, 1); document.write("Linked list before " + "moving first to end<br>");printList(start);start = moveToEnd(start); document.write("<br> Linked list after moving " + "first to end<br>");printList(start); // This code is contributed by rdtank </script>
Linked list before moving first to end
1 2 3 4 5
Linked list after moving first to end
2 3 4 5 1
Time Complexity: O(n) where n is the number of nodes in the given Linked List.
andrew1234
29AjayKumar
Akanksha_Rai
rdtank
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Types of Linked List
Circular Singly Linked List | Insertion
Find first node of loop in a linked list
Add two numbers represented by linked lists | Set 2
Flattening a Linked List
Real-time application of Data Structures
Insert a node at a specific position in a linked list
Clone a linked list with next and random pointer | Set 1 | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 250,
"s": 53,
"text": "Write a C function that moves first element to end in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 2->3->4->5->1."
},
{
"code": null,
"e": 262,
"s": 250,
"text": "Algorithm: "
},
{
"code": null,
"e": 610,
"s": 262,
"text": "Traverse the list till last node. Use two pointers: one to store the address of last node(last) and other for address of first node(first). After the end of loop do following operations. i) Make head as second node (*head_ref = first->next). ii) Set next of first as NULL (first->next = NULL). iii) Set next of last as first ( last->next = first) "
},
{
"code": null,
"e": 614,
"s": 610,
"text": "C++"
},
{
"code": null,
"e": 619,
"s": 614,
"text": "Java"
},
{
"code": null,
"e": 627,
"s": 619,
"text": "Python3"
},
{
"code": null,
"e": 630,
"s": 627,
"text": "C#"
},
{
"code": null,
"e": 641,
"s": 630,
"text": "Javascript"
},
{
"code": "/* C++ Program to move first element to end in a given linked list */#include <stdio.h>#include <stdlib.h> /* A linked list node */struct Node { int data; struct Node* next;}; /* We are using a double pointer head_ref here because we change head of the linked list inside this function.*/void moveToEnd(struct Node** head_ref){ /* If linked list is empty, or it contains only one node, then nothing needs to be done, simply return */ if (*head_ref == NULL || (*head_ref)->next == NULL) return; /* Initialize first and last pointers */ struct Node* first = *head_ref; struct Node* last = *head_ref; /*After this loop last contains address of last node in Linked List */ while (last->next != NULL) { last = last->next; } /* Change the head pointer to point to second node now */ *head_ref = first->next; /* Set the next of first as NULL */ first->next = NULL; /* Set the next of last as first */ last->next = first;} /* UTILITY FUNCTIONS *//* Function to add a node at the beginning of Linked List */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above function */int main(){ struct Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5 */ push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); printf(\"\\n Linked list before moving first to end\\n\"); printList(start); moveToEnd(&start); printf(\"\\n Linked list after moving first to end\\n\"); printList(start); return 0;}",
"e": 2533,
"s": 641,
"text": null
},
{
"code": "/* Java Program to move first element to endin a given linked list */class Sol{ /* A linked list node */static class Node{ int data; Node next;}; /* We are using a double pointer head_refhere because we change head of the linkedlist inside this function.*/static Node moveToEnd( Node head_ref){ /* If linked list is empty, or it contains only one node, then nothing needs to be done, simply return */ if (head_ref == null || (head_ref).next == null) return null; /* Initialize first and last pointers */ Node first = head_ref; Node last = head_ref; /*After this loop last contains address of last node in Linked List */ while (last.next != null) { last = last.next; } /* Change the head pointer to point to second node now */ head_ref = first.next; /* Set the next of first as null */ first.next = null; /* Set the next of last as first */ last.next = first; return head_ref;} /* UTILITY FUNCTIONS *//* Function to add a node at the beginningof Linked List */static Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} /* Function to print nodes in a given linked list */static void printList( Node node){ while (node != null) { System.out.printf(\"%d \", node.data); node = node.next; }} /* Driver code */public static void main(String args[]){ Node start = null; /* The constructed linked list is: 1.2.3.4.5 */ start = push(start, 5); start = push(start, 4); start = push(start, 3); start = push(start, 2); start = push(start, 1); System.out.printf(\"\\n Linked list before moving first to end\\n\"); printList(start); start = moveToEnd(start); System.out.printf(\"\\n Linked list after moving first to end\\n\"); printList(start);}} // This code is contributed by Arnab Kundu",
"e": 4483,
"s": 2533,
"text": null
},
{
"code": "# Python3 Program to move first element to end# in a given linked list # A linked list nodeclass Node: def __init__(self): self.data = 0 self.next = None # We are using a double pointer head_ref# here because we change head of the linked# list inside this function.def moveToEnd( head_ref) : # If linked list is empty, or it contains # only one node, then nothing needs to be # done, simply return if (head_ref == None or (head_ref).next == None) : return None # Initialize first and last pointers first = head_ref last = head_ref # After this loop last contains address # of last node in Linked List while (last.next != None) : last = last.next # Change the head pointer to point # to second node now head_ref = first.next # Set the next of first as None first.next = None # Set the next of last as first last.next = first return head_ref # UTILITY FUNCTIONS# Function to add a node at the beginning# of Linked Listdef push( head_ref, new_data) : new_node = Node() new_node.data = new_data new_node.next = (head_ref) (head_ref) = new_node return head_ref # Function to print nodes in a given linked listdef printList(node) : while (node != None): print(node.data, end = \" \") node = node.next # Driver code start = None # The constructed linked list is:#1.2.3.4.5start = push(start, 5)start = push(start, 4)start = push(start, 3)start = push(start, 2)start = push(start, 1) print(\"\\n Linked list before moving first to end\")printList(start) start = moveToEnd(start) print(\"\\n Linked list after moving first to end\")printList(start) # This code is contributed by Arnab Kundu",
"e": 6200,
"s": 4483,
"text": null
},
{
"code": "/* C# Program to move first element to endin a given linked list */using System; class GFG{ /* A linked list node */public class Node{ public int data; public Node next;}; /* We are using a double pointer head_refhere because we change head of the linkedlist inside this function.*/static Node moveToEnd( Node head_ref){ /* If linked list is empty, or it contains only one node, then nothing needs to be done, simply return */ if (head_ref == null || (head_ref).next == null) return null; /* Initialize first and last pointers */ Node first = head_ref; Node last = head_ref; /*After this loop last contains address of last node in Linked List */ while (last.next != null) { last = last.next; } /* Change the head pointer to point to second node now */ head_ref = first.next; /* Set the next of first as null */ first.next = null; /* Set the next of last as first */ last.next = first; return head_ref;} /* UTILITY FUNCTIONS *//* Function to add a node at the beginningof Linked List */static Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} /* Function to print nodes in a given linked list */static void printList( Node node){ while (node != null) { Console.Write(\"{0} \", node.data); node = node.next; }} /* Driver code */public static void Main(String []args){ Node start = null; /* The constructed linked list is: 1.2.3.4.5 */ start = push(start, 5); start = push(start, 4); start = push(start, 3); start = push(start, 2); start = push(start, 1); Console.Write(\"\\n Linked list before moving first to end\\n\"); printList(start); start = moveToEnd(start); Console.Write(\"\\n Linked list after moving first to end\\n\"); printList(start);}} // This code is contributed by 29AjayKumar",
"e": 8165,
"s": 6200,
"text": null
},
{
"code": "<script> // JavaScript program to move first element// to end in a given linked list /* A linked list node */class Node{ constructor() { this.data = 0; this.next = null; }} /* We are using a double pointer head_refhere because we change head of the linkedlist inside this function.*/function moveToEnd(head_ref){ /* If linked list is empty, or it contains only one node, then nothing needs to be done, simply return */ if (head_ref == null || head_ref.next == null) return null; /* Initialize first and last pointers */ var first = head_ref; var last = head_ref; /*After this loop last contains address of last node in Linked List */ while (last.next != null) { last = last.next; } /* Change the head pointer to point to second node now */ head_ref = first.next; /* Set the next of first as null */ first.next = null; /* Set the next of last as first */ last.next = first; return head_ref;} /* UTILITY FUNCTIONS *//* Function to add a node at the beginningof Linked List */function push(head_ref, new_data){ var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref;} // Function to print nodes in// a given linked listfunction printList(node){ while (node != null) { document.write(node.data + \" \"); node = node.next; }} // Driver codevar start = null; // The constructed linked list is:// 1.2.3.4.5start = push(start, 5);start = push(start, 4);start = push(start, 3);start = push(start, 2);start = push(start, 1); document.write(\"Linked list before \" + \"moving first to end<br>\");printList(start);start = moveToEnd(start); document.write(\"<br> Linked list after moving \" + \"first to end<br>\");printList(start); // This code is contributed by rdtank </script>",
"e": 10077,
"s": 8165,
"text": null
},
{
"code": null,
"e": 10176,
"s": 10077,
"text": "Linked list before moving first to end\n1 2 3 4 5 \n Linked list after moving first to end\n2 3 4 5 1"
},
{
"code": null,
"e": 10258,
"s": 10178,
"text": "Time Complexity: O(n) where n is the number of nodes in the given Linked List. "
},
{
"code": null,
"e": 10269,
"s": 10258,
"text": "andrew1234"
},
{
"code": null,
"e": 10281,
"s": 10269,
"text": "29AjayKumar"
},
{
"code": null,
"e": 10294,
"s": 10281,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 10301,
"s": 10294,
"text": "rdtank"
},
{
"code": null,
"e": 10313,
"s": 10301,
"text": "Linked List"
},
{
"code": null,
"e": 10325,
"s": 10313,
"text": "Linked List"
},
{
"code": null,
"e": 10423,
"s": 10325,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10455,
"s": 10423,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 10519,
"s": 10455,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 10540,
"s": 10519,
"text": "Types of Linked List"
},
{
"code": null,
"e": 10580,
"s": 10540,
"text": "Circular Singly Linked List | Insertion"
},
{
"code": null,
"e": 10621,
"s": 10580,
"text": "Find first node of loop in a linked list"
},
{
"code": null,
"e": 10673,
"s": 10621,
"text": "Add two numbers represented by linked lists | Set 2"
},
{
"code": null,
"e": 10698,
"s": 10673,
"text": "Flattening a Linked List"
},
{
"code": null,
"e": 10739,
"s": 10698,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 10793,
"s": 10739,
"text": "Insert a node at a specific position in a linked list"
}
] |
Queries of nCr%p in O(1) time complexity | 19 Jan, 2022
Given Q queries and P where P is a prime number, each query has two numbers N and R and the task is to calculate nCr mod p. Constraints:
N <= 106
R <= 106
p is a prime number
Examples:
Input: Q = 2 p = 1000000007 1st query: N = 15, R = 4 2nd query: N = 20, R = 3 Output: 1st query: 1365 2nd query: 1140 15!/(4!*(15-4)!)%1000000007 = 1365 20!/(20!*(20-3)!)%1000000007 = 1140
A naive approach is to calculate nCr using formulae by applying modular operations at any time. Hence time complexity will be O(q*n).
A better approach is to use fermat little theorem. According to it nCr can also be written as (n!/(r!*(n-r)!) ) mod which is equivalent to (n!*inverse(r!)*inverse((n-r)!) ) mod p. So, precomputing factorial of numbers from 1 to n will allow queries to be answered in O(log n). The only calculation that needs to be done is calculating inverse of r! and (n-r)!. Hence overall complexity will be q*( log(n)) .
A efficient approach will be to reduce the better approach to an efficient one by precomputing the inverse of factorials. Precompute inverse of factorial in O(n) time and then queries can be answered in O(1) time. Inverse of 1 to N natural number can be computed in O(n) time using Modular multiplicative inverse. Using recursive definition of factorial, the following can be written:
n! = n * (n-1) !
taking inverse on both side
inverse( n! ) = inverse( n ) * inverse( (n-1)! )
Since N’s maximum value is 106, precomputing values till 106 will do.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to answer queries// of nCr in O(1) time.#include <bits/stdc++.h>#define ll long longconst int N = 1000001;using namespace std; // array to store inverse of 1 to Nll factorialNumInverse[N + 1]; // array to precompute inverse of 1! to N!ll naturalNumInverse[N + 1]; // array to store factorial of first N numbersll fact[N + 1]; // Function to precompute inverse of numbersvoid InverseofNumber(ll p){ naturalNumInverse[0] = naturalNumInverse[1] = 1; for (int i = 2; i <= N; i++) naturalNumInverse[i] = naturalNumInverse[p % i] * (p - p / i) % p;}// Function to precompute inverse of factorialsvoid InverseofFactorial(ll p){ factorialNumInverse[0] = factorialNumInverse[1] = 1; // precompute inverse of natural numbers for (int i = 2; i <= N; i++) factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p;} // Function to calculate factorial of 1 to Nvoid factorial(ll p){ fact[0] = 1; // precompute factorials for (int i = 1; i <= N; i++) { fact[i] = (fact[i - 1] * i) % p; }} // Function to return nCr % p in O(1) timell Binomial(ll N, ll R, ll p){ // n C r = n!*inverse(r!)*inverse((n-r)!) ll ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p; return ans;} // Driver Codeint main(){ // Calling functions to precompute the // required arrays which will be required // to answer every query in O(1) ll p = 1000000007; InverseofNumber(p); InverseofFactorial(p); factorial(p); // 1st query ll N = 15; ll R = 4; cout << Binomial(N, R, p) << endl; // 2nd query N = 20; R = 3; cout << Binomial(N, R, p) << endl; return 0;}
// Java program to answer queries// of nCr in O(1) timeimport java.io.*; class GFG{ static int N = 1000001; // Array to store inverse of 1 to Nstatic long[] factorialNumInverse = new long[N + 1]; // Array to precompute inverse of 1! to N!static long[] naturalNumInverse = new long[N + 1]; // Array to store factorial of first N numbersstatic long[] fact = new long[N + 1]; // Function to precompute inverse of numberspublic static void InverseofNumber(int p){ naturalNumInverse[0] = naturalNumInverse[1] = 1; for(int i = 2; i <= N; i++) naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p;} // Function to precompute inverse of factorialspublic static void InverseofFactorial(int p){ factorialNumInverse[0] = factorialNumInverse[1] = 1; // Precompute inverse of natural numbers for(int i = 2; i <= N; i++) factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p;} // Function to calculate factorial of 1 to Npublic static void factorial(int p){ fact[0] = 1; // Precompute factorials for(int i = 1; i <= N; i++) { fact[i] = (fact[i - 1] * (long)i) % p; }} // Function to return nCr % p in O(1) timepublic static long Binomial(int N, int R, int p){ // n C r = n!*inverse(r!)*inverse((n-r)!) long ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p; return ans;} // Driver codepublic static void main (String[] args){ // Calling functions to precompute the // required arrays which will be required // to answer every query in O(1) int p = 1000000007; InverseofNumber(p); InverseofFactorial(p); factorial(p); // 1st query int n = 15; int R = 4; System.out.println(Binomial(n, R, p)); // 2nd query n = 20; R = 3; System.out.println(Binomial(n, R, p));}} // This code is contributed by RohitOberoi
# Python3 program to answer queries# of nCr in O(1) time.N = 1000001 # array to store inverse of 1 to NfactorialNumInverse = [None] * (N + 1) # array to precompute inverse of 1! to N!naturalNumInverse = [None] * (N + 1) # array to store factorial of# first N numbersfact = [None] * (N + 1) # Function to precompute inverse of numbersdef InverseofNumber(p): naturalNumInverse[0] = naturalNumInverse[1] = 1 for i in range(2, N + 1, 1): naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - int(p / i)) % p) # Function to precompute inverse# of factorialsdef InverseofFactorial(p): factorialNumInverse[0] = factorialNumInverse[1] = 1 # precompute inverse of natural numbers for i in range(2, N + 1, 1): factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p # Function to calculate factorial of 1 to Ndef factorial(p): fact[0] = 1 # precompute factorials for i in range(1, N + 1): fact[i] = (fact[i - 1] * i) % p # Function to return nCr % p in O(1) timedef Binomial(N, R, p): # n C r = n!*inverse(r!)*inverse((n-r)!) ans = ((fact[N] * factorialNumInverse[R])% p * factorialNumInverse[N - R])% p return ans # Driver Codeif __name__ == '__main__': # Calling functions to precompute the # required arrays which will be required # to answer every query in O(1) p = 1000000007 InverseofNumber(p) InverseofFactorial(p) factorial(p) # 1st query N = 15 R = 4 print(Binomial(N, R, p)) # 2nd query N = 20 R = 3 print(Binomial(N, R, p)) # This code is contributed by# Surendra_Gangwar
// C# program to answer queries // of nCr in O(1) timeusing System; class GFG{ static int N = 1000001; // Array to store inverse of 1 to N static long[] factorialNumInverse = new long[N + 1]; // Array to precompute inverse of 1! to N! static long[] naturalNumInverse = new long[N + 1]; // Array to store factorial of first N numbers static long[] fact = new long[N + 1]; // Function to precompute inverse of numbers static void InverseofNumber(int p) { naturalNumInverse[0] = naturalNumInverse[1] = 1; for(int i = 2; i <= N; i++) naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p; } // Function to precompute inverse of factorials static void InverseofFactorial(int p) { factorialNumInverse[0] = factorialNumInverse[1] = 1; // Precompute inverse of natural numbers for(int i = 2; i <= N; i++) factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p; } // Function to calculate factorial of 1 to N static void factorial(int p) { fact[0] = 1; // Precompute factorials for(int i = 1; i <= N; i++) { fact[i] = (fact[i - 1] * (long)i) % p; } } // Function to return nCr % p in O(1) time static long Binomial(int N, int R, int p) { // n C r = n!*inverse(r!)*inverse((n-r)!) long ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p; return ans; } // Driver codestatic void Main(){ // Calling functions to precompute the // required arrays which will be required // to answer every query in O(1) int p = 1000000007; InverseofNumber(p); InverseofFactorial(p); factorial(p); // 1st query int n = 15; int R = 4; Console.WriteLine(Binomial(n, R, p)); // 2nd query n = 20; R = 3; Console.WriteLine(Binomial(n, R, p));}} // This code is contributed by divyeshrabadiya07
<script> // Javascript program to answer queries// of nCr in O(1) time.var N = 1000001; // array to store inverse of 1 to NfactorialNumInverse = Array(N+1).fill(0); // array to precompute inverse of 1! to N!naturalNumInverse = Array(N+1).fill(0); // array to store factorial of first N numbersfact = Array(N+1).fill(0); // Function to precompute inverse of numbersfunction InverseofNumber(p){ naturalNumInverse[0] = naturalNumInverse[1] = 1; for (var i = 2; i <= N; i++) naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - parseInt(p / i))) % p;} // Function to precompute inverse of factorialsfunction InverseofFactorial(p){ factorialNumInverse[0] = factorialNumInverse[1] = 1; // precompute inverse of natural numbers for (var i = 2; i <= N; i++) factorialNumInverse[i] = ((naturalNumInverse[i] * factorialNumInverse[i - 1])) % p;} // Function to calculate factorial of 1 to Nfunction factorial(p){ fact[0] = 1; // precompute factorials for (var i = 1; i <= N; i++) { fact[i] = (fact[i - 1] * i) % p; }} // Function to return nCr % p in O(1) timefunction Binomial(N, R, p){ // n C r = n!*inverse(r!)*inverse((n-r)!) var ans = ((((fact[N] * factorialNumInverse[R])% p) * factorialNumInverse[N - R]))% p; return ans;} // Driver Code // Calling functions to precompute the// required arrays which will be required// to answer every query in O(1)p = 100000007;InverseofNumber(p);InverseofFactorial(p);factorial(p); // 1st queryN = 15;R = 4;document.write(Binomial(N, R, p)+"<br>") // 2nd queryN = 20;R = 3;document.write(Binomial(N, R, p)); // This code is contributed by noob2000.</script>
1365
1140
Time Complexity: O(N) for precomputing and O(1) for every query.Auxiliary Space: O(N)
SURENDRA_GANGWAR
RohitOberoi
divyeshrabadiya07
noob2000
pankajsharmagfg
surinderdawra388
binomial coefficient
factorial
Modular Arithmetic
Permutation and Combination
Prime Number
Algorithms
Prime Number
Modular Arithmetic
factorial
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Understanding Time Complexity with Simple Examples
CPU Scheduling in Operating Systems
Find if there is a path between two vertices in an undirected graph
A* Search Algorithm
What is Algorithm | Introduction to Algorithms
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
Analysis of Algorithms | Set 3 (Asymptotic Notations) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 190,
"s": 52,
"text": "Given Q queries and P where P is a prime number, each query has two numbers N and R and the task is to calculate nCr mod p. Constraints: "
},
{
"code": null,
"e": 228,
"s": 190,
"text": "N <= 106\nR <= 106\np is a prime number"
},
{
"code": null,
"e": 238,
"s": 228,
"text": "Examples:"
},
{
"code": null,
"e": 427,
"s": 238,
"text": "Input: Q = 2 p = 1000000007 1st query: N = 15, R = 4 2nd query: N = 20, R = 3 Output: 1st query: 1365 2nd query: 1140 15!/(4!*(15-4)!)%1000000007 = 1365 20!/(20!*(20-3)!)%1000000007 = 1140"
},
{
"code": null,
"e": 561,
"s": 427,
"text": "A naive approach is to calculate nCr using formulae by applying modular operations at any time. Hence time complexity will be O(q*n)."
},
{
"code": null,
"e": 969,
"s": 561,
"text": "A better approach is to use fermat little theorem. According to it nCr can also be written as (n!/(r!*(n-r)!) ) mod which is equivalent to (n!*inverse(r!)*inverse((n-r)!) ) mod p. So, precomputing factorial of numbers from 1 to n will allow queries to be answered in O(log n). The only calculation that needs to be done is calculating inverse of r! and (n-r)!. Hence overall complexity will be q*( log(n)) ."
},
{
"code": null,
"e": 1354,
"s": 969,
"text": "A efficient approach will be to reduce the better approach to an efficient one by precomputing the inverse of factorials. Precompute inverse of factorial in O(n) time and then queries can be answered in O(1) time. Inverse of 1 to N natural number can be computed in O(n) time using Modular multiplicative inverse. Using recursive definition of factorial, the following can be written:"
},
{
"code": null,
"e": 1449,
"s": 1354,
"text": "n! = n * (n-1) !\ntaking inverse on both side \ninverse( n! ) = inverse( n ) * inverse( (n-1)! )"
},
{
"code": null,
"e": 1519,
"s": 1449,
"text": "Since N’s maximum value is 106, precomputing values till 106 will do."
},
{
"code": null,
"e": 1570,
"s": 1519,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1574,
"s": 1570,
"text": "C++"
},
{
"code": null,
"e": 1579,
"s": 1574,
"text": "Java"
},
{
"code": null,
"e": 1587,
"s": 1579,
"text": "Python3"
},
{
"code": null,
"e": 1590,
"s": 1587,
"text": "C#"
},
{
"code": null,
"e": 1601,
"s": 1590,
"text": "Javascript"
},
{
"code": "// C++ program to answer queries// of nCr in O(1) time.#include <bits/stdc++.h>#define ll long longconst int N = 1000001;using namespace std; // array to store inverse of 1 to Nll factorialNumInverse[N + 1]; // array to precompute inverse of 1! to N!ll naturalNumInverse[N + 1]; // array to store factorial of first N numbersll fact[N + 1]; // Function to precompute inverse of numbersvoid InverseofNumber(ll p){ naturalNumInverse[0] = naturalNumInverse[1] = 1; for (int i = 2; i <= N; i++) naturalNumInverse[i] = naturalNumInverse[p % i] * (p - p / i) % p;}// Function to precompute inverse of factorialsvoid InverseofFactorial(ll p){ factorialNumInverse[0] = factorialNumInverse[1] = 1; // precompute inverse of natural numbers for (int i = 2; i <= N; i++) factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p;} // Function to calculate factorial of 1 to Nvoid factorial(ll p){ fact[0] = 1; // precompute factorials for (int i = 1; i <= N; i++) { fact[i] = (fact[i - 1] * i) % p; }} // Function to return nCr % p in O(1) timell Binomial(ll N, ll R, ll p){ // n C r = n!*inverse(r!)*inverse((n-r)!) ll ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p; return ans;} // Driver Codeint main(){ // Calling functions to precompute the // required arrays which will be required // to answer every query in O(1) ll p = 1000000007; InverseofNumber(p); InverseofFactorial(p); factorial(p); // 1st query ll N = 15; ll R = 4; cout << Binomial(N, R, p) << endl; // 2nd query N = 20; R = 3; cout << Binomial(N, R, p) << endl; return 0;}",
"e": 3320,
"s": 1601,
"text": null
},
{
"code": "// Java program to answer queries// of nCr in O(1) timeimport java.io.*; class GFG{ static int N = 1000001; // Array to store inverse of 1 to Nstatic long[] factorialNumInverse = new long[N + 1]; // Array to precompute inverse of 1! to N!static long[] naturalNumInverse = new long[N + 1]; // Array to store factorial of first N numbersstatic long[] fact = new long[N + 1]; // Function to precompute inverse of numberspublic static void InverseofNumber(int p){ naturalNumInverse[0] = naturalNumInverse[1] = 1; for(int i = 2; i <= N; i++) naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p;} // Function to precompute inverse of factorialspublic static void InverseofFactorial(int p){ factorialNumInverse[0] = factorialNumInverse[1] = 1; // Precompute inverse of natural numbers for(int i = 2; i <= N; i++) factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p;} // Function to calculate factorial of 1 to Npublic static void factorial(int p){ fact[0] = 1; // Precompute factorials for(int i = 1; i <= N; i++) { fact[i] = (fact[i - 1] * (long)i) % p; }} // Function to return nCr % p in O(1) timepublic static long Binomial(int N, int R, int p){ // n C r = n!*inverse(r!)*inverse((n-r)!) long ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p; return ans;} // Driver codepublic static void main (String[] args){ // Calling functions to precompute the // required arrays which will be required // to answer every query in O(1) int p = 1000000007; InverseofNumber(p); InverseofFactorial(p); factorial(p); // 1st query int n = 15; int R = 4; System.out.println(Binomial(n, R, p)); // 2nd query n = 20; R = 3; System.out.println(Binomial(n, R, p));}} // This code is contributed by RohitOberoi",
"e": 5308,
"s": 3320,
"text": null
},
{
"code": "# Python3 program to answer queries# of nCr in O(1) time.N = 1000001 # array to store inverse of 1 to NfactorialNumInverse = [None] * (N + 1) # array to precompute inverse of 1! to N!naturalNumInverse = [None] * (N + 1) # array to store factorial of# first N numbersfact = [None] * (N + 1) # Function to precompute inverse of numbersdef InverseofNumber(p): naturalNumInverse[0] = naturalNumInverse[1] = 1 for i in range(2, N + 1, 1): naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - int(p / i)) % p) # Function to precompute inverse# of factorialsdef InverseofFactorial(p): factorialNumInverse[0] = factorialNumInverse[1] = 1 # precompute inverse of natural numbers for i in range(2, N + 1, 1): factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p # Function to calculate factorial of 1 to Ndef factorial(p): fact[0] = 1 # precompute factorials for i in range(1, N + 1): fact[i] = (fact[i - 1] * i) % p # Function to return nCr % p in O(1) timedef Binomial(N, R, p): # n C r = n!*inverse(r!)*inverse((n-r)!) ans = ((fact[N] * factorialNumInverse[R])% p * factorialNumInverse[N - R])% p return ans # Driver Codeif __name__ == '__main__': # Calling functions to precompute the # required arrays which will be required # to answer every query in O(1) p = 1000000007 InverseofNumber(p) InverseofFactorial(p) factorial(p) # 1st query N = 15 R = 4 print(Binomial(N, R, p)) # 2nd query N = 20 R = 3 print(Binomial(N, R, p)) # This code is contributed by# Surendra_Gangwar",
"e": 7009,
"s": 5308,
"text": null
},
{
"code": "// C# program to answer queries // of nCr in O(1) timeusing System; class GFG{ static int N = 1000001; // Array to store inverse of 1 to N static long[] factorialNumInverse = new long[N + 1]; // Array to precompute inverse of 1! to N! static long[] naturalNumInverse = new long[N + 1]; // Array to store factorial of first N numbers static long[] fact = new long[N + 1]; // Function to precompute inverse of numbers static void InverseofNumber(int p) { naturalNumInverse[0] = naturalNumInverse[1] = 1; for(int i = 2; i <= N; i++) naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p; } // Function to precompute inverse of factorials static void InverseofFactorial(int p) { factorialNumInverse[0] = factorialNumInverse[1] = 1; // Precompute inverse of natural numbers for(int i = 2; i <= N; i++) factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p; } // Function to calculate factorial of 1 to N static void factorial(int p) { fact[0] = 1; // Precompute factorials for(int i = 1; i <= N; i++) { fact[i] = (fact[i - 1] * (long)i) % p; } } // Function to return nCr % p in O(1) time static long Binomial(int N, int R, int p) { // n C r = n!*inverse(r!)*inverse((n-r)!) long ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p; return ans; } // Driver codestatic void Main(){ // Calling functions to precompute the // required arrays which will be required // to answer every query in O(1) int p = 1000000007; InverseofNumber(p); InverseofFactorial(p); factorial(p); // 1st query int n = 15; int R = 4; Console.WriteLine(Binomial(n, R, p)); // 2nd query n = 20; R = 3; Console.WriteLine(Binomial(n, R, p));}} // This code is contributed by divyeshrabadiya07",
"e": 9025,
"s": 7009,
"text": null
},
{
"code": "<script> // Javascript program to answer queries// of nCr in O(1) time.var N = 1000001; // array to store inverse of 1 to NfactorialNumInverse = Array(N+1).fill(0); // array to precompute inverse of 1! to N!naturalNumInverse = Array(N+1).fill(0); // array to store factorial of first N numbersfact = Array(N+1).fill(0); // Function to precompute inverse of numbersfunction InverseofNumber(p){ naturalNumInverse[0] = naturalNumInverse[1] = 1; for (var i = 2; i <= N; i++) naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - parseInt(p / i))) % p;} // Function to precompute inverse of factorialsfunction InverseofFactorial(p){ factorialNumInverse[0] = factorialNumInverse[1] = 1; // precompute inverse of natural numbers for (var i = 2; i <= N; i++) factorialNumInverse[i] = ((naturalNumInverse[i] * factorialNumInverse[i - 1])) % p;} // Function to calculate factorial of 1 to Nfunction factorial(p){ fact[0] = 1; // precompute factorials for (var i = 1; i <= N; i++) { fact[i] = (fact[i - 1] * i) % p; }} // Function to return nCr % p in O(1) timefunction Binomial(N, R, p){ // n C r = n!*inverse(r!)*inverse((n-r)!) var ans = ((((fact[N] * factorialNumInverse[R])% p) * factorialNumInverse[N - R]))% p; return ans;} // Driver Code // Calling functions to precompute the// required arrays which will be required// to answer every query in O(1)p = 100000007;InverseofNumber(p);InverseofFactorial(p);factorial(p); // 1st queryN = 15;R = 4;document.write(Binomial(N, R, p)+\"<br>\") // 2nd queryN = 20;R = 3;document.write(Binomial(N, R, p)); // This code is contributed by noob2000.</script>",
"e": 10678,
"s": 9025,
"text": null
},
{
"code": null,
"e": 10688,
"s": 10678,
"text": "1365\n1140"
},
{
"code": null,
"e": 10775,
"s": 10688,
"text": "Time Complexity: O(N) for precomputing and O(1) for every query.Auxiliary Space: O(N) "
},
{
"code": null,
"e": 10792,
"s": 10775,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 10804,
"s": 10792,
"text": "RohitOberoi"
},
{
"code": null,
"e": 10822,
"s": 10804,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 10831,
"s": 10822,
"text": "noob2000"
},
{
"code": null,
"e": 10847,
"s": 10831,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 10864,
"s": 10847,
"text": "surinderdawra388"
},
{
"code": null,
"e": 10885,
"s": 10864,
"text": "binomial coefficient"
},
{
"code": null,
"e": 10895,
"s": 10885,
"text": "factorial"
},
{
"code": null,
"e": 10914,
"s": 10895,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 10942,
"s": 10914,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 10955,
"s": 10942,
"text": "Prime Number"
},
{
"code": null,
"e": 10966,
"s": 10955,
"text": "Algorithms"
},
{
"code": null,
"e": 10979,
"s": 10966,
"text": "Prime Number"
},
{
"code": null,
"e": 10998,
"s": 10979,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 11008,
"s": 10998,
"text": "factorial"
},
{
"code": null,
"e": 11019,
"s": 11008,
"text": "Algorithms"
},
{
"code": null,
"e": 11117,
"s": 11019,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11142,
"s": 11117,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 11191,
"s": 11142,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 11229,
"s": 11191,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 11280,
"s": 11229,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 11316,
"s": 11280,
"text": "CPU Scheduling in Operating Systems"
},
{
"code": null,
"e": 11384,
"s": 11316,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 11404,
"s": 11384,
"text": "A* Search Algorithm"
},
{
"code": null,
"e": 11451,
"s": 11404,
"text": "What is Algorithm | Introduction to Algorithms"
},
{
"code": null,
"e": 11514,
"s": 11451,
"text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)"
}
] |
How to Copy or Append HashSet to Another HashSet in Java? | 15 Dec, 2020
HashSet is used to store distinct values in Java. HashSet stores the elements in random order, so there is no guarantee of the elements’ order. The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance.
We can copy or append a HashSet to another HashSet. There is a couple of ways to copy HashSet or append HashSet to another HashSet in Java:
Using HashSet constructor
Using clone() method
Using the addAll() method
Method 1: Using the HashSet constructor
Using the constructor, we can copy the original HashSet to another HashSet bypassing the original HashSet to the constructor.
// passing the original HashSet to the constructor
HashSet<Integer> copySet = new HashSet<>(originalSet)
Code:
Java
// Java program to copy a HashSet to// another HashSet using the constructor import java.util.*; public class GFG { public static void main(String[] args) { // New HashSet HashSet<Integer> set = new HashSet<>(); // Add elements to original set set.add(10); set.add(20); set.add(30); set.add(10); set.add(50); set.add(20); // Make a new HashSet and copy all elements of // original HashSet using constructor HashSet<Integer> copyOfSet = new HashSet<>(set); // Print original HashSet System.out.println("Original HashSet: " + set); // Print Copy HashSet System.out.println("Copy HashSet: " + copyOfSet); }}
Original HashSet: [50, 20, 10, 30]
Copy HashSet: [50, 20, 10, 30]
Method 2: Using the clone method
Using the clone method, we can copy all elements of the original HashSet to another HashSet in Java.
Note: The order of elements may be the same or may not be the same. So there is no guarantee of the order.
Code:
Java
// Java program to copy a HashSet to // another HashSet using clone method in Java import java.util.*; public class GFG { public static void main(String[] args) { // New empty HashSet HashSet<Integer> set = new HashSet<>(); // Add elements to set set.add(10); set.add(20); set.add(30); set.add(10); set.add(50); set.add(20); // Create a new HashSet to copy the original HashSet HashSet copyOfSet = new HashSet(); // Copy HashSet using clone method copyOfSet = (HashSet)set.clone(); // Print original HashSet System.out.println("Original HashSet: " + set); // Print Copy HashSet System.out.println("Copy HashSet: " + copyOfSet); }}
Original HashSet: [50, 20, 10, 30]
Copy HashSet: [50, 10, 20, 30]
Method 3: Using the addAll method
We can use the addAll() method to copy or to append a HashSet to a another HashSet. addAll method in Java add all elements to the HashSet.
Note: The order of elements may be the same or may not be the same. So there is no guarantee of the order.
Code:
Java
// Java program to copy a HashSet to // another HashSet using addAll method in Java import java.util.*; public class GFG { public static void main(String[] args) { // New empty HashSet HashSet<Integer> set = new HashSet<>(); // Add elements to set set.add(10); set.add(20); set.add(30); set.add(10); set.add(50); set.add(20); // Create a new HashSet to copy the original HashSet HashSet<Integer> copyOfSet = new HashSet<>(); // Copy HashSet using addAll method copyOfSet.addAll(set); // Print original HashSet System.out.println("Original HashSet: " + set); // Print Copy HashSet System.out.println("Copy HashSet: " + copyOfSet); }}
Original HashSet: [50, 20, 10, 30]
Copy HashSet: [50, 20, 10, 30]
Append using addAll method in the already existing HashSet:
Code:
Java
// Java program to copy a HashSet to another // HashSet using addAll method in Java import java.util.*; public class GFG { public static void main(String[] args) { // New empty HashSet HashSet<Integer> set = new HashSet<>(); // Add elements to set set.add(10); set.add(20); set.add(30); set.add(10); set.add(50); set.add(20); // Create a new HashSet to append a HashSet HashSet<Integer> appendedSet = new HashSet<>(); // Add elements to appendedSet appendedSet.add(100); appendedSet.add(200); System.out.println("Before appending :"); // Print original HashSet System.out.println("Original HashSet: " + set); // Print appendedSet before append System.out.println("Appended HashSet: " + appendedSet); // Add all elements of set HashSet to appendedSet // using addAll method appendedSet.addAll(set); System.out.println("After appending"); // Print appendedSet after append System.out.println("Appended HashSet: " + appendedSet); }}
Before appending :
Original HashSet: [50, 20, 10, 30]
Appended HashSet: [100, 200]
After appending
Appended HashSet: [50, 100, 20, 200, 10, 30]
java-hashset
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Dec, 2020"
},
{
"code": null,
"e": 282,
"s": 28,
"text": "HashSet is used to store distinct values in Java. HashSet stores the elements in random order, so there is no guarantee of the elements’ order. The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. "
},
{
"code": null,
"e": 422,
"s": 282,
"text": "We can copy or append a HashSet to another HashSet. There is a couple of ways to copy HashSet or append HashSet to another HashSet in Java:"
},
{
"code": null,
"e": 448,
"s": 422,
"text": "Using HashSet constructor"
},
{
"code": null,
"e": 469,
"s": 448,
"text": "Using clone() method"
},
{
"code": null,
"e": 495,
"s": 469,
"text": "Using the addAll() method"
},
{
"code": null,
"e": 535,
"s": 495,
"text": "Method 1: Using the HashSet constructor"
},
{
"code": null,
"e": 661,
"s": 535,
"text": "Using the constructor, we can copy the original HashSet to another HashSet bypassing the original HashSet to the constructor."
},
{
"code": null,
"e": 767,
"s": 661,
"text": "// passing the original HashSet to the constructor\n\nHashSet<Integer> copySet = new HashSet<>(originalSet)"
},
{
"code": null,
"e": 773,
"s": 767,
"text": "Code:"
},
{
"code": null,
"e": 778,
"s": 773,
"text": "Java"
},
{
"code": "// Java program to copy a HashSet to// another HashSet using the constructor import java.util.*; public class GFG { public static void main(String[] args) { // New HashSet HashSet<Integer> set = new HashSet<>(); // Add elements to original set set.add(10); set.add(20); set.add(30); set.add(10); set.add(50); set.add(20); // Make a new HashSet and copy all elements of // original HashSet using constructor HashSet<Integer> copyOfSet = new HashSet<>(set); // Print original HashSet System.out.println(\"Original HashSet: \" + set); // Print Copy HashSet System.out.println(\"Copy HashSet: \" + copyOfSet); }}",
"e": 1516,
"s": 778,
"text": null
},
{
"code": null,
"e": 1582,
"s": 1516,
"text": "Original HashSet: [50, 20, 10, 30]\nCopy HashSet: [50, 20, 10, 30]"
},
{
"code": null,
"e": 1615,
"s": 1582,
"text": "Method 2: Using the clone method"
},
{
"code": null,
"e": 1716,
"s": 1615,
"text": "Using the clone method, we can copy all elements of the original HashSet to another HashSet in Java."
},
{
"code": null,
"e": 1823,
"s": 1716,
"text": "Note: The order of elements may be the same or may not be the same. So there is no guarantee of the order."
},
{
"code": null,
"e": 1829,
"s": 1823,
"text": "Code:"
},
{
"code": null,
"e": 1834,
"s": 1829,
"text": "Java"
},
{
"code": "// Java program to copy a HashSet to // another HashSet using clone method in Java import java.util.*; public class GFG { public static void main(String[] args) { // New empty HashSet HashSet<Integer> set = new HashSet<>(); // Add elements to set set.add(10); set.add(20); set.add(30); set.add(10); set.add(50); set.add(20); // Create a new HashSet to copy the original HashSet HashSet copyOfSet = new HashSet(); // Copy HashSet using clone method copyOfSet = (HashSet)set.clone(); // Print original HashSet System.out.println(\"Original HashSet: \" + set); // Print Copy HashSet System.out.println(\"Copy HashSet: \" + copyOfSet); }}",
"e": 2607,
"s": 1834,
"text": null
},
{
"code": null,
"e": 2673,
"s": 2607,
"text": "Original HashSet: [50, 20, 10, 30]\nCopy HashSet: [50, 10, 20, 30]"
},
{
"code": null,
"e": 2707,
"s": 2673,
"text": "Method 3: Using the addAll method"
},
{
"code": null,
"e": 2848,
"s": 2707,
"text": "We can use the addAll() method to copy or to append a HashSet to a another HashSet. addAll method in Java add all elements to the HashSet. "
},
{
"code": null,
"e": 2955,
"s": 2848,
"text": "Note: The order of elements may be the same or may not be the same. So there is no guarantee of the order."
},
{
"code": null,
"e": 2961,
"s": 2955,
"text": "Code:"
},
{
"code": null,
"e": 2966,
"s": 2961,
"text": "Java"
},
{
"code": "// Java program to copy a HashSet to // another HashSet using addAll method in Java import java.util.*; public class GFG { public static void main(String[] args) { // New empty HashSet HashSet<Integer> set = new HashSet<>(); // Add elements to set set.add(10); set.add(20); set.add(30); set.add(10); set.add(50); set.add(20); // Create a new HashSet to copy the original HashSet HashSet<Integer> copyOfSet = new HashSet<>(); // Copy HashSet using addAll method copyOfSet.addAll(set); // Print original HashSet System.out.println(\"Original HashSet: \" + set); // Print Copy HashSet System.out.println(\"Copy HashSet: \" + copyOfSet); }}",
"e": 3674,
"s": 2966,
"text": null
},
{
"code": null,
"e": 3740,
"s": 3674,
"text": "Original HashSet: [50, 20, 10, 30]\nCopy HashSet: [50, 20, 10, 30]"
},
{
"code": null,
"e": 3800,
"s": 3740,
"text": "Append using addAll method in the already existing HashSet:"
},
{
"code": null,
"e": 3806,
"s": 3800,
"text": "Code:"
},
{
"code": null,
"e": 3811,
"s": 3806,
"text": "Java"
},
{
"code": "// Java program to copy a HashSet to another // HashSet using addAll method in Java import java.util.*; public class GFG { public static void main(String[] args) { // New empty HashSet HashSet<Integer> set = new HashSet<>(); // Add elements to set set.add(10); set.add(20); set.add(30); set.add(10); set.add(50); set.add(20); // Create a new HashSet to append a HashSet HashSet<Integer> appendedSet = new HashSet<>(); // Add elements to appendedSet appendedSet.add(100); appendedSet.add(200); System.out.println(\"Before appending :\"); // Print original HashSet System.out.println(\"Original HashSet: \" + set); // Print appendedSet before append System.out.println(\"Appended HashSet: \" + appendedSet); // Add all elements of set HashSet to appendedSet // using addAll method appendedSet.addAll(set); System.out.println(\"After appending\"); // Print appendedSet after append System.out.println(\"Appended HashSet: \" + appendedSet); }}",
"e": 4999,
"s": 3811,
"text": null
},
{
"code": null,
"e": 5143,
"s": 4999,
"text": "Before appending :\nOriginal HashSet: [50, 20, 10, 30]\nAppended HashSet: [100, 200]\nAfter appending\nAppended HashSet: [50, 100, 20, 200, 10, 30]"
},
{
"code": null,
"e": 5156,
"s": 5143,
"text": "java-hashset"
},
{
"code": null,
"e": 5163,
"s": 5156,
"text": "Picked"
},
{
"code": null,
"e": 5168,
"s": 5163,
"text": "Java"
},
{
"code": null,
"e": 5182,
"s": 5168,
"text": "Java Programs"
},
{
"code": null,
"e": 5187,
"s": 5182,
"text": "Java"
}
] |
Laplace Transform in MATLAB | 21 Apr, 2021
In this article, we will see how to find Laplace Transform in MATLAB. Laplace Transform helps to simplify problems that involve Differential Equations into algebraic equations. As the name suggests, it transforms the time-domain function f(t) into Laplace domain function F(s).
Using the above function one can generate a Laplace Transform of any expression.
Example 1: Find the Laplace Transform of .
Matlab
% specify the variable a, t and s as symbolic ones % The syms function creates a variable dynamically % and automatically assigns to a MATLAB variable% with the same namesyms a t s % define function f(t) f=cos(a*t); % laplace command to transform into % Laplace domain function F(s)F=laplace(f,t,s); % Display the output valuedisp('Laplace Transform of cos(at):')disp(F);
Output:
Example 2: Find the Laplace Transform of a particular expression i.e. 1+2e^{(-t)}+3e^{(-2t)}.
Matlab
% specify the variable a, t and s % as symbolic ones syms a t s e % define function f(t) f=1+2*exp(-t)+3*exp(-2*t); % laplace command to transform into % Laplace domain function F(s)F=laplace(f,t,s); % Display the output valuedisp('Laplace Transform of 1+2e^{(-t)}+3e^{(-2t)}:')disp(F);
Output:
MATLAB-Maths
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
Classes and Object in MATLAB
How to find inverse Laplace Transforms using MATLAB ?
2D Array Interpolation in MATLAB
Create Array of Zeros in MATLAB
Installing MATLAB on MacOS
Page-wise matrix multiplication in MATLAB
MATLAB - Trapezoidal numerical integration without using trapz
Mesh Surface Plot in MATLAB | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 330,
"s": 52,
"text": "In this article, we will see how to find Laplace Transform in MATLAB. Laplace Transform helps to simplify problems that involve Differential Equations into algebraic equations. As the name suggests, it transforms the time-domain function f(t) into Laplace domain function F(s)."
},
{
"code": null,
"e": 413,
"s": 332,
"text": "Using the above function one can generate a Laplace Transform of any expression."
},
{
"code": null,
"e": 456,
"s": 413,
"text": "Example 1: Find the Laplace Transform of ."
},
{
"code": null,
"e": 463,
"s": 456,
"text": "Matlab"
},
{
"code": "% specify the variable a, t and s as symbolic ones % The syms function creates a variable dynamically % and automatically assigns to a MATLAB variable% with the same namesyms a t s % define function f(t) f=cos(a*t); % laplace command to transform into % Laplace domain function F(s)F=laplace(f,t,s); % Display the output valuedisp('Laplace Transform of cos(at):')disp(F);",
"e": 840,
"s": 463,
"text": null
},
{
"code": null,
"e": 848,
"s": 840,
"text": "Output:"
},
{
"code": null,
"e": 942,
"s": 848,
"text": "Example 2: Find the Laplace Transform of a particular expression i.e. 1+2e^{(-t)}+3e^{(-2t)}."
},
{
"code": null,
"e": 949,
"s": 942,
"text": "Matlab"
},
{
"code": "% specify the variable a, t and s % as symbolic ones syms a t s e % define function f(t) f=1+2*exp(-t)+3*exp(-2*t); % laplace command to transform into % Laplace domain function F(s)F=laplace(f,t,s); % Display the output valuedisp('Laplace Transform of 1+2e^{(-t)}+3e^{(-2t)}:')disp(F);",
"e": 1242,
"s": 949,
"text": null
},
{
"code": null,
"e": 1251,
"s": 1242,
"text": "Output: "
},
{
"code": null,
"e": 1264,
"s": 1251,
"text": "MATLAB-Maths"
},
{
"code": null,
"e": 1271,
"s": 1264,
"text": "Picked"
},
{
"code": null,
"e": 1278,
"s": 1271,
"text": "MATLAB"
},
{
"code": null,
"e": 1376,
"s": 1278,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1441,
"s": 1376,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 1481,
"s": 1441,
"text": "How to Normalize a Histogram in MATLAB?"
},
{
"code": null,
"e": 1510,
"s": 1481,
"text": "Classes and Object in MATLAB"
},
{
"code": null,
"e": 1564,
"s": 1510,
"text": "How to find inverse Laplace Transforms using MATLAB ?"
},
{
"code": null,
"e": 1597,
"s": 1564,
"text": "2D Array Interpolation in MATLAB"
},
{
"code": null,
"e": 1629,
"s": 1597,
"text": "Create Array of Zeros in MATLAB"
},
{
"code": null,
"e": 1656,
"s": 1629,
"text": "Installing MATLAB on MacOS"
},
{
"code": null,
"e": 1698,
"s": 1656,
"text": "Page-wise matrix multiplication in MATLAB"
},
{
"code": null,
"e": 1761,
"s": 1698,
"text": "MATLAB - Trapezoidal numerical integration without using trapz"
}
] |
BlockingQueue Interface in Java | 15 Sep, 2021
The BlockingQueue interface in Java is added in Java 1.5 along with various other concurrent Utility classes like ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrrayList, etc. 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.Java provides several BlockingQueue implementations such as LinkedBlockingQueue, ArrayBlockingQueue, PriorityBlockingQueue, SynchronousQueue, etc. Java BlockingQueue interface implementations are thread-safe. All methods of BlockingQueue are atomic in nature and use internal locks or other forms of concurrency control. Java 5 comes with BlockingQueue implementations in the java.util.concurrent package.
Usage of BlockingQueue
A BlockingQueue accessed by a producer(put) thread and a consumer(take) thread
The Hierarchy of BlockingQueue
Declaration
public interface BlockingQueue<E> extends Queue<E>
Here, E is the type of elements stored in the Collection.
We directly cannot provide an instance of BlockingQueue since it is an interface, so to utilize the functionality of the BlockingQueue, we need to make use of the classes implementing it. Also, to use BlockingQueue in your code, use this import statement.
import java.util.concurrent.BlockingQueue;
(or)
import java.util.concurrent.*;
LinkedBlockingQueue
ArrayBlockingQueue
The implementing class of BlockingDeque is LinkedBlockingDeque. This class is the implementation of the BlockingDeque and the linked list data structure. The LinkedBlockingDeque can be optionally bounded using a constructor, however, if the capacity is unspecified it is Integer.MAX_VALUE by default. The nodes are added dynamically at the time of insertion obeying the capacity constraints.
The syntax for creating objects:
BlockingQueue<?> objectName = new LinkedBlockingDeque<?>();
(or)
LinkedBlockingDeque<?> objectName = new LinkedBlockingDeque<?>();
Example: In the code given below we perform some basic operations on a LinkedBlockingDeque, like creating an object, adding elements, deleting elements, and using an iterator to traverse through the LinkedBlockingDeque.
The BlockingQueue are two types:
1. Unbounded Queue: The Capacity of the blocking queue will be set to Integer.MAX_VALUE. In the case of an unbounded blocking queue, the queue will never block because it could grow to a very large size. when you add elements its size grows.
Syntax:
BlockingQueue blockingQueue = new LinkedBlockingDeque();
2. Bounded Queue: The second type of queue is the bounded queue. In the case of a bounded queue you can create a queue passing the capacity of the queue in queues constructor:
Syntax:
// Creates a Blocking Queue with capacity 5
BlockingQueue blockingQueue = new LinkedBlockingDeque(5);
To implement Bounded Semaphore using BlockingQueue
Java
// Java program that explains the internal// implementation of BlockingQueue import java.io.*;import java.util.*; class BlockingQueue<E> { // BlockingQueue using LinkedList structure // with a constraint on capacity private List<E> queue = new LinkedList<E>(); // limit variable to define capacity private int limit = 10; // constructor of BlockingQueue public BlockingQueue(int limit) { this.limit = limit; } // enqueue method that throws Exception // when you try to insert after the limit public synchronized void enqueue(E item) throws InterruptedException { while (this.queue.size() == this.limit) { wait(); } if (this.queue.size() == 0) { notifyAll(); } this.queue.add(item); } // dequeue methods that throws Exception // when you try to remove element from an // empty queue public synchronized E dequeue() throws InterruptedException { while (this.queue.size() == 0) { wait(); } if (this.queue.size() == this.limit) { notifyAll(); } return this.queue.remove(0); } public static void main(String []args) { }}
Example:
Java
// Java Program to demonstrate usuage of BlockingQueue import java.util.concurrent.*;import java.util.*; public class GFG { public static void main(String[] args) throws InterruptedException { // define capacity of ArrayBlockingQueue int capacity = 5; // create object of ArrayBlockingQueue BlockingQueue<String> queue = new ArrayBlockingQueue<String>(capacity); // Add elements to ArrayBlockingQueue using put // method queue.put("StarWars"); queue.put("SuperMan"); queue.put("Flash"); queue.put("BatMan"); queue.put("Avengers"); // print Queue System.out.println("queue contains " + queue); // remove some elements queue.remove(); queue.remove(); // Add elements to ArrayBlockingQueue // using put method queue.put("CaptainAmerica"); queue.put("Thor"); System.out.println("queue contains " + queue); }}
queue contains [StarWars, SuperMan, Flash, BatMan, Avengers]
queue contains [Flash, BatMan, Avengers, CaptainAmerica, Thor]
1. Adding Elements
Elements can be added into a LinkedBlockedDeque in different ways depending on the type of structure we are trying to use it as. The most common method is the add() method using which we can add elements at the end of the deque. We can also use the addAll() method (which is a method of the Collection interface) to add an entire collection to LinkedBlockingDeque. If we wish to use the deque as a queue we can use add() and put().
Java
// Java Program Demonstrate add()// method of BlockingQueue import java.util.concurrent.LinkedBlockingDeque;import java.util.concurrent.BlockingQueue;import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of BlockingQueue BlockingQueue<Integer> BQ = new LinkedBlockingDeque<Integer>(); // Add numbers to the BlockingQueue BQ.add(7855642); BQ.add(35658786); BQ.add(5278367); BQ.add(74381793); // before removing print BlockingQueue System.out.println("Blocking Queue: " + BQ); }}
Blocking Queue: [7855642, 35658786, 5278367, 74381793]
2. Accessing Elements
The elements of the LinkedBlockingDeque can be accessed using contains(), element(), peek(), poll(). There are variations of these methods too which are given in the table above along with their descriptions.
Java
// Java Program for Accessing the elements of a// LinkedBlockingDeque import java.util.concurrent.*; public class AccessingElements { public static void main(String[] args) { // Instantiate an object of LinkedBlockingDeque // named lbdq BlockingQueue<Integer> lbdq = new LinkedBlockingDeque<Integer>(); // Add elements using add() lbdq.add(22); lbdq.add(125); lbdq.add(723); lbdq.add(172); lbdq.add(100); // Print the elements of lbdq on the console System.out.println( "The LinkedBlockingDeque, lbdq contains:"); System.out.println(lbdq); // To check if the deque contains 22 if (lbdq.contains(22)) System.out.println( "The LinkedBlockingDeque, lbdq contains 22"); else System.out.println("No such element exists"); // Using element() to retrieve the head of the deque int head = lbdq.element(); System.out.println("The head of lbdq: " + head); }}
The LinkedBlockingDeque, lbdq contains:
[22, 125, 723, 172, 100]
The LinkedBlockingDeque, lbdq contains 22
The head of lbdq: 22
3. Deleting Elements
Elements can be deleted from a LinkedBlockingDeque using remove(). Other methods such as take() and poll() can also be used in a way to remove the first and the last elements.
Java
// Java Program for removing elements from a// LinkedBlockingDeque import java.util.concurrent.*; public class RemovingElements { public static void main(String[] args) { // Instantiate an object of LinkedBlockingDeque // named lbdq BlockingQueue<Integer> lbdq = new LinkedBlockingDeque<Integer>(); // Add elements using add() lbdq.add(75); lbdq.add(86); lbdq.add(13); lbdq.add(44); lbdq.add(10); // Print the elements of lbdq on the console System.out.println( "The LinkedBlockingDeque, lbdq contains:"); System.out.println(lbdq); // Remove elements using remove(); lbdq.remove(86); lbdq.remove(44); // Trying to remove an element // that doesn't exist // in the LinkedBlockingDeque lbdq.remove(1); // Print the elements of lbdq on the console System.out.println( "\nThe LinkedBlockingDeque, lbdq contains:"); System.out.println(lbdq); }}
The LinkedBlockingDeque, lbdq contains:
[75, 86, 13, 44, 10]
The LinkedBlockingDeque, lbdq contains:
[75, 13, 10]
4. Iterating through the Elements
To iterate through the elements of a LinkedBlockingDeque we can create an iterator and use the methods of the Iterable interface, which is the root of the Collection Framework of Java, to access the elements. The next() method of Iterable returns the element of any collection.
Java
// Java Program to iterate// through the LinkedBlockingDequeimport java.util.Iterator;import java.util.concurrent.*; public class IteratingThroughElements { public static void main(String[] args) { // Instantiate an object of LinkedBlockingDeque named lbdq BlockingQueue<Integer> lbdq = new LinkedBlockingDeque<Integer>(); // Add elements using add() lbdq.add(166); lbdq.add(246); lbdq.add(66); lbdq.add(292); lbdq.add(98); // Create an iterator to traverse lbdq Iterator<Integer> lbdqIter = lbdq.iterator(); // Print the elements of lbdq on to the console System.out.println("The LinkedBlockingDeque, lbdq contains:"); for(int i = 0; i<lbdq.size(); i++) { System.out.print(lbdqIter.next() + " "); } } }
The LinkedBlockingDeque, lbdq contains:
166 246 66 292 98
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
The following are the methods provided by the BlockingQueue for insertion, removal, and examine operations on the queue. Each of the four sets of methods behaves differently if the requested operation is not satisfied immediately.
Throws Exception: An exception will be thrown, if the requested operation is not satisfied immediately.
Special value: A special value is returned if the operation is not satisfied immediately.
Blocks: The method call is blocked if the attempted operation is not satisfied immediately and it waits until it gets executed.
Times out: A special value is returned telling whether the operation succeeded or not. If the requested operation is not possible immediately, the method call blocks until it is, but waits no longer than the given timeout.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/BlockingQueue.html
Ganeshchowdharysadanala
adnanirshad158
Java-BlockingQueue
Java-Collections
Technical Scripter 2018
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
Introduction to Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 1190,
"s": 52,
"text": "The BlockingQueue interface in Java is added in Java 1.5 along with various other concurrent Utility classes like ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrrayList, etc. 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.Java provides several BlockingQueue implementations such as LinkedBlockingQueue, ArrayBlockingQueue, PriorityBlockingQueue, SynchronousQueue, etc. Java BlockingQueue interface implementations are thread-safe. All methods of BlockingQueue are atomic in nature and use internal locks or other forms of concurrency control. Java 5 comes with BlockingQueue implementations in the java.util.concurrent package. "
},
{
"code": null,
"e": 1215,
"s": 1190,
"text": "Usage of BlockingQueue "
},
{
"code": null,
"e": 1295,
"s": 1215,
"text": "A BlockingQueue accessed by a producer(put) thread and a consumer(take) thread"
},
{
"code": null,
"e": 1326,
"s": 1295,
"text": "The Hierarchy of BlockingQueue"
},
{
"code": null,
"e": 1338,
"s": 1326,
"text": "Declaration"
},
{
"code": null,
"e": 1389,
"s": 1338,
"text": "public interface BlockingQueue<E> extends Queue<E>"
},
{
"code": null,
"e": 1447,
"s": 1389,
"text": "Here, E is the type of elements stored in the Collection."
},
{
"code": null,
"e": 1703,
"s": 1447,
"text": "We directly cannot provide an instance of BlockingQueue since it is an interface, so to utilize the functionality of the BlockingQueue, we need to make use of the classes implementing it. Also, to use BlockingQueue in your code, use this import statement."
},
{
"code": null,
"e": 1802,
"s": 1703,
"text": "import java.util.concurrent.BlockingQueue;\n (or)\nimport java.util.concurrent.*;"
},
{
"code": null,
"e": 1822,
"s": 1802,
"text": "LinkedBlockingQueue"
},
{
"code": null,
"e": 1841,
"s": 1822,
"text": "ArrayBlockingQueue"
},
{
"code": null,
"e": 2233,
"s": 1841,
"text": "The implementing class of BlockingDeque is LinkedBlockingDeque. This class is the implementation of the BlockingDeque and the linked list data structure. The LinkedBlockingDeque can be optionally bounded using a constructor, however, if the capacity is unspecified it is Integer.MAX_VALUE by default. The nodes are added dynamically at the time of insertion obeying the capacity constraints."
},
{
"code": null,
"e": 2266,
"s": 2233,
"text": "The syntax for creating objects:"
},
{
"code": null,
"e": 2425,
"s": 2266,
"text": "BlockingQueue<?> objectName = new LinkedBlockingDeque<?>(); \n (or)\nLinkedBlockingDeque<?> objectName = new LinkedBlockingDeque<?>();"
},
{
"code": null,
"e": 2645,
"s": 2425,
"text": "Example: In the code given below we perform some basic operations on a LinkedBlockingDeque, like creating an object, adding elements, deleting elements, and using an iterator to traverse through the LinkedBlockingDeque."
},
{
"code": null,
"e": 2678,
"s": 2645,
"text": "The BlockingQueue are two types:"
},
{
"code": null,
"e": 2920,
"s": 2678,
"text": "1. Unbounded Queue: The Capacity of the blocking queue will be set to Integer.MAX_VALUE. In the case of an unbounded blocking queue, the queue will never block because it could grow to a very large size. when you add elements its size grows."
},
{
"code": null,
"e": 2928,
"s": 2920,
"text": "Syntax:"
},
{
"code": null,
"e": 2985,
"s": 2928,
"text": "BlockingQueue blockingQueue = new LinkedBlockingDeque();"
},
{
"code": null,
"e": 3161,
"s": 2985,
"text": "2. Bounded Queue: The second type of queue is the bounded queue. In the case of a bounded queue you can create a queue passing the capacity of the queue in queues constructor:"
},
{
"code": null,
"e": 3169,
"s": 3161,
"text": "Syntax:"
},
{
"code": null,
"e": 3271,
"s": 3169,
"text": "// Creates a Blocking Queue with capacity 5\nBlockingQueue blockingQueue = new LinkedBlockingDeque(5);"
},
{
"code": null,
"e": 3323,
"s": 3271,
"text": "To implement Bounded Semaphore using BlockingQueue "
},
{
"code": null,
"e": 3328,
"s": 3323,
"text": "Java"
},
{
"code": "// Java program that explains the internal// implementation of BlockingQueue import java.io.*;import java.util.*; class BlockingQueue<E> { // BlockingQueue using LinkedList structure // with a constraint on capacity private List<E> queue = new LinkedList<E>(); // limit variable to define capacity private int limit = 10; // constructor of BlockingQueue public BlockingQueue(int limit) { this.limit = limit; } // enqueue method that throws Exception // when you try to insert after the limit public synchronized void enqueue(E item) throws InterruptedException { while (this.queue.size() == this.limit) { wait(); } if (this.queue.size() == 0) { notifyAll(); } this.queue.add(item); } // dequeue methods that throws Exception // when you try to remove element from an // empty queue public synchronized E dequeue() throws InterruptedException { while (this.queue.size() == 0) { wait(); } if (this.queue.size() == this.limit) { notifyAll(); } return this.queue.remove(0); } public static void main(String []args) { }}",
"e": 4544,
"s": 3328,
"text": null
},
{
"code": null,
"e": 4560,
"s": 4548,
"text": " Example: "
},
{
"code": null,
"e": 4567,
"s": 4562,
"text": "Java"
},
{
"code": "// Java Program to demonstrate usuage of BlockingQueue import java.util.concurrent.*;import java.util.*; public class GFG { public static void main(String[] args) throws InterruptedException { // define capacity of ArrayBlockingQueue int capacity = 5; // create object of ArrayBlockingQueue BlockingQueue<String> queue = new ArrayBlockingQueue<String>(capacity); // Add elements to ArrayBlockingQueue using put // method queue.put(\"StarWars\"); queue.put(\"SuperMan\"); queue.put(\"Flash\"); queue.put(\"BatMan\"); queue.put(\"Avengers\"); // print Queue System.out.println(\"queue contains \" + queue); // remove some elements queue.remove(); queue.remove(); // Add elements to ArrayBlockingQueue // using put method queue.put(\"CaptainAmerica\"); queue.put(\"Thor\"); System.out.println(\"queue contains \" + queue); }}",
"e": 5554,
"s": 4567,
"text": null
},
{
"code": null,
"e": 5678,
"s": 5554,
"text": "queue contains [StarWars, SuperMan, Flash, BatMan, Avengers]\nqueue contains [Flash, BatMan, Avengers, CaptainAmerica, Thor]"
},
{
"code": null,
"e": 5699,
"s": 5680,
"text": "1. Adding Elements"
},
{
"code": null,
"e": 6131,
"s": 5699,
"text": "Elements can be added into a LinkedBlockedDeque in different ways depending on the type of structure we are trying to use it as. The most common method is the add() method using which we can add elements at the end of the deque. We can also use the addAll() method (which is a method of the Collection interface) to add an entire collection to LinkedBlockingDeque. If we wish to use the deque as a queue we can use add() and put()."
},
{
"code": null,
"e": 6136,
"s": 6131,
"text": "Java"
},
{
"code": "// Java Program Demonstrate add()// method of BlockingQueue import java.util.concurrent.LinkedBlockingDeque;import java.util.concurrent.BlockingQueue;import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of BlockingQueue BlockingQueue<Integer> BQ = new LinkedBlockingDeque<Integer>(); // Add numbers to the BlockingQueue BQ.add(7855642); BQ.add(35658786); BQ.add(5278367); BQ.add(74381793); // before removing print BlockingQueue System.out.println(\"Blocking Queue: \" + BQ); }}",
"e": 6782,
"s": 6136,
"text": null
},
{
"code": null,
"e": 6837,
"s": 6782,
"text": "Blocking Queue: [7855642, 35658786, 5278367, 74381793]"
},
{
"code": null,
"e": 6859,
"s": 6837,
"text": "2. Accessing Elements"
},
{
"code": null,
"e": 7068,
"s": 6859,
"text": "The elements of the LinkedBlockingDeque can be accessed using contains(), element(), peek(), poll(). There are variations of these methods too which are given in the table above along with their descriptions."
},
{
"code": null,
"e": 7073,
"s": 7068,
"text": "Java"
},
{
"code": "// Java Program for Accessing the elements of a// LinkedBlockingDeque import java.util.concurrent.*; public class AccessingElements { public static void main(String[] args) { // Instantiate an object of LinkedBlockingDeque // named lbdq BlockingQueue<Integer> lbdq = new LinkedBlockingDeque<Integer>(); // Add elements using add() lbdq.add(22); lbdq.add(125); lbdq.add(723); lbdq.add(172); lbdq.add(100); // Print the elements of lbdq on the console System.out.println( \"The LinkedBlockingDeque, lbdq contains:\"); System.out.println(lbdq); // To check if the deque contains 22 if (lbdq.contains(22)) System.out.println( \"The LinkedBlockingDeque, lbdq contains 22\"); else System.out.println(\"No such element exists\"); // Using element() to retrieve the head of the deque int head = lbdq.element(); System.out.println(\"The head of lbdq: \" + head); }}",
"e": 8122,
"s": 7073,
"text": null
},
{
"code": null,
"e": 8253,
"s": 8125,
"text": "The LinkedBlockingDeque, lbdq contains:\n[22, 125, 723, 172, 100]\nThe LinkedBlockingDeque, lbdq contains 22\nThe head of lbdq: 22"
},
{
"code": null,
"e": 8276,
"s": 8255,
"text": "3. Deleting Elements"
},
{
"code": null,
"e": 8454,
"s": 8278,
"text": "Elements can be deleted from a LinkedBlockingDeque using remove(). Other methods such as take() and poll() can also be used in a way to remove the first and the last elements."
},
{
"code": null,
"e": 8461,
"s": 8456,
"text": "Java"
},
{
"code": "// Java Program for removing elements from a// LinkedBlockingDeque import java.util.concurrent.*; public class RemovingElements { public static void main(String[] args) { // Instantiate an object of LinkedBlockingDeque // named lbdq BlockingQueue<Integer> lbdq = new LinkedBlockingDeque<Integer>(); // Add elements using add() lbdq.add(75); lbdq.add(86); lbdq.add(13); lbdq.add(44); lbdq.add(10); // Print the elements of lbdq on the console System.out.println( \"The LinkedBlockingDeque, lbdq contains:\"); System.out.println(lbdq); // Remove elements using remove(); lbdq.remove(86); lbdq.remove(44); // Trying to remove an element // that doesn't exist // in the LinkedBlockingDeque lbdq.remove(1); // Print the elements of lbdq on the console System.out.println( \"\\nThe LinkedBlockingDeque, lbdq contains:\"); System.out.println(lbdq); }}",
"e": 9504,
"s": 8461,
"text": null
},
{
"code": null,
"e": 9619,
"s": 9504,
"text": "The LinkedBlockingDeque, lbdq contains:\n[75, 86, 13, 44, 10]\n\nThe LinkedBlockingDeque, lbdq contains:\n[75, 13, 10]"
},
{
"code": null,
"e": 9653,
"s": 9619,
"text": "4. Iterating through the Elements"
},
{
"code": null,
"e": 9931,
"s": 9653,
"text": "To iterate through the elements of a LinkedBlockingDeque we can create an iterator and use the methods of the Iterable interface, which is the root of the Collection Framework of Java, to access the elements. The next() method of Iterable returns the element of any collection."
},
{
"code": null,
"e": 9936,
"s": 9931,
"text": "Java"
},
{
"code": "// Java Program to iterate// through the LinkedBlockingDequeimport java.util.Iterator;import java.util.concurrent.*; public class IteratingThroughElements { public static void main(String[] args) { // Instantiate an object of LinkedBlockingDeque named lbdq BlockingQueue<Integer> lbdq = new LinkedBlockingDeque<Integer>(); // Add elements using add() lbdq.add(166); lbdq.add(246); lbdq.add(66); lbdq.add(292); lbdq.add(98); // Create an iterator to traverse lbdq Iterator<Integer> lbdqIter = lbdq.iterator(); // Print the elements of lbdq on to the console System.out.println(\"The LinkedBlockingDeque, lbdq contains:\"); for(int i = 0; i<lbdq.size(); i++) { System.out.print(lbdqIter.next() + \" \"); } } }",
"e": 10815,
"s": 9936,
"text": null
},
{
"code": null,
"e": 10874,
"s": 10815,
"text": "The LinkedBlockingDeque, lbdq contains:\n166 246 66 292 98 "
},
{
"code": null,
"e": 10881,
"s": 10874,
"text": "METHOD"
},
{
"code": null,
"e": 10893,
"s": 10881,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 10900,
"s": 10893,
"text": "METHOD"
},
{
"code": null,
"e": 10912,
"s": 10900,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 10919,
"s": 10912,
"text": "METHOD"
},
{
"code": null,
"e": 10931,
"s": 10919,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 10938,
"s": 10931,
"text": "METHOD"
},
{
"code": null,
"e": 10950,
"s": 10938,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 11181,
"s": 10950,
"text": "The following are the methods provided by the BlockingQueue for insertion, removal, and examine operations on the queue. Each of the four sets of methods behaves differently if the requested operation is not satisfied immediately."
},
{
"code": null,
"e": 11285,
"s": 11181,
"text": "Throws Exception: An exception will be thrown, if the requested operation is not satisfied immediately."
},
{
"code": null,
"e": 11375,
"s": 11285,
"text": "Special value: A special value is returned if the operation is not satisfied immediately."
},
{
"code": null,
"e": 11503,
"s": 11375,
"text": "Blocks: The method call is blocked if the attempted operation is not satisfied immediately and it waits until it gets executed."
},
{
"code": null,
"e": 11726,
"s": 11503,
"text": "Times out: A special value is returned telling whether the operation succeeded or not. If the requested operation is not possible immediately, the method call blocks until it is, but waits no longer than the given timeout."
},
{
"code": null,
"e": 11838,
"s": 11726,
"text": "Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/BlockingQueue.html"
},
{
"code": null,
"e": 11862,
"s": 11838,
"text": "Ganeshchowdharysadanala"
},
{
"code": null,
"e": 11877,
"s": 11862,
"text": "adnanirshad158"
},
{
"code": null,
"e": 11896,
"s": 11877,
"text": "Java-BlockingQueue"
},
{
"code": null,
"e": 11913,
"s": 11896,
"text": "Java-Collections"
},
{
"code": null,
"e": 11937,
"s": 11913,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 11942,
"s": 11937,
"text": "Java"
},
{
"code": null,
"e": 11961,
"s": 11942,
"text": "Technical Scripter"
},
{
"code": null,
"e": 11966,
"s": 11961,
"text": "Java"
},
{
"code": null,
"e": 11983,
"s": 11966,
"text": "Java-Collections"
},
{
"code": null,
"e": 12081,
"s": 11983,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12100,
"s": 12081,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 12130,
"s": 12100,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 12145,
"s": 12130,
"text": "Stream In Java"
},
{
"code": null,
"e": 12163,
"s": 12145,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 12183,
"s": 12163,
"text": "Collections in Java"
},
{
"code": null,
"e": 12207,
"s": 12183,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 12239,
"s": 12207,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 12251,
"s": 12239,
"text": "Set in Java"
},
{
"code": null,
"e": 12271,
"s": 12251,
"text": "Stack Class in Java"
}
] |
How to run a node.js application permanently ? | 03 Feb, 2021
NodeJS is a runtime environment on a V8 engine for executing JavaScript code with some additional functionality that allows the development of fast and scalable web applications but we can’t run the Node.js application locally after closing the terminal or Application, to run the nodeJS application permanently. We use NPM modules such as forever or PM2 to ensure that a given script runs continuously. NPM is a Default Package manager for Node.js Which enables us to access a lot of packages or modules that make things a lot easier for developing a web application.
Method 1:
Using PM2 module:
Installing module in project Directory:
npm install pm2 -g
Start Your Node.js Application by pm2.
pm2 start [Your fileName]
All processes listed up which are registered with pm2.
pm2 list
Console output:
We can also stop any process runs by pm2 stop command:
pm2 stop all
pm2 stop [id number]
Method 2:
Using forever module
Installing module in your project Directory:
npm install forever -g
Start Your Node.js Application by forever module.
forever start [Your FileName]
All processes listed up which are registered with forever
forever list
Console output:
We can also remove or stop any processes that are registered with forever using index (such as 0 in this case)
forever stopall
forever stop [index]
So now your Application will be running permanently even after exiting the terminal or Application.
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
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 ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 Feb, 2021"
},
{
"code": null,
"e": 623,
"s": 53,
"text": "NodeJS is a runtime environment on a V8 engine for executing JavaScript code with some additional functionality that allows the development of fast and scalable web applications but we can’t run the Node.js application locally after closing the terminal or Application, to run the nodeJS application permanently. We use NPM modules such as forever or PM2 to ensure that a given script runs continuously. NPM is a Default Package manager for Node.js Which enables us to access a lot of packages or modules that make things a lot easier for developing a web application."
},
{
"code": null,
"e": 634,
"s": 623,
"text": "Method 1: "
},
{
"code": null,
"e": 652,
"s": 634,
"text": "Using PM2 module:"
},
{
"code": null,
"e": 692,
"s": 652,
"text": "Installing module in project Directory:"
},
{
"code": null,
"e": 711,
"s": 692,
"text": "npm install pm2 -g"
},
{
"code": null,
"e": 750,
"s": 711,
"text": "Start Your Node.js Application by pm2."
},
{
"code": null,
"e": 776,
"s": 750,
"text": "pm2 start [Your fileName]"
},
{
"code": null,
"e": 831,
"s": 776,
"text": "All processes listed up which are registered with pm2."
},
{
"code": null,
"e": 840,
"s": 831,
"text": "pm2 list"
},
{
"code": null,
"e": 856,
"s": 840,
"text": "Console output:"
},
{
"code": null,
"e": 911,
"s": 856,
"text": "We can also stop any process runs by pm2 stop command:"
},
{
"code": null,
"e": 972,
"s": 911,
"text": " pm2 stop all \n pm2 stop [id number] "
},
{
"code": null,
"e": 983,
"s": 972,
"text": "Method 2: "
},
{
"code": null,
"e": 1004,
"s": 983,
"text": "Using forever module"
},
{
"code": null,
"e": 1049,
"s": 1004,
"text": "Installing module in your project Directory:"
},
{
"code": null,
"e": 1072,
"s": 1049,
"text": "npm install forever -g"
},
{
"code": null,
"e": 1123,
"s": 1072,
"text": "Start Your Node.js Application by forever module. "
},
{
"code": null,
"e": 1153,
"s": 1123,
"text": "forever start [Your FileName]"
},
{
"code": null,
"e": 1211,
"s": 1153,
"text": "All processes listed up which are registered with forever"
},
{
"code": null,
"e": 1224,
"s": 1211,
"text": "forever list"
},
{
"code": null,
"e": 1240,
"s": 1224,
"text": "Console output:"
},
{
"code": null,
"e": 1366,
"s": 1240,
"text": " We can also remove or stop any processes that are registered with forever using index (such as 0 in this case) "
},
{
"code": null,
"e": 1403,
"s": 1366,
"text": "forever stopall\nforever stop [index]"
},
{
"code": null,
"e": 1503,
"s": 1403,
"text": "So now your Application will be running permanently even after exiting the terminal or Application."
},
{
"code": null,
"e": 1520,
"s": 1503,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 1527,
"s": 1520,
"text": "Picked"
},
{
"code": null,
"e": 1535,
"s": 1527,
"text": "Node.js"
},
{
"code": null,
"e": 1552,
"s": 1535,
"text": "Web Technologies"
},
{
"code": null,
"e": 1650,
"s": 1552,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1682,
"s": 1650,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 1717,
"s": 1682,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 1787,
"s": 1717,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 1814,
"s": 1787,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 1839,
"s": 1814,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 1901,
"s": 1839,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1962,
"s": 1901,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2012,
"s": 1962,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2055,
"s": 2012,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
CSS | rgb() Function | 04 Dec, 2018
The rgb() function is an inbuilt function in CSS which is used to define the colors using the Red Green Blue (RGB) model.
Syntax:
rgb( red, green, blue )
Parameters: This function accepts three parameters as mentioned above and described below:
red: This parameter is used to define the intensity of red color. It is an integer value lies between 0 to 255, or as a percentage value between 0% to 100%.
green: This parameter is used to define the intensity of green color. It is an integer value lies between 0 to 255, or as a percentage value between 0% to 100%.
blue: This parameter is used to define the intensity of blue color. It is an integer value lies between 0 to 255, or as a percentage value between 0% to 100%.
Below programs illustrates the rgb() function in CSS:
Program:
<!DOCTYPE html><html> <head> <title>rgb function</title> <style> .gfg1 { background-color:rgb(1, 153, 0); text-align:center; } .gfg2 { background-color:rgb(0, 255, 0); text-align:center } .gfg3 { background-color:rgb(133, 150, 150); text-align:center } .gfg { font-size:40px; font-weight:bold; color:green; text-align:center; } h1 { text-align:center; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <h1>The rgb() Function</h1> <p class = "gfg1">Green</p> <p class = "gfg2">Light green</p> <p class = "gfg3">Light black</p> </body></html>
Output:
Supported Browsers: The browser supported by rgb() function are listed below:
Chrome 1.0 and above
Internet Explorer 4.0 and above
Firefox 1.0 and above
Safari 1.0 and above
Opera 3.5 and above
CSS-Functions
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 150,
"s": 28,
"text": "The rgb() function is an inbuilt function in CSS which is used to define the colors using the Red Green Blue (RGB) model."
},
{
"code": null,
"e": 158,
"s": 150,
"text": "Syntax:"
},
{
"code": null,
"e": 182,
"s": 158,
"text": "rgb( red, green, blue )"
},
{
"code": null,
"e": 273,
"s": 182,
"text": "Parameters: This function accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 430,
"s": 273,
"text": "red: This parameter is used to define the intensity of red color. It is an integer value lies between 0 to 255, or as a percentage value between 0% to 100%."
},
{
"code": null,
"e": 591,
"s": 430,
"text": "green: This parameter is used to define the intensity of green color. It is an integer value lies between 0 to 255, or as a percentage value between 0% to 100%."
},
{
"code": null,
"e": 750,
"s": 591,
"text": "blue: This parameter is used to define the intensity of blue color. It is an integer value lies between 0 to 255, or as a percentage value between 0% to 100%."
},
{
"code": null,
"e": 804,
"s": 750,
"text": "Below programs illustrates the rgb() function in CSS:"
},
{
"code": null,
"e": 813,
"s": 804,
"text": "Program:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>rgb function</title> <style> .gfg1 { background-color:rgb(1, 153, 0); text-align:center; } .gfg2 { background-color:rgb(0, 255, 0); text-align:center } .gfg3 { background-color:rgb(133, 150, 150); text-align:center } .gfg { font-size:40px; font-weight:bold; color:green; text-align:center; } h1 { text-align:center; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <h1>The rgb() Function</h1> <p class = \"gfg1\">Green</p> <p class = \"gfg2\">Light green</p> <p class = \"gfg3\">Light black</p> </body></html> ",
"e": 1733,
"s": 813,
"text": null
},
{
"code": null,
"e": 1741,
"s": 1733,
"text": "Output:"
},
{
"code": null,
"e": 1819,
"s": 1741,
"text": "Supported Browsers: The browser supported by rgb() function are listed below:"
},
{
"code": null,
"e": 1840,
"s": 1819,
"text": "Chrome 1.0 and above"
},
{
"code": null,
"e": 1872,
"s": 1840,
"text": "Internet Explorer 4.0 and above"
},
{
"code": null,
"e": 1894,
"s": 1872,
"text": "Firefox 1.0 and above"
},
{
"code": null,
"e": 1915,
"s": 1894,
"text": "Safari 1.0 and above"
},
{
"code": null,
"e": 1935,
"s": 1915,
"text": "Opera 3.5 and above"
},
{
"code": null,
"e": 1949,
"s": 1935,
"text": "CSS-Functions"
},
{
"code": null,
"e": 1953,
"s": 1949,
"text": "CSS"
},
{
"code": null,
"e": 1958,
"s": 1953,
"text": "HTML"
},
{
"code": null,
"e": 1975,
"s": 1958,
"text": "Web Technologies"
},
{
"code": null,
"e": 1980,
"s": 1975,
"text": "HTML"
},
{
"code": null,
"e": 2078,
"s": 1980,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2126,
"s": 2078,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2188,
"s": 2126,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2238,
"s": 2188,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2296,
"s": 2238,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 2346,
"s": 2296,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 2394,
"s": 2346,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2456,
"s": 2394,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2506,
"s": 2456,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2530,
"s": 2506,
"text": "REST API (Introduction)"
}
] |
Construct a Binary Tree from Postorder and Inorder | 18 May, 2022
Given Postorder and Inorder traversals, construct the tree.
Examples:
Input:
in[] = {2, 1, 3}
post[] = {2, 3, 1}
Output: Root of below tree
1
/ \
2 3
Input:
in[] = {4, 8, 2, 5, 1, 6, 3, 7}
post[] = {8, 4, 5, 2, 6, 7, 3, 1}
Output: Root of below tree
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
We have already discussed the construction of trees from Inorder and Preorder traversals. The idea is similar.Let us see the process of constructing tree from in[] = {4, 8, 2, 5, 1, 6, 3, 7} and post[] = {8, 4, 5, 2, 6, 7, 3, 1} 1) We first find the last node in post[]. The last node is “1”, we know this value is root as the root always appears at the end of postorder traversal.2) We search “1” in in[] to find the left and right subtrees of the root. Everything on the left of “1” in in[] is in the left subtree and everything on right is in the right subtree.
1
/ \
[4, 8, 2, 5] [6, 3, 7]
3) We recur the above process for following two. ....b) Recur for in[] = {6, 3, 7} and post[] = {6, 7, 3} .......Make the created tree as right child of root. ....a) Recur for in[] = {4, 8, 2, 5} and post[] = {8, 4, 5, 2}. .......Make the created tree as left child of root.Below is the implementation of the above idea. One important observation is, we recursively call for the right subtree before the left subtree as we decrease the index of the postorder index whenever we create a new node.
C++
Java
Python3
C#
Javascript
/* C++ program to construct tree using inorder and postorder traversals */#include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node { int data; Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int data); /* Prototypes for utility functions */int search(int arr[], int strt, int end, int value); /* Recursive function to construct binary of size n from Inorder traversal in[] and Postorder traversal post[]. Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and postorder do not form a tree */Node* buildUtil(int in[], int post[], int inStrt, int inEnd, int* pIndex){ // Base case if (inStrt > inEnd) return NULL; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ Node* node = newNode(post[*pIndex]); (*pIndex)--; /* If this node has no children then return */ if (inStrt == inEnd) return node; /* Else find the index of this node in Inorder traversal */ int iIndex = search(in, inStrt, inEnd, node->data); /* Using index in Inorder traversal, construct left and right subtress */ node->right = buildUtil(in, post, iIndex + 1, inEnd, pIndex); node->left = buildUtil(in, post, inStrt, iIndex - 1, pIndex); return node;} // This function mainly initializes index of root// and calls buildUtil()Node* buildTree(int in[], int post[], int n){ int pIndex = n - 1; return buildUtil(in, post, 0, n - 1, &pIndex);} /* Function to find index of value in arr[start...end] The function assumes that value is postsent in in[] */int search(int arr[], int strt, int end, int value){ int i; for (i = strt; i <= end; i++) { if (arr[i] == value) break; } return i;} /* Helper function that allocates a new node */Node* newNode(int data){ Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node);} /* This function is here just to test */void preOrder(Node* node){ if (node == NULL) return; printf("%d ", node->data); preOrder(node->left); preOrder(node->right);} // Driver codeint main(){ int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = sizeof(in) / sizeof(in[0]); Node* root = buildTree(in, post, n); cout << "Preorder of the constructed tree : \n"; preOrder(root); return 0;}
// Java program to construct a tree using inorder// and postorder traversals /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { int data; Node left, right; public Node(int data) { this.data = data; left = right = null; }} class BinaryTree { /* Recursive function to construct binary of size n from Inorder traversal in[] and Postorder traversal post[]. Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and postorder do not form a tree */ Node buildUtil(int in[], int post[], int inStrt, int inEnd, int postStrt, int postEnd) { // Base case if (inStrt > inEnd) return null; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ Node node = new Node(post[postEnd]); /* If this node has no children then return */ if (inStrt == inEnd) return node; int iIndex = search(in, inStrt, inEnd, node.data); /* Using index in Inorder traversal, construct left and right subtress */ node.left = buildUtil( in, post, inStrt, iIndex - 1, postStrt, postStrt - inStrt + iIndex - 1); node.right = buildUtil(in, post, iIndex + 1, inEnd, postEnd - inEnd + iIndex, postEnd - 1); return node; } /* Function to find index of value in arr[start...end] The function assumes that value is postsent in in[] */ int search(int arr[], int strt, int end, int value) { int i; for (i = strt; i <= end; i++) { if (arr[i] == value) break; } return i; } /* This function is here just to test */ void preOrder(Node node) { if (node == null) return; System.out.print(node.data + " "); preOrder(node.left); preOrder(node.right); } // Driver Code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int in[] = new int[] { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = new int[] { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = in.length; Node root = tree.buildUtil(in, post, 0, n - 1, 0, n - 1); System.out.println( "Preorder of the constructed tree : "); tree.preOrder(root); }} // This code has been contributed by Mayank// Jaiswal(mayank_24)
# Python3 program to construct tree using# inorder and postorder traversals # Helper function that allocates# a new nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # Recursive function to construct binary# of size n from Inorder traversal in[]# and Postorder traversal post[]. Initial# values of inStrt and inEnd should be# 0 and n -1. The function doesn't do any# error checking for cases where inorder# and postorder do not form a treedef buildUtil(In, post, inStrt, inEnd, pIndex): # Base case if (inStrt > inEnd): return None # Pick current node from Postorder traversal # using postIndex and decrement postIndex node = newNode(post[pIndex[0]]) pIndex[0] -= 1 # If this node has no children # then return if (inStrt == inEnd): return node # Else find the index of this node # in Inorder traversal iIndex = search(In, inStrt, inEnd, node.data) # Using index in Inorder traversal, # construct left and right subtress node.right = buildUtil(In, post, iIndex + 1, inEnd, pIndex) node.left = buildUtil(In, post, inStrt, iIndex - 1, pIndex) return node # This function mainly initializes index# of root and calls buildUtil()def buildTree(In, post, n): pIndex = [n - 1] return buildUtil(In, post, 0, n - 1, pIndex) # Function to find index of value in# arr[start...end]. The function assumes# that value is postsent in in[]def search(arr, strt, end, value): i = 0 for i in range(strt, end + 1): if (arr[i] == value): break return i # This function is here just to testdef preOrder(node): if node == None: return print(node.data,end=" ") preOrder(node.left) preOrder(node.right) # Driver codeif __name__ == '__main__': In = [4, 8, 2, 5, 1, 6, 3, 7] post = [8, 4, 5, 2, 6, 7, 3, 1] n = len(In) root = buildTree(In, post, n) print("Preorder of the constructed tree :") preOrder(root) # This code is contributed by PranchalK
// C# program to construct a tree using// inorder and postorder traversalsusing System; /* A binary tree node has data, pointerto left child and a pointer to right child */public class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} // Class Index created to implement// pass by reference of Indexpublic class Index{ public int index;} class GFG{/* Recursive function to construct binaryof size n from Inorder traversal in[] andPostorder traversal post[]. Initial valuesof inStrt and inEnd should be 0 and n -1.The function doesn't do any error checkingfor cases where inorder and postorder donot form a tree */public virtual Node buildUtil(int[] @in, int[] post, int inStrt, int inEnd, Index pIndex){ // Base case if (inStrt > inEnd) { return null; } /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ Node node = new Node(post[pIndex.index]); (pIndex.index)--; /* If this node has no children then return */ if (inStrt == inEnd) { return node; } /* Else find the index of this node in Inorder traversal */ int iIndex = search(@in, inStrt, inEnd, node.data); /* Using index in Inorder traversal, construct left and right subtress */ node.right = buildUtil(@in, post, iIndex + 1, inEnd, pIndex); node.left = buildUtil(@in, post, inStrt, iIndex - 1, pIndex); return node;} // This function mainly initializes// index of root and calls buildUtil()public virtual Node buildTree(int[] @in, int[] post, int n){ Index pIndex = new Index(); pIndex.index = n - 1; return buildUtil(@in, post, 0, n - 1, pIndex);} /* Function to find index of value inarr[start...end]. The function assumesthat value is postsent in in[] */public virtual int search(int[] arr, int strt, int end, int value){ int i; for (i = strt; i <= end; i++) { if (arr[i] == value) { break; } } return i;} /* This function is here just to test */public virtual void preOrder(Node node){ if (node == null) { return; } Console.Write(node.data + " "); preOrder(node.left); preOrder(node.right);} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); int[] @in = new int[] {4, 8, 2, 5, 1, 6, 3, 7}; int[] post = new int[] {8, 4, 5, 2, 6, 7, 3, 1}; int n = @in.Length; Node root = tree.buildTree(@in, post, n); Console.WriteLine("Preorder of the constructed tree : "); tree.preOrder(root);}} // This code is contributed by Shrikant13
<script>// Javascript program to construct a tree using inorder// and postorder traversals /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { constructor(data) { this.data = data; this.left = this.right = null; } } /* Recursive function to construct binary of size n from Inorder traversal in[] and Postorder traversal post[]. Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and postorder do not form a tree */ function buildUtil(In, post, inStrt, inEnd, postStrt, postEnd) { // Base case if (inStrt > inEnd) return null; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ let node = new Node(post[postEnd]); /* If this node has no children then return */ if (inStrt == inEnd) return node; let iIndex = search(In, inStrt, inEnd, node.data); /* Using index in Inorder traversal, construct left and right subtress */ node.left = buildUtil( In, post, inStrt, iIndex - 1, postStrt, postStrt - inStrt + iIndex - 1); node.right = buildUtil(In, post, iIndex + 1, inEnd, postEnd - inEnd + iIndex, postEnd - 1); return node; } /* Function to find index of value in arr[start...end] The function assumes that value is postsent in in[] */ function search(arr,strt,end,value) { let i; for (i = strt; i <= end; i++) { if (arr[i] == value) break; } return i; } /* This function is here just to test */ function preOrder(node) { if (node == null) return; document.write(node.data + " "); preOrder(node.left); preOrder(node.right); } // Driver Code let In=[4, 8, 2, 5, 1, 6, 3, 7]; let post=[8, 4, 5, 2, 6, 7, 3, 1]; let n = In.length; let root = buildUtil(In, post, 0, n - 1, 0, n - 1); document.write( "Preorder of the constructed tree : <br>"); preOrder(root); // This code is contributed by unknown2108</script>
Preorder of the constructed tree :
1 2 4 8 5 3 6 7
Time Complexity: O(n2)
Optimized approach: We can optimize the above solution using hashing (unordered_map in C++ or HashMap in Java). We store indexes of inorder traversal in a hash table. So that search can be done O(1) time If given that element in the tree are not repeated.
C++
Java
Python3
C#
Javascript
/* C++ program to construct tree using inorder andpostorder traversals */#include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to leftchild and a pointer to right child */struct Node { int data; Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int data); /* Recursive function to construct binary of size nfrom Inorder traversal in[] and Postorder traversalpost[]. Initial values of inStrt and inEnd shouldbe 0 and n -1. The function doesn't do any errorchecking for cases where inorder and postorderdo not form a tree */Node* buildUtil(int in[], int post[], int inStrt, int inEnd, int* pIndex, unordered_map<int, int>& mp){ // Base case if (inStrt > inEnd) return NULL; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ int curr = post[*pIndex]; Node* node = newNode(curr); (*pIndex)--; /* If this node has no children then return */ if (inStrt == inEnd) return node; /* Else find the index of this node in Inorder traversal */ int iIndex = mp[curr]; /* Using index in Inorder traversal, construct left and right subtress */ node->right = buildUtil(in, post, iIndex + 1, inEnd, pIndex, mp); node->left = buildUtil(in, post, inStrt, iIndex - 1, pIndex, mp); return node;} // This function mainly creates an unordered_map, then// calls buildTreeUtil()struct Node* buildTree(int in[], int post[], int len){ // Store indexes of all items so that we // we can quickly find later unordered_map<int, int> mp; for (int i = 0; i < len; i++) mp[in[i]] = i; int index = len - 1; // Index in postorder return buildUtil(in, post, 0, len - 1, &index, mp);} /* Helper function that allocates a new node */Node* newNode(int data){ Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node);} /* This function is here just to test */void preOrder(Node* node){ if (node == NULL) return; printf("%d ", node->data); preOrder(node->left); preOrder(node->right);} // Driver codeint main(){ int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = sizeof(in) / sizeof(in[0]); Node* root = buildTree(in, post, n); cout << "Preorder of the constructed tree : \n"; preOrder(root); return 0;}
/* Java program to construct tree using inorder andpostorder traversals */import java.util.*;class GFG{ /* A binary tree node has data, pointer to leftchild and a pointer to right child */static class Node{ int data; Node left, right;}; // Utility function to create a new node/* Helper function that allocates a new node */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return (node);} /* Recursive function to construct binary of size nfrom Inorder traversal in[] and Postorder traversalpost[]. Initial values of inStrt and inEnd shouldbe 0 and n -1. The function doesn't do any errorchecking for cases where inorder and postorderdo not form a tree */static Node buildUtil(int in[], int post[], int inStrt, int inEnd){ // Base case if (inStrt > inEnd) return null; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ int curr = post[index]; Node node = newNode(curr); (index)--; /* If this node has no children then return */ if (inStrt == inEnd) return node; /* Else find the index of this node in Inorder traversal */ int iIndex = mp.get(curr); /* Using index in Inorder traversal, con left and right subtress */ node.right = buildUtil(in, post, iIndex + 1, inEnd); node.left = buildUtil(in, post, inStrt, iIndex - 1); return node;}static HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();static int index; // This function mainly creates an unordered_map, then// calls buildTreeUtil()static Node buildTree(int in[], int post[], int len){ // Store indexes of all items so that we // we can quickly find later for (int i = 0; i < len; i++) mp.put(in[i], i); index = len - 1; // Index in postorder return buildUtil(in, post, 0, len - 1 );} /* This function is here just to test */static void preOrder(Node node){ if (node == null) return; System.out.printf("%d ", node.data); preOrder(node.left); preOrder(node.right);} // Driver codepublic static void main(String[] args){ int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = in.length; Node root = buildTree(in, post, n); System.out.print("Preorder of the constructed tree : \n"); preOrder(root);}} // This code is contributed by Rajput-Ji
# Python3 program to construct tree using inorder# and postorder traversals # A binary tree node has data, pointer to left# child and a pointer to right childclass Node: def __init__(self, x): self.data = x self.left = None self.right = None # Recursive function to construct binary of size n# from Inorder traversal in[] and Postorder traversal# post[]. Initial values of inStrt and inEnd should# be 0 and n -1. The function doesn't do any error# checking for cases where inorder and postorder# do not form a treedef buildUtil(inn, post, innStrt, innEnd): global mp, index # Base case if (innStrt > innEnd): return None # Pick current node from Postorder traversal # using postIndex and decrement postIndex curr = post[index] node = Node(curr) index -= 1 # If this node has no children then return if (innStrt == innEnd): return node # Else find the index of this node inn # Inorder traversal iIndex = mp[curr] # Using index inn Inorder traversal, # construct left and right subtress node.right = buildUtil(inn, post, iIndex + 1, innEnd) node.left = buildUtil(inn, post, innStrt, iIndex - 1) return node # This function mainly creates an unordered_map,# then calls buildTreeUtil()def buildTree(inn, post, lenn): global index # Store indexes of all items so that we # we can quickly find later for i in range(lenn): mp[inn[i]] = i # Index in postorder index = lenn - 1 return buildUtil(inn, post, 0, lenn - 1) # This function is here just to testdef preOrder(node): if (node == None): return print(node.data, end = " ") preOrder(node.left) preOrder(node.right) # Driver Codeif __name__ == '__main__': inn = [ 4, 8, 2, 5, 1, 6, 3, 7 ] post = [ 8, 4, 5, 2, 6, 7, 3, 1 ] n = len(inn) mp, index = {}, 0 root = buildTree(inn, post, n) print("Preorder of the constructed tree :") preOrder(root) # This code is contributed by mohit kumar 29
/* C# program to construct tree using inorder andpostorder traversals */using System;using System.Collections.Generic;class GFG{ /* A binary tree node has data, pointer to leftchild and a pointer to right child */ public class Node { public int data; public Node left, right; }; // Utility function to create a new node /* Helper function that allocates a new node */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return (node); } /* Recursive function to construct binary of size nfrom Inorder traversal in[] and Postorder traversalpost[]. Initial values of inStrt and inEnd shouldbe 0 and n -1. The function doesn't do any errorchecking for cases where inorder and postorderdo not form a tree */ static Node buildUtil(int []init, int []post, int inStrt, int inEnd) { // Base case if (inStrt > inEnd) return null; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ int curr = post[index]; Node node = newNode(curr); (index)--; /* If this node has no children then return */ if (inStrt == inEnd) return node; /* Else find the index of this node in Inorder traversal */ int iIndex = mp[curr]; /* Using index in Inorder traversal, con left and right subtress */ node.right = buildUtil(init, post, iIndex + 1, inEnd); node.left = buildUtil(init, post, inStrt, iIndex - 1); return node; } static Dictionary<int,int> mp = new Dictionary<int,int>(); static int index; // This function mainly creates an unordered_map, then // calls buildTreeUtil() static Node buildTree(int []init, int []post, int len) { // Store indexes of all items so that we // we can quickly find later for (int i = 0; i < len; i++) mp.Add(init[i], i); index = len - 1; // Index in postorder return buildUtil(init, post, 0, len - 1 ); } /* This function is here just to test */ static void preOrder(Node node) { if (node == null) return; Console.Write( node.data + " "); preOrder(node.left); preOrder(node.right); } // Driver code public static void Main(String[] args) { int []init = { 4, 8, 2, 5, 1, 6, 3, 7 }; int []post = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = init.Length; Node root = buildTree(init, post, n); Console.Write("Preorder of the constructed tree : \n"); preOrder(root); }} // This code is contributed by Rajput-Ji
<script> /* JavaScript program to construct tree using inorder and postorder traversals */ /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { constructor() { this.data = 0; this.left = null; this.right = null; } } // Utility function to create a new node /* Helper function that allocates a new node */ function newNode(data) { var node = new Node(); node.data = data; node.left = node.right = null; return node; } /* Recursive function to construct binary of size n from Inorder traversal in[] and Postorder traversal post[]. Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and postorder do not form a tree */ function buildUtil(init, post, inStrt, inEnd) { // Base case if (inStrt > inEnd) { return null; } /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ var curr = post[index]; var node = newNode(curr); index--; /* If this node has no children then return */ if (inStrt == inEnd) { return node; } /* Else find the index of this node in Inorder traversal */ var iIndex = mp[curr]; /* Using index in Inorder traversal, con left and right subtress */ node.right = buildUtil(init, post, iIndex + 1, inEnd); node.left = buildUtil(init, post, inStrt, iIndex - 1); return node; } var mp = {}; var index; // This function mainly creates an unordered_map, then // calls buildTreeUtil() function buildTree(init, post, len) { // Store indexes of all items so that we // we can quickly find later for (var i = 0; i < len; i++) { mp[init[i]] = i; } index = len - 1; // Index in postorder return buildUtil(init, post, 0, len - 1); } /* This function is here just to test */ function preOrder(node) { if (node == null) { return; } document.write(node.data + " "); preOrder(node.left); preOrder(node.right); } // Driver code var init = [4, 8, 2, 5, 1, 6, 3, 7]; var post = [8, 4, 5, 2, 6, 7, 3, 1]; var n = init.length; var root = buildTree(init, post, n); document.write("Preorder of the constructed tree : <br>"); preOrder(root); </script>
Preorder of the constructed tree :
1 2 4 8 5 3 6 7
Time Complexity: O(n)
Another approach:
Using stack and set without using recursion.
Below is the implementation of the above idea:
C++
Java
C#
// C++ program for above approach#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointerto left child and a pointer to rightchild */struct Node{ int data; Node *left, *right; Node(int x) { data = x; left = right = NULL; }}; /*Tree building function*/Node *buildTree(int in[], int post[], int n){ // Create Stack of type Node* stack<Node*> st; // Create Set of type Node* set<Node*> s; // Initialise postIndex with n - 1 int postIndex = n - 1; // Initialise root with NULL Node* root = NULL; for (int p = n - 1, i = n - 1; p>=0) { // Initialise node with NULL Node* node = NULL; // Run do-while loop do { // Initialise node with // new Node(post[p]); node = new Node(post[p]); // Check is root is // equal to NULL if (root == NULL) { root = node; } // If size of set // is greater than 0 if (st.size() > 0) { // If st.top() is present in the // set s if (s.find(st.top()) != s.end()) { s.erase(st.top()); st.top()->left = node; st.pop(); } else { st.top()->right = node; } } st.push(node); } while (post[p--] != in[i] && p >=0); node = NULL; // If the stack is not empty and // st.top()->data is equal to in[i] while (st.size() > 0 && i>=0 && st.top()->data == in[i]) { node = st.top(); // Pop elements from stack st.pop(); i--; } // if node not equal to NULL if (node != NULL) { s.insert(node); st.push(node); } } // Return root return root; }/* for print preOrder Traversal */void preOrder(Node* node){ if (node == NULL) return; printf("%d ", node->data); preOrder(node->left); preOrder(node->right);} // Driver Codeint main(){ int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = sizeof(in) / sizeof(in[0]); // Function Call Node* root = buildTree(in, post, n); cout << "Preorder of the constructed tree : \n"; // Function Call for preOrder preOrder(root); return 0;}
// Java program for above approachimport java.io.*;import java.util.*; class GFG { // Node class static class Node { int data; Node left, right; // Constructor Node(int x) { data = x; left = right = null; } } // Tree building function static Node buildTree(int in[], int post[], int n) { // Create Stack of type Node* Stack<Node> st = new Stack<>(); // Create HashSet of type Node* HashSet<Node> s = new HashSet<>(); // Initialise postIndex with n - 1 int postIndex = n - 1; // Initialise root with null Node root = null; for (int p = n - 1, i = n - 1; p >= 0; ) { // Initialise node with NULL Node node = null; // Run do-while loop do { // Initialise node with // new Node(post[p]); node = new Node(post[p]); // Check is root is // equal to NULL if (root == null) { root = node; } // If size of set // is greater than 0 if (st.size() > 0) { // If st.peek() is present in the // set s if (s.contains(st.peek())) { s.remove(st.peek()); st.peek().left = node; st.pop(); } else { st.peek().right = node; } } st.push(node); } while (post[p--] != in[i] && p >= 0); node = null; // If the stack is not empty and // st.top().data is equal to in[i] while (st.size() > 0 && i >= 0 && st.peek().data == in[i]) { node = st.peek(); // Pop elements from stack st.pop(); i--; } // If node not equal to NULL if (node != null) { s.add(node); st.push(node); } } // Return root return root; } // For print preOrder Traversal static void preOrder(Node node) { if (node == null) return; System.out.printf("%d ", node.data); preOrder(node.left); preOrder(node.right); } // Driver Code public static void main(String[] args) { int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = in.length; // Function Call Node root = buildTree(in, post, n); System.out.print( "Preorder of the constructed tree : \n"); // Function Call for preOrder preOrder(root); }} // This code is contributed by sujitmeshram
// C# program for above approachusing System;using System.Collections.Generic;class GFG{ // Node class public class Node { public int data; public Node left, right; // Constructor public Node(int x) { data = x; left = right = null; } } // Tree building function static Node buildTree(int []init, int []post, int n) { // Create Stack of type Node* Stack<Node> st = new Stack<Node>(); // Create HashSet of type Node* HashSet<Node> s = new HashSet<Node>(); // Initialise postIndex with n - 1 int postIndex = n - 1; // Initialise root with null Node root = null; for(int p = n - 1, i = n - 1; p >= 0;) { // Initialise node with NULL Node node = null; // Run do-while loop do { // Initialise node with // new Node(post[p]); node = new Node(post[p]); // Check is root is // equal to NULL if (root == null) { root = node; } // If size of set // is greater than 0 if (st.Count > 0) { // If st.Peek() is present in the // set s if (s.Contains(st.Peek())) { s.Remove(st.Peek()); st.Peek().left = node; st.Pop(); } else { st.Peek().right = node; } } st.Push(node); }while (post[p--] != init[i] && p >= 0); node = null; // If the stack is not empty and // st.top().data is equal to in[i] while (st.Count > 0 && i >= 0 && st.Peek().data == init[i]) { node = st.Peek(); // Pop elements from stack st.Pop(); i--; } // If node not equal to NULL if (node != null) { s.Add(node); st.Push(node); } } // Return root return root; } // For print preOrder Traversal static void preOrder(Node node) { if (node == null) return; Console.Write(node.data + " "); preOrder(node.left); preOrder(node.right); } // Driver Code public static void Main(String[] args) { int []init = { 4, 8, 2, 5, 1, 6, 3, 7 }; int []post = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = init.Length; // Function Call Node root = buildTree(init, post, n); Console.Write( "Preorder of the constructed tree : \n"); // Function Call for preOrder preOrder(root); }} // This code is contributed by aashish1995
Preorder of the constructed tree :
1 2 4 8 5 3 6 7
This article is contributed by Rishi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Naman-Bhalla
shrikanth13
PranchalKatiyar
codej
sujitmeshram
mohit kumar 29
aashish1995
Rajput-Ji
pp12
unknown2108
karnalrohit
itwasme
varshagumber28
yashdoshi9904
surinderdawra388
punamsingh628700
simmytarika5
jyoti369
Adobe
Amazon
cpp-unordered_map
Hash
Tree
Amazon
Adobe
Hash
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hash Functions and list/types of Hash functions
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Sorting a Map by value in C++ STL
File Organization in DBMS | Set 2
Applications of Hashing
Print Right View of a Binary Tree
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
Write a Program to Find the Maximum Depth or Height of a Tree | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 May, 2022"
},
{
"code": null,
"e": 114,
"s": 54,
"text": "Given Postorder and Inorder traversals, construct the tree."
},
{
"code": null,
"e": 125,
"s": 114,
"text": "Examples: "
},
{
"code": null,
"e": 430,
"s": 125,
"text": "Input: \nin[] = {2, 1, 3}\npost[] = {2, 3, 1}\n\nOutput: Root of below tree\n 1\n / \\\n 2 3 \n\n\nInput: \nin[] = {4, 8, 2, 5, 1, 6, 3, 7}\npost[] = {8, 4, 5, 2, 6, 7, 3, 1} \n\nOutput: Root of below tree\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n \\\n 8"
},
{
"code": null,
"e": 996,
"s": 430,
"text": "We have already discussed the construction of trees from Inorder and Preorder traversals. The idea is similar.Let us see the process of constructing tree from in[] = {4, 8, 2, 5, 1, 6, 3, 7} and post[] = {8, 4, 5, 2, 6, 7, 3, 1} 1) We first find the last node in post[]. The last node is “1”, we know this value is root as the root always appears at the end of postorder traversal.2) We search “1” in in[] to find the left and right subtrees of the root. Everything on the left of “1” in in[] is in the left subtree and everything on right is in the right subtree. "
},
{
"code": null,
"e": 1046,
"s": 996,
"text": " 1\n / \\\n[4, 8, 2, 5] [6, 3, 7]"
},
{
"code": null,
"e": 1543,
"s": 1046,
"text": "3) We recur the above process for following two. ....b) Recur for in[] = {6, 3, 7} and post[] = {6, 7, 3} .......Make the created tree as right child of root. ....a) Recur for in[] = {4, 8, 2, 5} and post[] = {8, 4, 5, 2}. .......Make the created tree as left child of root.Below is the implementation of the above idea. One important observation is, we recursively call for the right subtree before the left subtree as we decrease the index of the postorder index whenever we create a new node. "
},
{
"code": null,
"e": 1547,
"s": 1543,
"text": "C++"
},
{
"code": null,
"e": 1552,
"s": 1547,
"text": "Java"
},
{
"code": null,
"e": 1560,
"s": 1552,
"text": "Python3"
},
{
"code": null,
"e": 1563,
"s": 1560,
"text": "C#"
},
{
"code": null,
"e": 1574,
"s": 1563,
"text": "Javascript"
},
{
"code": "/* C++ program to construct tree using inorder and postorder traversals */#include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node { int data; Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int data); /* Prototypes for utility functions */int search(int arr[], int strt, int end, int value); /* Recursive function to construct binary of size n from Inorder traversal in[] and Postorder traversal post[]. Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and postorder do not form a tree */Node* buildUtil(int in[], int post[], int inStrt, int inEnd, int* pIndex){ // Base case if (inStrt > inEnd) return NULL; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ Node* node = newNode(post[*pIndex]); (*pIndex)--; /* If this node has no children then return */ if (inStrt == inEnd) return node; /* Else find the index of this node in Inorder traversal */ int iIndex = search(in, inStrt, inEnd, node->data); /* Using index in Inorder traversal, construct left and right subtress */ node->right = buildUtil(in, post, iIndex + 1, inEnd, pIndex); node->left = buildUtil(in, post, inStrt, iIndex - 1, pIndex); return node;} // This function mainly initializes index of root// and calls buildUtil()Node* buildTree(int in[], int post[], int n){ int pIndex = n - 1; return buildUtil(in, post, 0, n - 1, &pIndex);} /* Function to find index of value in arr[start...end] The function assumes that value is postsent in in[] */int search(int arr[], int strt, int end, int value){ int i; for (i = strt; i <= end; i++) { if (arr[i] == value) break; } return i;} /* Helper function that allocates a new node */Node* newNode(int data){ Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node);} /* This function is here just to test */void preOrder(Node* node){ if (node == NULL) return; printf(\"%d \", node->data); preOrder(node->left); preOrder(node->right);} // Driver codeint main(){ int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = sizeof(in) / sizeof(in[0]); Node* root = buildTree(in, post, n); cout << \"Preorder of the constructed tree : \\n\"; preOrder(root); return 0;}",
"e": 4157,
"s": 1574,
"text": null
},
{
"code": "// Java program to construct a tree using inorder// and postorder traversals /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { int data; Node left, right; public Node(int data) { this.data = data; left = right = null; }} class BinaryTree { /* Recursive function to construct binary of size n from Inorder traversal in[] and Postorder traversal post[]. Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and postorder do not form a tree */ Node buildUtil(int in[], int post[], int inStrt, int inEnd, int postStrt, int postEnd) { // Base case if (inStrt > inEnd) return null; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ Node node = new Node(post[postEnd]); /* If this node has no children then return */ if (inStrt == inEnd) return node; int iIndex = search(in, inStrt, inEnd, node.data); /* Using index in Inorder traversal, construct left and right subtress */ node.left = buildUtil( in, post, inStrt, iIndex - 1, postStrt, postStrt - inStrt + iIndex - 1); node.right = buildUtil(in, post, iIndex + 1, inEnd, postEnd - inEnd + iIndex, postEnd - 1); return node; } /* Function to find index of value in arr[start...end] The function assumes that value is postsent in in[] */ int search(int arr[], int strt, int end, int value) { int i; for (i = strt; i <= end; i++) { if (arr[i] == value) break; } return i; } /* This function is here just to test */ void preOrder(Node node) { if (node == null) return; System.out.print(node.data + \" \"); preOrder(node.left); preOrder(node.right); } // Driver Code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int in[] = new int[] { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = new int[] { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = in.length; Node root = tree.buildUtil(in, post, 0, n - 1, 0, n - 1); System.out.println( \"Preorder of the constructed tree : \"); tree.preOrder(root); }} // This code has been contributed by Mayank// Jaiswal(mayank_24)",
"e": 6737,
"s": 4157,
"text": null
},
{
"code": "# Python3 program to construct tree using# inorder and postorder traversals # Helper function that allocates# a new nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # Recursive function to construct binary# of size n from Inorder traversal in[]# and Postorder traversal post[]. Initial# values of inStrt and inEnd should be# 0 and n -1. The function doesn't do any# error checking for cases where inorder# and postorder do not form a treedef buildUtil(In, post, inStrt, inEnd, pIndex): # Base case if (inStrt > inEnd): return None # Pick current node from Postorder traversal # using postIndex and decrement postIndex node = newNode(post[pIndex[0]]) pIndex[0] -= 1 # If this node has no children # then return if (inStrt == inEnd): return node # Else find the index of this node # in Inorder traversal iIndex = search(In, inStrt, inEnd, node.data) # Using index in Inorder traversal, # construct left and right subtress node.right = buildUtil(In, post, iIndex + 1, inEnd, pIndex) node.left = buildUtil(In, post, inStrt, iIndex - 1, pIndex) return node # This function mainly initializes index# of root and calls buildUtil()def buildTree(In, post, n): pIndex = [n - 1] return buildUtil(In, post, 0, n - 1, pIndex) # Function to find index of value in# arr[start...end]. The function assumes# that value is postsent in in[]def search(arr, strt, end, value): i = 0 for i in range(strt, end + 1): if (arr[i] == value): break return i # This function is here just to testdef preOrder(node): if node == None: return print(node.data,end=\" \") preOrder(node.left) preOrder(node.right) # Driver codeif __name__ == '__main__': In = [4, 8, 2, 5, 1, 6, 3, 7] post = [8, 4, 5, 2, 6, 7, 3, 1] n = len(In) root = buildTree(In, post, n) print(\"Preorder of the constructed tree :\") preOrder(root) # This code is contributed by PranchalK",
"e": 8819,
"s": 6737,
"text": null
},
{
"code": "// C# program to construct a tree using// inorder and postorder traversalsusing System; /* A binary tree node has data, pointerto left child and a pointer to right child */public class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} // Class Index created to implement// pass by reference of Indexpublic class Index{ public int index;} class GFG{/* Recursive function to construct binaryof size n from Inorder traversal in[] andPostorder traversal post[]. Initial valuesof inStrt and inEnd should be 0 and n -1.The function doesn't do any error checkingfor cases where inorder and postorder donot form a tree */public virtual Node buildUtil(int[] @in, int[] post, int inStrt, int inEnd, Index pIndex){ // Base case if (inStrt > inEnd) { return null; } /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ Node node = new Node(post[pIndex.index]); (pIndex.index)--; /* If this node has no children then return */ if (inStrt == inEnd) { return node; } /* Else find the index of this node in Inorder traversal */ int iIndex = search(@in, inStrt, inEnd, node.data); /* Using index in Inorder traversal, construct left and right subtress */ node.right = buildUtil(@in, post, iIndex + 1, inEnd, pIndex); node.left = buildUtil(@in, post, inStrt, iIndex - 1, pIndex); return node;} // This function mainly initializes// index of root and calls buildUtil()public virtual Node buildTree(int[] @in, int[] post, int n){ Index pIndex = new Index(); pIndex.index = n - 1; return buildUtil(@in, post, 0, n - 1, pIndex);} /* Function to find index of value inarr[start...end]. The function assumesthat value is postsent in in[] */public virtual int search(int[] arr, int strt, int end, int value){ int i; for (i = strt; i <= end; i++) { if (arr[i] == value) { break; } } return i;} /* This function is here just to test */public virtual void preOrder(Node node){ if (node == null) { return; } Console.Write(node.data + \" \"); preOrder(node.left); preOrder(node.right);} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); int[] @in = new int[] {4, 8, 2, 5, 1, 6, 3, 7}; int[] post = new int[] {8, 4, 5, 2, 6, 7, 3, 1}; int n = @in.Length; Node root = tree.buildTree(@in, post, n); Console.WriteLine(\"Preorder of the constructed tree : \"); tree.preOrder(root);}} // This code is contributed by Shrikant13",
"e": 11622,
"s": 8819,
"text": null
},
{
"code": "<script>// Javascript program to construct a tree using inorder// and postorder traversals /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { constructor(data) { this.data = data; this.left = this.right = null; } } /* Recursive function to construct binary of size n from Inorder traversal in[] and Postorder traversal post[]. Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and postorder do not form a tree */ function buildUtil(In, post, inStrt, inEnd, postStrt, postEnd) { // Base case if (inStrt > inEnd) return null; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ let node = new Node(post[postEnd]); /* If this node has no children then return */ if (inStrt == inEnd) return node; let iIndex = search(In, inStrt, inEnd, node.data); /* Using index in Inorder traversal, construct left and right subtress */ node.left = buildUtil( In, post, inStrt, iIndex - 1, postStrt, postStrt - inStrt + iIndex - 1); node.right = buildUtil(In, post, iIndex + 1, inEnd, postEnd - inEnd + iIndex, postEnd - 1); return node; } /* Function to find index of value in arr[start...end] The function assumes that value is postsent in in[] */ function search(arr,strt,end,value) { let i; for (i = strt; i <= end; i++) { if (arr[i] == value) break; } return i; } /* This function is here just to test */ function preOrder(node) { if (node == null) return; document.write(node.data + \" \"); preOrder(node.left); preOrder(node.right); } // Driver Code let In=[4, 8, 2, 5, 1, 6, 3, 7]; let post=[8, 4, 5, 2, 6, 7, 3, 1]; let n = In.length; let root = buildUtil(In, post, 0, n - 1, 0, n - 1); document.write( \"Preorder of the constructed tree : <br>\"); preOrder(root); // This code is contributed by unknown2108</script>",
"e": 14003,
"s": 11622,
"text": null
},
{
"code": null,
"e": 14055,
"s": 14003,
"text": "Preorder of the constructed tree : \n1 2 4 8 5 3 6 7"
},
{
"code": null,
"e": 14078,
"s": 14055,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 14334,
"s": 14078,
"text": "Optimized approach: We can optimize the above solution using hashing (unordered_map in C++ or HashMap in Java). We store indexes of inorder traversal in a hash table. So that search can be done O(1) time If given that element in the tree are not repeated."
},
{
"code": null,
"e": 14338,
"s": 14334,
"text": "C++"
},
{
"code": null,
"e": 14343,
"s": 14338,
"text": "Java"
},
{
"code": null,
"e": 14351,
"s": 14343,
"text": "Python3"
},
{
"code": null,
"e": 14354,
"s": 14351,
"text": "C#"
},
{
"code": null,
"e": 14365,
"s": 14354,
"text": "Javascript"
},
{
"code": "/* C++ program to construct tree using inorder andpostorder traversals */#include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to leftchild and a pointer to right child */struct Node { int data; Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int data); /* Recursive function to construct binary of size nfrom Inorder traversal in[] and Postorder traversalpost[]. Initial values of inStrt and inEnd shouldbe 0 and n -1. The function doesn't do any errorchecking for cases where inorder and postorderdo not form a tree */Node* buildUtil(int in[], int post[], int inStrt, int inEnd, int* pIndex, unordered_map<int, int>& mp){ // Base case if (inStrt > inEnd) return NULL; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ int curr = post[*pIndex]; Node* node = newNode(curr); (*pIndex)--; /* If this node has no children then return */ if (inStrt == inEnd) return node; /* Else find the index of this node in Inorder traversal */ int iIndex = mp[curr]; /* Using index in Inorder traversal, construct left and right subtress */ node->right = buildUtil(in, post, iIndex + 1, inEnd, pIndex, mp); node->left = buildUtil(in, post, inStrt, iIndex - 1, pIndex, mp); return node;} // This function mainly creates an unordered_map, then// calls buildTreeUtil()struct Node* buildTree(int in[], int post[], int len){ // Store indexes of all items so that we // we can quickly find later unordered_map<int, int> mp; for (int i = 0; i < len; i++) mp[in[i]] = i; int index = len - 1; // Index in postorder return buildUtil(in, post, 0, len - 1, &index, mp);} /* Helper function that allocates a new node */Node* newNode(int data){ Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node);} /* This function is here just to test */void preOrder(Node* node){ if (node == NULL) return; printf(\"%d \", node->data); preOrder(node->left); preOrder(node->right);} // Driver codeint main(){ int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = sizeof(in) / sizeof(in[0]); Node* root = buildTree(in, post, n); cout << \"Preorder of the constructed tree : \\n\"; preOrder(root); return 0;}",
"e": 16844,
"s": 14365,
"text": null
},
{
"code": "/* Java program to construct tree using inorder andpostorder traversals */import java.util.*;class GFG{ /* A binary tree node has data, pointer to leftchild and a pointer to right child */static class Node{ int data; Node left, right;}; // Utility function to create a new node/* Helper function that allocates a new node */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return (node);} /* Recursive function to construct binary of size nfrom Inorder traversal in[] and Postorder traversalpost[]. Initial values of inStrt and inEnd shouldbe 0 and n -1. The function doesn't do any errorchecking for cases where inorder and postorderdo not form a tree */static Node buildUtil(int in[], int post[], int inStrt, int inEnd){ // Base case if (inStrt > inEnd) return null; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ int curr = post[index]; Node node = newNode(curr); (index)--; /* If this node has no children then return */ if (inStrt == inEnd) return node; /* Else find the index of this node in Inorder traversal */ int iIndex = mp.get(curr); /* Using index in Inorder traversal, con left and right subtress */ node.right = buildUtil(in, post, iIndex + 1, inEnd); node.left = buildUtil(in, post, inStrt, iIndex - 1); return node;}static HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();static int index; // This function mainly creates an unordered_map, then// calls buildTreeUtil()static Node buildTree(int in[], int post[], int len){ // Store indexes of all items so that we // we can quickly find later for (int i = 0; i < len; i++) mp.put(in[i], i); index = len - 1; // Index in postorder return buildUtil(in, post, 0, len - 1 );} /* This function is here just to test */static void preOrder(Node node){ if (node == null) return; System.out.printf(\"%d \", node.data); preOrder(node.left); preOrder(node.right);} // Driver codepublic static void main(String[] args){ int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = in.length; Node root = buildTree(in, post, n); System.out.print(\"Preorder of the constructed tree : \\n\"); preOrder(root);}} // This code is contributed by Rajput-Ji",
"e": 19313,
"s": 16844,
"text": null
},
{
"code": "# Python3 program to construct tree using inorder# and postorder traversals # A binary tree node has data, pointer to left# child and a pointer to right childclass Node: def __init__(self, x): self.data = x self.left = None self.right = None # Recursive function to construct binary of size n# from Inorder traversal in[] and Postorder traversal# post[]. Initial values of inStrt and inEnd should# be 0 and n -1. The function doesn't do any error# checking for cases where inorder and postorder# do not form a treedef buildUtil(inn, post, innStrt, innEnd): global mp, index # Base case if (innStrt > innEnd): return None # Pick current node from Postorder traversal # using postIndex and decrement postIndex curr = post[index] node = Node(curr) index -= 1 # If this node has no children then return if (innStrt == innEnd): return node # Else find the index of this node inn # Inorder traversal iIndex = mp[curr] # Using index inn Inorder traversal, # construct left and right subtress node.right = buildUtil(inn, post, iIndex + 1, innEnd) node.left = buildUtil(inn, post, innStrt, iIndex - 1) return node # This function mainly creates an unordered_map,# then calls buildTreeUtil()def buildTree(inn, post, lenn): global index # Store indexes of all items so that we # we can quickly find later for i in range(lenn): mp[inn[i]] = i # Index in postorder index = lenn - 1 return buildUtil(inn, post, 0, lenn - 1) # This function is here just to testdef preOrder(node): if (node == None): return print(node.data, end = \" \") preOrder(node.left) preOrder(node.right) # Driver Codeif __name__ == '__main__': inn = [ 4, 8, 2, 5, 1, 6, 3, 7 ] post = [ 8, 4, 5, 2, 6, 7, 3, 1 ] n = len(inn) mp, index = {}, 0 root = buildTree(inn, post, n) print(\"Preorder of the constructed tree :\") preOrder(root) # This code is contributed by mohit kumar 29",
"e": 21427,
"s": 19313,
"text": null
},
{
"code": "/* C# program to construct tree using inorder andpostorder traversals */using System;using System.Collections.Generic;class GFG{ /* A binary tree node has data, pointer to leftchild and a pointer to right child */ public class Node { public int data; public Node left, right; }; // Utility function to create a new node /* Helper function that allocates a new node */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return (node); } /* Recursive function to construct binary of size nfrom Inorder traversal in[] and Postorder traversalpost[]. Initial values of inStrt and inEnd shouldbe 0 and n -1. The function doesn't do any errorchecking for cases where inorder and postorderdo not form a tree */ static Node buildUtil(int []init, int []post, int inStrt, int inEnd) { // Base case if (inStrt > inEnd) return null; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ int curr = post[index]; Node node = newNode(curr); (index)--; /* If this node has no children then return */ if (inStrt == inEnd) return node; /* Else find the index of this node in Inorder traversal */ int iIndex = mp[curr]; /* Using index in Inorder traversal, con left and right subtress */ node.right = buildUtil(init, post, iIndex + 1, inEnd); node.left = buildUtil(init, post, inStrt, iIndex - 1); return node; } static Dictionary<int,int> mp = new Dictionary<int,int>(); static int index; // This function mainly creates an unordered_map, then // calls buildTreeUtil() static Node buildTree(int []init, int []post, int len) { // Store indexes of all items so that we // we can quickly find later for (int i = 0; i < len; i++) mp.Add(init[i], i); index = len - 1; // Index in postorder return buildUtil(init, post, 0, len - 1 ); } /* This function is here just to test */ static void preOrder(Node node) { if (node == null) return; Console.Write( node.data + \" \"); preOrder(node.left); preOrder(node.right); } // Driver code public static void Main(String[] args) { int []init = { 4, 8, 2, 5, 1, 6, 3, 7 }; int []post = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = init.Length; Node root = buildTree(init, post, n); Console.Write(\"Preorder of the constructed tree : \\n\"); preOrder(root); }} // This code is contributed by Rajput-Ji",
"e": 23999,
"s": 21427,
"text": null
},
{
"code": "<script> /* JavaScript program to construct tree using inorder and postorder traversals */ /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { constructor() { this.data = 0; this.left = null; this.right = null; } } // Utility function to create a new node /* Helper function that allocates a new node */ function newNode(data) { var node = new Node(); node.data = data; node.left = node.right = null; return node; } /* Recursive function to construct binary of size n from Inorder traversal in[] and Postorder traversal post[]. Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and postorder do not form a tree */ function buildUtil(init, post, inStrt, inEnd) { // Base case if (inStrt > inEnd) { return null; } /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ var curr = post[index]; var node = newNode(curr); index--; /* If this node has no children then return */ if (inStrt == inEnd) { return node; } /* Else find the index of this node in Inorder traversal */ var iIndex = mp[curr]; /* Using index in Inorder traversal, con left and right subtress */ node.right = buildUtil(init, post, iIndex + 1, inEnd); node.left = buildUtil(init, post, inStrt, iIndex - 1); return node; } var mp = {}; var index; // This function mainly creates an unordered_map, then // calls buildTreeUtil() function buildTree(init, post, len) { // Store indexes of all items so that we // we can quickly find later for (var i = 0; i < len; i++) { mp[init[i]] = i; } index = len - 1; // Index in postorder return buildUtil(init, post, 0, len - 1); } /* This function is here just to test */ function preOrder(node) { if (node == null) { return; } document.write(node.data + \" \"); preOrder(node.left); preOrder(node.right); } // Driver code var init = [4, 8, 2, 5, 1, 6, 3, 7]; var post = [8, 4, 5, 2, 6, 7, 3, 1]; var n = init.length; var root = buildTree(init, post, n); document.write(\"Preorder of the constructed tree : <br>\"); preOrder(root); </script>",
"e": 26602,
"s": 23999,
"text": null
},
{
"code": null,
"e": 26654,
"s": 26602,
"text": "Preorder of the constructed tree : \n1 2 4 8 5 3 6 7"
},
{
"code": null,
"e": 26677,
"s": 26654,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 26696,
"s": 26677,
"text": "Another approach: "
},
{
"code": null,
"e": 26741,
"s": 26696,
"text": "Using stack and set without using recursion."
},
{
"code": null,
"e": 26788,
"s": 26741,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 26792,
"s": 26788,
"text": "C++"
},
{
"code": null,
"e": 26797,
"s": 26792,
"text": "Java"
},
{
"code": null,
"e": 26800,
"s": 26797,
"text": "C#"
},
{
"code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointerto left child and a pointer to rightchild */struct Node{ int data; Node *left, *right; Node(int x) { data = x; left = right = NULL; }}; /*Tree building function*/Node *buildTree(int in[], int post[], int n){ // Create Stack of type Node* stack<Node*> st; // Create Set of type Node* set<Node*> s; // Initialise postIndex with n - 1 int postIndex = n - 1; // Initialise root with NULL Node* root = NULL; for (int p = n - 1, i = n - 1; p>=0) { // Initialise node with NULL Node* node = NULL; // Run do-while loop do { // Initialise node with // new Node(post[p]); node = new Node(post[p]); // Check is root is // equal to NULL if (root == NULL) { root = node; } // If size of set // is greater than 0 if (st.size() > 0) { // If st.top() is present in the // set s if (s.find(st.top()) != s.end()) { s.erase(st.top()); st.top()->left = node; st.pop(); } else { st.top()->right = node; } } st.push(node); } while (post[p--] != in[i] && p >=0); node = NULL; // If the stack is not empty and // st.top()->data is equal to in[i] while (st.size() > 0 && i>=0 && st.top()->data == in[i]) { node = st.top(); // Pop elements from stack st.pop(); i--; } // if node not equal to NULL if (node != NULL) { s.insert(node); st.push(node); } } // Return root return root; }/* for print preOrder Traversal */void preOrder(Node* node){ if (node == NULL) return; printf(\"%d \", node->data); preOrder(node->left); preOrder(node->right);} // Driver Codeint main(){ int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = sizeof(in) / sizeof(in[0]); // Function Call Node* root = buildTree(in, post, n); cout << \"Preorder of the constructed tree : \\n\"; // Function Call for preOrder preOrder(root); return 0;}",
"e": 29037,
"s": 26800,
"text": null
},
{
"code": "// Java program for above approachimport java.io.*;import java.util.*; class GFG { // Node class static class Node { int data; Node left, right; // Constructor Node(int x) { data = x; left = right = null; } } // Tree building function static Node buildTree(int in[], int post[], int n) { // Create Stack of type Node* Stack<Node> st = new Stack<>(); // Create HashSet of type Node* HashSet<Node> s = new HashSet<>(); // Initialise postIndex with n - 1 int postIndex = n - 1; // Initialise root with null Node root = null; for (int p = n - 1, i = n - 1; p >= 0; ) { // Initialise node with NULL Node node = null; // Run do-while loop do { // Initialise node with // new Node(post[p]); node = new Node(post[p]); // Check is root is // equal to NULL if (root == null) { root = node; } // If size of set // is greater than 0 if (st.size() > 0) { // If st.peek() is present in the // set s if (s.contains(st.peek())) { s.remove(st.peek()); st.peek().left = node; st.pop(); } else { st.peek().right = node; } } st.push(node); } while (post[p--] != in[i] && p >= 0); node = null; // If the stack is not empty and // st.top().data is equal to in[i] while (st.size() > 0 && i >= 0 && st.peek().data == in[i]) { node = st.peek(); // Pop elements from stack st.pop(); i--; } // If node not equal to NULL if (node != null) { s.add(node); st.push(node); } } // Return root return root; } // For print preOrder Traversal static void preOrder(Node node) { if (node == null) return; System.out.printf(\"%d \", node.data); preOrder(node.left); preOrder(node.right); } // Driver Code public static void main(String[] args) { int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = in.length; // Function Call Node root = buildTree(in, post, n); System.out.print( \"Preorder of the constructed tree : \\n\"); // Function Call for preOrder preOrder(root); }} // This code is contributed by sujitmeshram",
"e": 31928,
"s": 29037,
"text": null
},
{
"code": "// C# program for above approachusing System;using System.Collections.Generic;class GFG{ // Node class public class Node { public int data; public Node left, right; // Constructor public Node(int x) { data = x; left = right = null; } } // Tree building function static Node buildTree(int []init, int []post, int n) { // Create Stack of type Node* Stack<Node> st = new Stack<Node>(); // Create HashSet of type Node* HashSet<Node> s = new HashSet<Node>(); // Initialise postIndex with n - 1 int postIndex = n - 1; // Initialise root with null Node root = null; for(int p = n - 1, i = n - 1; p >= 0;) { // Initialise node with NULL Node node = null; // Run do-while loop do { // Initialise node with // new Node(post[p]); node = new Node(post[p]); // Check is root is // equal to NULL if (root == null) { root = node; } // If size of set // is greater than 0 if (st.Count > 0) { // If st.Peek() is present in the // set s if (s.Contains(st.Peek())) { s.Remove(st.Peek()); st.Peek().left = node; st.Pop(); } else { st.Peek().right = node; } } st.Push(node); }while (post[p--] != init[i] && p >= 0); node = null; // If the stack is not empty and // st.top().data is equal to in[i] while (st.Count > 0 && i >= 0 && st.Peek().data == init[i]) { node = st.Peek(); // Pop elements from stack st.Pop(); i--; } // If node not equal to NULL if (node != null) { s.Add(node); st.Push(node); } } // Return root return root; } // For print preOrder Traversal static void preOrder(Node node) { if (node == null) return; Console.Write(node.data + \" \"); preOrder(node.left); preOrder(node.right); } // Driver Code public static void Main(String[] args) { int []init = { 4, 8, 2, 5, 1, 6, 3, 7 }; int []post = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = init.Length; // Function Call Node root = buildTree(init, post, n); Console.Write( \"Preorder of the constructed tree : \\n\"); // Function Call for preOrder preOrder(root); }} // This code is contributed by aashish1995",
"e": 34448,
"s": 31928,
"text": null
},
{
"code": null,
"e": 34500,
"s": 34448,
"text": "Preorder of the constructed tree : \n1 2 4 8 5 3 6 7"
},
{
"code": null,
"e": 34662,
"s": 34500,
"text": "This article is contributed by Rishi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 34675,
"s": 34662,
"text": "Naman-Bhalla"
},
{
"code": null,
"e": 34687,
"s": 34675,
"text": "shrikanth13"
},
{
"code": null,
"e": 34703,
"s": 34687,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 34709,
"s": 34703,
"text": "codej"
},
{
"code": null,
"e": 34722,
"s": 34709,
"text": "sujitmeshram"
},
{
"code": null,
"e": 34737,
"s": 34722,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34749,
"s": 34737,
"text": "aashish1995"
},
{
"code": null,
"e": 34759,
"s": 34749,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34764,
"s": 34759,
"text": "pp12"
},
{
"code": null,
"e": 34776,
"s": 34764,
"text": "unknown2108"
},
{
"code": null,
"e": 34788,
"s": 34776,
"text": "karnalrohit"
},
{
"code": null,
"e": 34796,
"s": 34788,
"text": "itwasme"
},
{
"code": null,
"e": 34811,
"s": 34796,
"text": "varshagumber28"
},
{
"code": null,
"e": 34825,
"s": 34811,
"text": "yashdoshi9904"
},
{
"code": null,
"e": 34842,
"s": 34825,
"text": "surinderdawra388"
},
{
"code": null,
"e": 34859,
"s": 34842,
"text": "punamsingh628700"
},
{
"code": null,
"e": 34872,
"s": 34859,
"text": "simmytarika5"
},
{
"code": null,
"e": 34881,
"s": 34872,
"text": "jyoti369"
},
{
"code": null,
"e": 34887,
"s": 34881,
"text": "Adobe"
},
{
"code": null,
"e": 34894,
"s": 34887,
"text": "Amazon"
},
{
"code": null,
"e": 34912,
"s": 34894,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 34917,
"s": 34912,
"text": "Hash"
},
{
"code": null,
"e": 34922,
"s": 34917,
"text": "Tree"
},
{
"code": null,
"e": 34929,
"s": 34922,
"text": "Amazon"
},
{
"code": null,
"e": 34935,
"s": 34929,
"text": "Adobe"
},
{
"code": null,
"e": 34940,
"s": 34935,
"text": "Hash"
},
{
"code": null,
"e": 34945,
"s": 34940,
"text": "Tree"
},
{
"code": null,
"e": 35043,
"s": 34945,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35091,
"s": 35043,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 35161,
"s": 35091,
"text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"
},
{
"code": null,
"e": 35195,
"s": 35161,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 35229,
"s": 35195,
"text": "File Organization in DBMS | Set 2"
},
{
"code": null,
"e": 35253,
"s": 35229,
"text": "Applications of Hashing"
},
{
"code": null,
"e": 35287,
"s": 35253,
"text": "Print Right View of a Binary Tree"
},
{
"code": null,
"e": 35322,
"s": 35287,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 35351,
"s": 35322,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 35383,
"s": 35351,
"text": "Introduction to Data Structures"
}
] |
Python – Difference between json.dump() and json.dumps() | 02 Jun, 2022
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json.
Note: For more information, refer to Working With JSON Data in Python
json.dumps() method can convert a Python object into a JSON string.
Syntax: json.dumps(dict, indent)
Parameters:
dictionary – name of dictionary which should be converted to JSON object.
indent – defines the number of units for indentation
Example:
Python3
# Python program to convert# Python to JSON import json # Data to be writtendictionary ={ "id": "04", "name": "sunil", "department": "HR"} # Serializing json json_object = json.dumps(dictionary, indent = 4)print(json_object)
Output:
{
"department": "HR",
"id": "04",
"name": "sunil"
}
Python objects and their equivalent conversion to JSON:
json.dump() method can be used for writing to JSON file.
Syntax: json.dump(dict, file_pointer)
Parameters:
dictionary – name of dictionary which should be converted to JSON object.
file pointer – pointer of the file opened in write or append mode.
Example:
Python3
# Python program to write JSON# to a file import json # Data to be writtendictionary ={ "name" : "sathiyajith", "rollno" : 56, "cgpa" : 8.6, "phonenumber" : "9976770500"} with open("sample.json", "w") as outfile: json.dump(dictionary, outfile)
Output:
Let us see the differences in a tabular form -:
Its syntax is -:
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
Its syntax is -:
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
sagar0719kumar
prachisoda1234
mayank007rawa
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jun, 2022"
},
{
"code": null,
"e": 291,
"s": 28,
"text": "JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. "
},
{
"code": null,
"e": 361,
"s": 291,
"text": "Note: For more information, refer to Working With JSON Data in Python"
},
{
"code": null,
"e": 429,
"s": 361,
"text": "json.dumps() method can convert a Python object into a JSON string."
},
{
"code": null,
"e": 463,
"s": 429,
"text": "Syntax: json.dumps(dict, indent) "
},
{
"code": null,
"e": 475,
"s": 463,
"text": "Parameters:"
},
{
"code": null,
"e": 549,
"s": 475,
"text": "dictionary – name of dictionary which should be converted to JSON object."
},
{
"code": null,
"e": 602,
"s": 549,
"text": "indent – defines the number of units for indentation"
},
{
"code": null,
"e": 612,
"s": 602,
"text": "Example: "
},
{
"code": null,
"e": 620,
"s": 612,
"text": "Python3"
},
{
"code": "# Python program to convert# Python to JSON import json # Data to be writtendictionary ={ \"id\": \"04\", \"name\": \"sunil\", \"department\": \"HR\"} # Serializing json json_object = json.dumps(dictionary, indent = 4)print(json_object)",
"e": 861,
"s": 620,
"text": null
},
{
"code": null,
"e": 869,
"s": 861,
"text": "Output:"
},
{
"code": null,
"e": 933,
"s": 869,
"text": "{\n \"department\": \"HR\",\n \"id\": \"04\",\n \"name\": \"sunil\"\n}"
},
{
"code": null,
"e": 989,
"s": 933,
"text": "Python objects and their equivalent conversion to JSON:"
},
{
"code": null,
"e": 1046,
"s": 989,
"text": "json.dump() method can be used for writing to JSON file."
},
{
"code": null,
"e": 1085,
"s": 1046,
"text": "Syntax: json.dump(dict, file_pointer) "
},
{
"code": null,
"e": 1097,
"s": 1085,
"text": "Parameters:"
},
{
"code": null,
"e": 1171,
"s": 1097,
"text": "dictionary – name of dictionary which should be converted to JSON object."
},
{
"code": null,
"e": 1238,
"s": 1171,
"text": "file pointer – pointer of the file opened in write or append mode."
},
{
"code": null,
"e": 1248,
"s": 1238,
"text": "Example: "
},
{
"code": null,
"e": 1256,
"s": 1248,
"text": "Python3"
},
{
"code": "# Python program to write JSON# to a file import json # Data to be writtendictionary ={ \"name\" : \"sathiyajith\", \"rollno\" : 56, \"cgpa\" : 8.6, \"phonenumber\" : \"9976770500\"} with open(\"sample.json\", \"w\") as outfile: json.dump(dictionary, outfile)",
"e": 1520,
"s": 1256,
"text": null
},
{
"code": null,
"e": 1529,
"s": 1520,
"text": "Output: "
},
{
"code": null,
"e": 1577,
"s": 1529,
"text": "Let us see the differences in a tabular form -:"
},
{
"code": null,
"e": 1594,
"s": 1577,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 1765,
"s": 1594,
"text": "json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)"
},
{
"code": null,
"e": 1782,
"s": 1765,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 1951,
"s": 1782,
"text": "json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) "
},
{
"code": null,
"e": 1966,
"s": 1951,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 1981,
"s": 1966,
"text": "prachisoda1234"
},
{
"code": null,
"e": 1995,
"s": 1981,
"text": "mayank007rawa"
},
{
"code": null,
"e": 2007,
"s": 1995,
"text": "Python-json"
},
{
"code": null,
"e": 2014,
"s": 2007,
"text": "Python"
},
{
"code": null,
"e": 2112,
"s": 2014,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2154,
"s": 2112,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2176,
"s": 2154,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2211,
"s": 2176,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2237,
"s": 2211,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2269,
"s": 2237,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2298,
"s": 2269,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2325,
"s": 2298,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2355,
"s": 2325,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2376,
"s": 2355,
"text": "Python OOPs Concepts"
}
] |
Deploy Keras Models using TensorFlow Serving — TF 2.x | by Pranit Bankar | Towards Data Science | Created a great Deep Learning model? Congratulations!
Don’t know how to create a Deep Learning model using Keras? No worries!
I shall cover how to create a basic and super simple Keras Model and how to deploy it on your local machine. This model would definitely be simpler than whatever you plan to deploy (well, I hope so!). But since the goal of this post is to enable you to deploy your Keras Model, I want to ensure that we don’t deviate from our goal.
Now why do we need to deploy it on our local server? To verify that whatever problem we intend to solve with our model, can be solved in the real world. You would expect that your model works in the same way and gives the same performance on the real world data that it gave on your test input in your local IDE or notebook. But the truth is it will hardly ever do that. If it does, great! But you wouldn’t want to realize the gap between your test data and the real world data after you have deployed your model for consumption.
What if the real world images are different from the white background studio images you used to train, validate and test your model? What if it takes too much time to process your data on the network calls due to latency issues than it did in your IDE? Finding these problems early are key to successfully transitioning your model from your cozy laptop to the reality outside.
TensorFlow Serving is a flexible, high-performance serving system for machine learning models, designed for production environments. TensorFlow Serving makes it easy to deploy new algorithms and experiments, while keeping the same server architecture and APIs. TensorFlow Serving provides out-of-the-box integration with TensorFlow models, but can be easily extended to serve other types of models and data.
If you are used to building your models using TensorFlow or Keras, then the easiest way of deploying your models is by using TensorFlow Serving.
Most of the TensorFlow documentation is written for TensorFlow-1.0 and it sadly doesn’t work as is for TensorFlow-2.0. Hence the need for this blog.
You can find my notebook here: (You can also run it in Google Colab)
[If you already have your model ready in SavedModel format, skip this part.]
Here I shall be creating a model that predicts a linear relationship:
y = 2x + 1
I used Google Colab but you can use any tool of your choice as long as the generated model remains the same.
Let’s dig in.
We first load the necessary libraries
We then create our dataset
Then we build our model. Since it is a simple linear relationship, a single neuron is enough.
We now train our model for 20 epochs. After 20 epochs, our model’s losses were around 2e-12 for training as well as validation. Then, we evaluate our model on the test data. Our test loss came out to be around 2e-12. You can try predicting some values to verify the results like I did here. The output I received is 15.866.
Everything looks great.Let’s now save and download our model in the SavedModel format.
From this step onwards, the process would be independent of the type of input and output data used. It could be numeric arrays, texts, images, audios or videos. In Colab, you should be able to see a folder named ‘linear_model’ created in your directory. The ‘export_path’ variable here indicates that our model is named ‘linear_model’ and this is the first version of it. Having a version number is mandatory for deploying using TensorFlow Serving so ensure that you have your ‘export_path’ in the form of {MODEL}/{VERSION}, where VERSION is numeric without any alphabets or special characters.
Now to download this model, we will zip this folder and then use ‘google.colab.files’ to download the zip file.
Once you extract this zip file on your local machine, you should be able to see a folder named ‘linear_model’, which contains a folder named ‘1’, which contains your variables and model architecture.
This is a one-time setup activity.
To start our local server we need a TensorFlow Serving instance on our local machine. Instead of downloading and installing all the necessary libraries, we shall use the recommended way of using Docker.
You can read more details about it in the Guide here.
We won’t be following all the steps mentioned in the Guide, as some of the things are specific for TF 1.0 and some things are specific to reusing already available models.
Once you download Docker on your system from here, go ahead and finish the installation steps. You would need to restart your system so save all your work.
Once the installation is finished successfully, go to Command Prompt (Mac and Linux users, kindly use appropriate tools) and type
docker pull tensorflow/serving
That’s it! Let’s now proceed to deploy our model.
What if I told you that deploying the model is just one line of command script.
All you need is the absolute path to your ‘linear_model’ folder. Do not forget to use the absolute path as this would cause errors that you would need to spend time and break your head to solve.
My ‘linear_model’ was saved inside ‘D:/my_own_models/’. So my command looked like:
docker run -p 8038:8501 — mount type=bind,source=D:/my_own_models/linear_model,target=/models/linear_model -e MODEL_NAME=linear_model -t tensorflow/serving
This is all a single line. For your subsequent models, you need to just change your ‘source’ path. Changing your ‘target’ and MODEL_NAME is optional, but, of course, necessary based on the context.
Now let us try to understand what the above command script indicates. The generic form of this script is
docker run -p {LOCAL_PORT}:8501 — mount type=bind,source={ABSOLUTE_PATH},target=/models/{MODEL_NAME} -e MODEL_NAME={MODEL_NAME} -t tensorflow/serving
{LOCAL_PORT}: This is the local port of your machine, so make sure you do not have anything else running there. We are mapping it to the 8501 port exposed for REST API calls by TensorFlow Serving
{ABSOLUTE_PATH}: This is the absolute path for your model. This tells the TensorFlow Serving where your model is located at (obviously).
{MODEL_NAME}: This is the service end-point for your REST API call with the prefix ‘/models/’. Do not change the ‘/models/’ prefix in the target variable and only change the {MODEL_NAME} part based on your need
Once you see the below message in your command window, your model has been hosted successfully. You can also see a container running successfully in your Docker dashboard.
[evhttp_server.cc : 238] NET_LOG: Entering the event loop ...
I used Postman for testing my queries, but you can use any form of API calls.
[Note: You won’t be able to make direct calls from browser or any other host to your REST API since CORS is not enabled by TensorFlow Serving. However, there are ways to achieve a call from the browser to your model that I would cover in a separate post.]
You need a POST query to test our model. Our request URL looks like:
http://localhost:8509/v1/models/linear_model:predict
Again, the generic form is:
http://localhost:{LOCAL_PORT}}/v1/models/{MODEL_NAME}:predict
Add ‘Content-Type’ as ‘application/json’ in your header and your body as:
{ "instances": [[ 0 ]]}
Ensure that your JSON key is ‘instances’ and your values are inside an array. Since our input is [0], we write it as [[0]].
Remember, that we created a model to predict y = 2x + 1 which means for input value 0, our prediction should have value 1 (or close to it).
Let’s send our query. The response looks like:
{ "predictions": [[ 0.999998748 ]]}
Well, that looks pretty much like 1 to me. Play around with your model by making POST queries.
We were able to create a model from scratch and deploy it on our local server. This is a very good way to see if your model would work the same way in the real world as it does on your IDE.
As I previously mentioned, however, you won’t be able to make calls to this model apart from Postman (or similar tools). How to overcome that? I shall cover that in a separate post as this is already becoming too long.
If you have reached here, thanks for reading. If you have any queries, suggestions or comments, please feel free to comment on this post. This is my first blog on Machine Learning and I would gladly appreciate any and all feedback. | [
{
"code": null,
"e": 226,
"s": 172,
"text": "Created a great Deep Learning model? Congratulations!"
},
{
"code": null,
"e": 298,
"s": 226,
"text": "Don’t know how to create a Deep Learning model using Keras? No worries!"
},
{
"code": null,
"e": 630,
"s": 298,
"text": "I shall cover how to create a basic and super simple Keras Model and how to deploy it on your local machine. This model would definitely be simpler than whatever you plan to deploy (well, I hope so!). But since the goal of this post is to enable you to deploy your Keras Model, I want to ensure that we don’t deviate from our goal."
},
{
"code": null,
"e": 1160,
"s": 630,
"text": "Now why do we need to deploy it on our local server? To verify that whatever problem we intend to solve with our model, can be solved in the real world. You would expect that your model works in the same way and gives the same performance on the real world data that it gave on your test input in your local IDE or notebook. But the truth is it will hardly ever do that. If it does, great! But you wouldn’t want to realize the gap between your test data and the real world data after you have deployed your model for consumption."
},
{
"code": null,
"e": 1537,
"s": 1160,
"text": "What if the real world images are different from the white background studio images you used to train, validate and test your model? What if it takes too much time to process your data on the network calls due to latency issues than it did in your IDE? Finding these problems early are key to successfully transitioning your model from your cozy laptop to the reality outside."
},
{
"code": null,
"e": 1945,
"s": 1537,
"text": "TensorFlow Serving is a flexible, high-performance serving system for machine learning models, designed for production environments. TensorFlow Serving makes it easy to deploy new algorithms and experiments, while keeping the same server architecture and APIs. TensorFlow Serving provides out-of-the-box integration with TensorFlow models, but can be easily extended to serve other types of models and data."
},
{
"code": null,
"e": 2090,
"s": 1945,
"text": "If you are used to building your models using TensorFlow or Keras, then the easiest way of deploying your models is by using TensorFlow Serving."
},
{
"code": null,
"e": 2239,
"s": 2090,
"text": "Most of the TensorFlow documentation is written for TensorFlow-1.0 and it sadly doesn’t work as is for TensorFlow-2.0. Hence the need for this blog."
},
{
"code": null,
"e": 2308,
"s": 2239,
"text": "You can find my notebook here: (You can also run it in Google Colab)"
},
{
"code": null,
"e": 2385,
"s": 2308,
"text": "[If you already have your model ready in SavedModel format, skip this part.]"
},
{
"code": null,
"e": 2455,
"s": 2385,
"text": "Here I shall be creating a model that predicts a linear relationship:"
},
{
"code": null,
"e": 2466,
"s": 2455,
"text": "y = 2x + 1"
},
{
"code": null,
"e": 2575,
"s": 2466,
"text": "I used Google Colab but you can use any tool of your choice as long as the generated model remains the same."
},
{
"code": null,
"e": 2589,
"s": 2575,
"text": "Let’s dig in."
},
{
"code": null,
"e": 2627,
"s": 2589,
"text": "We first load the necessary libraries"
},
{
"code": null,
"e": 2654,
"s": 2627,
"text": "We then create our dataset"
},
{
"code": null,
"e": 2748,
"s": 2654,
"text": "Then we build our model. Since it is a simple linear relationship, a single neuron is enough."
},
{
"code": null,
"e": 3072,
"s": 2748,
"text": "We now train our model for 20 epochs. After 20 epochs, our model’s losses were around 2e-12 for training as well as validation. Then, we evaluate our model on the test data. Our test loss came out to be around 2e-12. You can try predicting some values to verify the results like I did here. The output I received is 15.866."
},
{
"code": null,
"e": 3159,
"s": 3072,
"text": "Everything looks great.Let’s now save and download our model in the SavedModel format."
},
{
"code": null,
"e": 3754,
"s": 3159,
"text": "From this step onwards, the process would be independent of the type of input and output data used. It could be numeric arrays, texts, images, audios or videos. In Colab, you should be able to see a folder named ‘linear_model’ created in your directory. The ‘export_path’ variable here indicates that our model is named ‘linear_model’ and this is the first version of it. Having a version number is mandatory for deploying using TensorFlow Serving so ensure that you have your ‘export_path’ in the form of {MODEL}/{VERSION}, where VERSION is numeric without any alphabets or special characters."
},
{
"code": null,
"e": 3866,
"s": 3754,
"text": "Now to download this model, we will zip this folder and then use ‘google.colab.files’ to download the zip file."
},
{
"code": null,
"e": 4066,
"s": 3866,
"text": "Once you extract this zip file on your local machine, you should be able to see a folder named ‘linear_model’, which contains a folder named ‘1’, which contains your variables and model architecture."
},
{
"code": null,
"e": 4101,
"s": 4066,
"text": "This is a one-time setup activity."
},
{
"code": null,
"e": 4304,
"s": 4101,
"text": "To start our local server we need a TensorFlow Serving instance on our local machine. Instead of downloading and installing all the necessary libraries, we shall use the recommended way of using Docker."
},
{
"code": null,
"e": 4358,
"s": 4304,
"text": "You can read more details about it in the Guide here."
},
{
"code": null,
"e": 4530,
"s": 4358,
"text": "We won’t be following all the steps mentioned in the Guide, as some of the things are specific for TF 1.0 and some things are specific to reusing already available models."
},
{
"code": null,
"e": 4686,
"s": 4530,
"text": "Once you download Docker on your system from here, go ahead and finish the installation steps. You would need to restart your system so save all your work."
},
{
"code": null,
"e": 4816,
"s": 4686,
"text": "Once the installation is finished successfully, go to Command Prompt (Mac and Linux users, kindly use appropriate tools) and type"
},
{
"code": null,
"e": 4847,
"s": 4816,
"text": "docker pull tensorflow/serving"
},
{
"code": null,
"e": 4897,
"s": 4847,
"text": "That’s it! Let’s now proceed to deploy our model."
},
{
"code": null,
"e": 4977,
"s": 4897,
"text": "What if I told you that deploying the model is just one line of command script."
},
{
"code": null,
"e": 5172,
"s": 4977,
"text": "All you need is the absolute path to your ‘linear_model’ folder. Do not forget to use the absolute path as this would cause errors that you would need to spend time and break your head to solve."
},
{
"code": null,
"e": 5255,
"s": 5172,
"text": "My ‘linear_model’ was saved inside ‘D:/my_own_models/’. So my command looked like:"
},
{
"code": null,
"e": 5411,
"s": 5255,
"text": "docker run -p 8038:8501 — mount type=bind,source=D:/my_own_models/linear_model,target=/models/linear_model -e MODEL_NAME=linear_model -t tensorflow/serving"
},
{
"code": null,
"e": 5609,
"s": 5411,
"text": "This is all a single line. For your subsequent models, you need to just change your ‘source’ path. Changing your ‘target’ and MODEL_NAME is optional, but, of course, necessary based on the context."
},
{
"code": null,
"e": 5714,
"s": 5609,
"text": "Now let us try to understand what the above command script indicates. The generic form of this script is"
},
{
"code": null,
"e": 5864,
"s": 5714,
"text": "docker run -p {LOCAL_PORT}:8501 — mount type=bind,source={ABSOLUTE_PATH},target=/models/{MODEL_NAME} -e MODEL_NAME={MODEL_NAME} -t tensorflow/serving"
},
{
"code": null,
"e": 6060,
"s": 5864,
"text": "{LOCAL_PORT}: This is the local port of your machine, so make sure you do not have anything else running there. We are mapping it to the 8501 port exposed for REST API calls by TensorFlow Serving"
},
{
"code": null,
"e": 6197,
"s": 6060,
"text": "{ABSOLUTE_PATH}: This is the absolute path for your model. This tells the TensorFlow Serving where your model is located at (obviously)."
},
{
"code": null,
"e": 6408,
"s": 6197,
"text": "{MODEL_NAME}: This is the service end-point for your REST API call with the prefix ‘/models/’. Do not change the ‘/models/’ prefix in the target variable and only change the {MODEL_NAME} part based on your need"
},
{
"code": null,
"e": 6580,
"s": 6408,
"text": "Once you see the below message in your command window, your model has been hosted successfully. You can also see a container running successfully in your Docker dashboard."
},
{
"code": null,
"e": 6642,
"s": 6580,
"text": "[evhttp_server.cc : 238] NET_LOG: Entering the event loop ..."
},
{
"code": null,
"e": 6720,
"s": 6642,
"text": "I used Postman for testing my queries, but you can use any form of API calls."
},
{
"code": null,
"e": 6976,
"s": 6720,
"text": "[Note: You won’t be able to make direct calls from browser or any other host to your REST API since CORS is not enabled by TensorFlow Serving. However, there are ways to achieve a call from the browser to your model that I would cover in a separate post.]"
},
{
"code": null,
"e": 7045,
"s": 6976,
"text": "You need a POST query to test our model. Our request URL looks like:"
},
{
"code": null,
"e": 7098,
"s": 7045,
"text": "http://localhost:8509/v1/models/linear_model:predict"
},
{
"code": null,
"e": 7126,
"s": 7098,
"text": "Again, the generic form is:"
},
{
"code": null,
"e": 7188,
"s": 7126,
"text": "http://localhost:{LOCAL_PORT}}/v1/models/{MODEL_NAME}:predict"
},
{
"code": null,
"e": 7262,
"s": 7188,
"text": "Add ‘Content-Type’ as ‘application/json’ in your header and your body as:"
},
{
"code": null,
"e": 7303,
"s": 7262,
"text": "{ \"instances\": [[ 0 ]]}"
},
{
"code": null,
"e": 7427,
"s": 7303,
"text": "Ensure that your JSON key is ‘instances’ and your values are inside an array. Since our input is [0], we write it as [[0]]."
},
{
"code": null,
"e": 7567,
"s": 7427,
"text": "Remember, that we created a model to predict y = 2x + 1 which means for input value 0, our prediction should have value 1 (or close to it)."
},
{
"code": null,
"e": 7614,
"s": 7567,
"text": "Let’s send our query. The response looks like:"
},
{
"code": null,
"e": 7667,
"s": 7614,
"text": "{ \"predictions\": [[ 0.999998748 ]]}"
},
{
"code": null,
"e": 7762,
"s": 7667,
"text": "Well, that looks pretty much like 1 to me. Play around with your model by making POST queries."
},
{
"code": null,
"e": 7952,
"s": 7762,
"text": "We were able to create a model from scratch and deploy it on our local server. This is a very good way to see if your model would work the same way in the real world as it does on your IDE."
},
{
"code": null,
"e": 8171,
"s": 7952,
"text": "As I previously mentioned, however, you won’t be able to make calls to this model apart from Postman (or similar tools). How to overcome that? I shall cover that in a separate post as this is already becoming too long."
}
] |
Hibernate - Native SQL | You can use native SQL to express database queries if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. Hibernate 3.x allows you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.
Your application will create a native SQL query from the session with the createSQLQuery() method on the Session interface −
public SQLQuery createSQLQuery(String sqlString) throws HibernateException
After you pass a string containing the SQL query to the createSQLQuery() method, you can associate the SQL result with either an existing Hibernate entity, a join, or a scalar result using addEntity(), addJoin(), and addScalar() methods respectively.
The most basic SQL query is to get a list of scalars (values) from one or more tables. Following is the syntax for using native SQL for scalar values −
String sql = "SELECT first_name, salary FROM EMPLOYEE";
SQLQuery query = session.createSQLQuery(sql);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List results = query.list();
The above queries were all about returning scalar values, basically returning the "raw" values from the result set. Following is the syntax to get entity objects as a whole from a native sql query via addEntity().
String sql = "SELECT * FROM EMPLOYEE";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Employee.class);
List results = query.list();
Following is the syntax to get entity objects from a native sql query via addEntity() and using named SQL query.
String sql = "SELECT * FROM EMPLOYEE WHERE id = :employee_id";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Employee.class);
query.setParameter("employee_id", 10);
List results = query.list();
Consider the following POJO class −
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
Let us create the following EMPLOYEE table to store Employee objects −
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
Following will be mapping file −
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name = "Employee" table = "EMPLOYEE">
<meta attribute = "class-description">
This class contains the employee detail.
</meta>
<id name = "id" type = "int" column = "id">
<generator class="native"/>
</id>
<property name = "firstName" column = "first_name" type = "string"/>
<property name = "lastName" column = "last_name" type = "string"/>
<property name = "salary" column = "salary" type = "int"/>
</class>
</hibernate-mapping>
Finally, we will create our application class with the main() method to run the application where we will use Native SQL queries −
import java.util.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.SQLQuery;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Add few employee records in database */
Integer empID1 = ME.addEmployee("Zara", "Ali", 2000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 5000);
Integer empID4 = ME.addEmployee("Mohd", "Yasee", 3000);
/* List down employees and their salary using Scalar Query */
ME.listEmployeesScalar();
/* List down complete employees information using Entity Query */
ME.listEmployeesEntity();
}
/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try {
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return employeeID;
}
/* Method to READ all the employees using Scalar Query */
public void listEmployeesScalar( ){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
String sql = "SELECT first_name, salary FROM EMPLOYEE";
SQLQuery query = session.createSQLQuery(sql);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List data = query.list();
for(Object object : data) {
Map row = (Map)object;
System.out.print("First Name: " + row.get("first_name"));
System.out.println(", Salary: " + row.get("salary"));
}
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
/* Method to READ all the employees using Entity Query */
public void listEmployeesEntity( ){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
String sql = "SELECT * FROM EMPLOYEE";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Employee.class);
List employees = query.list();
for (Iterator iterator = employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
Here are the steps to compile and run the above mentioned application. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.
Create hibernate.cfg.xml configuration file as explained in configuration chapter.
Create hibernate.cfg.xml configuration file as explained in configuration chapter.
Create Employee.hbm.xml mapping file as shown above.
Create Employee.hbm.xml mapping file as shown above.
Create Employee.java source file as shown above and compile it.
Create Employee.java source file as shown above and compile it.
Create ManageEmployee.java source file as shown above and compile it.
Create ManageEmployee.java source file as shown above and compile it.
Execute ManageEmployee binary to run the program.
Execute ManageEmployee binary to run the program.
You would get the following result, and records would be created in the EMPLOYEE table.
$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........
First Name: Zara, Salary: 2000
First Name: Daisy, Salary: 5000
First Name: John, Salary: 5000
First Name: Mohd, Salary: 3000
First Name: Zara Last Name: Ali Salary: 2000
First Name: Daisy Last Name: Das Salary: 5000
First Name: John Last Name: Paul Salary: 5000
First Name: Mohd Last Name: Yasee Salary: 3000
If you check your EMPLOYEE table, it should have the following records −
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 26 | Zara | Ali | 2000 |
| 27 | Daisy | Das | 5000 |
| 28 | John | Paul | 5000 |
| 29 | Mohd | Yasee | 3000 |
+----+------------+-----------+--------+
4 rows in set (0.00 sec)
mysql>
108 Lectures
11 hours
Chaand Sheikh
65 Lectures
5 hours
Karthikeya T
39 Lectures
4.5 hours
TELCOMA Global
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2353,
"s": 2063,
"text": "You can use native SQL to express database queries if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. Hibernate 3.x allows you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations."
},
{
"code": null,
"e": 2478,
"s": 2353,
"text": "Your application will create a native SQL query from the session with the createSQLQuery() method on the Session interface −"
},
{
"code": null,
"e": 2553,
"s": 2478,
"text": "public SQLQuery createSQLQuery(String sqlString) throws HibernateException"
},
{
"code": null,
"e": 2804,
"s": 2553,
"text": "After you pass a string containing the SQL query to the createSQLQuery() method, you can associate the SQL result with either an existing Hibernate entity, a join, or a scalar result using addEntity(), addJoin(), and addScalar() methods respectively."
},
{
"code": null,
"e": 2956,
"s": 2804,
"text": "The most basic SQL query is to get a list of scalars (values) from one or more tables. Following is the syntax for using native SQL for scalar values −"
},
{
"code": null,
"e": 3145,
"s": 2956,
"text": "String sql = \"SELECT first_name, salary FROM EMPLOYEE\";\nSQLQuery query = session.createSQLQuery(sql);\nquery.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);\nList results = query.list();"
},
{
"code": null,
"e": 3359,
"s": 3145,
"text": "The above queries were all about returning scalar values, basically returning the \"raw\" values from the result set. Following is the syntax to get entity objects as a whole from a native sql query via addEntity()."
},
{
"code": null,
"e": 3506,
"s": 3359,
"text": "String sql = \"SELECT * FROM EMPLOYEE\";\nSQLQuery query = session.createSQLQuery(sql);\nquery.addEntity(Employee.class);\nList results = query.list();"
},
{
"code": null,
"e": 3619,
"s": 3506,
"text": "Following is the syntax to get entity objects from a native sql query via addEntity() and using named SQL query."
},
{
"code": null,
"e": 3829,
"s": 3619,
"text": "String sql = \"SELECT * FROM EMPLOYEE WHERE id = :employee_id\";\nSQLQuery query = session.createSQLQuery(sql);\nquery.addEntity(Employee.class);\nquery.setParameter(\"employee_id\", 10);\nList results = query.list();"
},
{
"code": null,
"e": 3865,
"s": 3829,
"text": "Consider the following POJO class −"
},
{
"code": null,
"e": 4744,
"s": 3865,
"text": "public class Employee {\n private int id;\n private String firstName; \n private String lastName; \n private int salary; \n\n public Employee() {}\n \n public Employee(String fname, String lname, int salary) {\n this.firstName = fname;\n this.lastName = lname;\n this.salary = salary;\n }\n \n public int getId() {\n return id;\n }\n \n public void setId( int id ) {\n this.id = id;\n }\n \n public String getFirstName() {\n return firstName;\n }\n \n public void setFirstName( String first_name ) {\n this.firstName = first_name;\n }\n \n public String getLastName() {\n return lastName;\n }\n \n public void setLastName( String last_name ) {\n this.lastName = last_name;\n }\n \n public int getSalary() {\n return salary;\n }\n \n public void setSalary( int salary ) {\n this.salary = salary;\n }\n}"
},
{
"code": null,
"e": 4815,
"s": 4744,
"text": "Let us create the following EMPLOYEE table to store Employee objects −"
},
{
"code": null,
"e": 5010,
"s": 4815,
"text": "create table EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n PRIMARY KEY (id)\n);"
},
{
"code": null,
"e": 5043,
"s": 5010,
"text": "Following will be mapping file −"
},
{
"code": null,
"e": 5774,
"s": 5043,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<!DOCTYPE hibernate-mapping PUBLIC \n\"-//Hibernate/Hibernate Mapping DTD//EN\"\n\"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\"> \n\n<hibernate-mapping>\n <class name = \"Employee\" table = \"EMPLOYEE\">\n \n <meta attribute = \"class-description\">\n This class contains the employee detail. \n </meta>\n \n <id name = \"id\" type = \"int\" column = \"id\">\n <generator class=\"native\"/>\n </id>\n \n <property name = \"firstName\" column = \"first_name\" type = \"string\"/>\n <property name = \"lastName\" column = \"last_name\" type = \"string\"/>\n <property name = \"salary\" column = \"salary\" type = \"int\"/>\n \n </class>\n</hibernate-mapping>"
},
{
"code": null,
"e": 5905,
"s": 5774,
"text": "Finally, we will create our application class with the main() method to run the application where we will use Native SQL queries −"
},
{
"code": null,
"e": 9632,
"s": 5905,
"text": "import java.util.*; \n \nimport org.hibernate.HibernateException; \nimport org.hibernate.Session; \nimport org.hibernate.Transaction;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.SQLQuery;\nimport org.hibernate.Criteria;\nimport org.hibernate.Hibernate;\nimport org.hibernate.cfg.Configuration;\n\npublic class ManageEmployee {\n private static SessionFactory factory; \n public static void main(String[] args) {\n \n try {\n factory = new Configuration().configure().buildSessionFactory();\n } catch (Throwable ex) { \n System.err.println(\"Failed to create sessionFactory object.\" + ex);\n throw new ExceptionInInitializerError(ex); \n }\n \n ManageEmployee ME = new ManageEmployee();\n\n /* Add few employee records in database */\n Integer empID1 = ME.addEmployee(\"Zara\", \"Ali\", 2000);\n Integer empID2 = ME.addEmployee(\"Daisy\", \"Das\", 5000);\n Integer empID3 = ME.addEmployee(\"John\", \"Paul\", 5000);\n Integer empID4 = ME.addEmployee(\"Mohd\", \"Yasee\", 3000);\n\n /* List down employees and their salary using Scalar Query */\n ME.listEmployeesScalar();\n\n /* List down complete employees information using Entity Query */\n ME.listEmployeesEntity();\n }\n \n /* Method to CREATE an employee in the database */\n public Integer addEmployee(String fname, String lname, int salary){\n Session session = factory.openSession();\n Transaction tx = null;\n Integer employeeID = null;\n \n try {\n tx = session.beginTransaction();\n Employee employee = new Employee(fname, lname, salary);\n employeeID = (Integer) session.save(employee); \n tx.commit();\n } catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n } finally {\n session.close(); \n }\n return employeeID;\n }\n\n /* Method to READ all the employees using Scalar Query */\n public void listEmployeesScalar( ){\n Session session = factory.openSession();\n Transaction tx = null;\n \n try {\n tx = session.beginTransaction();\n String sql = \"SELECT first_name, salary FROM EMPLOYEE\";\n SQLQuery query = session.createSQLQuery(sql);\n query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);\n List data = query.list();\n\n for(Object object : data) {\n Map row = (Map)object;\n System.out.print(\"First Name: \" + row.get(\"first_name\")); \n System.out.println(\", Salary: \" + row.get(\"salary\")); \n }\n tx.commit();\n } catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n } finally {\n session.close(); \n }\n }\n\n /* Method to READ all the employees using Entity Query */\n public void listEmployeesEntity( ){\n Session session = factory.openSession();\n Transaction tx = null;\n \n try {\n tx = session.beginTransaction();\n String sql = \"SELECT * FROM EMPLOYEE\";\n SQLQuery query = session.createSQLQuery(sql);\n query.addEntity(Employee.class);\n List employees = query.list();\n\n for (Iterator iterator = employees.iterator(); iterator.hasNext();){\n Employee employee = (Employee) iterator.next(); \n System.out.print(\"First Name: \" + employee.getFirstName()); \n System.out.print(\" Last Name: \" + employee.getLastName()); \n System.out.println(\" Salary: \" + employee.getSalary()); \n }\n tx.commit();\n } catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n } finally {\n session.close(); \n }\n }\n}"
},
{
"code": null,
"e": 9813,
"s": 9632,
"text": "Here are the steps to compile and run the above mentioned application. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution."
},
{
"code": null,
"e": 9896,
"s": 9813,
"text": "Create hibernate.cfg.xml configuration file as explained in configuration chapter."
},
{
"code": null,
"e": 9979,
"s": 9896,
"text": "Create hibernate.cfg.xml configuration file as explained in configuration chapter."
},
{
"code": null,
"e": 10032,
"s": 9979,
"text": "Create Employee.hbm.xml mapping file as shown above."
},
{
"code": null,
"e": 10085,
"s": 10032,
"text": "Create Employee.hbm.xml mapping file as shown above."
},
{
"code": null,
"e": 10149,
"s": 10085,
"text": "Create Employee.java source file as shown above and compile it."
},
{
"code": null,
"e": 10213,
"s": 10149,
"text": "Create Employee.java source file as shown above and compile it."
},
{
"code": null,
"e": 10283,
"s": 10213,
"text": "Create ManageEmployee.java source file as shown above and compile it."
},
{
"code": null,
"e": 10353,
"s": 10283,
"text": "Create ManageEmployee.java source file as shown above and compile it."
},
{
"code": null,
"e": 10403,
"s": 10353,
"text": "Execute ManageEmployee binary to run the program."
},
{
"code": null,
"e": 10453,
"s": 10403,
"text": "Execute ManageEmployee binary to run the program."
},
{
"code": null,
"e": 10541,
"s": 10453,
"text": "You would get the following result, and records would be created in the EMPLOYEE table."
},
{
"code": null,
"e": 10934,
"s": 10541,
"text": "$java ManageEmployee\n.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........\n\nFirst Name: Zara, Salary: 2000\nFirst Name: Daisy, Salary: 5000\nFirst Name: John, Salary: 5000\nFirst Name: Mohd, Salary: 3000\nFirst Name: Zara Last Name: Ali Salary: 2000\nFirst Name: Daisy Last Name: Das Salary: 5000\nFirst Name: John Last Name: Paul Salary: 5000\nFirst Name: Mohd Last Name: Yasee Salary: 3000"
},
{
"code": null,
"e": 11007,
"s": 10934,
"text": "If you check your EMPLOYEE table, it should have the following records −"
},
{
"code": null,
"e": 11398,
"s": 11007,
"text": "mysql> select * from EMPLOYEE;\n+----+------------+-----------+--------+\n| id | first_name | last_name | salary |\n+----+------------+-----------+--------+\n| 26 | Zara | Ali | 2000 |\n| 27 | Daisy | Das | 5000 |\n| 28 | John | Paul | 5000 |\n| 29 | Mohd | Yasee | 3000 |\n+----+------------+-----------+--------+\n4 rows in set (0.00 sec)\nmysql>"
},
{
"code": null,
"e": 11433,
"s": 11398,
"text": "\n 108 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 11448,
"s": 11433,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 11481,
"s": 11448,
"text": "\n 65 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 11495,
"s": 11481,
"text": " Karthikeya T"
},
{
"code": null,
"e": 11530,
"s": 11495,
"text": "\n 39 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11546,
"s": 11530,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 11553,
"s": 11546,
"text": " Print"
},
{
"code": null,
"e": 11564,
"s": 11553,
"text": " Add Notes"
}
] |
BillCipher – An Information Gathering Tool in Kali Linux - GeeksforGeeks | 27 Apr, 2021
BillCipher is a free and open-source tool available on Github. BillCipher is based upon Open Source Intelligence (OSINT), the easiest and useful tool for reconnaissance. BillCipher interface is very similar to Metasploit 1 and Metasploit 2. This tool provides a command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain) which can be a website or an IP address. The interactive console provides a number of helpful features, such as command completion and contextual help. BillCipher is a web reconnaissance tool written in python. It has so many modules such as database interaction, built-in convenience functions, interactive help, and command completion. BillCipher provides a powerful environment in which open source web-based reconnaissance can be conducted, and you can gather all information about the target.
Features of BillCipher:
BillCipher is a free and open-source tool.
BillCipher is a complete package of information gathering modules
BillCipher works and acts as a web application/website scanner.
BillCipher is used for information gathering and vulnerability assessment of web applications.
BillCipher uses shodan search engine to scan IoT devices.
BillCipher can easily find loopholes in the code of web applications and websites.
BillCipher has the following modules Geoip lookup, Banner grabbing, DNS lookup, port scanning.
BillCipher can target a single domain and can found all the subdomains of that domain which makes work easy for pentesters.
BillCipher is written in python language.
Step 1: Open your kali Linux operating system. Move to desktop. Here you have to create a directory called BillCipher. In this directory, you have to install the tool. To move to desktop use the following command.
cd Desktop
Step 2: Now you are on the desktop. Here you have to create a directory BillCipher. To create BillCipher directory use the following command.
mkdir BillCipher
Step 3: You have created a directory. Now use the following command to move into that directory.
cd BillCipher
Step 4: To install all the dependencies of this tool use the following command.
sudo apt update && sudo apt install ruby python python-pip python3 python3-pip
sudo apt install httrack whatweb
Step 5: Now you are in Billcipher directory. Now you have to install the tool using the following command. Use the following command to install Billcipher.
git clone https://github.com/GitHackTools/BillCipher
Step 6: Now to list out the contents of the directory use the following command.
ls
Step 7: You can see a new directory has been created. Use the following command to change the directory.
cd BillCipher
ls
Step 8: You can see many files of the tool. Now you have to give permission to the tool. Use the following command.
chmod +x billcipher.py
ls
Step 9: The tool has been downloaded. Now you can run the tool using the following command.
python3 billcipher.py
The tool is running successfully. Now we will see some examples of how to use the billcipher tool.
Use billcipher tool to gather information about a website.
These are options from these options you can choose any options.
This is how you can use the tool. Similarly, you can use this tool for your domain target. This tool can be used to get information about our target(domain) website and IP address. The interactive console provides a number of helpful features, such as command completion and contextual help. BillCipher is a Web Reconnaissance tool written in Python. It has so many modules, database interaction, built-in convenience functions, interactive help, and command completion, BillCipher provides a powerful environment in which open source web-based reconnaissance can be conducted, and we can gather all information.
Cyber-security
Kali-Linux
Linux-Tools
Linux-Unix
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
ZIP command in Linux with examples
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
diff command in Linux with examples
Conditional Statements | Shell Script
echo command in Linux with Examples
Compiling with g++ | [
{
"code": null,
"e": 24179,
"s": 24151,
"text": "\n27 Apr, 2021"
},
{
"code": null,
"e": 25060,
"s": 24179,
"text": "BillCipher is a free and open-source tool available on Github. BillCipher is based upon Open Source Intelligence (OSINT), the easiest and useful tool for reconnaissance. BillCipher interface is very similar to Metasploit 1 and Metasploit 2. This tool provides a command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain) which can be a website or an IP address. The interactive console provides a number of helpful features, such as command completion and contextual help. BillCipher is a web reconnaissance tool written in python. It has so many modules such as database interaction, built-in convenience functions, interactive help, and command completion. BillCipher provides a powerful environment in which open source web-based reconnaissance can be conducted, and you can gather all information about the target."
},
{
"code": null,
"e": 25084,
"s": 25060,
"text": "Features of BillCipher:"
},
{
"code": null,
"e": 25127,
"s": 25084,
"text": "BillCipher is a free and open-source tool."
},
{
"code": null,
"e": 25193,
"s": 25127,
"text": "BillCipher is a complete package of information gathering modules"
},
{
"code": null,
"e": 25257,
"s": 25193,
"text": "BillCipher works and acts as a web application/website scanner."
},
{
"code": null,
"e": 25352,
"s": 25257,
"text": "BillCipher is used for information gathering and vulnerability assessment of web applications."
},
{
"code": null,
"e": 25410,
"s": 25352,
"text": "BillCipher uses shodan search engine to scan IoT devices."
},
{
"code": null,
"e": 25493,
"s": 25410,
"text": "BillCipher can easily find loopholes in the code of web applications and websites."
},
{
"code": null,
"e": 25588,
"s": 25493,
"text": "BillCipher has the following modules Geoip lookup, Banner grabbing, DNS lookup, port scanning."
},
{
"code": null,
"e": 25712,
"s": 25588,
"text": "BillCipher can target a single domain and can found all the subdomains of that domain which makes work easy for pentesters."
},
{
"code": null,
"e": 25754,
"s": 25712,
"text": "BillCipher is written in python language."
},
{
"code": null,
"e": 25968,
"s": 25754,
"text": "Step 1: Open your kali Linux operating system. Move to desktop. Here you have to create a directory called BillCipher. In this directory, you have to install the tool. To move to desktop use the following command."
},
{
"code": null,
"e": 25979,
"s": 25968,
"text": "cd Desktop"
},
{
"code": null,
"e": 26121,
"s": 25979,
"text": "Step 2: Now you are on the desktop. Here you have to create a directory BillCipher. To create BillCipher directory use the following command."
},
{
"code": null,
"e": 26138,
"s": 26121,
"text": "mkdir BillCipher"
},
{
"code": null,
"e": 26236,
"s": 26138,
"text": " Step 3: You have created a directory. Now use the following command to move into that directory."
},
{
"code": null,
"e": 26250,
"s": 26236,
"text": "cd BillCipher"
},
{
"code": null,
"e": 26330,
"s": 26250,
"text": "Step 4: To install all the dependencies of this tool use the following command."
},
{
"code": null,
"e": 26442,
"s": 26330,
"text": "sudo apt update && sudo apt install ruby python python-pip python3 python3-pip\nsudo apt install httrack whatweb"
},
{
"code": null,
"e": 26598,
"s": 26442,
"text": "Step 5: Now you are in Billcipher directory. Now you have to install the tool using the following command. Use the following command to install Billcipher."
},
{
"code": null,
"e": 26651,
"s": 26598,
"text": "git clone https://github.com/GitHackTools/BillCipher"
},
{
"code": null,
"e": 26732,
"s": 26651,
"text": "Step 6: Now to list out the contents of the directory use the following command."
},
{
"code": null,
"e": 26735,
"s": 26732,
"text": "ls"
},
{
"code": null,
"e": 26840,
"s": 26735,
"text": "Step 7: You can see a new directory has been created. Use the following command to change the directory."
},
{
"code": null,
"e": 26857,
"s": 26840,
"text": "cd BillCipher\nls"
},
{
"code": null,
"e": 26974,
"s": 26857,
"text": "Step 8: You can see many files of the tool. Now you have to give permission to the tool. Use the following command."
},
{
"code": null,
"e": 27000,
"s": 26974,
"text": "chmod +x billcipher.py\nls"
},
{
"code": null,
"e": 27092,
"s": 27000,
"text": "Step 9: The tool has been downloaded. Now you can run the tool using the following command."
},
{
"code": null,
"e": 27114,
"s": 27092,
"text": "python3 billcipher.py"
},
{
"code": null,
"e": 27214,
"s": 27114,
"text": "The tool is running successfully. Now we will see some examples of how to use the billcipher tool."
},
{
"code": null,
"e": 27273,
"s": 27214,
"text": "Use billcipher tool to gather information about a website."
},
{
"code": null,
"e": 27338,
"s": 27273,
"text": "These are options from these options you can choose any options."
},
{
"code": null,
"e": 27951,
"s": 27338,
"text": "This is how you can use the tool. Similarly, you can use this tool for your domain target. This tool can be used to get information about our target(domain) website and IP address. The interactive console provides a number of helpful features, such as command completion and contextual help. BillCipher is a Web Reconnaissance tool written in Python. It has so many modules, database interaction, built-in convenience functions, interactive help, and command completion, BillCipher provides a powerful environment in which open source web-based reconnaissance can be conducted, and we can gather all information."
},
{
"code": null,
"e": 27966,
"s": 27951,
"text": "Cyber-security"
},
{
"code": null,
"e": 27977,
"s": 27966,
"text": "Kali-Linux"
},
{
"code": null,
"e": 27989,
"s": 27977,
"text": "Linux-Tools"
},
{
"code": null,
"e": 28000,
"s": 27989,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28098,
"s": 28000,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28107,
"s": 28098,
"text": "Comments"
},
{
"code": null,
"e": 28120,
"s": 28107,
"text": "Old Comments"
},
{
"code": null,
"e": 28158,
"s": 28120,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 28193,
"s": 28158,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 28234,
"s": 28193,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 28269,
"s": 28234,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 28305,
"s": 28269,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 28343,
"s": 28305,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 28379,
"s": 28343,
"text": "diff command in Linux with examples"
},
{
"code": null,
"e": 28417,
"s": 28379,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 28453,
"s": 28417,
"text": "echo command in Linux with Examples"
}
] |
Program to check a number is power of two or not in Python | Suppose we have a number n. We have to check whether this is power of 2 or not.
So, if the input is like n = 2048, then the output will be True as 2048 is 2^11.
To solve this, we will follow these steps −
if n is same as 0, thenreturn False
if n is same as 0, then
return False
return False
return true when (n AND (n - 1)) is same as 0 otherwise false
return true when (n AND (n - 1)) is same as 0 otherwise false
Let us see the following implementation to get better understanding
def solve(n):
if n == 0:
return False
return (n & (n - 1)) == 0
n = 2048
print(solve(n))
2048
True | [
{
"code": null,
"e": 1142,
"s": 1062,
"text": "Suppose we have a number n. We have to check whether this is power of 2 or not."
},
{
"code": null,
"e": 1223,
"s": 1142,
"text": "So, if the input is like n = 2048, then the output will be True as 2048 is 2^11."
},
{
"code": null,
"e": 1267,
"s": 1223,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1303,
"s": 1267,
"text": "if n is same as 0, thenreturn False"
},
{
"code": null,
"e": 1327,
"s": 1303,
"text": "if n is same as 0, then"
},
{
"code": null,
"e": 1340,
"s": 1327,
"text": "return False"
},
{
"code": null,
"e": 1353,
"s": 1340,
"text": "return False"
},
{
"code": null,
"e": 1415,
"s": 1353,
"text": "return true when (n AND (n - 1)) is same as 0 otherwise false"
},
{
"code": null,
"e": 1477,
"s": 1415,
"text": "return true when (n AND (n - 1)) is same as 0 otherwise false"
},
{
"code": null,
"e": 1545,
"s": 1477,
"text": "Let us see the following implementation to get better understanding"
},
{
"code": null,
"e": 1647,
"s": 1545,
"text": "def solve(n):\n if n == 0:\n return False\n return (n & (n - 1)) == 0\n\nn = 2048\nprint(solve(n))"
},
{
"code": null,
"e": 1652,
"s": 1647,
"text": "2048"
},
{
"code": null,
"e": 1657,
"s": 1652,
"text": "True"
}
] |
Simple Plotly Tutorials. Creating Beautiful Animated Maps | by Gabrielgilling | Towards Data Science | Animated maps are an efficient way to visualize and communicate data with geographic properties. In this tutorial, you will learn how to deploy the Plotly Express package in Python to quickly make beautiful maps with interactive features.
Plotly is one of the fastest growing visualization libraries available for data scientists, a testament to its ease of use and to the beautiful graphs it can produce. This is the first tutorial in a series of 3 showcasing Plotly capabilities with increasing complexity. This installment will show you how to use Plotly Express to quickly make animated maps. Later tutorials will in turn focus on further customizing Plotly graphs and visualizing them within Dash apps.
For this tutorial, we’ll make use of a Kaggle dataset, which provides data on different types of crime in the city of Vancouver, Canada.
Before starting to code, you’ll need to install the following packages in Python. Simply run the following pip installs in your terminal or in your Jupyter Notebook:
pip install plotly
pip install geopandas
Let’s load in the required packages and the dataset. We can create a Date column using the parse_dates argument as we read in the CSV file. Here, I choose to create the Date column using the MONTH and YEAR columns, but you can also include the HOUR and MINUTE columns if you’d like.
It’s good practice to plot data before starting an analysis in order to spot anything unusual. When looking at the distribution of the Latitudeand Longitude features, I noticed a couple of 0 values that messed with how the data was plotted — with points showing up on the other side of the world, making it impossible to visualize the data in Vancouver!
Let’s get rid of them, and work with a sample of 2000 rows for the purpose of this tutorial.
The “static” view
Before I do any “fancy” work with libraries like Plotly, I always like to look at a simple version of my maps in order to get a feel for how things should look like. Typically, this involves finding a shapefile or a geojson, and the City of Vancouver’s Open Data Portal has them handy. Since we’ll need the geojson file for mapping choropleth polygons later in the tutorial, let’s go ahead and download it. We load in the geojson with the Geopandas library and plot all of the incidents in our dataset over it.
This looks nice enough but the map looks crowded, making it difficult to derive insights. Let’s look at how Plotly Express can be used to show our audience how crime evolves with time.
The “dynamic” view
Mapboxes is a service that Plotly uses display scatter data on a map. Because it is a third-party service, you will need to generate an access token for yourself in order to display their maps. This can be easily done by following the instructions here. All you need to do is create an account with Mapbox and you will have access to your token — the entire process is free. Once you have your token, simply replace the “your_token” string in the code block below with yours.
px.set_mapbox_access_token("your_token")
You’re now ready to go!
Animations with Plotly Express functions can be quickly implemented by setting a feature as an animation_frame, which will use the feature’s values to subset and display your data. For instance, setting time_col as “YEAR” will allow you to visualize crime over all of the years in the dataset, “MONTH” for all months and so on.
We can specify the scatterplot’s color by setting a “color” parameter, the same way Seaborne’s “hue” parameter works. By default, the values passed to the “animate_frame” argument (which dictate the order in which maps are animated) aren’t ordered, so we add a“category_orders”argument: a sorted list with the values to iterate over.
Voila! We have ourselves a nice interactive map. If you want to show how the data evolves across months (or hours etc.) instead, simply change the time_colargument in the function above.
Notes:
Because Plotly Scatter Maps rely on the Mapbox service, a nice advantage of using them is that they will automatically display the map based on the coordinates you provide them— no need to provide a geographic file! However, you will need to provide a geojson file when displaying choropleth maps, as the next section shows.
As the gif shows, you can click on the categories in the Type variable to filter the data points shown on the map! This provides great initial interactivity and can help you guide how you convey your insights.
The “static” view
Another great way to plot the crime data is to visualize the amount of incidents per neighborhood using a choropleth map, and then to show how those numbers evolve with time. When displaying a choropleth map, we color the polygons (each polygon corresponding to a neighborhood) according to the underlying value we want to visualize. In the following example, we’ll shade each polygon according to the number of crime incidents that occurs within it, with darker shades representing higher amounts of crime incidents and lighter shades representing lower amounts of crime.
Before we plot anything, the dataset needs some additional manipulating. First, I noticed a couple of naming discrepancies between the geojson and crime data, so I renamed a couple of the neighborhoods to make sure their names are consistent. I also drop observations for the Stanley Park neighborhood, which unfortunately is missing in the geojson file.
We can now plot the reformatted data.
As we can see, each neighborhood in Vancouver is represented by a polygon whose color intensity is proportional to the number of crime incidents that occurred within it. Neighborhoods in the north of the city tend to have higher crime counts than those in the south, with the CBD (Central Business District) neighborhood having the highest crime counts over the entire sample, and the neighborhood with white shading having the lowest crime count.
The “dynamic” view
Let’s animate the graph above. For each timestamp, we want to visualize the distribution of cumulative incidents across the different neighborhoods in Vancouver.
We need to go through a couple of additional steps before we can work with the finalized Dataframe, which will contain the cumulative sum of all incidents per neighborhood at each timestamp in the data.
Now here’s a slightly tricky part. If you look at the counts_rolling Dataframe we’ve just produced, you’ll notice that not all neighborhoods have values for each timestamp. That’s because some neighborhoods don’t have any recorded crimes on certain dates, therefore we need to fill in those “missing” values by using forward filling.
Here we go, we now have a complete Dataframe with values for every timestamp/neighborhood combination. We can finally plot the graph!
In order to use Plotly’s choropleth_mapbox function we must make sure the dataframe that contains the crime numbers and the geojson used to plot the map have the same identifier, so that the mapping function can properly associate each polygon with its crime counts. Here, I take advantage of the featureidkey argument to tell the mapping function that the polygon identifiers are in the “properties.name” location of the geojson file. These identifiers are the same neighborhood names contained in the crime dataframe.
As we’ve just seen, making animated graphs with Plotly is a painless and quick affair. In the next tutorials, I will showcase how to further customize Plotly Express graphs. For instance, we might want the option of selecting a year in particular and visualizing how crime evolves over the months in that year in particular. Or we might want to have an option to filter the data by types of crime, and visualize its evolution over time. Luckily for us, Plotly makes it easy for us to build on top of Plotly Express graphs, adding layers of customization one step at a time. In later tutorials we’ll see how everything can be wrapped into a nice Dash app!
I’d like to give a huge shoutout to my coworkers on the Data Science and AI Elite team for inspiring me to write this blog post. In particular, thank you to Andre Violante and Rakshith Dasenahalli Lingaraju for their advice and suggestions, as well as Robert Uleman for his extremely thorough proofreading and code improvements! | [
{
"code": null,
"e": 410,
"s": 171,
"text": "Animated maps are an efficient way to visualize and communicate data with geographic properties. In this tutorial, you will learn how to deploy the Plotly Express package in Python to quickly make beautiful maps with interactive features."
},
{
"code": null,
"e": 879,
"s": 410,
"text": "Plotly is one of the fastest growing visualization libraries available for data scientists, a testament to its ease of use and to the beautiful graphs it can produce. This is the first tutorial in a series of 3 showcasing Plotly capabilities with increasing complexity. This installment will show you how to use Plotly Express to quickly make animated maps. Later tutorials will in turn focus on further customizing Plotly graphs and visualizing them within Dash apps."
},
{
"code": null,
"e": 1016,
"s": 879,
"text": "For this tutorial, we’ll make use of a Kaggle dataset, which provides data on different types of crime in the city of Vancouver, Canada."
},
{
"code": null,
"e": 1182,
"s": 1016,
"text": "Before starting to code, you’ll need to install the following packages in Python. Simply run the following pip installs in your terminal or in your Jupyter Notebook:"
},
{
"code": null,
"e": 1201,
"s": 1182,
"text": "pip install plotly"
},
{
"code": null,
"e": 1223,
"s": 1201,
"text": "pip install geopandas"
},
{
"code": null,
"e": 1506,
"s": 1223,
"text": "Let’s load in the required packages and the dataset. We can create a Date column using the parse_dates argument as we read in the CSV file. Here, I choose to create the Date column using the MONTH and YEAR columns, but you can also include the HOUR and MINUTE columns if you’d like."
},
{
"code": null,
"e": 1860,
"s": 1506,
"text": "It’s good practice to plot data before starting an analysis in order to spot anything unusual. When looking at the distribution of the Latitudeand Longitude features, I noticed a couple of 0 values that messed with how the data was plotted — with points showing up on the other side of the world, making it impossible to visualize the data in Vancouver!"
},
{
"code": null,
"e": 1953,
"s": 1860,
"text": "Let’s get rid of them, and work with a sample of 2000 rows for the purpose of this tutorial."
},
{
"code": null,
"e": 1971,
"s": 1953,
"text": "The “static” view"
},
{
"code": null,
"e": 2482,
"s": 1971,
"text": "Before I do any “fancy” work with libraries like Plotly, I always like to look at a simple version of my maps in order to get a feel for how things should look like. Typically, this involves finding a shapefile or a geojson, and the City of Vancouver’s Open Data Portal has them handy. Since we’ll need the geojson file for mapping choropleth polygons later in the tutorial, let’s go ahead and download it. We load in the geojson with the Geopandas library and plot all of the incidents in our dataset over it."
},
{
"code": null,
"e": 2667,
"s": 2482,
"text": "This looks nice enough but the map looks crowded, making it difficult to derive insights. Let’s look at how Plotly Express can be used to show our audience how crime evolves with time."
},
{
"code": null,
"e": 2686,
"s": 2667,
"text": "The “dynamic” view"
},
{
"code": null,
"e": 3162,
"s": 2686,
"text": "Mapboxes is a service that Plotly uses display scatter data on a map. Because it is a third-party service, you will need to generate an access token for yourself in order to display their maps. This can be easily done by following the instructions here. All you need to do is create an account with Mapbox and you will have access to your token — the entire process is free. Once you have your token, simply replace the “your_token” string in the code block below with yours."
},
{
"code": null,
"e": 3203,
"s": 3162,
"text": "px.set_mapbox_access_token(\"your_token\")"
},
{
"code": null,
"e": 3227,
"s": 3203,
"text": "You’re now ready to go!"
},
{
"code": null,
"e": 3555,
"s": 3227,
"text": "Animations with Plotly Express functions can be quickly implemented by setting a feature as an animation_frame, which will use the feature’s values to subset and display your data. For instance, setting time_col as “YEAR” will allow you to visualize crime over all of the years in the dataset, “MONTH” for all months and so on."
},
{
"code": null,
"e": 3889,
"s": 3555,
"text": "We can specify the scatterplot’s color by setting a “color” parameter, the same way Seaborne’s “hue” parameter works. By default, the values passed to the “animate_frame” argument (which dictate the order in which maps are animated) aren’t ordered, so we add a“category_orders”argument: a sorted list with the values to iterate over."
},
{
"code": null,
"e": 4076,
"s": 3889,
"text": "Voila! We have ourselves a nice interactive map. If you want to show how the data evolves across months (or hours etc.) instead, simply change the time_colargument in the function above."
},
{
"code": null,
"e": 4083,
"s": 4076,
"text": "Notes:"
},
{
"code": null,
"e": 4408,
"s": 4083,
"text": "Because Plotly Scatter Maps rely on the Mapbox service, a nice advantage of using them is that they will automatically display the map based on the coordinates you provide them— no need to provide a geographic file! However, you will need to provide a geojson file when displaying choropleth maps, as the next section shows."
},
{
"code": null,
"e": 4618,
"s": 4408,
"text": "As the gif shows, you can click on the categories in the Type variable to filter the data points shown on the map! This provides great initial interactivity and can help you guide how you convey your insights."
},
{
"code": null,
"e": 4636,
"s": 4618,
"text": "The “static” view"
},
{
"code": null,
"e": 5209,
"s": 4636,
"text": "Another great way to plot the crime data is to visualize the amount of incidents per neighborhood using a choropleth map, and then to show how those numbers evolve with time. When displaying a choropleth map, we color the polygons (each polygon corresponding to a neighborhood) according to the underlying value we want to visualize. In the following example, we’ll shade each polygon according to the number of crime incidents that occurs within it, with darker shades representing higher amounts of crime incidents and lighter shades representing lower amounts of crime."
},
{
"code": null,
"e": 5564,
"s": 5209,
"text": "Before we plot anything, the dataset needs some additional manipulating. First, I noticed a couple of naming discrepancies between the geojson and crime data, so I renamed a couple of the neighborhoods to make sure their names are consistent. I also drop observations for the Stanley Park neighborhood, which unfortunately is missing in the geojson file."
},
{
"code": null,
"e": 5602,
"s": 5564,
"text": "We can now plot the reformatted data."
},
{
"code": null,
"e": 6050,
"s": 5602,
"text": "As we can see, each neighborhood in Vancouver is represented by a polygon whose color intensity is proportional to the number of crime incidents that occurred within it. Neighborhoods in the north of the city tend to have higher crime counts than those in the south, with the CBD (Central Business District) neighborhood having the highest crime counts over the entire sample, and the neighborhood with white shading having the lowest crime count."
},
{
"code": null,
"e": 6069,
"s": 6050,
"text": "The “dynamic” view"
},
{
"code": null,
"e": 6231,
"s": 6069,
"text": "Let’s animate the graph above. For each timestamp, we want to visualize the distribution of cumulative incidents across the different neighborhoods in Vancouver."
},
{
"code": null,
"e": 6434,
"s": 6231,
"text": "We need to go through a couple of additional steps before we can work with the finalized Dataframe, which will contain the cumulative sum of all incidents per neighborhood at each timestamp in the data."
},
{
"code": null,
"e": 6768,
"s": 6434,
"text": "Now here’s a slightly tricky part. If you look at the counts_rolling Dataframe we’ve just produced, you’ll notice that not all neighborhoods have values for each timestamp. That’s because some neighborhoods don’t have any recorded crimes on certain dates, therefore we need to fill in those “missing” values by using forward filling."
},
{
"code": null,
"e": 6902,
"s": 6768,
"text": "Here we go, we now have a complete Dataframe with values for every timestamp/neighborhood combination. We can finally plot the graph!"
},
{
"code": null,
"e": 7422,
"s": 6902,
"text": "In order to use Plotly’s choropleth_mapbox function we must make sure the dataframe that contains the crime numbers and the geojson used to plot the map have the same identifier, so that the mapping function can properly associate each polygon with its crime counts. Here, I take advantage of the featureidkey argument to tell the mapping function that the polygon identifiers are in the “properties.name” location of the geojson file. These identifiers are the same neighborhood names contained in the crime dataframe."
},
{
"code": null,
"e": 8077,
"s": 7422,
"text": "As we’ve just seen, making animated graphs with Plotly is a painless and quick affair. In the next tutorials, I will showcase how to further customize Plotly Express graphs. For instance, we might want the option of selecting a year in particular and visualizing how crime evolves over the months in that year in particular. Or we might want to have an option to filter the data by types of crime, and visualize its evolution over time. Luckily for us, Plotly makes it easy for us to build on top of Plotly Express graphs, adding layers of customization one step at a time. In later tutorials we’ll see how everything can be wrapped into a nice Dash app!"
}
] |
Python | Pandas dataframe.cumprod() | 16 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.cumprod() is used to find the cumulative product of the values seen so far over any axis.Each cell is populated with the cumulative product of the values seen so far.
Syntax: DataFrame.cumprod(axis=None, skipna=True, *args, **kwargs)
Parameters:axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NA
Returns: cumprod : Series
Example #1: Use cumprod() function to find the cumulative product of the values seen so far along the index axis.
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4], "B":[11, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, 8]}) # Print the dataframedf
Output :
Now find the cumulative product of the values seen so far over the index axis
# To find the cumulative proddf.cumprod(axis = 0)
Output :
Example #2: Use cumprod() function to find the cumulative product of the values seen so far along the column axis.
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4], "B":[11, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, 8]}) # cumulative product along column axisdf.cumprod(axis = 1)
Output :
Example #3: Use cumprod() function to find the cumulative product of the values seen so far along the index axis in a data frame with NaN value present in dataframe.
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[5, 3, None, 4], "B":[None, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, None]}) # To find the cumulative productdf.cumprod(axis = 0, skipna = True)
Output :
The output is a dataframe with cells containing the cumulative product of the values seen so far along the index axis. Any Nan value in the dataframe is skipped.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Nov, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 426,
"s": 242,
"text": "Pandas dataframe.cumprod() is used to find the cumulative product of the values seen so far over any axis.Each cell is populated with the cumulative product of the values seen so far."
},
{
"code": null,
"e": 493,
"s": 426,
"text": "Syntax: DataFrame.cumprod(axis=None, skipna=True, *args, **kwargs)"
},
{
"code": null,
"e": 621,
"s": 493,
"text": "Parameters:axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NA"
},
{
"code": null,
"e": 647,
"s": 621,
"text": "Returns: cumprod : Series"
},
{
"code": null,
"e": 761,
"s": 647,
"text": "Example #1: Use cumprod() function to find the cumulative product of the values seen so far along the index axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[5, 3, 6, 4], \"B\":[11, 2, 4, 3], \"C\":[4, 3, 8, 5], \"D\":[5, 4, 2, 8]}) # Print the dataframedf",
"e": 1003,
"s": 761,
"text": null
},
{
"code": null,
"e": 1012,
"s": 1003,
"text": "Output :"
},
{
"code": null,
"e": 1090,
"s": 1012,
"text": "Now find the cumulative product of the values seen so far over the index axis"
},
{
"code": "# To find the cumulative proddf.cumprod(axis = 0)",
"e": 1140,
"s": 1090,
"text": null
},
{
"code": null,
"e": 1149,
"s": 1140,
"text": "Output :"
},
{
"code": null,
"e": 1266,
"s": 1151,
"text": "Example #2: Use cumprod() function to find the cumulative product of the values seen so far along the column axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[5, 3, 6, 4], \"B\":[11, 2, 4, 3], \"C\":[4, 3, 8, 5], \"D\":[5, 4, 2, 8]}) # cumulative product along column axisdf.cumprod(axis = 1)",
"e": 1544,
"s": 1266,
"text": null
},
{
"code": null,
"e": 1553,
"s": 1544,
"text": "Output :"
},
{
"code": null,
"e": 1721,
"s": 1555,
"text": "Example #3: Use cumprod() function to find the cumulative product of the values seen so far along the index axis in a data frame with NaN value present in dataframe."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[5, 3, None, 4], \"B\":[None, 2, 4, 3], \"C\":[4, 3, 8, 5], \"D\":[5, 4, 2, None]}) # To find the cumulative productdf.cumprod(axis = 0, skipna = True)",
"e": 2016,
"s": 1721,
"text": null
},
{
"code": null,
"e": 2025,
"s": 2016,
"text": "Output :"
},
{
"code": null,
"e": 2187,
"s": 2025,
"text": "The output is a dataframe with cells containing the cumulative product of the values seen so far along the index axis. Any Nan value in the dataframe is skipped."
},
{
"code": null,
"e": 2211,
"s": 2187,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2243,
"s": 2211,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2257,
"s": 2243,
"text": "Python-pandas"
},
{
"code": null,
"e": 2264,
"s": 2257,
"text": "Python"
},
{
"code": null,
"e": 2362,
"s": 2264,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2380,
"s": 2362,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2422,
"s": 2380,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2444,
"s": 2422,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2470,
"s": 2444,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2502,
"s": 2470,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2531,
"s": 2502,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2558,
"s": 2531,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2579,
"s": 2558,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2609,
"s": 2579,
"text": "Iterate over a list in Python"
}
] |
How to make a beep sound in JavaScript ? | 13 Mar, 2020
A beep sound in a website can be used for the following tasks:
Alert notification
Make the website more interactive
There can be many more use cases of these sounds. It all depends on one’s creativity and needs. Usually, we create a function in Javascript and call that function whenever required. In this tutorial, we are using a button to play the “beep” sound using the onclick method.
Method 1: Use Audio function in Javascript to load the audio file.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head> <body> <h1>Press the Button</h1> <button onclick="play()">Press Here!</button> <script> function play() { var audio = new Audio('https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3'); audio.play(); } </script></body></html>
Output:
Method 2: Use the audio tag in html and play it using Javascript.
<html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head> <body> <h1>Press the Button</h1> <audio id="chatAudio" > <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3" type="audio/mpeg"> </audio> <button onclick="play()">Press Here!</button> <script> var audio = document.getElementById('chatAudio'); function play(){ audio.play() } </script></body></html>
Output:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Mar, 2020"
},
{
"code": null,
"e": 91,
"s": 28,
"text": "A beep sound in a website can be used for the following tasks:"
},
{
"code": null,
"e": 110,
"s": 91,
"text": "Alert notification"
},
{
"code": null,
"e": 144,
"s": 110,
"text": "Make the website more interactive"
},
{
"code": null,
"e": 417,
"s": 144,
"text": "There can be many more use cases of these sounds. It all depends on one’s creativity and needs. Usually, we create a function in Javascript and call that function whenever required. In this tutorial, we are using a button to play the “beep” sound using the onclick method."
},
{
"code": null,
"e": 484,
"s": 417,
"text": "Method 1: Use Audio function in Javascript to load the audio file."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head> <body> <h1>Press the Button</h1> <button onclick=\"play()\">Press Here!</button> <script> function play() { var audio = new Audio('https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3'); audio.play(); } </script></body></html>",
"e": 964,
"s": 484,
"text": null
},
{
"code": null,
"e": 972,
"s": 964,
"text": "Output:"
},
{
"code": null,
"e": 1038,
"s": 972,
"text": "Method 2: Use the audio tag in html and play it using Javascript."
},
{
"code": "<html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head> <body> <h1>Press the Button</h1> <audio id=\"chatAudio\" > <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3\" type=\"audio/mpeg\"> </audio> <button onclick=\"play()\">Press Here!</button> <script> var audio = document.getElementById('chatAudio'); function play(){ audio.play() } </script></body></html>",
"e": 1609,
"s": 1038,
"text": null
},
{
"code": null,
"e": 1617,
"s": 1609,
"text": "Output:"
},
{
"code": null,
"e": 1633,
"s": 1617,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 1640,
"s": 1633,
"text": "Picked"
},
{
"code": null,
"e": 1651,
"s": 1640,
"text": "JavaScript"
},
{
"code": null,
"e": 1668,
"s": 1651,
"text": "Web Technologies"
},
{
"code": null,
"e": 1695,
"s": 1668,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1793,
"s": 1695,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1854,
"s": 1793,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1926,
"s": 1854,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1966,
"s": 1926,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2008,
"s": 1966,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2049,
"s": 2008,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2082,
"s": 2049,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2143,
"s": 2082,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2193,
"s": 2143,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2236,
"s": 2193,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
PHP | preg_match() Function | 27 Feb, 2019
This function searches string for pattern, returns true if pattern exists, otherwise returns false. Usually search starts from beginning of subject string. The optional parameter offset is used to specify the position from where to start the search.
Syntax:
int preg_match( $pattern, $input, $matches, $flags, $offset )
Parameters: This function accepts five parameters as mentioned above and described below:
pattern: This parameter holds the pattern to search for, as a string.
input: This parameter holds the input string.
matches: If matches exists then it contains results of search. The $matches[0] will contain the text that matched full pattern, $matches[1] will contain the text that matched the first captured parenthesized subpattern, and so on.
flags: The flags can be following flags:PREG_OFFSET_CAPTURE: If this flag is passed, for every match the append string offset will be returned.PREG_UNMATCHED_AS_NULL: If this flag is passed, subpatterns which are not matched reports as NULL; otherwise they reports as empty string.
PREG_OFFSET_CAPTURE: If this flag is passed, for every match the append string offset will be returned.
PREG_UNMATCHED_AS_NULL: If this flag is passed, subpatterns which are not matched reports as NULL; otherwise they reports as empty string.
offset: Usually, search starts from the beginning of input string. This optional parameter offset is used to specify the place from where to start the search (in bytes).
Return value: It returns true if pattern exists, otherwise false.
Below examples illustrate the preg_match() function in PHP:
Example 1: This example accepts the PREG_OFFSET_CAPTURE flag.
<?php // Declare a variable and initialize it$geeks = 'GeeksforGeeks'; // Use preg_match() function to check matchpreg_match('/(Geeks)(for)(Geeks)/', $geeks, $matches, PREG_OFFSET_CAPTURE); // Display matches resultprint_r($matches); ?>
Array
(
[0] => Array
(
[0] => GeeksforGeeks
[1] => 0
)
[1] => Array
(
[0] => Geeks
[1] => 0
)
[2] => Array
(
[0] => for
[1] => 5
)
[3] => Array
(
[0] => Geeks
[1] => 8
)
)
Example 2:
<?php // Declare a variable and initialize it$gfg = "GFG is the best Platform."; // case-Insensitive search for the word "GFG"if (preg_match("/\bGFG\b/i", $gfg, $match)) echo "Matched!";else echo "not matched"; ?>
Matched!
Reference: http://php.net/manual/en/function.preg-match.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to receive JSON POST with PHP ?
How to get parameters from a URL string in PHP?
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": "\n27 Feb, 2019"
},
{
"code": null,
"e": 278,
"s": 28,
"text": "This function searches string for pattern, returns true if pattern exists, otherwise returns false. Usually search starts from beginning of subject string. The optional parameter offset is used to specify the position from where to start the search."
},
{
"code": null,
"e": 286,
"s": 278,
"text": "Syntax:"
},
{
"code": null,
"e": 348,
"s": 286,
"text": "int preg_match( $pattern, $input, $matches, $flags, $offset )"
},
{
"code": null,
"e": 438,
"s": 348,
"text": "Parameters: This function accepts five parameters as mentioned above and described below:"
},
{
"code": null,
"e": 508,
"s": 438,
"text": "pattern: This parameter holds the pattern to search for, as a string."
},
{
"code": null,
"e": 554,
"s": 508,
"text": "input: This parameter holds the input string."
},
{
"code": null,
"e": 785,
"s": 554,
"text": "matches: If matches exists then it contains results of search. The $matches[0] will contain the text that matched full pattern, $matches[1] will contain the text that matched the first captured parenthesized subpattern, and so on."
},
{
"code": null,
"e": 1067,
"s": 785,
"text": "flags: The flags can be following flags:PREG_OFFSET_CAPTURE: If this flag is passed, for every match the append string offset will be returned.PREG_UNMATCHED_AS_NULL: If this flag is passed, subpatterns which are not matched reports as NULL; otherwise they reports as empty string."
},
{
"code": null,
"e": 1171,
"s": 1067,
"text": "PREG_OFFSET_CAPTURE: If this flag is passed, for every match the append string offset will be returned."
},
{
"code": null,
"e": 1310,
"s": 1171,
"text": "PREG_UNMATCHED_AS_NULL: If this flag is passed, subpatterns which are not matched reports as NULL; otherwise they reports as empty string."
},
{
"code": null,
"e": 1480,
"s": 1310,
"text": "offset: Usually, search starts from the beginning of input string. This optional parameter offset is used to specify the place from where to start the search (in bytes)."
},
{
"code": null,
"e": 1546,
"s": 1480,
"text": "Return value: It returns true if pattern exists, otherwise false."
},
{
"code": null,
"e": 1606,
"s": 1546,
"text": "Below examples illustrate the preg_match() function in PHP:"
},
{
"code": null,
"e": 1668,
"s": 1606,
"text": "Example 1: This example accepts the PREG_OFFSET_CAPTURE flag."
},
{
"code": "<?php // Declare a variable and initialize it$geeks = 'GeeksforGeeks'; // Use preg_match() function to check matchpreg_match('/(Geeks)(for)(Geeks)/', $geeks, $matches, PREG_OFFSET_CAPTURE); // Display matches resultprint_r($matches); ?>",
"e": 1909,
"s": 1668,
"text": null
},
{
"code": null,
"e": 2262,
"s": 1909,
"text": "Array\n(\n [0] => Array\n (\n [0] => GeeksforGeeks\n [1] => 0\n )\n\n [1] => Array\n (\n [0] => Geeks\n [1] => 0\n )\n\n [2] => Array\n (\n [0] => for\n [1] => 5\n )\n\n [3] => Array\n (\n [0] => Geeks\n [1] => 8\n )\n\n)\n"
},
{
"code": null,
"e": 2273,
"s": 2262,
"text": "Example 2:"
},
{
"code": "<?php // Declare a variable and initialize it$gfg = \"GFG is the best Platform.\"; // case-Insensitive search for the word \"GFG\"if (preg_match(\"/\\bGFG\\b/i\", $gfg, $match)) echo \"Matched!\";else echo \"not matched\"; ?>",
"e": 2501,
"s": 2273,
"text": null
},
{
"code": null,
"e": 2511,
"s": 2501,
"text": "Matched!\n"
},
{
"code": null,
"e": 2571,
"s": 2511,
"text": "Reference: http://php.net/manual/en/function.preg-match.php"
},
{
"code": null,
"e": 2584,
"s": 2571,
"text": "PHP-function"
},
{
"code": null,
"e": 2588,
"s": 2584,
"text": "PHP"
},
{
"code": null,
"e": 2605,
"s": 2588,
"text": "Web Technologies"
},
{
"code": null,
"e": 2609,
"s": 2605,
"text": "PHP"
},
{
"code": null,
"e": 2707,
"s": 2609,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2747,
"s": 2707,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2792,
"s": 2747,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2819,
"s": 2792,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 2855,
"s": 2819,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 2903,
"s": 2855,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 2936,
"s": 2903,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2998,
"s": 2936,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3059,
"s": 2998,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3109,
"s": 3059,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to remove the border of the legend of a chart created by plot function in R? | When we create a chart using plot function and add a legend to that chart, the output of the chart has the legend that is covered with borders. But this breaks the flow of the chart and the area covered by the order make the chart unattractive. Therefore, we can use bty="n" with the legend function and it will remove the border of the legend.
Creating the chart with legend that has border −
plot(x=1:10,y=10:1)
legend(1,2,"This is a scatterplot between x and y")
Creating the chart with legend which does not have a border −
plot(x=1:10,y=10:1)
legend(1,2,"This is a scatterplot between x and y",bty="n") | [
{
"code": null,
"e": 1532,
"s": 1187,
"text": "When we create a chart using plot function and add a legend to that chart, the output of the chart has the legend that is covered with borders. But this breaks the flow of the chart and the area covered by the order make the chart unattractive. Therefore, we can use bty=\"n\" with the legend function and it will remove the border of the legend."
},
{
"code": null,
"e": 1581,
"s": 1532,
"text": "Creating the chart with legend that has border −"
},
{
"code": null,
"e": 1653,
"s": 1581,
"text": "plot(x=1:10,y=10:1)\nlegend(1,2,\"This is a scatterplot between x and y\")"
},
{
"code": null,
"e": 1715,
"s": 1653,
"text": "Creating the chart with legend which does not have a border −"
},
{
"code": null,
"e": 1795,
"s": 1715,
"text": "plot(x=1:10,y=10:1)\nlegend(1,2,\"This is a scatterplot between x and y\",bty=\"n\")"
}
] |
Java.net.DatagramSocket class in Java | 30 Nov, 2021
Datagram socket is a type of network socket which provides connection-less point for sending and receiving packets. Every packet sent from a datagram socket is individually routed and delivered. It can also be used for sending and receiving broadcast messages. Datagram Sockets is the java’s mechanism for providing network communication via UDP instead of TCP.
Constructors :
1. DatagramSocket() : Creates a datagramSocket and binds it to any available port on local machine. If this constructor is used, the OS would assign any port to this socket.
Syntax :public DatagramSocket()
throws SocketException
Throws :
SocketException : if the socket could not be opened
2. DatagramSocket(DatagramSocketImpl impl) : Creates an unbound datagram socket with given datagramImpl.
Syntax :protected DatagramSocket(DatagramSocketImpl impl)
Parameters :
impl : instance of datagramScketImpl
3. DatagramSocket(int port) : Creates and binds the datagram socket to the specified port. The socket will be bound to the a wildcard address chosen by kernel.
Syntax : public DatagramSocket(int port)
throws SocketException
Parameters :
port : port number to bind this socket to
4. DatagramSocket(int port, InetAddress laddr) : Constructs a datagram socket and binds it to specified port and inetaddress.
Syntax : public DatagramSocket(int port,
InetAddress laddr)
throws SocketException
Parameters :
port : local port to bind
laddr : local address to bind
Throws :
SocketException : If the socket could not be opened
5. DatagramSocket(SocketAddress bindaddr) : Constructs a new socket object and binds it the specified socket address(IP address+port number).
Syntax :public DatagramSocket(SocketAddress bindaddr)
throws SocketException
Parameters :
bindaddr : socket address to bind to
Throws :
SocketException : If socket could not be opened
Methods :
1. bind() : Binds this socket to specified address and port number.
Syntax : public void bind(SocketAddress addr)
Parameters :
addr : socket address to bind to
2. connect() : Connects to the specified address and port. After connecting to the remote host, this socket can send or receive packet from this remote host only. If a connection cannot be made to the specified remote host, the calls to send() or receive() would throw PortUnreachable Exception.
Syntax :public void connect(InetAddress address,
int port)
Parameters :
address : address of remote host
port : port number of remote host
Another overloaded method takes socket address as a parameter.
Syntax :public void connect(SocketAddress address)
Parameters :
address : socket address of remote host
3. disconnect() : Disconnects the socket. If the socket is not connected, then this method has no effect.
Syntax :public void disconnect()
4. isBound() : Returns a boolean value indicating whether this socket is bound or not.
Syntax :public boolean isBound()
isConnected() : Returns a boolean value indicating whether this socket is connected or not.
Syntax :public boolean isConnected()
5. isConnected() : Returns boolean value representing connection state of the socket. Please note that even after closing the socket, this method will continue to return true if this socket was connected prior to closing the socket.
Syntax :public boolean isConnected()
6. getInetAddress() : Returns the address to which this socket is connected.
Syntax : public InetAddress getInetAddress()
7. getPort() : Returns the port on the machine to which this socket is connected.
Syntax : public int getPort()
8. getRemoteSocketAddress() : Returns the socket address (IP address+port number) to which this socket is connected.
Syntax : public SocketAddress getRemoteSocketAddress()
9. getLocalSocketAddress() : Returns the address of the machine this socket is bound to, i.e. local machine socket address.
public SocketAddress getLocalSocketAddress()
10. send() : Sends a datagram packet from this socket. It should be noted that the information about the data to be sent, the address to which it is sent etc are all handled by the packet itself.
Syntax : public void send(DatagramPacket p)
Parameters :
p : packet to send
11. receive() : It is used to receive the packet from a sender. When a packet is successfully received, the buffer of the packet is filled with received message. The packet also contains valuable information like the senders address and the port number. This method waits till a packet is received.
Syntax : public void receive(DatagramPacket p)
Parameters :
p : datagram packet into which incoming data is filled
12. getLocalAddress() : Returns the local address to which this socket is bound.
Syntax : public InetAddress getLocalAddress()
13. getLocalPort() : Returns the port on local machine to which this socket is bound.
Syntax : public int getLocalPort()
14. setSOTimeout() : This is used to set the waiting time for receiving a datagram packet. As a call to receive() method blocks execution of the program indefinitely until a packet is received, this method can be used to limit that time. Once the time specified expires, java.net.SocketTimeoutException is thrown.
Syntax : public void setSoTimeout(int timeout)
Parameters :
timeout : time to wait
15. getSoTimeout() : Returns the timeout parameter if specified, or 0 which indicates infinite time.
Syntax : public int getSoTimeout()
16. setSendBufferSize() : Used to set a limit to maximum size of the packet that can be sent from this socket. It sets the SO_SNDBUF option, which is used by network implementation to set size of underlying network buffers. Increasing the size may allow to queue the packets before sending when send rate is high.
Syntax : public void setSendBufferSize(int size)
Parameters :
size : size of send buffer to set
Java Implementation :
Java
import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.util.Arrays; public class datasocket { public static void main(String[] args) throws IOException { // Constructor to create a datagram socket DatagramSocket socket = new DatagramSocket(); InetAddress address = InetAddress.getByName("localhost"); int port = 5252; byte buf[] = { 12, 13 }; byte buf1[] = new byte[2]; DatagramPacket dp = new DatagramPacket(buf, 2, address, port); DatagramPacket dptorec = new DatagramPacket(buf1, 2); // connect() method socket.connect(address, port); // isBound() method System.out.println("IsBound : " + socket.isBound()); // isConnected() method System.out.println("isConnected : " + socket.isConnected()); // getInetAddress() method System.out.println("InetAddress : " + socket.getInetAddress()); // getPort() method System.out.println("Port : " + socket.getPort()); // getRemoteSocketAddress() method System.out.println("Remote socket address : " + socket.getRemoteSocketAddress()); // getLocalSocketAddress() method System.out.println("Local socket address : " + socket.getLocalSocketAddress()); // send() method socket.send(dp); System.out.println("...packet sent successfully...."); // receive() method socket.receive(dptorec); System.out.println("Received packet data : " + Arrays.toString(dptorec.getData())); // getLocalPort() method System.out.println("Local Port : " + socket.getLocalPort()); // getLocalAddress() method System.out.println("Local Address : " + socket.getLocalAddress()); // setSOTimeout() method socket.setSoTimeout(50); // getSOTimeout() method System.out.println("SO Timeout : " + socket.getSoTimeout()); } }
To test the above program, a small server program is required for receiving the sent packet and for implementing receive() method. Its implementation is given below.
Java
import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;public class smallserver { public static void main(String[] args) throws IOException { DatagramSocket ds = new DatagramSocket(5252); byte buf[] = new byte[2]; byte send[] = { 13, 18 }; DatagramPacket dp = new DatagramPacket(buf, 2); ds.receive(dp); DatagramPacket senddp = new DatagramPacket(send, 2, dp.getAddress(), dp.getPort()); ds.send(senddp); } }
Output: On the client-side
IsBound : true
isConnected : true
InetAddress : localhost/127.0.0.1
Port : 5252
Remote socket address : localhost/127.0.0.1:5252
Local socket address : /127.0.0.1:59498
packet sent successfully
Received packet data : [13, 18]
Local Port : 59498
Local Address : /127.0.0.1
SO Timeout : 50
17. getSendBufferSize() : Returns the value of SO_SNDBUF option of this socket.
Syntax : public int getSendBufferSize()
18. setReceiveBufferSize() : Used to set a limit to maximum size of the packet that is received on this socket. It sets the SO_RCVBUF option, which is used by network implementation to set size of underlying network buffers. Increasing the size may allow to queue the packets on receiving end when packets are sent faster than they are consumed.
Syntax : public void setReceiveBufferSize(int size)
Parameters :
size : size of receive buffer to set
19. getReceiveBufferSize() : Returns the value of SO_RCVBUF option of this socket.
Syntax : public int getReceiveBufferSize()
20. setReuseAddress() : Sometimes it may be necessary to bind multiple sockets to the same address. Enabling this option enables other socket to bind to same address as this. It must be set before a call to bind() is made. It sets the value of SO_REUSEADDR socket option.
Syntax : public void setReuseAddress(boolean on)
Parameters :
on : true for enable, false otherwise
21. getReuseAddress() : Returns boolean value indicating the setting of SO_REUSEADDR socket option.
Syntax : public boolean getReuseAddress()
22. setBroadcast() : Sets the value of SO_BROADCAST socket option.
Syntax : public void setBroadcast(boolean on)
Parameters :
on : true to allow broadcast, false otherwise
23. getBroadcast() : Returns true if broadcast is enabled, false otherwise.
Syntax : public boolean getBroadcast()
24. setTrafficClass() : used to set the type-of-service octet in the IP datagram header for datagrams sent from this DatagramSocket. For more details about traffic, class refer to Wikipedia
Syntax : public void setTrafficClass(int tc)
Parameters :
tc : int value of bitset, 0<=tc<=255
25. getTrafficClass() : Gets traffic class or type of service from the IP header of packets sent from this socket.
Syntax : public int getTrafficClass()
26. close() : Closes this datagram socket. Any pending receive call will throw SocketException.
Syntax : public void close()
27. isClosed() : Returns the boolean value indicating if the socket is closed or not.
Syntax : public boolean isClosed()
28. getChannel() : Returns a data channel if any associated with this socket. More details about Datagram channels can be found on Official Java Documentation.
Syntax : public DatagramChannel getChannel()
29. setDatagramSocketImplFactory() : Sets the datagram socket implementation factory for the application.
Syntax :public static void setDatagramSocketImplFactory(
DatagramSocketImplFactory fac)
Parameters :
fac - the desired factory.
Throws :
IOException - if an I/O error occurs when setting the datagram socket factory.
SocketException - if the factory is already defined.
Java Implementation :
Java
import java.io.IOException;import java.net.DatagramSocket; public class datasock2 { public static void main(String[] args) throws IOException { // Constructor DatagramSocket socket = new DatagramSocket(1235); // setSendBufferSize() method socket.setSendBufferSize(20); // getSendBufferSize() method System.out.println("Send buffer size : " + socket.getSendBufferSize()); // setReceiveBufferSize() method socket.setReceiveBufferSize(20); // getReceiveBufferSize() method System.out.println("Receive buffer size : " + socket.getReceiveBufferSize()); // setReuseAddress() method socket.setReuseAddress(true); // getReuseAddress() method System.out.println("SetReuse address : " + socket.getReuseAddress()); // setBroadcast() method socket.setBroadcast(false); // getBroadcast() method System.out.println("setBroadcast : " + socket.getBroadcast()); // setTrafficClass() method socket.setTrafficClass(45); // getTrafficClass() method System.out.println("Traffic class : " + socket.getTrafficClass()); // getChannel() method System.out.println("Channel : " + ((socket.getChannel()!=null)?socket.getChannel():"null")); // setSocketImplFactory() method socket.setDatagramSocketImplFactory(null); // close() method socket.close(); // isClosed() method System.out.println("Is Closed : " + socket.isClosed()); }}
Output :
Send buffer size : 20
Receive buffer size : 20
SetReuse address : true
setBroadcast : false
Traffic class : 44
Channel : null
Is Closed : true
References: Official Java Documentation
This article is contributed by Rishabh Mahrsee. 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.
sagartomar9927
simmytarika5
Java-Networking
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 391,
"s": 28,
"text": "Datagram socket is a type of network socket which provides connection-less point for sending and receiving packets. Every packet sent from a datagram socket is individually routed and delivered. It can also be used for sending and receiving broadcast messages. Datagram Sockets is the java’s mechanism for providing network communication via UDP instead of TCP. "
},
{
"code": null,
"e": 408,
"s": 391,
"text": "Constructors : "
},
{
"code": null,
"e": 583,
"s": 408,
"text": "1. DatagramSocket() : Creates a datagramSocket and binds it to any available port on local machine. If this constructor is used, the OS would assign any port to this socket. "
},
{
"code": null,
"e": 714,
"s": 583,
"text": "Syntax :public DatagramSocket()\n throws SocketException\nThrows :\nSocketException : if the socket could not be opened"
},
{
"code": null,
"e": 820,
"s": 714,
"text": "2. DatagramSocket(DatagramSocketImpl impl) : Creates an unbound datagram socket with given datagramImpl. "
},
{
"code": null,
"e": 928,
"s": 820,
"text": "Syntax :protected DatagramSocket(DatagramSocketImpl impl)\nParameters :\nimpl : instance of datagramScketImpl"
},
{
"code": null,
"e": 1089,
"s": 928,
"text": "3. DatagramSocket(int port) : Creates and binds the datagram socket to the specified port. The socket will be bound to the a wildcard address chosen by kernel. "
},
{
"code": null,
"e": 1224,
"s": 1089,
"text": "Syntax : public DatagramSocket(int port)\n throws SocketException\nParameters : \nport : port number to bind this socket to"
},
{
"code": null,
"e": 1351,
"s": 1224,
"text": "4. DatagramSocket(int port, InetAddress laddr) : Constructs a datagram socket and binds it to specified port and inetaddress. "
},
{
"code": null,
"e": 1593,
"s": 1351,
"text": "Syntax : public DatagramSocket(int port,\n InetAddress laddr)\n throws SocketException\nParameters :\nport : local port to bind\nladdr : local address to bind\nThrows :\nSocketException : If the socket could not be opened"
},
{
"code": null,
"e": 1736,
"s": 1593,
"text": "5. DatagramSocket(SocketAddress bindaddr) : Constructs a new socket object and binds it the specified socket address(IP address+port number). "
},
{
"code": null,
"e": 1936,
"s": 1736,
"text": "Syntax :public DatagramSocket(SocketAddress bindaddr)\n throws SocketException\nParameters :\nbindaddr : socket address to bind to\nThrows : \nSocketException : If socket could not be opened"
},
{
"code": null,
"e": 1947,
"s": 1936,
"text": "Methods : "
},
{
"code": null,
"e": 2016,
"s": 1947,
"text": "1. bind() : Binds this socket to specified address and port number. "
},
{
"code": null,
"e": 2109,
"s": 2016,
"text": "Syntax : public void bind(SocketAddress addr)\nParameters : \naddr : socket address to bind to"
},
{
"code": null,
"e": 2406,
"s": 2109,
"text": "2. connect() : Connects to the specified address and port. After connecting to the remote host, this socket can send or receive packet from this remote host only. If a connection cannot be made to the specified remote host, the calls to send() or receive() would throw PortUnreachable Exception. "
},
{
"code": null,
"e": 2556,
"s": 2406,
"text": "Syntax :public void connect(InetAddress address,\n int port)\nParameters :\naddress : address of remote host\nport : port number of remote host"
},
{
"code": null,
"e": 2620,
"s": 2556,
"text": "Another overloaded method takes socket address as a parameter. "
},
{
"code": null,
"e": 2724,
"s": 2620,
"text": "Syntax :public void connect(SocketAddress address)\nParameters :\naddress : socket address of remote host"
},
{
"code": null,
"e": 2831,
"s": 2724,
"text": "3. disconnect() : Disconnects the socket. If the socket is not connected, then this method has no effect. "
},
{
"code": null,
"e": 2864,
"s": 2831,
"text": "Syntax :public void disconnect()"
},
{
"code": null,
"e": 2952,
"s": 2864,
"text": "4. isBound() : Returns a boolean value indicating whether this socket is bound or not. "
},
{
"code": null,
"e": 2985,
"s": 2952,
"text": "Syntax :public boolean isBound()"
},
{
"code": null,
"e": 3078,
"s": 2985,
"text": "isConnected() : Returns a boolean value indicating whether this socket is connected or not. "
},
{
"code": null,
"e": 3115,
"s": 3078,
"text": "Syntax :public boolean isConnected()"
},
{
"code": null,
"e": 3349,
"s": 3115,
"text": "5. isConnected() : Returns boolean value representing connection state of the socket. Please note that even after closing the socket, this method will continue to return true if this socket was connected prior to closing the socket. "
},
{
"code": null,
"e": 3386,
"s": 3349,
"text": "Syntax :public boolean isConnected()"
},
{
"code": null,
"e": 3464,
"s": 3386,
"text": "6. getInetAddress() : Returns the address to which this socket is connected. "
},
{
"code": null,
"e": 3509,
"s": 3464,
"text": "Syntax : public InetAddress getInetAddress()"
},
{
"code": null,
"e": 3592,
"s": 3509,
"text": "7. getPort() : Returns the port on the machine to which this socket is connected. "
},
{
"code": null,
"e": 3622,
"s": 3592,
"text": "Syntax : public int getPort()"
},
{
"code": null,
"e": 3740,
"s": 3622,
"text": "8. getRemoteSocketAddress() : Returns the socket address (IP address+port number) to which this socket is connected. "
},
{
"code": null,
"e": 3795,
"s": 3740,
"text": "Syntax : public SocketAddress getRemoteSocketAddress()"
},
{
"code": null,
"e": 3920,
"s": 3795,
"text": "9. getLocalSocketAddress() : Returns the address of the machine this socket is bound to, i.e. local machine socket address. "
},
{
"code": null,
"e": 3965,
"s": 3920,
"text": "public SocketAddress getLocalSocketAddress()"
},
{
"code": null,
"e": 4162,
"s": 3965,
"text": "10. send() : Sends a datagram packet from this socket. It should be noted that the information about the data to be sent, the address to which it is sent etc are all handled by the packet itself. "
},
{
"code": null,
"e": 4238,
"s": 4162,
"text": "Syntax : public void send(DatagramPacket p)\nParameters :\np : packet to send"
},
{
"code": null,
"e": 4538,
"s": 4238,
"text": "11. receive() : It is used to receive the packet from a sender. When a packet is successfully received, the buffer of the packet is filled with received message. The packet also contains valuable information like the senders address and the port number. This method waits till a packet is received. "
},
{
"code": null,
"e": 4654,
"s": 4538,
"text": "Syntax : public void receive(DatagramPacket p)\nParameters : \np : datagram packet into which incoming data is filled"
},
{
"code": null,
"e": 4736,
"s": 4654,
"text": "12. getLocalAddress() : Returns the local address to which this socket is bound. "
},
{
"code": null,
"e": 4782,
"s": 4736,
"text": "Syntax : public InetAddress getLocalAddress()"
},
{
"code": null,
"e": 4869,
"s": 4782,
"text": "13. getLocalPort() : Returns the port on local machine to which this socket is bound. "
},
{
"code": null,
"e": 4904,
"s": 4869,
"text": "Syntax : public int getLocalPort()"
},
{
"code": null,
"e": 5219,
"s": 4904,
"text": "14. setSOTimeout() : This is used to set the waiting time for receiving a datagram packet. As a call to receive() method blocks execution of the program indefinitely until a packet is received, this method can be used to limit that time. Once the time specified expires, java.net.SocketTimeoutException is thrown. "
},
{
"code": null,
"e": 5302,
"s": 5219,
"text": "Syntax : public void setSoTimeout(int timeout)\nParameters :\ntimeout : time to wait"
},
{
"code": null,
"e": 5404,
"s": 5302,
"text": "15. getSoTimeout() : Returns the timeout parameter if specified, or 0 which indicates infinite time. "
},
{
"code": null,
"e": 5439,
"s": 5404,
"text": "Syntax : public int getSoTimeout()"
},
{
"code": null,
"e": 5754,
"s": 5439,
"text": "16. setSendBufferSize() : Used to set a limit to maximum size of the packet that can be sent from this socket. It sets the SO_SNDBUF option, which is used by network implementation to set size of underlying network buffers. Increasing the size may allow to queue the packets before sending when send rate is high. "
},
{
"code": null,
"e": 5851,
"s": 5754,
"text": "Syntax : public void setSendBufferSize(int size)\nParameters : \nsize : size of send buffer to set"
},
{
"code": null,
"e": 5873,
"s": 5851,
"text": "Java Implementation :"
},
{
"code": null,
"e": 5878,
"s": 5873,
"text": "Java"
},
{
"code": "import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.util.Arrays; public class datasocket { public static void main(String[] args) throws IOException { // Constructor to create a datagram socket DatagramSocket socket = new DatagramSocket(); InetAddress address = InetAddress.getByName(\"localhost\"); int port = 5252; byte buf[] = { 12, 13 }; byte buf1[] = new byte[2]; DatagramPacket dp = new DatagramPacket(buf, 2, address, port); DatagramPacket dptorec = new DatagramPacket(buf1, 2); // connect() method socket.connect(address, port); // isBound() method System.out.println(\"IsBound : \" + socket.isBound()); // isConnected() method System.out.println(\"isConnected : \" + socket.isConnected()); // getInetAddress() method System.out.println(\"InetAddress : \" + socket.getInetAddress()); // getPort() method System.out.println(\"Port : \" + socket.getPort()); // getRemoteSocketAddress() method System.out.println(\"Remote socket address : \" + socket.getRemoteSocketAddress()); // getLocalSocketAddress() method System.out.println(\"Local socket address : \" + socket.getLocalSocketAddress()); // send() method socket.send(dp); System.out.println(\"...packet sent successfully....\"); // receive() method socket.receive(dptorec); System.out.println(\"Received packet data : \" + Arrays.toString(dptorec.getData())); // getLocalPort() method System.out.println(\"Local Port : \" + socket.getLocalPort()); // getLocalAddress() method System.out.println(\"Local Address : \" + socket.getLocalAddress()); // setSOTimeout() method socket.setSoTimeout(50); // getSOTimeout() method System.out.println(\"SO Timeout : \" + socket.getSoTimeout()); } }",
"e": 7973,
"s": 5878,
"text": null
},
{
"code": null,
"e": 8139,
"s": 7973,
"text": "To test the above program, a small server program is required for receiving the sent packet and for implementing receive() method. Its implementation is given below."
},
{
"code": null,
"e": 8144,
"s": 8139,
"text": "Java"
},
{
"code": "import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;public class smallserver { public static void main(String[] args) throws IOException { DatagramSocket ds = new DatagramSocket(5252); byte buf[] = new byte[2]; byte send[] = { 13, 18 }; DatagramPacket dp = new DatagramPacket(buf, 2); ds.receive(dp); DatagramPacket senddp = new DatagramPacket(send, 2, dp.getAddress(), dp.getPort()); ds.send(senddp); } }",
"e": 8695,
"s": 8144,
"text": null
},
{
"code": null,
"e": 8722,
"s": 8695,
"text": "Output: On the client-side"
},
{
"code": null,
"e": 9010,
"s": 8722,
"text": "IsBound : true\nisConnected : true\nInetAddress : localhost/127.0.0.1\nPort : 5252\nRemote socket address : localhost/127.0.0.1:5252\nLocal socket address : /127.0.0.1:59498\npacket sent successfully\nReceived packet data : [13, 18]\nLocal Port : 59498\nLocal Address : /127.0.0.1\nSO Timeout : 50"
},
{
"code": null,
"e": 9091,
"s": 9010,
"text": "17. getSendBufferSize() : Returns the value of SO_SNDBUF option of this socket. "
},
{
"code": null,
"e": 9131,
"s": 9091,
"text": "Syntax : public int getSendBufferSize()"
},
{
"code": null,
"e": 9478,
"s": 9131,
"text": "18. setReceiveBufferSize() : Used to set a limit to maximum size of the packet that is received on this socket. It sets the SO_RCVBUF option, which is used by network implementation to set size of underlying network buffers. Increasing the size may allow to queue the packets on receiving end when packets are sent faster than they are consumed. "
},
{
"code": null,
"e": 9581,
"s": 9478,
"text": "Syntax : public void setReceiveBufferSize(int size)\nParameters : \nsize : size of receive buffer to set"
},
{
"code": null,
"e": 9665,
"s": 9581,
"text": "19. getReceiveBufferSize() : Returns the value of SO_RCVBUF option of this socket. "
},
{
"code": null,
"e": 9708,
"s": 9665,
"text": "Syntax : public int getReceiveBufferSize()"
},
{
"code": null,
"e": 9981,
"s": 9708,
"text": "20. setReuseAddress() : Sometimes it may be necessary to bind multiple sockets to the same address. Enabling this option enables other socket to bind to same address as this. It must be set before a call to bind() is made. It sets the value of SO_REUSEADDR socket option. "
},
{
"code": null,
"e": 10082,
"s": 9981,
"text": "Syntax : public void setReuseAddress(boolean on)\nParameters : \non : true for enable, false otherwise"
},
{
"code": null,
"e": 10183,
"s": 10082,
"text": "21. getReuseAddress() : Returns boolean value indicating the setting of SO_REUSEADDR socket option. "
},
{
"code": null,
"e": 10225,
"s": 10183,
"text": "Syntax : public boolean getReuseAddress()"
},
{
"code": null,
"e": 10293,
"s": 10225,
"text": "22. setBroadcast() : Sets the value of SO_BROADCAST socket option. "
},
{
"code": null,
"e": 10399,
"s": 10293,
"text": "Syntax : public void setBroadcast(boolean on)\nParameters : \non : true to allow broadcast, false otherwise"
},
{
"code": null,
"e": 10476,
"s": 10399,
"text": "23. getBroadcast() : Returns true if broadcast is enabled, false otherwise. "
},
{
"code": null,
"e": 10515,
"s": 10476,
"text": "Syntax : public boolean getBroadcast()"
},
{
"code": null,
"e": 10706,
"s": 10515,
"text": "24. setTrafficClass() : used to set the type-of-service octet in the IP datagram header for datagrams sent from this DatagramSocket. For more details about traffic, class refer to Wikipedia "
},
{
"code": null,
"e": 10802,
"s": 10706,
"text": "Syntax : public void setTrafficClass(int tc)\nParameters : \ntc : int value of bitset, 0<=tc<=255"
},
{
"code": null,
"e": 10918,
"s": 10802,
"text": "25. getTrafficClass() : Gets traffic class or type of service from the IP header of packets sent from this socket. "
},
{
"code": null,
"e": 10956,
"s": 10918,
"text": "Syntax : public int getTrafficClass()"
},
{
"code": null,
"e": 11053,
"s": 10956,
"text": "26. close() : Closes this datagram socket. Any pending receive call will throw SocketException. "
},
{
"code": null,
"e": 11082,
"s": 11053,
"text": "Syntax : public void close()"
},
{
"code": null,
"e": 11169,
"s": 11082,
"text": "27. isClosed() : Returns the boolean value indicating if the socket is closed or not. "
},
{
"code": null,
"e": 11204,
"s": 11169,
"text": "Syntax : public boolean isClosed()"
},
{
"code": null,
"e": 11365,
"s": 11204,
"text": "28. getChannel() : Returns a data channel if any associated with this socket. More details about Datagram channels can be found on Official Java Documentation. "
},
{
"code": null,
"e": 11410,
"s": 11365,
"text": "Syntax : public DatagramChannel getChannel()"
},
{
"code": null,
"e": 11517,
"s": 11410,
"text": "29. setDatagramSocketImplFactory() : Sets the datagram socket implementation factory for the application. "
},
{
"code": null,
"e": 11821,
"s": 11517,
"text": "Syntax :public static void setDatagramSocketImplFactory(\n DatagramSocketImplFactory fac)\nParameters : \nfac - the desired factory.\nThrows : \nIOException - if an I/O error occurs when setting the datagram socket factory.\nSocketException - if the factory is already defined."
},
{
"code": null,
"e": 11843,
"s": 11821,
"text": "Java Implementation :"
},
{
"code": null,
"e": 11848,
"s": 11843,
"text": "Java"
},
{
"code": "import java.io.IOException;import java.net.DatagramSocket; public class datasock2 { public static void main(String[] args) throws IOException { // Constructor DatagramSocket socket = new DatagramSocket(1235); // setSendBufferSize() method socket.setSendBufferSize(20); // getSendBufferSize() method System.out.println(\"Send buffer size : \" + socket.getSendBufferSize()); // setReceiveBufferSize() method socket.setReceiveBufferSize(20); // getReceiveBufferSize() method System.out.println(\"Receive buffer size : \" + socket.getReceiveBufferSize()); // setReuseAddress() method socket.setReuseAddress(true); // getReuseAddress() method System.out.println(\"SetReuse address : \" + socket.getReuseAddress()); // setBroadcast() method socket.setBroadcast(false); // getBroadcast() method System.out.println(\"setBroadcast : \" + socket.getBroadcast()); // setTrafficClass() method socket.setTrafficClass(45); // getTrafficClass() method System.out.println(\"Traffic class : \" + socket.getTrafficClass()); // getChannel() method System.out.println(\"Channel : \" + ((socket.getChannel()!=null)?socket.getChannel():\"null\")); // setSocketImplFactory() method socket.setDatagramSocketImplFactory(null); // close() method socket.close(); // isClosed() method System.out.println(\"Is Closed : \" + socket.isClosed()); }}",
"e": 13564,
"s": 11848,
"text": null
},
{
"code": null,
"e": 13573,
"s": 13564,
"text": "Output :"
},
{
"code": null,
"e": 13716,
"s": 13573,
"text": "Send buffer size : 20\nReceive buffer size : 20\nSetReuse address : true\nsetBroadcast : false\nTraffic class : 44\nChannel : null\nIs Closed : true"
},
{
"code": null,
"e": 13757,
"s": 13716,
"text": "References: Official Java Documentation "
},
{
"code": null,
"e": 14181,
"s": 13757,
"text": "This article is contributed by Rishabh Mahrsee. 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": 14196,
"s": 14181,
"text": "sagartomar9927"
},
{
"code": null,
"e": 14209,
"s": 14196,
"text": "simmytarika5"
},
{
"code": null,
"e": 14225,
"s": 14209,
"text": "Java-Networking"
},
{
"code": null,
"e": 14230,
"s": 14225,
"text": "Java"
},
{
"code": null,
"e": 14235,
"s": 14230,
"text": "Java"
}
] |
Fermat’s Last Theorem | 23 Jun, 2022
According to Fermat’s Last Theorem, no three positive integers a, b, c satisfy the equation, for any integer value of n greater than 2. For n = 1 and n = 2, the equation have infinitely many solutions.
Some solutions for n = 1 are,
2 + 3 = 5
7 + 13 = 20
5 + 6 = 11
10 + 9 = 19
Some solutions for n = 2 are,
C++
Java
Python3
C#
PHP
Javascript
// C++ program to verify fermat's last theorem// for a given range and n.#include <bits/stdc++.h>using namespace std; void testSomeNumbers(int limit, int n){ if (n < 3) return; for (int a=1; a<=limit; a++) for (int b=a; b<=limit; b++) { // Check if there exists a triplet // such that a^n + b^n = c^n int pow_sum = pow(a, n) + pow(b, n); double c = pow(pow_sum, 1.0/n); int c_pow = pow((int)c, n); if (c_pow == pow_sum) { cout << "Count example found"; return; } } cout << "No counter example within given" " range and data";} // driver codeint main(){ testSomeNumbers(10, 3); return 0;}
// Java program to verify fermat's last theorem// for a given range and n.import java.io.*; class GFG{ static void testSomeNumbers(int limit, int n) { if (n < 3) return; for (int a = 1; a <= limit; a++) for (int b = a; b <= limit; b++) { // Check if there exists a triplet // such that a^n + b^n = c^n int pow_sum = (int)(Math.pow(a, n) + Math.pow(b, n)); double c = Math.pow(pow_sum, 1.0 / n); int c_pow = (int)Math.pow((int)c, n); if (c_pow == pow_sum) { System.out.println("Count example found"); return; } } System.out.println("No counter example within given"+ " range and data"); } // Driver code public static void main (String[] args) { testSomeNumbers(12, 5); }} // This code is contributed by vt_m.
# Python3 program to verify fermat's last# theorem for a given range and n. def testSomeNumbers(limit, n) : if (n < 3): return for a in range(1, limit + 1): for b in range(a, limit + 1): # Check if there exists a triplet # such that a^n + b^n = c^n pow_sum = pow(a, n) + pow(b, n) c = pow(pow_sum, 1.0 / n) c_pow = pow(int(c), n) if (c_pow == pow_sum): print("Count example found") return print("No counter example within given range and data") # Driver codetestSomeNumbers(10, 3) # This code is contributed by Smitha Dinesh Semwal.
// C# program to verify fermat's last theorem// for a given range and n.using System; class GFG { static void testSomeNumbers(int limit, int n) { if (n < 3) return; for (int a = 1; a <= limit; a++) for (int b = a; b <= limit; b++) { // Check if there exists a triplet // such that a^n + b^n = c^n int pow_sum = (int)(Math.Pow(a, n) + Math.Pow(b, n)); double c = Math.Pow(pow_sum, 1.0 / n); int c_pow = (int)Math.Pow((int)c, n); if (c_pow == pow_sum) { Console.WriteLine("Count example found"); return; } } Console.WriteLine("No counter example within" + " given range and data"); } // Driver code public static void Main () { testSomeNumbers(12, 3); }} // This code is contributed by vt_m.
<?php// PHP program to verify fermat's// last theorem for a given range//and n. function testSomeNumbers($limit, $n){ if ($n < 3) for($a = 1; $a <= $limit; $a++) for($b = $a; $b <= $limit; $b++) { // Check if there exists a triplet // such that a^n + b^n = c^n $pow_sum = pow($a, $n) + pow($b, $n); $c = pow($pow_sum, 1.0 / $n); $c_pow = pow($c, $n); if ($c_pow != $pow_sum) { echo "Count example found"; return; } } echo "No counter example within ". "given range and data";} // Driver Code testSomeNumbers(10, 3); // This code is contributed by m_kit?>
<script> // JavaScript program to verify fermat's last theorem// for a given range and n. function testSomeNumbers(limit, n) { if (n < 3) return; for (let a = 1; a <= limit; a++) for (let b = a; b <= limit; b++) { // Check if there exists a triplet // such that a^n + b^n = c^n let pow_sum = (Math.pow(a, n) + Math.pow(b, n)); let c = Math.pow(pow_sum, 1.0 / n); let c_pow = Math.pow(Math.round(c), n); if (c_pow == pow_sum) { document.write("Count example found"); return; } } document.write("No counter example within given"+ " range and data"); } // Driver Code testSomeNumbers(12, 5); </script>
No counter example within given range and data
Time Complexity: O(m2logn) , where m is the limitAuxiliary Space: O(1)
Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
chinmoy1997pal
codewithmini
number-theory
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Count ways to reach the n'th stair
Fizz Buzz Implementation
Median of two sorted arrays of same size
Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms
Product of Array except itself | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 256,
"s": 53,
"text": "According to Fermat’s Last Theorem, no three positive integers a, b, c satisfy the equation, for any integer value of n greater than 2. For n = 1 and n = 2, the equation have infinitely many solutions. "
},
{
"code": null,
"e": 367,
"s": 256,
"text": "Some solutions for n = 1 are,\n 2 + 3 = 5\n 7 + 13 = 20\n 5 + 6 = 11\n 10 + 9 = 19\n\nSome solutions for n = 2 are,\n"
},
{
"code": null,
"e": 373,
"s": 369,
"text": "C++"
},
{
"code": null,
"e": 378,
"s": 373,
"text": "Java"
},
{
"code": null,
"e": 386,
"s": 378,
"text": "Python3"
},
{
"code": null,
"e": 389,
"s": 386,
"text": "C#"
},
{
"code": null,
"e": 393,
"s": 389,
"text": "PHP"
},
{
"code": null,
"e": 404,
"s": 393,
"text": "Javascript"
},
{
"code": "// C++ program to verify fermat's last theorem// for a given range and n.#include <bits/stdc++.h>using namespace std; void testSomeNumbers(int limit, int n){ if (n < 3) return; for (int a=1; a<=limit; a++) for (int b=a; b<=limit; b++) { // Check if there exists a triplet // such that a^n + b^n = c^n int pow_sum = pow(a, n) + pow(b, n); double c = pow(pow_sum, 1.0/n); int c_pow = pow((int)c, n); if (c_pow == pow_sum) { cout << \"Count example found\"; return; } } cout << \"No counter example within given\" \" range and data\";} // driver codeint main(){ testSomeNumbers(10, 3); return 0;}",
"e": 1123,
"s": 404,
"text": null
},
{
"code": "// Java program to verify fermat's last theorem// for a given range and n.import java.io.*; class GFG{ static void testSomeNumbers(int limit, int n) { if (n < 3) return; for (int a = 1; a <= limit; a++) for (int b = a; b <= limit; b++) { // Check if there exists a triplet // such that a^n + b^n = c^n int pow_sum = (int)(Math.pow(a, n) + Math.pow(b, n)); double c = Math.pow(pow_sum, 1.0 / n); int c_pow = (int)Math.pow((int)c, n); if (c_pow == pow_sum) { System.out.println(\"Count example found\"); return; } } System.out.println(\"No counter example within given\"+ \" range and data\"); } // Driver code public static void main (String[] args) { testSomeNumbers(12, 5); }} // This code is contributed by vt_m.",
"e": 2175,
"s": 1123,
"text": null
},
{
"code": "# Python3 program to verify fermat's last# theorem for a given range and n. def testSomeNumbers(limit, n) : if (n < 3): return for a in range(1, limit + 1): for b in range(a, limit + 1): # Check if there exists a triplet # such that a^n + b^n = c^n pow_sum = pow(a, n) + pow(b, n) c = pow(pow_sum, 1.0 / n) c_pow = pow(int(c), n) if (c_pow == pow_sum): print(\"Count example found\") return print(\"No counter example within given range and data\") # Driver codetestSomeNumbers(10, 3) # This code is contributed by Smitha Dinesh Semwal.",
"e": 2855,
"s": 2175,
"text": null
},
{
"code": "// C# program to verify fermat's last theorem// for a given range and n.using System; class GFG { static void testSomeNumbers(int limit, int n) { if (n < 3) return; for (int a = 1; a <= limit; a++) for (int b = a; b <= limit; b++) { // Check if there exists a triplet // such that a^n + b^n = c^n int pow_sum = (int)(Math.Pow(a, n) + Math.Pow(b, n)); double c = Math.Pow(pow_sum, 1.0 / n); int c_pow = (int)Math.Pow((int)c, n); if (c_pow == pow_sum) { Console.WriteLine(\"Count example found\"); return; } } Console.WriteLine(\"No counter example within\" + \" given range and data\"); } // Driver code public static void Main () { testSomeNumbers(12, 3); }} // This code is contributed by vt_m.",
"e": 3929,
"s": 2855,
"text": null
},
{
"code": "<?php// PHP program to verify fermat's// last theorem for a given range//and n. function testSomeNumbers($limit, $n){ if ($n < 3) for($a = 1; $a <= $limit; $a++) for($b = $a; $b <= $limit; $b++) { // Check if there exists a triplet // such that a^n + b^n = c^n $pow_sum = pow($a, $n) + pow($b, $n); $c = pow($pow_sum, 1.0 / $n); $c_pow = pow($c, $n); if ($c_pow != $pow_sum) { echo \"Count example found\"; return; } } echo \"No counter example within \". \"given range and data\";} // Driver Code testSomeNumbers(10, 3); // This code is contributed by m_kit?>",
"e": 4628,
"s": 3929,
"text": null
},
{
"code": "<script> // JavaScript program to verify fermat's last theorem// for a given range and n. function testSomeNumbers(limit, n) { if (n < 3) return; for (let a = 1; a <= limit; a++) for (let b = a; b <= limit; b++) { // Check if there exists a triplet // such that a^n + b^n = c^n let pow_sum = (Math.pow(a, n) + Math.pow(b, n)); let c = Math.pow(pow_sum, 1.0 / n); let c_pow = Math.pow(Math.round(c), n); if (c_pow == pow_sum) { document.write(\"Count example found\"); return; } } document.write(\"No counter example within given\"+ \" range and data\"); } // Driver Code testSomeNumbers(12, 5); </script>",
"e": 5566,
"s": 4628,
"text": null
},
{
"code": null,
"e": 5613,
"s": 5566,
"text": "No counter example within given range and data"
},
{
"code": null,
"e": 5686,
"s": 5615,
"text": "Time Complexity: O(m2logn) , where m is the limitAuxiliary Space: O(1)"
},
{
"code": null,
"e": 5953,
"s": 5686,
"text": "Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 5959,
"s": 5953,
"text": "jit_t"
},
{
"code": null,
"e": 5974,
"s": 5959,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 5987,
"s": 5974,
"text": "codewithmini"
},
{
"code": null,
"e": 6001,
"s": 5987,
"text": "number-theory"
},
{
"code": null,
"e": 6014,
"s": 6001,
"text": "Mathematical"
},
{
"code": null,
"e": 6028,
"s": 6014,
"text": "number-theory"
},
{
"code": null,
"e": 6041,
"s": 6028,
"text": "Mathematical"
},
{
"code": null,
"e": 6139,
"s": 6041,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6171,
"s": 6139,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 6217,
"s": 6171,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 6261,
"s": 6217,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 6303,
"s": 6261,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 6335,
"s": 6303,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 6370,
"s": 6335,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 6395,
"s": 6370,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 6436,
"s": 6395,
"text": "Median of two sorted arrays of same size"
},
{
"code": null,
"e": 6498,
"s": 6436,
"text": "Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms"
}
] |
Largest connected component on a grid | 17 Dec, 2020
Given a grid with different colors in a different cell, each color represented by a different number. The task is to find out the largest connected component on the grid. Largest component grid refers to a maximum set of cells such that you can move from any cell to any other cell in this set by only moving between side-adjacent cells from the set. Examples:
Input :
Grid of different colors
Output : 9
Largest connected component of grid
Approach : The approach is to visualize the given grid as a graph with each cell representing a separate node of the graph and each node connected to four other nodes which are to immediately up, down, left, and right of that grid. Now doing a BFS search for every node of the graph, find all the nodes connected to the current node with same color value as the current node. Here is the graph for above example :
Graph representation of grid
. At every cell (i, j), a BFS can be done. The possible moves from a cell will be either to right, left, top or bottom. Move to only those cells which are in range and are of the same color. It the same nodes have been visited previously, then the largest component value of the grid is stored in result[][] array. Using memoization, reduce the number of BFS on any cell. visited[][] array is used to mark if the cell has been visited previously and count stores the count of the connected component when a BFS is done for every cell. Store the maximum of the count and print the resultant grid using result[][] array. Below is the illustration of the above approach:
C++
Java
Python3
C#
// CPP program to print the largest// connected component in a grid#include <bits/stdc++.h>using namespace std; const int n = 6;const int m = 8; // stores information about which cell// are already visited in a particular BFSint visited[n][m]; // result stores the final result gridint result[n][m]; // stores the count of cells in the largest// connected componentint COUNT; // Function checks if a cell is valid i.e it// is inside the grid and equal to the keybool is_valid(int x, int y, int key, int input[n][m]){ if (x < n && y < m && x >= 0 && y >= 0) { if (visited[x][y] == false && input[x][y] == key) return true; else return false; } else return false;} // BFS to find all cells in// connection with key = input[i][j]void BFS(int x, int y, int i, int j, int input[n][m]){ // terminating case for BFS if (x != y) return; visited[i][j] = 1; COUNT++; // x_move and y_move arrays // are the possible movements // in x or y direction int x_move[] = { 0, 0, 1, -1 }; int y_move[] = { 1, -1, 0, 0 }; // checks all four points connected with input[i][j] for (int u = 0; u < 4; u++) if (is_valid(i + y_move[u], j + x_move[u], x, input)) BFS(x, y, i + y_move[u], j + x_move[u], input);} // called every time before a BFS// so that visited array is reset to zerovoid reset_visited(){ for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) visited[i][j] = 0;} // If a larger connected component// is found this function is called// to store information about that component.void reset_result(int key, int input[n][m]){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (visited[i][j] && input[i][j] == key) result[i][j] = visited[i][j]; else result[i][j] = 0; } }}// function to print the resultvoid print_result(int res){ cout << "The largest connected " << "component of the grid is :" << res << "\n"; // prints the largest component for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (result[i][j]) cout << result[i][j] << " "; else cout << ". "; } cout << "\n"; }} // function to calculate the largest connected// componentvoid computeLargestConnectedGrid(int input[n][m]){ int current_max = INT_MIN; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { reset_visited(); COUNT = 0; // checking cell to the right if (j + 1 < m) BFS(input[i][j], input[i][j + 1], i, j, input); // updating result if (COUNT >= current_max) { current_max = COUNT; reset_result(input[i][j], input); } reset_visited(); COUNT = 0; // checking cell downwards if (i + 1 < n) BFS(input[i][j], input[i + 1][j], i, j, input); // updating result if (COUNT >= current_max) { current_max = COUNT; reset_result(input[i][j], input); } } } print_result(current_max);}// Drivers Codeint main(){ int input[n][m] = { { 1, 4, 4, 4, 4, 3, 3, 1 }, { 2, 1, 1, 4, 3, 3, 1, 1 }, { 3, 2, 1, 1, 2, 3, 2, 1 }, { 3, 3, 2, 1, 2, 2, 2, 2 }, { 3, 1, 3, 1, 1, 4, 4, 4 }, { 1, 1, 3, 1, 1, 4, 4, 4 } }; // function to compute the largest // connected component in the grid computeLargestConnectedGrid(input); return 0;}
// Java program to print the largest// connected component in a gridimport java.util.*;import java.lang.*;import java.io.*; class GFG{static final int n = 6;static final int m = 8; // stores information about which cell// are already visited in a particular BFSstatic final int visited[][] = new int [n][m]; // result stores the final result gridstatic final int result[][] = new int [n][m]; // stores the count of// cells in the largest// connected componentstatic int COUNT; // Function checks if a cell// is valid i.e it is inside// the grid and equal to the keystatic boolean is_valid(int x, int y, int key, int input[][]){ if (x < n && y < m && x >= 0 && y >= 0) { if (visited[x][y] == 0 && input[x][y] == key) return true; else return false; } else return false;} // BFS to find all cells in// connection with key = input[i][j]static void BFS(int x, int y, int i, int j, int input[][]){ // terminating case for BFS if (x != y) return; visited[i][j] = 1; COUNT++; // x_move and y_move arrays // are the possible movements // in x or y direction int x_move[] = { 0, 0, 1, -1 }; int y_move[] = { 1, -1, 0, 0 }; // checks all four points // connected with input[i][j] for (int u = 0; u < 4; u++) if ((is_valid(i + y_move[u], j + x_move[u], x, input)) == true) BFS(x, y, i + y_move[u], j + x_move[u], input);} // called every time before// a BFS so that visited// array is reset to zerostatic void reset_visited(){ for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) visited[i][j] = 0;} // If a larger connected component// is found this function is// called to store information// about that component.static void reset_result(int key, int input[][]){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (visited[i][j] ==1 && input[i][j] == key) result[i][j] = visited[i][j]; else result[i][j] = 0; } }} // function to print the resultstatic void print_result(int res){ System.out.println ("The largest connected " + "component of the grid is :" + res ); // prints the largest component for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (result[i][j] != 0) System.out.print(result[i][j] + " "); else System.out.print(". "); } System.out.println(); }} // function to calculate the// largest connected componentstatic void computeLargestConnectedGrid(int input[][]){ int current_max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { reset_visited(); COUNT = 0; // checking cell to the right if (j + 1 < m) BFS(input[i][j], input[i][j + 1], i, j, input); // updating result if (COUNT >= current_max) { current_max = COUNT; reset_result(input[i][j], input); } reset_visited(); COUNT = 0; // checking cell downwards if (i + 1 < n) BFS(input[i][j], input[i + 1][j], i, j, input); // updating result if (COUNT >= current_max) { current_max = COUNT; reset_result(input[i][j], input); } } } print_result(current_max);}// Driver Codepublic static void main(String args[]){ int input[][] = {{1, 4, 4, 4, 4, 3, 3, 1}, {2, 1, 1, 4, 3, 3, 1, 1}, {3, 2, 1, 1, 2, 3, 2, 1}, {3, 3, 2, 1, 2, 2, 2, 2}, {3, 1, 3, 1, 1, 4, 4, 4}, {1, 1, 3, 1, 1, 4, 4, 4}}; // function to compute the largest // connected component in the grid computeLargestConnectedGrid(input);}} // This code is contributed by Subhadeep
# Python3 program to print the largest# connected component in a grid n = 6;m = 8; # stores information about which cell# are already visited in a particular BFSvisited = [[0 for j in range(m)]for i in range(n)] # result stores the final result gridresult = [[0 for j in range(m)]for i in range(n)] # stores the count of cells in the largest# connected componentCOUNT = 0 # Function checks if a cell is valid i.e it# is inside the grid and equal to the keydef is_valid(x, y, key, input): if (x < n and y < m and x >= 0 and y >= 0): if (visited[x][y] == 0 and input[x][y] == key): return True; else: return False; else: return False; # BFS to find all cells in# connection with key = input[i][j]def BFS(x, y, i, j, input): global COUNT # terminating case for BFS if (x != y): return; visited[i][j] = 1; COUNT += 1 # x_move and y_move arrays # are the possible movements # in x or y direction x_move = [ 0, 0, 1, -1 ] y_move = [ 1, -1, 0, 0 ] # checks all four points connected with input[i][j] for u in range(4): if (is_valid(i + y_move[u], j + x_move[u], x, input)): BFS(x, y, i + y_move[u], j + x_move[u], input); # called every time before a BFS# so that visited array is reset to zerodef reset_visited(): for i in range(n): for j in range(m): visited[i][j] = 0 # If a larger connected component# is found this function is called# to store information about that component.def reset_result(key, input): for i in range(n): for j in range(m): if (visited[i][j] != 0 and input[i][j] == key): result[i][j] = visited[i][j]; else: result[i][j] = 0; # function to print the resultdef print_result(res): print("The largest connected "+ "component of the grid is :" + str(res)); # prints the largest component for i in range(n): for j in range(m): if (result[i][j] != 0): print(result[i][j], end = ' ') else: print('. ',end = '') print() # function to calculate the largest connected# componentdef computeLargestConnectedGrid(input): global COUNT current_max = -10000000000 for i in range(n): for j in range(m): reset_visited(); COUNT = 0; # checking cell to the right if (j + 1 < m): BFS(input[i][j], input[i][j + 1], i, j, input); # updating result if (COUNT >= current_max): current_max = COUNT; reset_result(input[i][j], input); reset_visited(); COUNT = 0; # checking cell downwards if (i + 1 < n): BFS(input[i][j], input[i + 1][j], i, j, input); # updating result if (COUNT >= current_max): current_max = COUNT; reset_result(input[i][j], input); print_result(current_max); # Drivers Codeif __name__=='__main__': input = [ [ 1, 4, 4, 4, 4, 3, 3, 1 ], [ 2, 1, 1, 4, 3, 3, 1, 1 ], [ 3, 2, 1, 1, 2, 3, 2, 1 ], [ 3, 3, 2, 1, 2, 2, 2, 2 ], [ 3, 1, 3, 1, 1, 4, 4, 4 ], [ 1, 1, 3, 1, 1, 4, 4, 4 ] ]; # function to compute the largest # connected component in the grid computeLargestConnectedGrid(input); # This code is contributed by pratham76
// C# program to print the largest// connected component in a gridusing System; class GFG{public const int n = 6;public const int m = 8; // stores information about which cell// are already visited in a particular BFSpublic static readonly int[][] visited = RectangularArrays.ReturnRectangularIntArray(n, m); // result stores the final result gridpublic static readonly int[][] result = RectangularArrays.ReturnRectangularIntArray(n, m); // stores the count of cells in the// largest connected componentpublic static int COUNT; // Function checks if a cell is valid i.e// it is inside the grid and equal to the keyinternal static bool is_valid(int x, int y, int key, int[][] input){ if (x < n && y < m && x >= 0 && y >= 0) { if (visited[x][y] == 0 && input[x][y] == key) { return true; } else { return false; } } else { return false; }} // BFS to find all cells in// connection with key = input[i][j]public static void BFS(int x, int y, int i, int j, int[][] input){ // terminating case for BFS if (x != y) { return; } visited[i][j] = 1; COUNT++; // x_move and y_move arrays // are the possible movements // in x or y direction int[] x_move = new int[] {0, 0, 1, -1}; int[] y_move = new int[] {1, -1, 0, 0}; // checks all four points // connected with input[i][j] for (int u = 0; u < 4; u++) { if ((is_valid(i + y_move[u], j + x_move[u], x, input)) == true) { BFS(x, y, i + y_move[u], j + x_move[u], input); } }} // called every time before// a BFS so that visited// array is reset to zerointernal static void reset_visited(){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { visited[i][j] = 0; } }} // If a larger connected component is// found this function is called to// store information about that component.internal static void reset_result(int key, int[][] input){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (visited[i][j] == 1 && input[i][j] == key) { result[i][j] = visited[i][j]; } else { result[i][j] = 0; } } }} // function to print the resultinternal static void print_result(int res){ Console.WriteLine("The largest connected " + "component of the grid is :" + res); // prints the largest component for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (result[i][j] != 0) { Console.Write(result[i][j] + " "); } else { Console.Write(". "); } } Console.WriteLine(); }} // function to calculate the// largest connected componentpublic static void computeLargestConnectedGrid(int[][] input){ int current_max = int.MinValue; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { reset_visited(); COUNT = 0; // checking cell to the right if (j + 1 < m) { BFS(input[i][j], input[i][j + 1], i, j, input); } // updating result if (COUNT >= current_max) { current_max = COUNT; reset_result(input[i][j], input); } reset_visited(); COUNT = 0; // checking cell downwards if (i + 1 < n) { BFS(input[i][j], input[i + 1][j], i, j, input); } // updating result if (COUNT >= current_max) { current_max = COUNT; reset_result(input[i][j], input); } } } print_result(current_max);} public static class RectangularArrays{ public static int[][] ReturnRectangularIntArray(int size1, int size2) { int[][] newArray = new int[size1][]; for (int array1 = 0; array1 < size1; array1++) { newArray[array1] = new int[size2]; } return newArray; }} // Driver Codepublic static void Main(string[] args){ int[][] input = new int[][] { new int[] {1, 4, 4, 4, 4, 3, 3, 1}, new int[] {2, 1, 1, 4, 3, 3, 1, 1}, new int[] {3, 2, 1, 1, 2, 3, 2, 1}, new int[] {3, 3, 2, 1, 2, 2, 2, 2}, new int[] {3, 1, 3, 1, 1, 4, 4, 4}, new int[] {1, 1, 3, 1, 1, 4, 4, 4} }; // function to compute the largest // connected component in the grid computeLargestConnectedGrid(input);}}// This code is contributed by Shrikant13
The largest connected component of the grid is :9
. . . . . . . .
. 1 1 . . . . .
. . 1 1 . . . .
. . . 1 . . . .
. . . 1 1 . . .
. . . 1 1 . . .
tufan_gupta2000
shrikanth13
pratham76
Algorithms-Graph Traversals
BFS
Competitive Programming
Graph
Matrix
Pattern Searching
Matrix
Graph
Pattern Searching
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of strings whose prefix match with the given string to a given length k
Most important type of Algorithms
The Ultimate Beginner's Guide For DSA
Find two numbers from their sum and XOR
Equal Sum and XOR of three Numbers
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Graph and its representations | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 415,
"s": 52,
"text": "Given a grid with different colors in a different cell, each color represented by a different number. The task is to find out the largest connected component on the grid. Largest component grid refers to a maximum set of cells such that you can move from any cell to any other cell in this set by only moving between side-adjacent cells from the set. Examples: "
},
{
"code": null,
"e": 425,
"s": 415,
"text": "Input : "
},
{
"code": null,
"e": 450,
"s": 425,
"text": "Grid of different colors"
},
{
"code": null,
"e": 463,
"s": 450,
"text": "Output : 9 "
},
{
"code": null,
"e": 499,
"s": 463,
"text": "Largest connected component of grid"
},
{
"code": null,
"e": 917,
"s": 501,
"text": "Approach : The approach is to visualize the given grid as a graph with each cell representing a separate node of the graph and each node connected to four other nodes which are to immediately up, down, left, and right of that grid. Now doing a BFS search for every node of the graph, find all the nodes connected to the current node with same color value as the current node. Here is the graph for above example : "
},
{
"code": null,
"e": 946,
"s": 917,
"text": "Graph representation of grid"
},
{
"code": null,
"e": 1616,
"s": 946,
"text": ". At every cell (i, j), a BFS can be done. The possible moves from a cell will be either to right, left, top or bottom. Move to only those cells which are in range and are of the same color. It the same nodes have been visited previously, then the largest component value of the grid is stored in result[][] array. Using memoization, reduce the number of BFS on any cell. visited[][] array is used to mark if the cell has been visited previously and count stores the count of the connected component when a BFS is done for every cell. Store the maximum of the count and print the resultant grid using result[][] array. Below is the illustration of the above approach: "
},
{
"code": null,
"e": 1620,
"s": 1616,
"text": "C++"
},
{
"code": null,
"e": 1625,
"s": 1620,
"text": "Java"
},
{
"code": null,
"e": 1633,
"s": 1625,
"text": "Python3"
},
{
"code": null,
"e": 1636,
"s": 1633,
"text": "C#"
},
{
"code": "// CPP program to print the largest// connected component in a grid#include <bits/stdc++.h>using namespace std; const int n = 6;const int m = 8; // stores information about which cell// are already visited in a particular BFSint visited[n][m]; // result stores the final result gridint result[n][m]; // stores the count of cells in the largest// connected componentint COUNT; // Function checks if a cell is valid i.e it// is inside the grid and equal to the keybool is_valid(int x, int y, int key, int input[n][m]){ if (x < n && y < m && x >= 0 && y >= 0) { if (visited[x][y] == false && input[x][y] == key) return true; else return false; } else return false;} // BFS to find all cells in// connection with key = input[i][j]void BFS(int x, int y, int i, int j, int input[n][m]){ // terminating case for BFS if (x != y) return; visited[i][j] = 1; COUNT++; // x_move and y_move arrays // are the possible movements // in x or y direction int x_move[] = { 0, 0, 1, -1 }; int y_move[] = { 1, -1, 0, 0 }; // checks all four points connected with input[i][j] for (int u = 0; u < 4; u++) if (is_valid(i + y_move[u], j + x_move[u], x, input)) BFS(x, y, i + y_move[u], j + x_move[u], input);} // called every time before a BFS// so that visited array is reset to zerovoid reset_visited(){ for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) visited[i][j] = 0;} // If a larger connected component// is found this function is called// to store information about that component.void reset_result(int key, int input[n][m]){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (visited[i][j] && input[i][j] == key) result[i][j] = visited[i][j]; else result[i][j] = 0; } }}// function to print the resultvoid print_result(int res){ cout << \"The largest connected \" << \"component of the grid is :\" << res << \"\\n\"; // prints the largest component for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (result[i][j]) cout << result[i][j] << \" \"; else cout << \". \"; } cout << \"\\n\"; }} // function to calculate the largest connected// componentvoid computeLargestConnectedGrid(int input[n][m]){ int current_max = INT_MIN; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { reset_visited(); COUNT = 0; // checking cell to the right if (j + 1 < m) BFS(input[i][j], input[i][j + 1], i, j, input); // updating result if (COUNT >= current_max) { current_max = COUNT; reset_result(input[i][j], input); } reset_visited(); COUNT = 0; // checking cell downwards if (i + 1 < n) BFS(input[i][j], input[i + 1][j], i, j, input); // updating result if (COUNT >= current_max) { current_max = COUNT; reset_result(input[i][j], input); } } } print_result(current_max);}// Drivers Codeint main(){ int input[n][m] = { { 1, 4, 4, 4, 4, 3, 3, 1 }, { 2, 1, 1, 4, 3, 3, 1, 1 }, { 3, 2, 1, 1, 2, 3, 2, 1 }, { 3, 3, 2, 1, 2, 2, 2, 2 }, { 3, 1, 3, 1, 1, 4, 4, 4 }, { 1, 1, 3, 1, 1, 4, 4, 4 } }; // function to compute the largest // connected component in the grid computeLargestConnectedGrid(input); return 0;}",
"e": 5343,
"s": 1636,
"text": null
},
{
"code": "// Java program to print the largest// connected component in a gridimport java.util.*;import java.lang.*;import java.io.*; class GFG{static final int n = 6;static final int m = 8; // stores information about which cell// are already visited in a particular BFSstatic final int visited[][] = new int [n][m]; // result stores the final result gridstatic final int result[][] = new int [n][m]; // stores the count of// cells in the largest// connected componentstatic int COUNT; // Function checks if a cell// is valid i.e it is inside// the grid and equal to the keystatic boolean is_valid(int x, int y, int key, int input[][]){ if (x < n && y < m && x >= 0 && y >= 0) { if (visited[x][y] == 0 && input[x][y] == key) return true; else return false; } else return false;} // BFS to find all cells in// connection with key = input[i][j]static void BFS(int x, int y, int i, int j, int input[][]){ // terminating case for BFS if (x != y) return; visited[i][j] = 1; COUNT++; // x_move and y_move arrays // are the possible movements // in x or y direction int x_move[] = { 0, 0, 1, -1 }; int y_move[] = { 1, -1, 0, 0 }; // checks all four points // connected with input[i][j] for (int u = 0; u < 4; u++) if ((is_valid(i + y_move[u], j + x_move[u], x, input)) == true) BFS(x, y, i + y_move[u], j + x_move[u], input);} // called every time before// a BFS so that visited// array is reset to zerostatic void reset_visited(){ for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) visited[i][j] = 0;} // If a larger connected component// is found this function is// called to store information// about that component.static void reset_result(int key, int input[][]){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (visited[i][j] ==1 && input[i][j] == key) result[i][j] = visited[i][j]; else result[i][j] = 0; } }} // function to print the resultstatic void print_result(int res){ System.out.println (\"The largest connected \" + \"component of the grid is :\" + res ); // prints the largest component for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (result[i][j] != 0) System.out.print(result[i][j] + \" \"); else System.out.print(\". \"); } System.out.println(); }} // function to calculate the// largest connected componentstatic void computeLargestConnectedGrid(int input[][]){ int current_max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { reset_visited(); COUNT = 0; // checking cell to the right if (j + 1 < m) BFS(input[i][j], input[i][j + 1], i, j, input); // updating result if (COUNT >= current_max) { current_max = COUNT; reset_result(input[i][j], input); } reset_visited(); COUNT = 0; // checking cell downwards if (i + 1 < n) BFS(input[i][j], input[i + 1][j], i, j, input); // updating result if (COUNT >= current_max) { current_max = COUNT; reset_result(input[i][j], input); } } } print_result(current_max);}// Driver Codepublic static void main(String args[]){ int input[][] = {{1, 4, 4, 4, 4, 3, 3, 1}, {2, 1, 1, 4, 3, 3, 1, 1}, {3, 2, 1, 1, 2, 3, 2, 1}, {3, 3, 2, 1, 2, 2, 2, 2}, {3, 1, 3, 1, 1, 4, 4, 4}, {1, 1, 3, 1, 1, 4, 4, 4}}; // function to compute the largest // connected component in the grid computeLargestConnectedGrid(input);}} // This code is contributed by Subhadeep",
"e": 9595,
"s": 5343,
"text": null
},
{
"code": "# Python3 program to print the largest# connected component in a grid n = 6;m = 8; # stores information about which cell# are already visited in a particular BFSvisited = [[0 for j in range(m)]for i in range(n)] # result stores the final result gridresult = [[0 for j in range(m)]for i in range(n)] # stores the count of cells in the largest# connected componentCOUNT = 0 # Function checks if a cell is valid i.e it# is inside the grid and equal to the keydef is_valid(x, y, key, input): if (x < n and y < m and x >= 0 and y >= 0): if (visited[x][y] == 0 and input[x][y] == key): return True; else: return False; else: return False; # BFS to find all cells in# connection with key = input[i][j]def BFS(x, y, i, j, input): global COUNT # terminating case for BFS if (x != y): return; visited[i][j] = 1; COUNT += 1 # x_move and y_move arrays # are the possible movements # in x or y direction x_move = [ 0, 0, 1, -1 ] y_move = [ 1, -1, 0, 0 ] # checks all four points connected with input[i][j] for u in range(4): if (is_valid(i + y_move[u], j + x_move[u], x, input)): BFS(x, y, i + y_move[u], j + x_move[u], input); # called every time before a BFS# so that visited array is reset to zerodef reset_visited(): for i in range(n): for j in range(m): visited[i][j] = 0 # If a larger connected component# is found this function is called# to store information about that component.def reset_result(key, input): for i in range(n): for j in range(m): if (visited[i][j] != 0 and input[i][j] == key): result[i][j] = visited[i][j]; else: result[i][j] = 0; # function to print the resultdef print_result(res): print(\"The largest connected \"+ \"component of the grid is :\" + str(res)); # prints the largest component for i in range(n): for j in range(m): if (result[i][j] != 0): print(result[i][j], end = ' ') else: print('. ',end = '') print() # function to calculate the largest connected# componentdef computeLargestConnectedGrid(input): global COUNT current_max = -10000000000 for i in range(n): for j in range(m): reset_visited(); COUNT = 0; # checking cell to the right if (j + 1 < m): BFS(input[i][j], input[i][j + 1], i, j, input); # updating result if (COUNT >= current_max): current_max = COUNT; reset_result(input[i][j], input); reset_visited(); COUNT = 0; # checking cell downwards if (i + 1 < n): BFS(input[i][j], input[i + 1][j], i, j, input); # updating result if (COUNT >= current_max): current_max = COUNT; reset_result(input[i][j], input); print_result(current_max); # Drivers Codeif __name__=='__main__': input = [ [ 1, 4, 4, 4, 4, 3, 3, 1 ], [ 2, 1, 1, 4, 3, 3, 1, 1 ], [ 3, 2, 1, 1, 2, 3, 2, 1 ], [ 3, 3, 2, 1, 2, 2, 2, 2 ], [ 3, 1, 3, 1, 1, 4, 4, 4 ], [ 1, 1, 3, 1, 1, 4, 4, 4 ] ]; # function to compute the largest # connected component in the grid computeLargestConnectedGrid(input); # This code is contributed by pratham76",
"e": 13202,
"s": 9595,
"text": null
},
{
"code": "// C# program to print the largest// connected component in a gridusing System; class GFG{public const int n = 6;public const int m = 8; // stores information about which cell// are already visited in a particular BFSpublic static readonly int[][] visited = RectangularArrays.ReturnRectangularIntArray(n, m); // result stores the final result gridpublic static readonly int[][] result = RectangularArrays.ReturnRectangularIntArray(n, m); // stores the count of cells in the// largest connected componentpublic static int COUNT; // Function checks if a cell is valid i.e// it is inside the grid and equal to the keyinternal static bool is_valid(int x, int y, int key, int[][] input){ if (x < n && y < m && x >= 0 && y >= 0) { if (visited[x][y] == 0 && input[x][y] == key) { return true; } else { return false; } } else { return false; }} // BFS to find all cells in// connection with key = input[i][j]public static void BFS(int x, int y, int i, int j, int[][] input){ // terminating case for BFS if (x != y) { return; } visited[i][j] = 1; COUNT++; // x_move and y_move arrays // are the possible movements // in x or y direction int[] x_move = new int[] {0, 0, 1, -1}; int[] y_move = new int[] {1, -1, 0, 0}; // checks all four points // connected with input[i][j] for (int u = 0; u < 4; u++) { if ((is_valid(i + y_move[u], j + x_move[u], x, input)) == true) { BFS(x, y, i + y_move[u], j + x_move[u], input); } }} // called every time before// a BFS so that visited// array is reset to zerointernal static void reset_visited(){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { visited[i][j] = 0; } }} // If a larger connected component is// found this function is called to// store information about that component.internal static void reset_result(int key, int[][] input){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (visited[i][j] == 1 && input[i][j] == key) { result[i][j] = visited[i][j]; } else { result[i][j] = 0; } } }} // function to print the resultinternal static void print_result(int res){ Console.WriteLine(\"The largest connected \" + \"component of the grid is :\" + res); // prints the largest component for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (result[i][j] != 0) { Console.Write(result[i][j] + \" \"); } else { Console.Write(\". \"); } } Console.WriteLine(); }} // function to calculate the// largest connected componentpublic static void computeLargestConnectedGrid(int[][] input){ int current_max = int.MinValue; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { reset_visited(); COUNT = 0; // checking cell to the right if (j + 1 < m) { BFS(input[i][j], input[i][j + 1], i, j, input); } // updating result if (COUNT >= current_max) { current_max = COUNT; reset_result(input[i][j], input); } reset_visited(); COUNT = 0; // checking cell downwards if (i + 1 < n) { BFS(input[i][j], input[i + 1][j], i, j, input); } // updating result if (COUNT >= current_max) { current_max = COUNT; reset_result(input[i][j], input); } } } print_result(current_max);} public static class RectangularArrays{ public static int[][] ReturnRectangularIntArray(int size1, int size2) { int[][] newArray = new int[size1][]; for (int array1 = 0; array1 < size1; array1++) { newArray[array1] = new int[size2]; } return newArray; }} // Driver Codepublic static void Main(string[] args){ int[][] input = new int[][] { new int[] {1, 4, 4, 4, 4, 3, 3, 1}, new int[] {2, 1, 1, 4, 3, 3, 1, 1}, new int[] {3, 2, 1, 1, 2, 3, 2, 1}, new int[] {3, 3, 2, 1, 2, 2, 2, 2}, new int[] {3, 1, 3, 1, 1, 4, 4, 4}, new int[] {1, 1, 3, 1, 1, 4, 4, 4} }; // function to compute the largest // connected component in the grid computeLargestConnectedGrid(input);}}// This code is contributed by Shrikant13",
"e": 18196,
"s": 13202,
"text": null
},
{
"code": null,
"e": 18347,
"s": 18196,
"text": "The largest connected component of the grid is :9\n. . . . . . . . \n. 1 1 . . . . . \n. . 1 1 . . . . \n. . . 1 . . . . \n. . . 1 1 . . . \n. . . 1 1 . . ."
},
{
"code": null,
"e": 18365,
"s": 18349,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 18377,
"s": 18365,
"text": "shrikanth13"
},
{
"code": null,
"e": 18387,
"s": 18377,
"text": "pratham76"
},
{
"code": null,
"e": 18415,
"s": 18387,
"text": "Algorithms-Graph Traversals"
},
{
"code": null,
"e": 18419,
"s": 18415,
"text": "BFS"
},
{
"code": null,
"e": 18443,
"s": 18419,
"text": "Competitive Programming"
},
{
"code": null,
"e": 18449,
"s": 18443,
"text": "Graph"
},
{
"code": null,
"e": 18456,
"s": 18449,
"text": "Matrix"
},
{
"code": null,
"e": 18474,
"s": 18456,
"text": "Pattern Searching"
},
{
"code": null,
"e": 18481,
"s": 18474,
"text": "Matrix"
},
{
"code": null,
"e": 18487,
"s": 18481,
"text": "Graph"
},
{
"code": null,
"e": 18505,
"s": 18487,
"text": "Pattern Searching"
},
{
"code": null,
"e": 18509,
"s": 18505,
"text": "BFS"
},
{
"code": null,
"e": 18607,
"s": 18509,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18685,
"s": 18607,
"text": "Count of strings whose prefix match with the given string to a given length k"
},
{
"code": null,
"e": 18719,
"s": 18685,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 18757,
"s": 18719,
"text": "The Ultimate Beginner's Guide For DSA"
},
{
"code": null,
"e": 18797,
"s": 18757,
"text": "Find two numbers from their sum and XOR"
},
{
"code": null,
"e": 18832,
"s": 18797,
"text": "Equal Sum and XOR of three Numbers"
},
{
"code": null,
"e": 18872,
"s": 18832,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 18910,
"s": 18872,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 18961,
"s": 18910,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 19012,
"s": 18961,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
}
] |
Python | Reverse Geocoding to get location on a map using geographic coordinates | 12 Jul, 2021
Reverse geocoding is the process of finding a place or a location address from a given pair of geographic coordinates(latitude and longitude).Modules needed:
reverse_geocoder: A Python library for offline reverse geocoding.
pprint: A module which helps to "pretty-print" any arbitrary python data structure.
Installation: The modules can be easily installed using pip.
pip install reverse_geocoder
pip install pprint
Examples:
Input : (36.778259, -119.417931)
Output :
Loading formatted geocoded file...
[{'admin1': 'California',
'admin2': 'Fresno County',
'cc': 'US',
'lat': '36.72384',
'lon': '-119.45818',
'name': 'Minkler'}]
Input : (28.644800, 77.216721)
Output :
Loading formatted geocoded file...
[{'admin1': 'NCT',
'admin2': 'New Delhi',
'cc': 'IN',
'lat': '28.63576',
'lon': '77.22445',
'name': 'New Delhi'}]
Below is the implementation:
Python3
# Python3 program for reverse geocoding. # importing necessary librariesimport reverse_geocoder as rgimport pprint def reverseGeocode(coordinates): result = rg.search(coordinates) # result is a list containing ordered dictionary. pprint.pprint(result) # Driver functionif __name__=="__main__": # Coordinates tuple.Can contain more than one pair. coordinates =(28.613939, 77.209023) reverseGeocode(coordinates)
Output:
Loading formatted geocoded file...
[{'admin1': 'NCT',
'admin2': 'New Delhi',
'cc': 'IN',
'lat': '28.63576',
'lon': '77.22445',
'name': 'New Delhi'}]
References: https://pypi.org/project/reverse_geocoder/ https://www.latlong.net/
KrithikVaidya
surindertarika1234
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jul, 2021"
},
{
"code": null,
"e": 188,
"s": 28,
"text": "Reverse geocoding is the process of finding a place or a location address from a given pair of geographic coordinates(latitude and longitude).Modules needed: "
},
{
"code": null,
"e": 338,
"s": 188,
"text": "reverse_geocoder: A Python library for offline reverse geocoding.\npprint: A module which helps to \"pretty-print\" any arbitrary python data structure."
},
{
"code": null,
"e": 401,
"s": 338,
"text": "Installation: The modules can be easily installed using pip. "
},
{
"code": null,
"e": 449,
"s": 401,
"text": "pip install reverse_geocoder\npip install pprint"
},
{
"code": null,
"e": 461,
"s": 449,
"text": "Examples: "
},
{
"code": null,
"e": 874,
"s": 461,
"text": "Input : (36.778259, -119.417931)\nOutput : \nLoading formatted geocoded file...\n[{'admin1': 'California',\n 'admin2': 'Fresno County',\n 'cc': 'US',\n 'lat': '36.72384',\n 'lon': '-119.45818',\n 'name': 'Minkler'}]\nInput : (28.644800, 77.216721)\nOutput : \nLoading formatted geocoded file...\n[{'admin1': 'NCT',\n 'admin2': 'New Delhi',\n 'cc': 'IN',\n 'lat': '28.63576',\n 'lon': '77.22445',\n 'name': 'New Delhi'}]"
},
{
"code": null,
"e": 904,
"s": 874,
"text": "Below is the implementation: "
},
{
"code": null,
"e": 912,
"s": 904,
"text": "Python3"
},
{
"code": "# Python3 program for reverse geocoding. # importing necessary librariesimport reverse_geocoder as rgimport pprint def reverseGeocode(coordinates): result = rg.search(coordinates) # result is a list containing ordered dictionary. pprint.pprint(result) # Driver functionif __name__==\"__main__\": # Coordinates tuple.Can contain more than one pair. coordinates =(28.613939, 77.209023) reverseGeocode(coordinates)",
"e": 1355,
"s": 912,
"text": null
},
{
"code": null,
"e": 1365,
"s": 1355,
"text": "Output: "
},
{
"code": null,
"e": 1524,
"s": 1365,
"text": "Loading formatted geocoded file...\n[{'admin1': 'NCT',\n 'admin2': 'New Delhi',\n 'cc': 'IN',\n 'lat': '28.63576',\n 'lon': '77.22445',\n 'name': 'New Delhi'}]"
},
{
"code": null,
"e": 1605,
"s": 1524,
"text": "References: https://pypi.org/project/reverse_geocoder/ https://www.latlong.net/ "
},
{
"code": null,
"e": 1619,
"s": 1605,
"text": "KrithikVaidya"
},
{
"code": null,
"e": 1638,
"s": 1619,
"text": "surindertarika1234"
},
{
"code": null,
"e": 1653,
"s": 1638,
"text": "python-modules"
},
{
"code": null,
"e": 1660,
"s": 1653,
"text": "Python"
},
{
"code": null,
"e": 1758,
"s": 1660,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1776,
"s": 1758,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1818,
"s": 1776,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1840,
"s": 1818,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1875,
"s": 1840,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1901,
"s": 1875,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1933,
"s": 1901,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1962,
"s": 1933,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1992,
"s": 1962,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2019,
"s": 1992,
"text": "Python Classes and Objects"
}
] |
numpy.ndarray.fill() in Python | 28 Dec, 2018
numpy.ndarray.fill() method is used to fill the numpy array with a scalar value.
If we have to initialize a numpy array with an identical value then we use numpy.ndarray.fill(). Suppose we have to create a NumPy array a of length n, each element of which is v. Then we use this function as a.fill(v). We need not use loops to initialize an array if we are using this fill() function.
Syntax : ndarray.fill(value)
Parameters:value : All elements of a will be assigned this value.
Code #1:
# Python program explaining# numpy.ndarray.fill() functionimport numpy as geek a = geek.empty([3, 3]) # Initializing each element of the array# with 1 by using nested loops for i in range(3): for j in range(3): a[i][j] = 1 print("a is : \n", a) # now we are initializing each element# of the array with 1 using fill() function. a.fill(1) print("\nAfter using fill() a is : \n", a)
a is :
[[ 1. 1. 1.]
[ 1. 1. 1.]
[ 1. 1. 1.]]
After using fill() a is :
[[ 1. 1. 1.]
[ 1. 1. 1.]
[ 1. 1. 1.]]
Code #2:
# Python program explaining# numpy.ndarray.fill() functionimport numpy as geek a = geek.arange(5) print("a is \n", a) # Using fill() methoda.fill(0) print("\nNow a is :\n", a)
a is
[0 1 2 3 4]
Now a is :
[0 0 0 0 0]
Code #3: numpy.ndarray.fill() also works on multidimensional array.
# Python program explaining# numpy.ndarray.fill() function import numpy as geek a = geek.empty([3, 3]) # Using fill() methoda.fill(0) print("a is :\n", a)
a is :
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Dec, 2018"
},
{
"code": null,
"e": 109,
"s": 28,
"text": "numpy.ndarray.fill() method is used to fill the numpy array with a scalar value."
},
{
"code": null,
"e": 412,
"s": 109,
"text": "If we have to initialize a numpy array with an identical value then we use numpy.ndarray.fill(). Suppose we have to create a NumPy array a of length n, each element of which is v. Then we use this function as a.fill(v). We need not use loops to initialize an array if we are using this fill() function."
},
{
"code": null,
"e": 441,
"s": 412,
"text": "Syntax : ndarray.fill(value)"
},
{
"code": null,
"e": 507,
"s": 441,
"text": "Parameters:value : All elements of a will be assigned this value."
},
{
"code": null,
"e": 516,
"s": 507,
"text": "Code #1:"
},
{
"code": "# Python program explaining# numpy.ndarray.fill() functionimport numpy as geek a = geek.empty([3, 3]) # Initializing each element of the array# with 1 by using nested loops for i in range(3): for j in range(3): a[i][j] = 1 print(\"a is : \\n\", a) # now we are initializing each element# of the array with 1 using fill() function. a.fill(1) print(\"\\nAfter using fill() a is : \\n\", a) ",
"e": 925,
"s": 516,
"text": null
},
{
"code": null,
"e": 1056,
"s": 925,
"text": "a is : \n [[ 1. 1. 1.]\n [ 1. 1. 1.]\n [ 1. 1. 1.]]\n\nAfter using fill() a is : \n [[ 1. 1. 1.]\n [ 1. 1. 1.]\n [ 1. 1. 1.]]\n"
},
{
"code": null,
"e": 1067,
"s": 1058,
"text": "Code #2:"
},
{
"code": "# Python program explaining# numpy.ndarray.fill() functionimport numpy as geek a = geek.arange(5) print(\"a is \\n\", a) # Using fill() methoda.fill(0) print(\"\\nNow a is :\\n\", a) ",
"e": 1254,
"s": 1067,
"text": null
},
{
"code": null,
"e": 1299,
"s": 1254,
"text": "a is \n [0 1 2 3 4]\n\nNow a is :\n [0 0 0 0 0]\n"
},
{
"code": null,
"e": 1368,
"s": 1299,
"text": " Code #3: numpy.ndarray.fill() also works on multidimensional array."
},
{
"code": "# Python program explaining# numpy.ndarray.fill() function import numpy as geek a = geek.empty([3, 3]) # Using fill() methoda.fill(0) print(\"a is :\\n\", a)",
"e": 1527,
"s": 1368,
"text": null
},
{
"code": null,
"e": 1582,
"s": 1527,
"text": "a is :\n [[ 0. 0. 0.]\n [ 0. 0. 0.]\n [ 0. 0. 0.]]\n"
},
{
"code": null,
"e": 1603,
"s": 1582,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 1616,
"s": 1603,
"text": "Python-numpy"
},
{
"code": null,
"e": 1623,
"s": 1616,
"text": "Python"
},
{
"code": null,
"e": 1721,
"s": 1623,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1739,
"s": 1721,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1781,
"s": 1739,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1803,
"s": 1781,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1838,
"s": 1803,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1864,
"s": 1838,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1896,
"s": 1864,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1925,
"s": 1896,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1952,
"s": 1925,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1982,
"s": 1952,
"text": "Iterate over a list in Python"
}
] |
Python – Replace Substrings from String List | 06 Nov, 2021
Sometimes while working with data, we can have a problem in which we need to perform replace substrings with the mapped string to form a short form of some terms. This kind of problem can have applications in many domains involving data. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + replace() + enumerate() The combination of the above functions can be used to perform this task. In this, we perform the task of iteration using loop and enumerate() and replacement with a shorter form is done using replace().
Python3
# Python3 code to demonstrate# Replace Substrings from String List# using loop + replace() + enumerate() # Initializing list1test_list1 = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']test_list2 = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Replace Substrings from String List# using loop + replace() + enumerate()sub = dict(test_list2)for key, val in sub.items(): for idx, ele in enumerate(test_list1): if key in ele: test_list1[idx] = ele.replace(key, val) # printing resultprint ("The list after replacement : " + str(test_list1))
The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
The original list 2 is : [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
The list after replacement : ['GksforGks', 'is', 'Best', 'For', 'Gks', '&', 'Comp Science']
Method #2 : Using replace() + list comprehension This is another way in which this task can be performed. In this, we perform the task of replacing using the replace(), and the rest of the task is performed using list comprehension. It removes lists that don’t have replacements.
Python3
# Python3 code to demonstrate# Replace Substrings from String List# using replace() + list comprehension # Initializing list1test_list1 = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']test_list2 = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Replace Substrings from String List# using replace() + list comprehensionres = [sub.replace(sub2[0], sub2[1]) for sub in test_list1 for sub2 in test_list2 if sub2[0] in sub] # printing resultprint ("The list after replacement : " + str(res))
The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
The original list 2 is : [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
The list after replacement : ['GksforGks', 'Gks', '&', 'Comp Science']
reenadevi98412200
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Nov, 2021"
},
{
"code": null,
"e": 356,
"s": 54,
"text": "Sometimes while working with data, we can have a problem in which we need to perform replace substrings with the mapped string to form a short form of some terms. This kind of problem can have applications in many domains involving data. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 608,
"s": 356,
"text": "Method #1 : Using loop + replace() + enumerate() The combination of the above functions can be used to perform this task. In this, we perform the task of iteration using loop and enumerate() and replacement with a shorter form is done using replace()."
},
{
"code": null,
"e": 616,
"s": 608,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Replace Substrings from String List# using loop + replace() + enumerate() # Initializing list1test_list1 = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']test_list2 = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Replace Substrings from String List# using loop + replace() + enumerate()sub = dict(test_list2)for key, val in sub.items(): for idx, ele in enumerate(test_list1): if key in ele: test_list1[idx] = ele.replace(key, val) # printing resultprint (\"The list after replacement : \" + str(test_list1))",
"e": 1342,
"s": 616,
"text": null
},
{
"code": null,
"e": 1614,
"s": 1342,
"text": "The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']\nThe original list 2 is : [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]\nThe list after replacement : ['GksforGks', 'is', 'Best', 'For', 'Gks', '&', 'Comp Science']"
},
{
"code": null,
"e": 1896,
"s": 1616,
"text": "Method #2 : Using replace() + list comprehension This is another way in which this task can be performed. In this, we perform the task of replacing using the replace(), and the rest of the task is performed using list comprehension. It removes lists that don’t have replacements."
},
{
"code": null,
"e": 1904,
"s": 1896,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Replace Substrings from String List# using replace() + list comprehension # Initializing list1test_list1 = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']test_list2 = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Replace Substrings from String List# using replace() + list comprehensionres = [sub.replace(sub2[0], sub2[1]) for sub in test_list1 for sub2 in test_list2 if sub2[0] in sub] # printing resultprint (\"The list after replacement : \" + str(res))",
"e": 2563,
"s": 1904,
"text": null
},
{
"code": null,
"e": 2814,
"s": 2563,
"text": "The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']\nThe original list 2 is : [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]\nThe list after replacement : ['GksforGks', 'Gks', '&', 'Comp Science']"
},
{
"code": null,
"e": 2834,
"s": 2816,
"text": "reenadevi98412200"
},
{
"code": null,
"e": 2855,
"s": 2834,
"text": "Python list-programs"
},
{
"code": null,
"e": 2862,
"s": 2855,
"text": "Python"
},
{
"code": null,
"e": 2878,
"s": 2862,
"text": "Python Programs"
},
{
"code": null,
"e": 2976,
"s": 2878,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3018,
"s": 2976,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3040,
"s": 3018,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3072,
"s": 3040,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3101,
"s": 3072,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3128,
"s": 3101,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3150,
"s": 3128,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3189,
"s": 3150,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3227,
"s": 3189,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3276,
"s": 3227,
"text": "Python | Convert string dictionary to dictionary"
}
] |
p5.js | filter() Function | 27 Apr, 2021
The filter() function is used to apply filters to the canvas. p5.js has several presets that can be used with different levels of intensity to get the desired effect.Syntax:
filter( filterType, filterParam)
Parameters: This function accept two parameters as mentioned above and described below:
filterType: It is constant which defines the preset to be used as the filter. It can have the following values: THRESHOLD: This mode is used to convert the image to black and white depending on the threshold defined in the optional level parameter. A level value of 0.0 means that the image would be completely black and a value of 1.0 means that the image would be white. In case no value is specified, 0.5 is used.GRAY: This mode converts all colors in the image to grayscale equivalents. The optional parameter is not used for this preset.OPAQUE: This mode sets the alpha channel of the image to be entirely opaque. The optional parameter is not used for this preset.INVERT: This mode inverts each of the pixels in the image. The optional parameter is not used for this preset.POSTERIZE: This mode limits each channel of the image to the number of colors as specified in the value. The optional parameter can be set in the range of 2 to 255, with the most noticeable effects at the lower color ranges.BLUR: This mode applies a gaussian blur to the image. The optional parameter is used to specify the strength of the blur. If no parameter is specified, then a gaussian blur with a radius of 1 metre is applied.ERODE: This mode reduces the light areas. The optional parameter is not used for this preset.DILATE: This mode increases the light areas. The optional parameter is not used for this preset.
THRESHOLD: This mode is used to convert the image to black and white depending on the threshold defined in the optional level parameter. A level value of 0.0 means that the image would be completely black and a value of 1.0 means that the image would be white. In case no value is specified, 0.5 is used.
GRAY: This mode converts all colors in the image to grayscale equivalents. The optional parameter is not used for this preset.
OPAQUE: This mode sets the alpha channel of the image to be entirely opaque. The optional parameter is not used for this preset.
INVERT: This mode inverts each of the pixels in the image. The optional parameter is not used for this preset.
POSTERIZE: This mode limits each channel of the image to the number of colors as specified in the value. The optional parameter can be set in the range of 2 to 255, with the most noticeable effects at the lower color ranges.
BLUR: This mode applies a gaussian blur to the image. The optional parameter is used to specify the strength of the blur. If no parameter is specified, then a gaussian blur with a radius of 1 metre is applied.
ERODE: This mode reduces the light areas. The optional parameter is not used for this preset.
DILATE: This mode increases the light areas. The optional parameter is not used for this preset.
filterParam: It is a number which is unique to each filter and affects the functionality of the filter. It is an optional parameter.
Below examples illustrate the filter() function in p5.js:Example 1:
javascript
function preload() { img = loadImage("sample-image.png");} function setup() { filterModes = [ GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, DILATE, BLUR, THRESHOLD ]; index = 0; currFilterMode = filterModes[index]; createCanvas(500, 300); textSize(20); btn = createButton("Change filter"); btn.position(30, 200); btn.mousePressed(changeFilter);} function draw() { clear(); text('Click on the button to change the filter mode', 20, 20); text("Current filter: " + currFilterMode, 20, 50); image(img, 20, 80); // Set the filter filter(currFilterMode);} function changeFilter() { if (index < filterModes.length - 1) index++; else index = 0; currFilterMode = filterModes[index]; console.log("Current filter: " + currFilterMode);}
Output:
Example 2:
javascript
let level = 0; function preload() { img = loadImage("sample-image.png");} function setup() { createCanvas(500, 300); textSize(20); valueSlider = createSlider(0, 3, 0, 0.1); valueSlider.position(30, 200); valueSlider.input(changeLevel);} function draw() { clear(); text('Move the slider to change the blur radius', 20, 20); text("Current radius: " + level + "m", 20, 50); image(img, 20, 80); // Set the filter filter(BLUR, level);} function changeLevel() { level = valueSlider.value();}
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/filter
simmytarika5
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
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": "\n27 Apr, 2021"
},
{
"code": null,
"e": 204,
"s": 28,
"text": "The filter() function is used to apply filters to the canvas. p5.js has several presets that can be used with different levels of intensity to get the desired effect.Syntax: "
},
{
"code": null,
"e": 237,
"s": 204,
"text": "filter( filterType, filterParam)"
},
{
"code": null,
"e": 327,
"s": 237,
"text": "Parameters: This function accept two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 1730,
"s": 327,
"text": "filterType: It is constant which defines the preset to be used as the filter. It can have the following values: THRESHOLD: This mode is used to convert the image to black and white depending on the threshold defined in the optional level parameter. A level value of 0.0 means that the image would be completely black and a value of 1.0 means that the image would be white. In case no value is specified, 0.5 is used.GRAY: This mode converts all colors in the image to grayscale equivalents. The optional parameter is not used for this preset.OPAQUE: This mode sets the alpha channel of the image to be entirely opaque. The optional parameter is not used for this preset.INVERT: This mode inverts each of the pixels in the image. The optional parameter is not used for this preset.POSTERIZE: This mode limits each channel of the image to the number of colors as specified in the value. The optional parameter can be set in the range of 2 to 255, with the most noticeable effects at the lower color ranges.BLUR: This mode applies a gaussian blur to the image. The optional parameter is used to specify the strength of the blur. If no parameter is specified, then a gaussian blur with a radius of 1 metre is applied.ERODE: This mode reduces the light areas. The optional parameter is not used for this preset.DILATE: This mode increases the light areas. The optional parameter is not used for this preset."
},
{
"code": null,
"e": 2035,
"s": 1730,
"text": "THRESHOLD: This mode is used to convert the image to black and white depending on the threshold defined in the optional level parameter. A level value of 0.0 means that the image would be completely black and a value of 1.0 means that the image would be white. In case no value is specified, 0.5 is used."
},
{
"code": null,
"e": 2162,
"s": 2035,
"text": "GRAY: This mode converts all colors in the image to grayscale equivalents. The optional parameter is not used for this preset."
},
{
"code": null,
"e": 2291,
"s": 2162,
"text": "OPAQUE: This mode sets the alpha channel of the image to be entirely opaque. The optional parameter is not used for this preset."
},
{
"code": null,
"e": 2402,
"s": 2291,
"text": "INVERT: This mode inverts each of the pixels in the image. The optional parameter is not used for this preset."
},
{
"code": null,
"e": 2627,
"s": 2402,
"text": "POSTERIZE: This mode limits each channel of the image to the number of colors as specified in the value. The optional parameter can be set in the range of 2 to 255, with the most noticeable effects at the lower color ranges."
},
{
"code": null,
"e": 2837,
"s": 2627,
"text": "BLUR: This mode applies a gaussian blur to the image. The optional parameter is used to specify the strength of the blur. If no parameter is specified, then a gaussian blur with a radius of 1 metre is applied."
},
{
"code": null,
"e": 2931,
"s": 2837,
"text": "ERODE: This mode reduces the light areas. The optional parameter is not used for this preset."
},
{
"code": null,
"e": 3028,
"s": 2931,
"text": "DILATE: This mode increases the light areas. The optional parameter is not used for this preset."
},
{
"code": null,
"e": 3161,
"s": 3028,
"text": "filterParam: It is a number which is unique to each filter and affects the functionality of the filter. It is an optional parameter."
},
{
"code": null,
"e": 3230,
"s": 3161,
"text": "Below examples illustrate the filter() function in p5.js:Example 1: "
},
{
"code": null,
"e": 3241,
"s": 3230,
"text": "javascript"
},
{
"code": "function preload() { img = loadImage(\"sample-image.png\");} function setup() { filterModes = [ GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, DILATE, BLUR, THRESHOLD ]; index = 0; currFilterMode = filterModes[index]; createCanvas(500, 300); textSize(20); btn = createButton(\"Change filter\"); btn.position(30, 200); btn.mousePressed(changeFilter);} function draw() { clear(); text('Click on the button to change the filter mode', 20, 20); text(\"Current filter: \" + currFilterMode, 20, 50); image(img, 20, 80); // Set the filter filter(currFilterMode);} function changeFilter() { if (index < filterModes.length - 1) index++; else index = 0; currFilterMode = filterModes[index]; console.log(\"Current filter: \" + currFilterMode);}",
"e": 4026,
"s": 3241,
"text": null
},
{
"code": null,
"e": 4036,
"s": 4026,
"text": "Output: "
},
{
"code": null,
"e": 4049,
"s": 4036,
"text": "Example 2: "
},
{
"code": null,
"e": 4060,
"s": 4049,
"text": "javascript"
},
{
"code": "let level = 0; function preload() { img = loadImage(\"sample-image.png\");} function setup() { createCanvas(500, 300); textSize(20); valueSlider = createSlider(0, 3, 0, 0.1); valueSlider.position(30, 200); valueSlider.input(changeLevel);} function draw() { clear(); text('Move the slider to change the blur radius', 20, 20); text(\"Current radius: \" + level + \"m\", 20, 50); image(img, 20, 80); // Set the filter filter(BLUR, level);} function changeLevel() { level = valueSlider.value();}",
"e": 4563,
"s": 4060,
"text": null
},
{
"code": null,
"e": 4573,
"s": 4563,
"text": "Output: "
},
{
"code": null,
"e": 4760,
"s": 4573,
"text": "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/filter "
},
{
"code": null,
"e": 4773,
"s": 4760,
"text": "simmytarika5"
},
{
"code": null,
"e": 4790,
"s": 4773,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 4801,
"s": 4790,
"text": "JavaScript"
},
{
"code": null,
"e": 4818,
"s": 4801,
"text": "Web Technologies"
},
{
"code": null,
"e": 4916,
"s": 4818,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4977,
"s": 4916,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5049,
"s": 4977,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5089,
"s": 5049,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5142,
"s": 5089,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 5183,
"s": 5142,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 5216,
"s": 5183,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5278,
"s": 5216,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5339,
"s": 5278,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5389,
"s": 5339,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Speech Recognition in Hindi using Python | 17 May, 2022
We can use Python for Speech Recognition, it is mostly used to recognize English words. However, in this article, we are going to use Python so that it can also recognize Hindi words with the help of the Speech Recognition module.
Speech Recognition Module: It is a library with the help of which Python can recognize the command given. We have to use pip for Speech Recognition.
pip install SpeechRecognition
PyAudio Module: It is a set of Python bindings for PortAudio, a cross-platform C++ library interfacing with audio drivers. We need to also install Pyaudio as the Speech Recognition module is dependent on it.
pip install PyAudio
If the above command doesn’t work in windows then use the below commands in the windows command prompt:
pip install pipwin
pipwin install pyaudio
We will use Google Speech Recognition API for letting the software understand Hindi. We will assign language as hn-IN.
Below is the complete Python program to take input commands in Hindi and to recognize them:
Python3
# import required moduleimport speech_recognition as sr # explicit function to take input commands # and recognize themdef takeCommandHindi(): r = sr.Recognizer() with sr.Microphone() as source: # seconds of non-speaking audio before # a phrase is considered complete print('Listening') r.pause_threshold = 0.7 audio = r.listen(source) try: print("Recognizing") Query = r.recognize_google(audio, language='hi-In') # for listening the command in indian english print("the query is printed='", Query, "'") # handling the exception, so that assistant can # ask for telling again the command except Exception as e: print(e) print("Say that again sir") return "None" return Query # Driver Code # call the functiontakeCommandHindi()
Output:
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 May, 2022"
},
{
"code": null,
"e": 284,
"s": 52,
"text": "We can use Python for Speech Recognition, it is mostly used to recognize English words. However, in this article, we are going to use Python so that it can also recognize Hindi words with the help of the Speech Recognition module. "
},
{
"code": null,
"e": 434,
"s": 284,
"text": "Speech Recognition Module: It is a library with the help of which Python can recognize the command given. We have to use pip for Speech Recognition. "
},
{
"code": null,
"e": 465,
"s": 434,
"text": "pip install SpeechRecognition\n"
},
{
"code": null,
"e": 673,
"s": 465,
"text": "PyAudio Module: It is a set of Python bindings for PortAudio, a cross-platform C++ library interfacing with audio drivers. We need to also install Pyaudio as the Speech Recognition module is dependent on it."
},
{
"code": null,
"e": 694,
"s": 673,
"text": "pip install PyAudio\n"
},
{
"code": null,
"e": 798,
"s": 694,
"text": "If the above command doesn’t work in windows then use the below commands in the windows command prompt:"
},
{
"code": null,
"e": 817,
"s": 798,
"text": "pip install pipwin"
},
{
"code": null,
"e": 840,
"s": 817,
"text": "pipwin install pyaudio"
},
{
"code": null,
"e": 959,
"s": 840,
"text": "We will use Google Speech Recognition API for letting the software understand Hindi. We will assign language as hn-IN."
},
{
"code": null,
"e": 1051,
"s": 959,
"text": "Below is the complete Python program to take input commands in Hindi and to recognize them:"
},
{
"code": null,
"e": 1059,
"s": 1051,
"text": "Python3"
},
{
"code": "# import required moduleimport speech_recognition as sr # explicit function to take input commands # and recognize themdef takeCommandHindi(): r = sr.Recognizer() with sr.Microphone() as source: # seconds of non-speaking audio before # a phrase is considered complete print('Listening') r.pause_threshold = 0.7 audio = r.listen(source) try: print(\"Recognizing\") Query = r.recognize_google(audio, language='hi-In') # for listening the command in indian english print(\"the query is printed='\", Query, \"'\") # handling the exception, so that assistant can # ask for telling again the command except Exception as e: print(e) print(\"Say that again sir\") return \"None\" return Query # Driver Code # call the functiontakeCommandHindi()",
"e": 2010,
"s": 1059,
"text": null
},
{
"code": null,
"e": 2018,
"s": 2010,
"text": "Output:"
},
{
"code": null,
"e": 2034,
"s": 2018,
"text": "Python-projects"
},
{
"code": null,
"e": 2049,
"s": 2034,
"text": "python-utility"
},
{
"code": null,
"e": 2056,
"s": 2049,
"text": "Python"
}
] |
uDork – Google Hacking Tool | 23 Sep, 2021
Google Dorking is the technique used for advanced searching. Google Dorking can be beneficial in victim domain detection or collecting some sensitive data from the target domain, This can be done through automated tools which can decrease the time of old-fashioned searching.
uDork is an automated tool developed in the Python language which performs an advanced search for relevant results on the target domain. This search can retrieve the links to admin panels that are not easily discovered, along with this we can get the sensitive files and directories and also the password files through advanced search. This tool contains various modules for dividing the task. uDork tool is available on the GitHub platform, it’s free and open-source to use.
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/m3n0sd0n4ld/uDork
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd uDork
Step 3: Change the permissions of install.sh file by using the following command.
sudo chmod +x uDork.sh
Step 4: Open the file and write inside this line:
mousepad uDork.sh
cookie = ‘YOUR FACEBOOK COOKIES HERE’
Step 5: Launching the tool by using the following command.
./uDork -h
Example 1: Example of searching pdf files
./uDork.sh geeksforgeeks.org -e pdf -p 3
We have got all the PDF files which are available on the http://geeksforgeeks.org domain.
Example 2: Example of searching routes with the word “password”
./uDork.sh geeksforgeeks.org -s password
We have got all the URLs that contain the term Password.
Example 3: Dorks listing
./uDork.sh -l
We are displaying the list of available dorks.
Example 4: Example of use Dorks Massive
./uDork.sh geeksforgeeks.org -g admin -p 3 -o report.txt
In this example, we auDork – Google Hacking Toolre using the admin dork file to get results.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
Introduction to Linux Operating System
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
Array Basics in Shell Scripting | Set 1
chmod command in Linux with examples
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 305,
"s": 28,
"text": "Google Dorking is the technique used for advanced searching. Google Dorking can be beneficial in victim domain detection or collecting some sensitive data from the target domain, This can be done through automated tools which can decrease the time of old-fashioned searching. "
},
{
"code": null,
"e": 781,
"s": 305,
"text": "uDork is an automated tool developed in the Python language which performs an advanced search for relevant results on the target domain. This search can retrieve the links to admin panels that are not easily discovered, along with this we can get the sensitive files and directories and also the password files through advanced search. This tool contains various modules for dividing the task. uDork tool is available on the GitHub platform, it’s free and open-source to use."
},
{
"code": null,
"e": 872,
"s": 781,
"text": "Step 1: Use the following command to install the tool in your Kali Linux operating system."
},
{
"code": null,
"e": 919,
"s": 872,
"text": "git clone https://github.com/m3n0sd0n4ld/uDork"
},
{
"code": null,
"e": 1057,
"s": 919,
"text": "Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool."
},
{
"code": null,
"e": 1066,
"s": 1057,
"text": "cd uDork"
},
{
"code": null,
"e": 1148,
"s": 1066,
"text": "Step 3: Change the permissions of install.sh file by using the following command."
},
{
"code": null,
"e": 1171,
"s": 1148,
"text": "sudo chmod +x uDork.sh"
},
{
"code": null,
"e": 1221,
"s": 1171,
"text": "Step 4: Open the file and write inside this line:"
},
{
"code": null,
"e": 1277,
"s": 1221,
"text": "mousepad uDork.sh\ncookie = ‘YOUR FACEBOOK COOKIES HERE’"
},
{
"code": null,
"e": 1336,
"s": 1277,
"text": "Step 5: Launching the tool by using the following command."
},
{
"code": null,
"e": 1347,
"s": 1336,
"text": "./uDork -h"
},
{
"code": null,
"e": 1389,
"s": 1347,
"text": "Example 1: Example of searching pdf files"
},
{
"code": null,
"e": 1430,
"s": 1389,
"text": "./uDork.sh geeksforgeeks.org -e pdf -p 3"
},
{
"code": null,
"e": 1520,
"s": 1430,
"text": "We have got all the PDF files which are available on the http://geeksforgeeks.org domain."
},
{
"code": null,
"e": 1584,
"s": 1520,
"text": "Example 2: Example of searching routes with the word “password”"
},
{
"code": null,
"e": 1625,
"s": 1584,
"text": "./uDork.sh geeksforgeeks.org -s password"
},
{
"code": null,
"e": 1682,
"s": 1625,
"text": "We have got all the URLs that contain the term Password."
},
{
"code": null,
"e": 1707,
"s": 1682,
"text": "Example 3: Dorks listing"
},
{
"code": null,
"e": 1721,
"s": 1707,
"text": "./uDork.sh -l"
},
{
"code": null,
"e": 1768,
"s": 1721,
"text": "We are displaying the list of available dorks."
},
{
"code": null,
"e": 1808,
"s": 1768,
"text": "Example 4: Example of use Dorks Massive"
},
{
"code": null,
"e": 1865,
"s": 1808,
"text": "./uDork.sh geeksforgeeks.org -g admin -p 3 -o report.txt"
},
{
"code": null,
"e": 1958,
"s": 1865,
"text": "In this example, we auDork – Google Hacking Toolre using the admin dork file to get results."
},
{
"code": null,
"e": 1969,
"s": 1958,
"text": "Kali-Linux"
},
{
"code": null,
"e": 1981,
"s": 1969,
"text": "Linux-Tools"
},
{
"code": null,
"e": 1992,
"s": 1981,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2090,
"s": 1992,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2116,
"s": 2090,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2151,
"s": 2116,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2188,
"s": 2151,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 2227,
"s": 2188,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 2256,
"s": 2227,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 2293,
"s": 2256,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 2327,
"s": 2293,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 2367,
"s": 2327,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 2404,
"s": 2367,
"text": "chmod command in Linux with examples"
}
] |
Java Program to Empty an ArrayList in Java | 14 Dec, 2021
ArrayList class is a resizable array, present in ‘java.util package’. The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an ArrayList without the need to create a new array.
Approaches :
Using clear() method.Using removeAll() method.
Using clear() method.
Using removeAll() method.
Method 1: Using clear() method as the clear() method of ArrayList in Java is used to remove all the elements from an ArrayList. The ArrayList will be completely empty after this call returns.
Syntax:
public void clear() ;
Parameters: clear function takes no parameter
Return Value: This method does not return any value.
Exception: NA
Example:
Java
// Java Program to empty an ArrayList in Java // Illustrating clear functionimport java.util.ArrayList; public class GFG { // Main driver method public static void main(String[] arg) { // Create an empty array list // with an initial capacity of 4 ArrayList<String> numbers = new ArrayList<String>(4); // Use add() method to add elements // in numbers ArrayList numbers.add("10"); numbers.add("20"); numbers.add("30"); numbers.add("40"); // Printing numbers ArrayList System.out.println("Numbers ArrayList : " + numbers); // Finding size of numbers ArrayList int numbers_size = numbers.size(); // Display message System.out.println("Numbers ArrayList consists of: " + numbers_size + " elements"); // Display Message to between changes made in // ArrayList // System.out.println("Performing clear operation by // using clear function"); // Using clear function numbers.clear(); int numbers_size_new = numbers.size(); // Printing new ArrayList System.out.println( "Finally Numbers ArrayList consists of: " + numbers_size_new + " elements"); }}
Numbers ArrayList : [10, 20, 30, 40]
Numbers ArrayList consists of 4 elements
Performing clear operation by using clear function
Finally Numbers ArrayList consists of 0 elements
Method 2: Using removeAll() method as this method of ArrayList class is used to remove from this list all of its elements that are contained in the specified collection.
Syntax:
public boolean removeAll(Collection c) ;
Parameters: This method takes collection c as a parameter containing elements to be removed from this list.
Return Value: This method returns true if this list changed as a result of the call.
Exception/s: This method throws NullPointerException if this list contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null.
Example:
Java
// Java Program to empty an ArrayList in Java// Java code to illustrate removeAll function // Importing ArrayList libraryimport java.util.ArrayList; public class GFG { // Main driver method public static void main(String[] arg) { // Create an empty array list // with an initial capacity of 4 ArrayList<String> numbers = new ArrayList<String>(4); // Using add() method to add elements in numbers // ArrayList numbers.add("10"); numbers.add("20"); numbers.add("30"); numbers.add("40"); // Printing numbers ArrayList System.out.println("Numbers ArrayList : " + numbers); // Finding size of numbers ArrayList int numbers_size = numbers.size(); // Display message System.out.println("Numbers ArrayList consists of " + numbers_size + " elements"); // Display Message System.out.println( "Performing clear operation by using clear function"); // Using removeAll function numbers.removeAll(numbers); // Displaying final ArrayList count of elements int numbers_size_new = numbers.size(); System.out.println( "Finally Numbers ArrayList consists of " + numbers_size_new + " elements"); }}
Numbers ArrayList : [10, 20, 30, 40]
Numbers ArrayList consists of 4 elements
Performing clear operation by using clear function
Finally Numbers ArrayList consists of 0 elements
anikakapoor
Java-ArrayList
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 424,
"s": 28,
"text": "ArrayList class is a resizable array, present in ‘java.util package’. The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an ArrayList without the need to create a new array."
},
{
"code": null,
"e": 437,
"s": 424,
"text": "Approaches :"
},
{
"code": null,
"e": 484,
"s": 437,
"text": "Using clear() method.Using removeAll() method."
},
{
"code": null,
"e": 506,
"s": 484,
"text": "Using clear() method."
},
{
"code": null,
"e": 532,
"s": 506,
"text": "Using removeAll() method."
},
{
"code": null,
"e": 724,
"s": 532,
"text": "Method 1: Using clear() method as the clear() method of ArrayList in Java is used to remove all the elements from an ArrayList. The ArrayList will be completely empty after this call returns."
},
{
"code": null,
"e": 733,
"s": 724,
"text": "Syntax: "
},
{
"code": null,
"e": 755,
"s": 733,
"text": "public void clear() ;"
},
{
"code": null,
"e": 801,
"s": 755,
"text": "Parameters: clear function takes no parameter"
},
{
"code": null,
"e": 854,
"s": 801,
"text": "Return Value: This method does not return any value."
},
{
"code": null,
"e": 868,
"s": 854,
"text": "Exception: NA"
},
{
"code": null,
"e": 877,
"s": 868,
"text": "Example:"
},
{
"code": null,
"e": 882,
"s": 877,
"text": "Java"
},
{
"code": "// Java Program to empty an ArrayList in Java // Illustrating clear functionimport java.util.ArrayList; public class GFG { // Main driver method public static void main(String[] arg) { // Create an empty array list // with an initial capacity of 4 ArrayList<String> numbers = new ArrayList<String>(4); // Use add() method to add elements // in numbers ArrayList numbers.add(\"10\"); numbers.add(\"20\"); numbers.add(\"30\"); numbers.add(\"40\"); // Printing numbers ArrayList System.out.println(\"Numbers ArrayList : \" + numbers); // Finding size of numbers ArrayList int numbers_size = numbers.size(); // Display message System.out.println(\"Numbers ArrayList consists of: \" + numbers_size + \" elements\"); // Display Message to between changes made in // ArrayList // System.out.println(\"Performing clear operation by // using clear function\"); // Using clear function numbers.clear(); int numbers_size_new = numbers.size(); // Printing new ArrayList System.out.println( \"Finally Numbers ArrayList consists of: \" + numbers_size_new + \" elements\"); }}",
"e": 2201,
"s": 882,
"text": null
},
{
"code": null,
"e": 2379,
"s": 2201,
"text": "Numbers ArrayList : [10, 20, 30, 40]\nNumbers ArrayList consists of 4 elements\nPerforming clear operation by using clear function\nFinally Numbers ArrayList consists of 0 elements"
},
{
"code": null,
"e": 2549,
"s": 2379,
"text": "Method 2: Using removeAll() method as this method of ArrayList class is used to remove from this list all of its elements that are contained in the specified collection."
},
{
"code": null,
"e": 2557,
"s": 2549,
"text": "Syntax:"
},
{
"code": null,
"e": 2598,
"s": 2557,
"text": "public boolean removeAll(Collection c) ;"
},
{
"code": null,
"e": 2706,
"s": 2598,
"text": "Parameters: This method takes collection c as a parameter containing elements to be removed from this list."
},
{
"code": null,
"e": 2791,
"s": 2706,
"text": "Return Value: This method returns true if this list changed as a result of the call."
},
{
"code": null,
"e": 2992,
"s": 2791,
"text": "Exception/s: This method throws NullPointerException if this list contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null."
},
{
"code": null,
"e": 3001,
"s": 2992,
"text": "Example:"
},
{
"code": null,
"e": 3006,
"s": 3001,
"text": "Java"
},
{
"code": "// Java Program to empty an ArrayList in Java// Java code to illustrate removeAll function // Importing ArrayList libraryimport java.util.ArrayList; public class GFG { // Main driver method public static void main(String[] arg) { // Create an empty array list // with an initial capacity of 4 ArrayList<String> numbers = new ArrayList<String>(4); // Using add() method to add elements in numbers // ArrayList numbers.add(\"10\"); numbers.add(\"20\"); numbers.add(\"30\"); numbers.add(\"40\"); // Printing numbers ArrayList System.out.println(\"Numbers ArrayList : \" + numbers); // Finding size of numbers ArrayList int numbers_size = numbers.size(); // Display message System.out.println(\"Numbers ArrayList consists of \" + numbers_size + \" elements\"); // Display Message System.out.println( \"Performing clear operation by using clear function\"); // Using removeAll function numbers.removeAll(numbers); // Displaying final ArrayList count of elements int numbers_size_new = numbers.size(); System.out.println( \"Finally Numbers ArrayList consists of \" + numbers_size_new + \" elements\"); }}",
"e": 4357,
"s": 3006,
"text": null
},
{
"code": null,
"e": 4535,
"s": 4357,
"text": "Numbers ArrayList : [10, 20, 30, 40]\nNumbers ArrayList consists of 4 elements\nPerforming clear operation by using clear function\nFinally Numbers ArrayList consists of 0 elements"
},
{
"code": null,
"e": 4547,
"s": 4535,
"text": "anikakapoor"
},
{
"code": null,
"e": 4562,
"s": 4547,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 4567,
"s": 4562,
"text": "Java"
},
{
"code": null,
"e": 4581,
"s": 4567,
"text": "Java Programs"
},
{
"code": null,
"e": 4586,
"s": 4581,
"text": "Java"
}
] |
current_window_handle driver method – Selenium Python | 15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around current_window_handle driver method in Selenium. current_window_handle method returns the handle of the current window.
Syntax –
driver.current_window_handle
Example –Now one can use current_window_handle method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.current_window_handle
To demonstrate, current_window_handle method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get current_window_handle,
Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get current_window_handleprint(driver.current_window_handle)
Output –Screenshot added –
Terminal output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 767,
"s": 28,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc."
},
{
"code": null,
"e": 916,
"s": 767,
"text": "This article revolves around current_window_handle driver method in Selenium. current_window_handle method returns the handle of the current window."
},
{
"code": null,
"e": 925,
"s": 916,
"text": "Syntax –"
},
{
"code": null,
"e": 954,
"s": 925,
"text": "driver.current_window_handle"
},
{
"code": null,
"e": 1038,
"s": 954,
"text": "Example –Now one can use current_window_handle method as a driver method as below –"
},
{
"code": null,
"e": 1112,
"s": 1038,
"text": "diver.get(\"https://www.geeksforgeeks.org/\")\ndriver.current_window_handle\n"
},
{
"code": null,
"e": 1297,
"s": 1112,
"text": "To demonstrate, current_window_handle method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get current_window_handle,"
},
{
"code": null,
"e": 1307,
"s": 1297,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get current_window_handleprint(driver.current_window_handle)",
"e": 1544,
"s": 1307,
"text": null
},
{
"code": null,
"e": 1571,
"s": 1544,
"text": "Output –Screenshot added –"
},
{
"code": null,
"e": 1589,
"s": 1571,
"text": "Terminal output –"
},
{
"code": null,
"e": 1605,
"s": 1589,
"text": "Python-selenium"
},
{
"code": null,
"e": 1614,
"s": 1605,
"text": "selenium"
},
{
"code": null,
"e": 1621,
"s": 1614,
"text": "Python"
}
] |
Simple POST request using the fetch API | 25 May, 2020
The fetch() method, like the XMLHttpRequest and Axios request, is used to send the requests to the server. The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API. You will get the whole Get and Post method using fetch API
Syntax:
fetch(url, { config })
.then(res => {
// Handle response
})
.catch(err => {
// Handle errors
})
fetch(url, { config })
.then(res => {
// Handle response
})
.catch(err => {
// Handle errors
})
Since fetch returns a Promise, we can also use async/await keywords to make requests:async () => {
const resp = await fetch('http://example.com/example.json');
// Handle response
}
async () => {
const resp = await fetch('http://example.com/example.json');
// Handle response
}
Create a POST request using fetch(): The POST request is widely used to submit forms to the server.
fetch(url, { method: 'POST', headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, credentials: 'include', body: 'foo=bar&lorem=ipsum' }) .then(res.json()) .then(res => { // Handle response console.log('Response: ', res); }) .catch(err => { // Handle error console.log('Error message: ', error); });
Explanation:
To create a POST request we need to specify some parameters with the request such as method, headers, etc. First, we need to specify the request method (GET, POST, DELETE, etc.) which is POST in our case. This is followed by the Content-type, which tells the client what the content type of the returned data actually is. The credentials key is optional and should be used if you want to make a fetch request with credentials such as cookies. Then we set the body which consists of the data we wish to pass to the server.
The response of a fetch() request is a stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.
If the API returns a status of 201 (the HTTP status code for Created), the data returned by the API can be accessed- res(response). In case an error occurs, the code inside the catch block will be executed.
Picked
Web Technologies
Web technologies Questions
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Remove elements from a JavaScript Array
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
File uploading in React.js
How to Open URL in New Tab using JavaScript ? | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n25 May, 2020"
},
{
"code": null,
"e": 317,
"s": 53,
"text": "The fetch() method, like the XMLHttpRequest and Axios request, is used to send the requests to the server. The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API. You will get the whole Get and Post method using fetch API"
},
{
"code": null,
"e": 325,
"s": 317,
"text": "Syntax:"
},
{
"code": null,
"e": 437,
"s": 325,
"text": "fetch(url, { config }) \n.then(res => { \n // Handle response \n}) \n.catch(err => { \n // Handle errors \n}) \n"
},
{
"code": null,
"e": 549,
"s": 437,
"text": "fetch(url, { config }) \n.then(res => { \n // Handle response \n}) \n.catch(err => { \n // Handle errors \n}) \n"
},
{
"code": null,
"e": 735,
"s": 549,
"text": "Since fetch returns a Promise, we can also use async/await keywords to make requests:async () => {\n const resp = await fetch('http://example.com/example.json');\n // Handle response\n}\n"
},
{
"code": null,
"e": 836,
"s": 735,
"text": "async () => {\n const resp = await fetch('http://example.com/example.json');\n // Handle response\n}\n"
},
{
"code": null,
"e": 936,
"s": 836,
"text": "Create a POST request using fetch(): The POST request is widely used to submit forms to the server."
},
{
"code": "fetch(url, { method: 'POST', headers: { \"Content-type\": \"application/x-www-form-urlencoded; charset=UTF-8\" }, credentials: 'include', body: 'foo=bar&lorem=ipsum' }) .then(res.json()) .then(res => { // Handle response console.log('Response: ', res); }) .catch(err => { // Handle error console.log('Error message: ', error); });",
"e": 1303,
"s": 936,
"text": null
},
{
"code": null,
"e": 1316,
"s": 1303,
"text": "Explanation:"
},
{
"code": null,
"e": 1838,
"s": 1316,
"text": "To create a POST request we need to specify some parameters with the request such as method, headers, etc. First, we need to specify the request method (GET, POST, DELETE, etc.) which is POST in our case. This is followed by the Content-type, which tells the client what the content type of the returned data actually is. The credentials key is optional and should be used if you want to make a fetch request with credentials such as cookies. Then we set the body which consists of the data we wish to pass to the server."
},
{
"code": null,
"e": 2023,
"s": 1838,
"text": "The response of a fetch() request is a stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously."
},
{
"code": null,
"e": 2230,
"s": 2023,
"text": "If the API returns a status of 201 (the HTTP status code for Created), the data returned by the API can be accessed- res(response). In case an error occurs, the code inside the catch block will be executed."
},
{
"code": null,
"e": 2237,
"s": 2230,
"text": "Picked"
},
{
"code": null,
"e": 2254,
"s": 2237,
"text": "Web Technologies"
},
{
"code": null,
"e": 2281,
"s": 2254,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2297,
"s": 2281,
"text": "Write From Home"
},
{
"code": null,
"e": 2395,
"s": 2297,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2456,
"s": 2395,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2499,
"s": 2456,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2571,
"s": 2499,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2611,
"s": 2571,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2635,
"s": 2611,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2675,
"s": 2635,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2735,
"s": 2675,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2796,
"s": 2735,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 2823,
"s": 2796,
"text": "File uploading in React.js"
}
] |
How to validate Indian driving license number using Regular Expression | 27 Jan, 2021
Given string str, the task is to check whether the given string is a valid Indian driving license number or not by using Regular Expression.The valid Indian driving license number must satisfy the following conditions:
It should be 16 characters long (including space or hyphen (-)).The driving license number can be entered in any of the following formats:
It should be 16 characters long (including space or hyphen (-)).
The driving license number can be entered in any of the following formats:
HR-0619850034761
OR
HR06 19850034761
The first two characters should be upper case alphabets that represent the state code.The next two characters should be digits that represent the RTO code.The next four characters should be digits that represent the license issued year.The next seven characters should be any digits from 0-9.
The first two characters should be upper case alphabets that represent the state code.
The next two characters should be digits that represent the RTO code.
The next four characters should be digits that represent the license issued year.
The next seven characters should be any digits from 0-9.
Note: In this article, we will check the license issued year from 1900-2099. It can be customized to change the license issued year.
Examples:
Input: str = “HR-0619850034761”; Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore, it is not a valid Indian driving license number.
Input: str = “MH27 30120034761”; Output: false Explanation: The given string has the license issued year 3012, that is not a valid year because in this article we validate the year from 1900-2099. Therefore, it is not a valid Indian driving license number.
Input: str = “GJ-2420180”; Output: false Explanation: The given string has 10 characters. Therefore, it is not a valid Indian driving license number.
Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer:
Get the String.
Create a regular expression to check valid Indian driving license number as mentioned below:
regex = “^(([A-Z]{2}[0-9]{2})( )|([A-Z]{2}-[0-9]{2}))((19|20)[0-9][0-9])[0-9]{7}$”;
Where: ^ represents the starting of the string.( represents the starting of group 1.( represents the starting of group 2.[A-Z]{2} represents the first two characters should be upper case alphabets.[0-9]{2} represents the next two characters should be digits.) represents the ending of the group 2.( ) represents the white space character.| represents the or.( represents the starting of group 3.[A-Z]{2} represents the first two characters should be upper case alphabets.– represents the hyphen.[0-9]{2} represents the next two characters should be digits.) represents the ending of the group 3.) represents the ending of the group 1.((19|20)[0-9][0-9]) represents the year from 1900-2099.[0-9]{7} represents the next seven characters should be any digits from 0-9.$ represents the ending of the string.
^ represents the starting of the string.
( represents the starting of group 1.
( represents the starting of group 2.
[A-Z]{2} represents the first two characters should be upper case alphabets.
[0-9]{2} represents the next two characters should be digits.
) represents the ending of the group 2.
( ) represents the white space character.
| represents the or.
( represents the starting of group 3.
[A-Z]{2} represents the first two characters should be upper case alphabets.
– represents the hyphen.
[0-9]{2} represents the next two characters should be digits.
) represents the ending of the group 3.
) represents the ending of the group 1.
((19|20)[0-9][0-9]) represents the year from 1900-2099.
[0-9]{7} represents the next seven characters should be any digits from 0-9.
$ represents the ending of the string.
Match the given string with the Regular Expression, In Java, this can be done by using Pattern.matcher().
Return true if the string matches with the given regular expression, else return false.
Below is the implementation of the above approach:
Java
Python3
C++
// Java program to validate// Indian driving license number// using regular expression import java.util.regex.*;class GFG { // Function to validate // Indian driving license number // using regular expression public static boolean isValidLicenseNo(String str) { // Regex to check valid // Indian driving license number String regex = "^(([A-Z]{2}[0-9]{2})" + "( )|([A-Z]{2}-[0-9]" + "{2}))((19|20)[0-9]" + "[0-9])[0-9]{7}$"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Find match between given string // and regular expression // uSing Pattern.matcher() Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { // Test Case 1: String str1 = "HR-0619850034761"; System.out.println(isValidLicenseNo(str1)); // Test Case 2: String str2 = "UP14 20160034761"; System.out.println(isValidLicenseNo(str2)); // Test Case 3: String str3 = "12HR-37200602347"; System.out.println(isValidLicenseNo(str3)); // Test Case 4: String str4 = "MH27 30123476102"; System.out.println(isValidLicenseNo(str4)); // Test Case 5: String str5 = "GJ-2420180"; System.out.println(isValidLicenseNo(str5)); }}
# Python program to validate# Indian driving license number# using regular expression import re # Function to validate Indian# driving license number.def isValidLicenseNo(str): # Regex to check valid # Indian driving license number regex = ("^(([A-Z]{2}[0-9]{2})" + "( )|([A-Z]{2}-[0-9]" + "{2}))((19|20)[0-9]" + "[0-9])[0-9]{7}$") # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = "HR-0619850034761"print(isValidLicenseNo(str1)) # Test Case 2:str2 = "UP14 20160034761"print(isValidLicenseNo(str2)) # Test Case 3:str3 = "12HR-37200602347"print(isValidLicenseNo(str3)) # Test Case 4:str4 = "MH27 30123476102"print(isValidLicenseNo(str4)) # Test Case 5:str5 = "GJ-2420180"print(isValidLicenseNo(str5)) # This code is contributed by avanitrachhadiya2155
// C++ program to validate the// Indian driving license number// using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the// Indian driving license numberbool isValidLicenseNo(string str){ // Regex to check valid // Indian driving license number const regex pattern("^(([A-Z]{2}[0-9]{2})( " ")|([A-Z]{2}-[0-9]{2}))" "((19|20)[0-" "9][0-9])[0-9]{7}$"); // If the Indian driving // license number is empty return false if (str.empty()) { return false; } // Return true if the Indian // driving license number // matched the ReGex if (regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = "HR-0619850034761"; cout << isValidLicenseNo(str1) << endl; // Test Case 2: string str2 = "UP14 20160034761"; cout << isValidLicenseNo(str2) << endl; // Test Case 3: string str3 = "12HR-37200602347"; cout << isValidLicenseNo(str3) << endl; // Test Case 4: string str4 = "MH27 30123476102"; cout << isValidLicenseNo(str4) << endl; // Test Case 5: string str5 = "GJ-2420180"; cout << isValidLicenseNo(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra
true
true
false
false
false
avanitrachhadiya2155
yuvraj_chandra
CPP-regex
java-regular-expression
regular-expression
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jan, 2021"
},
{
"code": null,
"e": 248,
"s": 28,
"text": "Given string str, the task is to check whether the given string is a valid Indian driving license number or not by using Regular Expression.The valid Indian driving license number must satisfy the following conditions: "
},
{
"code": null,
"e": 387,
"s": 248,
"text": "It should be 16 characters long (including space or hyphen (-)).The driving license number can be entered in any of the following formats:"
},
{
"code": null,
"e": 452,
"s": 387,
"text": "It should be 16 characters long (including space or hyphen (-))."
},
{
"code": null,
"e": 527,
"s": 452,
"text": "The driving license number can be entered in any of the following formats:"
},
{
"code": null,
"e": 566,
"s": 527,
"text": "HR-0619850034761\n OR \nHR06 19850034761"
},
{
"code": null,
"e": 859,
"s": 566,
"text": "The first two characters should be upper case alphabets that represent the state code.The next two characters should be digits that represent the RTO code.The next four characters should be digits that represent the license issued year.The next seven characters should be any digits from 0-9."
},
{
"code": null,
"e": 946,
"s": 859,
"text": "The first two characters should be upper case alphabets that represent the state code."
},
{
"code": null,
"e": 1016,
"s": 946,
"text": "The next two characters should be digits that represent the RTO code."
},
{
"code": null,
"e": 1098,
"s": 1016,
"text": "The next four characters should be digits that represent the license issued year."
},
{
"code": null,
"e": 1155,
"s": 1098,
"text": "The next seven characters should be any digits from 0-9."
},
{
"code": null,
"e": 1288,
"s": 1155,
"text": "Note: In this article, we will check the license issued year from 1900-2099. It can be customized to change the license issued year."
},
{
"code": null,
"e": 1298,
"s": 1288,
"text": "Examples:"
},
{
"code": null,
"e": 1480,
"s": 1298,
"text": "Input: str = “HR-0619850034761”; Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore, it is not a valid Indian driving license number."
},
{
"code": null,
"e": 1737,
"s": 1480,
"text": "Input: str = “MH27 30120034761”; Output: false Explanation: The given string has the license issued year 3012, that is not a valid year because in this article we validate the year from 1900-2099. Therefore, it is not a valid Indian driving license number."
},
{
"code": null,
"e": 1889,
"s": 1737,
"text": "Input: str = “GJ-2420180”; Output: false Explanation: The given string has 10 characters. Therefore, it is not a valid Indian driving license number. "
},
{
"code": null,
"e": 2020,
"s": 1889,
"text": "Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer: "
},
{
"code": null,
"e": 2036,
"s": 2020,
"text": "Get the String."
},
{
"code": null,
"e": 2129,
"s": 2036,
"text": "Create a regular expression to check valid Indian driving license number as mentioned below:"
},
{
"code": null,
"e": 2214,
"s": 2129,
"text": "regex = “^(([A-Z]{2}[0-9]{2})( )|([A-Z]{2}-[0-9]{2}))((19|20)[0-9][0-9])[0-9]{7}$”; "
},
{
"code": null,
"e": 3018,
"s": 2214,
"text": "Where: ^ represents the starting of the string.( represents the starting of group 1.( represents the starting of group 2.[A-Z]{2} represents the first two characters should be upper case alphabets.[0-9]{2} represents the next two characters should be digits.) represents the ending of the group 2.( ) represents the white space character.| represents the or.( represents the starting of group 3.[A-Z]{2} represents the first two characters should be upper case alphabets.– represents the hyphen.[0-9]{2} represents the next two characters should be digits.) represents the ending of the group 3.) represents the ending of the group 1.((19|20)[0-9][0-9]) represents the year from 1900-2099.[0-9]{7} represents the next seven characters should be any digits from 0-9.$ represents the ending of the string."
},
{
"code": null,
"e": 3059,
"s": 3018,
"text": "^ represents the starting of the string."
},
{
"code": null,
"e": 3097,
"s": 3059,
"text": "( represents the starting of group 1."
},
{
"code": null,
"e": 3135,
"s": 3097,
"text": "( represents the starting of group 2."
},
{
"code": null,
"e": 3212,
"s": 3135,
"text": "[A-Z]{2} represents the first two characters should be upper case alphabets."
},
{
"code": null,
"e": 3274,
"s": 3212,
"text": "[0-9]{2} represents the next two characters should be digits."
},
{
"code": null,
"e": 3314,
"s": 3274,
"text": ") represents the ending of the group 2."
},
{
"code": null,
"e": 3356,
"s": 3314,
"text": "( ) represents the white space character."
},
{
"code": null,
"e": 3377,
"s": 3356,
"text": "| represents the or."
},
{
"code": null,
"e": 3415,
"s": 3377,
"text": "( represents the starting of group 3."
},
{
"code": null,
"e": 3492,
"s": 3415,
"text": "[A-Z]{2} represents the first two characters should be upper case alphabets."
},
{
"code": null,
"e": 3517,
"s": 3492,
"text": "– represents the hyphen."
},
{
"code": null,
"e": 3579,
"s": 3517,
"text": "[0-9]{2} represents the next two characters should be digits."
},
{
"code": null,
"e": 3619,
"s": 3579,
"text": ") represents the ending of the group 3."
},
{
"code": null,
"e": 3659,
"s": 3619,
"text": ") represents the ending of the group 1."
},
{
"code": null,
"e": 3715,
"s": 3659,
"text": "((19|20)[0-9][0-9]) represents the year from 1900-2099."
},
{
"code": null,
"e": 3792,
"s": 3715,
"text": "[0-9]{7} represents the next seven characters should be any digits from 0-9."
},
{
"code": null,
"e": 3831,
"s": 3792,
"text": "$ represents the ending of the string."
},
{
"code": null,
"e": 3937,
"s": 3831,
"text": "Match the given string with the Regular Expression, In Java, this can be done by using Pattern.matcher()."
},
{
"code": null,
"e": 4025,
"s": 3937,
"text": "Return true if the string matches with the given regular expression, else return false."
},
{
"code": null,
"e": 4076,
"s": 4025,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 4081,
"s": 4076,
"text": "Java"
},
{
"code": null,
"e": 4089,
"s": 4081,
"text": "Python3"
},
{
"code": null,
"e": 4093,
"s": 4089,
"text": "C++"
},
{
"code": "// Java program to validate// Indian driving license number// using regular expression import java.util.regex.*;class GFG { // Function to validate // Indian driving license number // using regular expression public static boolean isValidLicenseNo(String str) { // Regex to check valid // Indian driving license number String regex = \"^(([A-Z]{2}[0-9]{2})\" + \"( )|([A-Z]{2}-[0-9]\" + \"{2}))((19|20)[0-9]\" + \"[0-9])[0-9]{7}$\"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Find match between given string // and regular expression // uSing Pattern.matcher() Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { // Test Case 1: String str1 = \"HR-0619850034761\"; System.out.println(isValidLicenseNo(str1)); // Test Case 2: String str2 = \"UP14 20160034761\"; System.out.println(isValidLicenseNo(str2)); // Test Case 3: String str3 = \"12HR-37200602347\"; System.out.println(isValidLicenseNo(str3)); // Test Case 4: String str4 = \"MH27 30123476102\"; System.out.println(isValidLicenseNo(str4)); // Test Case 5: String str5 = \"GJ-2420180\"; System.out.println(isValidLicenseNo(str5)); }}",
"e": 5694,
"s": 4093,
"text": null
},
{
"code": "# Python program to validate# Indian driving license number# using regular expression import re # Function to validate Indian# driving license number.def isValidLicenseNo(str): # Regex to check valid # Indian driving license number regex = (\"^(([A-Z]{2}[0-9]{2})\" + \"( )|([A-Z]{2}-[0-9]\" + \"{2}))((19|20)[0-9]\" + \"[0-9])[0-9]{7}$\") # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = \"HR-0619850034761\"print(isValidLicenseNo(str1)) # Test Case 2:str2 = \"UP14 20160034761\"print(isValidLicenseNo(str2)) # Test Case 3:str3 = \"12HR-37200602347\"print(isValidLicenseNo(str3)) # Test Case 4:str4 = \"MH27 30123476102\"print(isValidLicenseNo(str4)) # Test Case 5:str5 = \"GJ-2420180\"print(isValidLicenseNo(str5)) # This code is contributed by avanitrachhadiya2155",
"e": 6741,
"s": 5694,
"text": null
},
{
"code": "// C++ program to validate the// Indian driving license number// using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the// Indian driving license numberbool isValidLicenseNo(string str){ // Regex to check valid // Indian driving license number const regex pattern(\"^(([A-Z]{2}[0-9]{2})( \" \")|([A-Z]{2}-[0-9]{2}))\" \"((19|20)[0-\" \"9][0-9])[0-9]{7}$\"); // If the Indian driving // license number is empty return false if (str.empty()) { return false; } // Return true if the Indian // driving license number // matched the ReGex if (regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = \"HR-0619850034761\"; cout << isValidLicenseNo(str1) << endl; // Test Case 2: string str2 = \"UP14 20160034761\"; cout << isValidLicenseNo(str2) << endl; // Test Case 3: string str3 = \"12HR-37200602347\"; cout << isValidLicenseNo(str3) << endl; // Test Case 4: string str4 = \"MH27 30123476102\"; cout << isValidLicenseNo(str4) << endl; // Test Case 5: string str5 = \"GJ-2420180\"; cout << isValidLicenseNo(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra",
"e": 8112,
"s": 6741,
"text": null
},
{
"code": null,
"e": 8141,
"s": 8112,
"text": "true\ntrue\nfalse\nfalse\nfalse\n"
},
{
"code": null,
"e": 8162,
"s": 8141,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 8177,
"s": 8162,
"text": "yuvraj_chandra"
},
{
"code": null,
"e": 8187,
"s": 8177,
"text": "CPP-regex"
},
{
"code": null,
"e": 8211,
"s": 8187,
"text": "java-regular-expression"
},
{
"code": null,
"e": 8230,
"s": 8211,
"text": "regular-expression"
},
{
"code": null,
"e": 8248,
"s": 8230,
"text": "Pattern Searching"
},
{
"code": null,
"e": 8256,
"s": 8248,
"text": "Strings"
},
{
"code": null,
"e": 8264,
"s": 8256,
"text": "Strings"
},
{
"code": null,
"e": 8282,
"s": 8264,
"text": "Pattern Searching"
}
] |
Node.js path.normalize() Method | 13 Oct, 2021
The path.normalize() method is used to normalize the given path. Normalization resolves the (.) and (..) segments of the path to their correct form. If the method encounters multiple path separators, it replaces all of them by a single platform-specific path separator. This method preserves all trailing separators.
Syntax:
path.normalize( path )
Parameters: This method accepts single parameter path which holds the file path that would be normalized. A TypeError is thrown if this parameter is not a string.
Return Value: It returns a string with the normalized form of the path.
Below example illustrates the path.normalize() method in node.js:
Example:
// Node.js program to demonstrate the // path.normalize() method // Import the path moduleconst path = require('path'); path1 = path.normalize("/users/admin/.");console.log(path1) path2 = path.normalize("/users/admin/..");console.log(path2) path3 = path.normalize("/users/admin/../comments")console.log(path3); path4 = path.normalize("/users///admin///comments")console.log(path4);
Output:
\users\admin
\users
\users\comments
\users\admin\comments
Reference: https://nodejs.org/api/path.html#path_path_normalize_path
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
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 ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 345,
"s": 28,
"text": "The path.normalize() method is used to normalize the given path. Normalization resolves the (.) and (..) segments of the path to their correct form. If the method encounters multiple path separators, it replaces all of them by a single platform-specific path separator. This method preserves all trailing separators."
},
{
"code": null,
"e": 353,
"s": 345,
"text": "Syntax:"
},
{
"code": null,
"e": 376,
"s": 353,
"text": "path.normalize( path )"
},
{
"code": null,
"e": 539,
"s": 376,
"text": "Parameters: This method accepts single parameter path which holds the file path that would be normalized. A TypeError is thrown if this parameter is not a string."
},
{
"code": null,
"e": 611,
"s": 539,
"text": "Return Value: It returns a string with the normalized form of the path."
},
{
"code": null,
"e": 677,
"s": 611,
"text": "Below example illustrates the path.normalize() method in node.js:"
},
{
"code": null,
"e": 686,
"s": 677,
"text": "Example:"
},
{
"code": "// Node.js program to demonstrate the // path.normalize() method // Import the path moduleconst path = require('path'); path1 = path.normalize(\"/users/admin/.\");console.log(path1) path2 = path.normalize(\"/users/admin/..\");console.log(path2) path3 = path.normalize(\"/users/admin/../comments\")console.log(path3); path4 = path.normalize(\"/users///admin///comments\")console.log(path4);",
"e": 1079,
"s": 686,
"text": null
},
{
"code": null,
"e": 1087,
"s": 1079,
"text": "Output:"
},
{
"code": null,
"e": 1145,
"s": 1087,
"text": "\\users\\admin\n\\users\n\\users\\comments\n\\users\\admin\\comments"
},
{
"code": null,
"e": 1214,
"s": 1145,
"text": "Reference: https://nodejs.org/api/path.html#path_path_normalize_path"
},
{
"code": null,
"e": 1230,
"s": 1214,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 1238,
"s": 1230,
"text": "Node.js"
},
{
"code": null,
"e": 1255,
"s": 1238,
"text": "Web Technologies"
},
{
"code": null,
"e": 1353,
"s": 1255,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1401,
"s": 1353,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 1434,
"s": 1401,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 1464,
"s": 1434,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 1484,
"s": 1464,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 1538,
"s": 1484,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 1600,
"s": 1538,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1661,
"s": 1600,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1711,
"s": 1661,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 1754,
"s": 1711,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Practice Questions for Recursion | Set 4 | 21 Jun, 2022
Question 1 Predict the output of the following program.
C++
C
Java
Python3
C#
Javascript
#include <iostream>using namespace std; void fun(int x){ if(x > 0) { fun(--x); cout << x <<" "; fun(--x); }} int main(){ int a = 4; fun(a); return 0;} // This code is contributed by SHUBHAMSINGH10
#include<stdio.h>void fun(int x){ if(x > 0) { fun(--x); printf("%d\t", x); fun(--x); }} int main(){ int a = 4; fun(a); getchar(); return 0;}
import java.io.*; class GFG { static void fun(int x) { if(x > 0) { fun(--x); System.out.print(x + " "); fun(--x); } } public static void main (String[] args) { int a = 4; fun(a); }} // This code is contributed by SHUBHAMSINGH10
def fun(x): if(x > 0): x -= 1 fun(x) print(x , end=" ") x -= 1 fun(x) # Driver codea = 4fun(a) # This code is contributed by SHUBHAMSINGH10
using System; class GFG{ static void fun(int x) { if(x > 0) { fun(--x); Console.Write(x + " "); fun(--x); } } static public void Main () { int a = 4; fun(a); }}// This code is contributed by SHUBHAMSINGH10
<script> function fun(x){ if (x > 0) { x -= 1 fun(x) document.write(x + " "); x -= 1 fun(x) } } // Driver codelet a = 4;fun(a) // This code is contributed by bobby </script>
0 1 2 0 3 0 1
Time complexity: O(2n)
Auxiliary Space: O(n)
fun(4);
/
fun(3), print(3), fun(2)(prints 0 1)
/
fun(2), print(2), fun(1)(prints 0)
/
fun(1), print(1), fun(0)(does nothing)
/
fun(0), print(0), fun(-1) (does nothing)
Question 2 Predict the output of the following program. What does the following fun() do in general?
C++
C
Java
Python3
C#
Javascript
#include <iostream>using namespace std; int fun(int a[],int n){ int x; if(n == 1) return a[0]; else x = fun(a, n - 1); if(x > a[n - 1]) return x; else return a[n - 1];} int main(){ int arr[] = {12, 10, 30, 50, 100}; cout << " " << fun(arr, 5) <<" "; getchar(); return 0;} // This code is contributed by shubhamsingh10
#include<stdio.h>int fun(int a[],int n){ int x; if(n == 1) return a[0]; else x = fun(a, n-1); if(x > a[n-1]) return x; else return a[n-1];} int main(){ int arr[] = {12, 10, 30, 50, 100}; printf(" %d ", fun(arr, 5)); getchar(); return 0;}
import java.io.*; class GFG { static int fun(int a[],int n) { int x; if(n == 1) return a[0]; else x = fun(a, n - 1); if(x > a[n - 1]) return x; else return a[n - 1]; } public static void main (String[] args) { int arr[] = {12, 10, 30, 50, 100}; System.out.println(" "+fun(arr, 5)+" "); }} // This code is contributed by shubhamsingh10
def fun( a, n): if(n == 1): return a[0] else: x = fun(a, n - 1) if(x > a[n - 1]): return x else: return a[n - 1] # Driver codearr = [12, 10, 30, 50, 100]print(fun(arr, 5)) # This code is contributed by shubhamsingh10
using System; public class GFG{ static int fun(int[] a,int n) { int x; if(n == 1) return a[0]; else x = fun(a, n - 1); if(x > a[n - 1]) return x; else return a[n - 1]; } static public void Main () { int[] arr = {12, 10, 30, 50, 100}; Console.Write(" "+fun(arr, 5)+" "); }} // This code is contributed by shubhamsingh10
<script>//Javascript Implementation function fun(a, n){ var x; if(n == 1) return a[0]; else x = fun(a, n - 1); if(x > a[n - 1]) return x; else return a[n - 1];} // Driver codevar arr = [12, 10, 30, 50, 100];document.write(fun(arr, 5));// This code is contributed by shubhamsingh10</script>
100
Time complexity: O(n)
Auxiliary Space: O(n)
fun() returns the maximum value in the input array a[] of size n.
Question 3 Predict the output of the following program. What does the following fun() do in general?
C++
C
Java
Python3
C#
Javascript
#include <iostream>using namespace std; int fun(int i){ if (i % 2) return (i++); else return fun(fun(i - 1));} int main(){ cout << " " << fun(200) << " "; getchar(); return 0;} // This code is contributed by Shubhamsingh10
int fun(int i){ if ( i%2 ) return (i++); else return fun(fun( i - 1 ));} int main(){ printf(" %d ", fun(200)); getchar(); return 0;}
import java.io.*; class GFG { static int fun(int i) { if (i % 2 == 1) return (i++); else return fun(fun(i - 1)); } public static void main (String[] args) { System.out.println(" " + fun(200) + " "); }} // This code is contributed by Shubhamsingh10
def fun(i) : if (i % 2 == 1) : i += 1 return (i - 1) else : return fun(fun(i - 1)) print(fun(200)) # This code is contributed by divyeshrabadiya07
using System; class GFG{ static int fun(int i){ if (i % 2 == 1) return (i++); else return fun(fun(i - 1));} // Driver code static public void Main (){ Console.WriteLine(fun(200));}} // This code is contributed by Shubhamsingh10
<script> function fun(i){ if (i % 2 == 1) return (i++); else return fun(fun(i - 1));} // Driver codedocument.write(fun(200)); // This code is contributed by bobby </script>
199
If n is odd, then return n, else returns (n-1). Eg., for n = 12, you get 11 and for n = 11 you get 11. The statement “return i++;” returns the value of i only as it is a post-increment.
Time complexity: O(n)
Auxiliary Space: O(1)
Please write comments if you find any of the answers/codes incorrect, or you want to share more information/questions about the topics discussed above.
SHUBHAMSINGH10
divyeshrabadiya07
gottumukkalabobby
geekygirl2001
Misc
Recursion
Misc
Recursion
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Virtualization In Cloud Computing and Types
How to write Regular Expressions?
OOPs | Object Oriented Design
Association Rule
Software Engineering | Prototyping Model
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Program for Tower of Hanoi
Backtracking | Introduction
Print all subsequences of a string | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 111,
"s": 54,
"text": "Question 1 Predict the output of the following program. "
},
{
"code": null,
"e": 115,
"s": 111,
"text": "C++"
},
{
"code": null,
"e": 117,
"s": 115,
"text": "C"
},
{
"code": null,
"e": 122,
"s": 117,
"text": "Java"
},
{
"code": null,
"e": 130,
"s": 122,
"text": "Python3"
},
{
"code": null,
"e": 133,
"s": 130,
"text": "C#"
},
{
"code": null,
"e": 144,
"s": 133,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; void fun(int x){ if(x > 0) { fun(--x); cout << x <<\" \"; fun(--x); }} int main(){ int a = 4; fun(a); return 0;} // This code is contributed by SHUBHAMSINGH10",
"e": 380,
"s": 144,
"text": null
},
{
"code": "#include<stdio.h>void fun(int x){ if(x > 0) { fun(--x); printf(\"%d\\t\", x); fun(--x); }} int main(){ int a = 4; fun(a); getchar(); return 0;}",
"e": 540,
"s": 380,
"text": null
},
{
"code": "import java.io.*; class GFG { static void fun(int x) { if(x > 0) { fun(--x); System.out.print(x + \" \"); fun(--x); } } public static void main (String[] args) { int a = 4; fun(a); }} // This code is contributed by SHUBHAMSINGH10",
"e": 860,
"s": 540,
"text": null
},
{
"code": "def fun(x): if(x > 0): x -= 1 fun(x) print(x , end=\" \") x -= 1 fun(x) # Driver codea = 4fun(a) # This code is contributed by SHUBHAMSINGH10",
"e": 1051,
"s": 860,
"text": null
},
{
"code": "using System; class GFG{ static void fun(int x) { if(x > 0) { fun(--x); Console.Write(x + \" \"); fun(--x); } } static public void Main () { int a = 4; fun(a); }}// This code is contributed by SHUBHAMSINGH10",
"e": 1351,
"s": 1051,
"text": null
},
{
"code": "<script> function fun(x){ if (x > 0) { x -= 1 fun(x) document.write(x + \" \"); x -= 1 fun(x) } } // Driver codelet a = 4;fun(a) // This code is contributed by bobby </script>",
"e": 1571,
"s": 1351,
"text": null
},
{
"code": null,
"e": 1585,
"s": 1571,
"text": "0 1 2 0 3 0 1"
},
{
"code": null,
"e": 1610,
"s": 1587,
"text": "Time complexity: O(2n)"
},
{
"code": null,
"e": 1633,
"s": 1610,
"text": "Auxiliary Space: O(n) "
},
{
"code": null,
"e": 1912,
"s": 1633,
"text": " \n fun(4);\n /\n fun(3), print(3), fun(2)(prints 0 1)\n /\n fun(2), print(2), fun(1)(prints 0)\n /\n fun(1), print(1), fun(0)(does nothing)\n /\n fun(0), print(0), fun(-1) (does nothing)"
},
{
"code": null,
"e": 2014,
"s": 1912,
"text": "Question 2 Predict the output of the following program. What does the following fun() do in general? "
},
{
"code": null,
"e": 2018,
"s": 2014,
"text": "C++"
},
{
"code": null,
"e": 2020,
"s": 2018,
"text": "C"
},
{
"code": null,
"e": 2025,
"s": 2020,
"text": "Java"
},
{
"code": null,
"e": 2033,
"s": 2025,
"text": "Python3"
},
{
"code": null,
"e": 2036,
"s": 2033,
"text": "C#"
},
{
"code": null,
"e": 2047,
"s": 2036,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; int fun(int a[],int n){ int x; if(n == 1) return a[0]; else x = fun(a, n - 1); if(x > a[n - 1]) return x; else return a[n - 1];} int main(){ int arr[] = {12, 10, 30, 50, 100}; cout << \" \" << fun(arr, 5) <<\" \"; getchar(); return 0;} // This code is contributed by shubhamsingh10",
"e": 2387,
"s": 2047,
"text": null
},
{
"code": "#include<stdio.h>int fun(int a[],int n){ int x; if(n == 1) return a[0]; else x = fun(a, n-1); if(x > a[n-1]) return x; else return a[n-1];} int main(){ int arr[] = {12, 10, 30, 50, 100}; printf(\" %d \", fun(arr, 5)); getchar(); return 0;}",
"e": 2646,
"s": 2387,
"text": null
},
{
"code": "import java.io.*; class GFG { static int fun(int a[],int n) { int x; if(n == 1) return a[0]; else x = fun(a, n - 1); if(x > a[n - 1]) return x; else return a[n - 1]; } public static void main (String[] args) { int arr[] = {12, 10, 30, 50, 100}; System.out.println(\" \"+fun(arr, 5)+\" \"); }} // This code is contributed by shubhamsingh10",
"e": 3100,
"s": 2646,
"text": null
},
{
"code": "def fun( a, n): if(n == 1): return a[0] else: x = fun(a, n - 1) if(x > a[n - 1]): return x else: return a[n - 1] # Driver codearr = [12, 10, 30, 50, 100]print(fun(arr, 5)) # This code is contributed by shubhamsingh10",
"e": 3357,
"s": 3100,
"text": null
},
{
"code": "using System; public class GFG{ static int fun(int[] a,int n) { int x; if(n == 1) return a[0]; else x = fun(a, n - 1); if(x > a[n - 1]) return x; else return a[n - 1]; } static public void Main () { int[] arr = {12, 10, 30, 50, 100}; Console.Write(\" \"+fun(arr, 5)+\" \"); }} // This code is contributed by shubhamsingh10",
"e": 3792,
"s": 3357,
"text": null
},
{
"code": "<script>//Javascript Implementation function fun(a, n){ var x; if(n == 1) return a[0]; else x = fun(a, n - 1); if(x > a[n - 1]) return x; else return a[n - 1];} // Driver codevar arr = [12, 10, 30, 50, 100];document.write(fun(arr, 5));// This code is contributed by shubhamsingh10</script>",
"e": 4100,
"s": 3792,
"text": null
},
{
"code": null,
"e": 4104,
"s": 4100,
"text": "100"
},
{
"code": null,
"e": 4128,
"s": 4106,
"text": "Time complexity: O(n)"
},
{
"code": null,
"e": 4151,
"s": 4128,
"text": "Auxiliary Space: O(n) "
},
{
"code": null,
"e": 4217,
"s": 4151,
"text": "fun() returns the maximum value in the input array a[] of size n."
},
{
"code": null,
"e": 4318,
"s": 4217,
"text": "Question 3 Predict the output of the following program. What does the following fun() do in general?"
},
{
"code": null,
"e": 4322,
"s": 4318,
"text": "C++"
},
{
"code": null,
"e": 4324,
"s": 4322,
"text": "C"
},
{
"code": null,
"e": 4329,
"s": 4324,
"text": "Java"
},
{
"code": null,
"e": 4337,
"s": 4329,
"text": "Python3"
},
{
"code": null,
"e": 4340,
"s": 4337,
"text": "C#"
},
{
"code": null,
"e": 4351,
"s": 4340,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; int fun(int i){ if (i % 2) return (i++); else return fun(fun(i - 1));} int main(){ cout << \" \" << fun(200) << \" \"; getchar(); return 0;} // This code is contributed by Shubhamsingh10",
"e": 4580,
"s": 4351,
"text": null
},
{
"code": "int fun(int i){ if ( i%2 ) return (i++); else return fun(fun( i - 1 ));} int main(){ printf(\" %d \", fun(200)); getchar(); return 0;}",
"e": 4718,
"s": 4580,
"text": null
},
{
"code": "import java.io.*; class GFG { static int fun(int i) { if (i % 2 == 1) return (i++); else return fun(fun(i - 1)); } public static void main (String[] args) { System.out.println(\" \" + fun(200) + \" \"); }} // This code is contributed by Shubhamsingh10",
"e": 5007,
"s": 4718,
"text": null
},
{
"code": "def fun(i) : if (i % 2 == 1) : i += 1 return (i - 1) else : return fun(fun(i - 1)) print(fun(200)) # This code is contributed by divyeshrabadiya07",
"e": 5184,
"s": 5007,
"text": null
},
{
"code": "using System; class GFG{ static int fun(int i){ if (i % 2 == 1) return (i++); else return fun(fun(i - 1));} // Driver code static public void Main (){ Console.WriteLine(fun(200));}} // This code is contributed by Shubhamsingh10",
"e": 5427,
"s": 5184,
"text": null
},
{
"code": "<script> function fun(i){ if (i % 2 == 1) return (i++); else return fun(fun(i - 1));} // Driver codedocument.write(fun(200)); // This code is contributed by bobby </script>",
"e": 5620,
"s": 5427,
"text": null
},
{
"code": null,
"e": 5624,
"s": 5620,
"text": "199"
},
{
"code": null,
"e": 5813,
"s": 5626,
"text": "If n is odd, then return n, else returns (n-1). Eg., for n = 12, you get 11 and for n = 11 you get 11. The statement “return i++;” returns the value of i only as it is a post-increment. "
},
{
"code": null,
"e": 5835,
"s": 5813,
"text": "Time complexity: O(n)"
},
{
"code": null,
"e": 5858,
"s": 5835,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 6011,
"s": 5858,
"text": "Please write comments if you find any of the answers/codes incorrect, or you want to share more information/questions about the topics discussed above. "
},
{
"code": null,
"e": 6026,
"s": 6011,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 6044,
"s": 6026,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 6062,
"s": 6044,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 6076,
"s": 6062,
"text": "geekygirl2001"
},
{
"code": null,
"e": 6081,
"s": 6076,
"text": "Misc"
},
{
"code": null,
"e": 6091,
"s": 6081,
"text": "Recursion"
},
{
"code": null,
"e": 6096,
"s": 6091,
"text": "Misc"
},
{
"code": null,
"e": 6106,
"s": 6096,
"text": "Recursion"
},
{
"code": null,
"e": 6111,
"s": 6106,
"text": "Misc"
},
{
"code": null,
"e": 6209,
"s": 6111,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6253,
"s": 6209,
"text": "Virtualization In Cloud Computing and Types"
},
{
"code": null,
"e": 6287,
"s": 6253,
"text": "How to write Regular Expressions?"
},
{
"code": null,
"e": 6317,
"s": 6287,
"text": "OOPs | Object Oriented Design"
},
{
"code": null,
"e": 6334,
"s": 6317,
"text": "Association Rule"
},
{
"code": null,
"e": 6375,
"s": 6334,
"text": "Software Engineering | Prototyping Model"
},
{
"code": null,
"e": 6435,
"s": 6375,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 6520,
"s": 6435,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 6547,
"s": 6520,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 6575,
"s": 6547,
"text": "Backtracking | Introduction"
}
] |
File.Replace(String, String, String) Method in C# with Examples | 08 Mar, 2021
File.Replace(String, String, String) is an inbuilt File class method that is used to replace the contents of a specified destination file with the contents of a source file then it deletes the source file and creates a backup of the replaced file.Syntax:
public static void Replace (string sourceFileName, string destinationFileName, string destinationBackupFileName);
Parameter: This function accepts three parameters which are illustrated below:
sourceFileName: This is the specified source file.
destinationFileName: This is the specified destination file whose contents get replaced with the contents of the source file.
destinationBackupFileName: This file contains the backup of replaced destination file’s content.
Exceptions:
ArgumentException: The path described by the destinationFileName parameter was not of a legal form. OR the path described by the destinationBackupFileName parameter was not of a legal form.
ArgumentNullException: The destinationFileName parameter is null.
DriveNotFoundException: An invalid drive was specified.
FileNotFoundException: The file described by the current FileInfo object could not be found. OR the file described by the destinationBackupFileName parameter could not be found.
IOException: An I/O error occurred while opening the file. OR the sourceFileName and destinationFileName parameters specify the same file.
PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length.
PlatformNotSupportedException: The operating system is Windows 98 Second Edition or earlier and the files system is not NTFS.
UnauthorizedAccessException: The sourceFileName or destinationFileName parameter specifies a file that is read-only. OR this operation is not supported on the current platform. OR source or destination parameters specify a directory instead of a file. OR the caller does not have the required permission.
Below are the programs to illustrate the File.Replace(String, String, String) method.Program 1: Before running the below code, three files have been created, where source file is file1.txt, destination file is file2.txt and backup file is file3.txt. These files’ contents are shown below-
CSharp
// Using System and System.IO namespacesusing System;using System.IO;
class GFG {public static void Main(){// Specifying 3 filesstring sourceFileName = "file1.txt";string destinationFileName = "file2.txt";string destinationBackupFileName = "file3.txt";
// Calling the Replace() functionFile.Replace(sourceFileName, destinationFileName,destinationBackupFileName);
Console.WriteLine("Replacement process has been done.");}}
Output:
Replacement process has been done.
After running the above code, the above output is shown, the source file is deleted, and the remaining two file’s contents are shown below-
Program 2: Before running the below code, two files have been created, where source file is file1.txt, destination file is file2.txt and there is no backup file because we do not want to keep backup of the replaced file. These files’ contents are shown below-
C#
// C# program to illustrate the usage// of File.Replace(String, String, String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { public static void Main() { // Specifying 2 files string sourceFileName = "file1.txt"; string destinationFileName = "file2.txt"; // Calling the Replace() function with // null parameter inplace of backup file because // we do not want to keep backup of the // replaced file. File.Replace(sourceFileName, destinationFileName, null); Console.WriteLine("Replacement process has been done."); }}
Output:
Replacement process has been done.
After running the above code, the above output is shown, the source file is deleted, and the destination file contents are shown below-
arorakashish0911
CSharp-File-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
C# | .NET Framework (Basic Architecture and Component Stack)
HashSet in C# with Examples
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C# | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Mar, 2021"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "File.Replace(String, String, String) is an inbuilt File class method that is used to replace the contents of a specified destination file with the contents of a source file then it deletes the source file and creates a backup of the replaced file.Syntax: "
},
{
"code": null,
"e": 401,
"s": 285,
"text": "public static void Replace (string sourceFileName, string destinationFileName, string destinationBackupFileName); "
},
{
"code": null,
"e": 482,
"s": 401,
"text": "Parameter: This function accepts three parameters which are illustrated below: "
},
{
"code": null,
"e": 533,
"s": 482,
"text": "sourceFileName: This is the specified source file."
},
{
"code": null,
"e": 659,
"s": 533,
"text": "destinationFileName: This is the specified destination file whose contents get replaced with the contents of the source file."
},
{
"code": null,
"e": 756,
"s": 659,
"text": "destinationBackupFileName: This file contains the backup of replaced destination file’s content."
},
{
"code": null,
"e": 769,
"s": 756,
"text": "Exceptions: "
},
{
"code": null,
"e": 959,
"s": 769,
"text": "ArgumentException: The path described by the destinationFileName parameter was not of a legal form. OR the path described by the destinationBackupFileName parameter was not of a legal form."
},
{
"code": null,
"e": 1025,
"s": 959,
"text": "ArgumentNullException: The destinationFileName parameter is null."
},
{
"code": null,
"e": 1081,
"s": 1025,
"text": "DriveNotFoundException: An invalid drive was specified."
},
{
"code": null,
"e": 1259,
"s": 1081,
"text": "FileNotFoundException: The file described by the current FileInfo object could not be found. OR the file described by the destinationBackupFileName parameter could not be found."
},
{
"code": null,
"e": 1398,
"s": 1259,
"text": "IOException: An I/O error occurred while opening the file. OR the sourceFileName and destinationFileName parameters specify the same file."
},
{
"code": null,
"e": 1501,
"s": 1398,
"text": "PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length."
},
{
"code": null,
"e": 1627,
"s": 1501,
"text": "PlatformNotSupportedException: The operating system is Windows 98 Second Edition or earlier and the files system is not NTFS."
},
{
"code": null,
"e": 1932,
"s": 1627,
"text": "UnauthorizedAccessException: The sourceFileName or destinationFileName parameter specifies a file that is read-only. OR this operation is not supported on the current platform. OR source or destination parameters specify a directory instead of a file. OR the caller does not have the required permission."
},
{
"code": null,
"e": 2222,
"s": 1932,
"text": "Below are the programs to illustrate the File.Replace(String, String, String) method.Program 1: Before running the below code, three files have been created, where source file is file1.txt, destination file is file2.txt and backup file is file3.txt. These files’ contents are shown below- "
},
{
"code": null,
"e": 2235,
"s": 2228,
"text": "CSharp"
},
{
"code": null,
"e": 2305,
"s": 2235,
"text": "// Using System and System.IO namespacesusing System;using System.IO;"
},
{
"code": null,
"e": 2488,
"s": 2305,
"text": "class GFG {public static void Main(){// Specifying 3 filesstring sourceFileName = \"file1.txt\";string destinationFileName = \"file2.txt\";string destinationBackupFileName = \"file3.txt\";"
},
{
"code": null,
"e": 2598,
"s": 2488,
"text": "// Calling the Replace() functionFile.Replace(sourceFileName, destinationFileName,destinationBackupFileName);"
},
{
"code": null,
"e": 2657,
"s": 2598,
"text": "Console.WriteLine(\"Replacement process has been done.\");}}"
},
{
"code": null,
"e": 2667,
"s": 2657,
"text": "Output: "
},
{
"code": null,
"e": 2702,
"s": 2667,
"text": "Replacement process has been done."
},
{
"code": null,
"e": 2843,
"s": 2702,
"text": "After running the above code, the above output is shown, the source file is deleted, and the remaining two file’s contents are shown below- "
},
{
"code": null,
"e": 3106,
"s": 2845,
"text": "Program 2: Before running the below code, two files have been created, where source file is file1.txt, destination file is file2.txt and there is no backup file because we do not want to keep backup of the replaced file. These files’ contents are shown below- "
},
{
"code": null,
"e": 3113,
"s": 3110,
"text": "C#"
},
{
"code": "// C# program to illustrate the usage// of File.Replace(String, String, String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { public static void Main() { // Specifying 2 files string sourceFileName = \"file1.txt\"; string destinationFileName = \"file2.txt\"; // Calling the Replace() function with // null parameter inplace of backup file because // we do not want to keep backup of the // replaced file. File.Replace(sourceFileName, destinationFileName, null); Console.WriteLine(\"Replacement process has been done.\"); }}",
"e": 3752,
"s": 3113,
"text": null
},
{
"code": null,
"e": 3762,
"s": 3752,
"text": "Output: "
},
{
"code": null,
"e": 3797,
"s": 3762,
"text": "Replacement process has been done."
},
{
"code": null,
"e": 3934,
"s": 3797,
"text": "After running the above code, the above output is shown, the source file is deleted, and the destination file contents are shown below- "
},
{
"code": null,
"e": 3951,
"s": 3934,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3972,
"s": 3951,
"text": "CSharp-File-Handling"
},
{
"code": null,
"e": 3975,
"s": 3972,
"text": "C#"
},
{
"code": null,
"e": 4073,
"s": 3975,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4116,
"s": 4073,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 4165,
"s": 4116,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 4188,
"s": 4165,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 4204,
"s": 4188,
"text": "C# | List Class"
},
{
"code": null,
"e": 4265,
"s": 4204,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 4293,
"s": 4265,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 4316,
"s": 4293,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 4338,
"s": 4316,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 4363,
"s": 4338,
"text": "Lambda Expressions in C#"
}
] |
chkconfig command in Linux with Examples | 15 May, 2019
chkconfig command is used to list all available services and view or update their run level settings. In simple words it is used to list current startup information of services or any particular service, updating runlevel settings of service and adding or removing service from management.
Synopsis:
chkconfig --list [name]
chkconfig --add name
chkconfig --del name
chkconfig --override name
chkconfig [--level levels] name
chkconfig [--level levels] name
Options:
To List current status of all system services.chkconfig --list
chkconfig --list
To View current status of a particular services.chkconfig --list rhnsd
chkconfig --list rhnsd
For Disabling a Service: By default 2 3 4 5 run levels are affected by this command to disable certain run levels only, add –level attribute followed by run level.chkconfig rhnsd off
chkconfig rhnsd off
Enabling a Service: By default 2 3 4 5 run levels are affected by this command to enable certain run levels only, add –level attribute followed by run level.chkconfig rhnsd on
chkconfig rhnsd on
To Delete a Servicechkconfig del rhnsd
chkconfig del rhnsd
To add a Servicechkconfig add rhnsd
chkconfig add rhnsd
linux-command
Linux-networking-commands
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 318,
"s": 28,
"text": "chkconfig command is used to list all available services and view or update their run level settings. In simple words it is used to list current startup information of services or any particular service, updating runlevel settings of service and adding or removing service from management."
},
{
"code": null,
"e": 328,
"s": 318,
"text": "Synopsis:"
},
{
"code": null,
"e": 486,
"s": 328,
"text": "chkconfig --list [name]\nchkconfig --add name\nchkconfig --del name\nchkconfig --override name\nchkconfig [--level levels] name \nchkconfig [--level levels] name\n"
},
{
"code": null,
"e": 495,
"s": 486,
"text": "Options:"
},
{
"code": null,
"e": 558,
"s": 495,
"text": "To List current status of all system services.chkconfig --list"
},
{
"code": null,
"e": 575,
"s": 558,
"text": "chkconfig --list"
},
{
"code": null,
"e": 646,
"s": 575,
"text": "To View current status of a particular services.chkconfig --list rhnsd"
},
{
"code": null,
"e": 669,
"s": 646,
"text": "chkconfig --list rhnsd"
},
{
"code": null,
"e": 852,
"s": 669,
"text": "For Disabling a Service: By default 2 3 4 5 run levels are affected by this command to disable certain run levels only, add –level attribute followed by run level.chkconfig rhnsd off"
},
{
"code": null,
"e": 872,
"s": 852,
"text": "chkconfig rhnsd off"
},
{
"code": null,
"e": 1048,
"s": 872,
"text": "Enabling a Service: By default 2 3 4 5 run levels are affected by this command to enable certain run levels only, add –level attribute followed by run level.chkconfig rhnsd on"
},
{
"code": null,
"e": 1067,
"s": 1048,
"text": "chkconfig rhnsd on"
},
{
"code": null,
"e": 1106,
"s": 1067,
"text": "To Delete a Servicechkconfig del rhnsd"
},
{
"code": null,
"e": 1126,
"s": 1106,
"text": "chkconfig del rhnsd"
},
{
"code": null,
"e": 1162,
"s": 1126,
"text": "To add a Servicechkconfig add rhnsd"
},
{
"code": null,
"e": 1182,
"s": 1162,
"text": "chkconfig add rhnsd"
},
{
"code": null,
"e": 1196,
"s": 1182,
"text": "linux-command"
},
{
"code": null,
"e": 1222,
"s": 1196,
"text": "Linux-networking-commands"
},
{
"code": null,
"e": 1244,
"s": 1222,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 1251,
"s": 1244,
"text": "Picked"
},
{
"code": null,
"e": 1262,
"s": 1251,
"text": "Linux-Unix"
}
] |
Last Minute Notes – Theory of Computation | 28 Jun, 2021
See Last Minute Notes on all subjects here.
We will discuss the important key points useful for GATE exams in summarized form. For details you may refer this.
Finite Automata: It is used to recognize patterns of specific type input. It is the most restricted type of automata which can accept only regular languages (languages which can be expressed by regular expression using OR (+), Concatenation (.), Kleene Closure(*) like a*b*, (a+b) etc.)
Deterministic FA and Non-Deterministic FA: In deterministic FA, there is only one move from every state on every input symbol but in Non-Deterministic FA, there can be zero or more than one move from one state for an input symbol.
Note:
Language accepted by NDFA and DFA are same.
Power of NDFA and DFA is same.
No. of states in NDFA is less than or equal to no. of states in equivalent DFA.
For NFA with n-states, in worst case, the maximum states possible in DFA is 2n
Every NFA can be converted to corresponding DFA.
Identities of Regular Expression :
Φ + R = R + Φ = RΦ * R = R * Φ = Φε * R = R * ε = Rε* = εΦ* = εε + RR* = R*R + ε = R*
(a+b)* = (a* + b*)* = (a* b*)* = (a* + b)* = (a + b*)* = a*(ba*)* = b*(ab*)*
Moore Machine: Moore machines are finite state machines with output value and its output depends only on present state.Mealy Machine: Mealy machines are also finite state machines with output value and its output depends on present state and current input symbol. Push Down Automata: Pushdown Automata has extra memory called stack which gives more power than Finite automata. It is used to recognize context free languages.
Deterministic and Non-Deterministic PDA: In deterministic PDA, there is only one move from every state on every input symbol but in Non-Deterministic PDA, there can be more than one move from one state for an input symbol.
Note:
Power of NPDA is more than DPDA.
It is not possible to convert every NPDA to corresponding DPDA.
Language accepted by DPDA is subset of language accepted by NPDA.
The languages accepted by DPDA are called DCFL (Deterministic Context Free Languages) which are subset of NCFL (Non Deterministic CFL) accepted by NPDA.
Linear Bound Automata: Linear Bound Automata has finite amount of memory called tape which can be used to recognize Context Sensitive Languages.
LBA is more powerful than Push down automata.
FA < PDA < LBA < TM
Turing Machine: Turing machine has infinite size tape and it is used to accept Recursive Enumerable Languages.
Turing Machine can move in both directions. Also, it doesn’t accept ε .
If the string inserted in not in language, machine will halt in non-final state.
Deterministic and Non-Deterministic Turing Machines: In deterministic turing machine, there is only one move from every state on every input symbol but in Non-Deterministic turing machine, there can be more than one move from one state for an input symbol.
Note:
Language accepted by NTM, multi-tape TM and DTM are same.
Power of NTM, Multi-Tape TM and DTM is same.
Every NTM can be converted to corresponding DTM.
Chomsky Classification of Languages:
A→ρ where A ∈ N
and ρ ∈ (T∪N)*
α →β where α, β ∈ (T∪N)* and α contains atleast 1 non-terminal
Relationship between these can be represented as:
Decidable and Undecidable Problems:
A language is Decidable or Recursive if a Turing machine can be constructed which accepts the strings which are part of language and rejects others. e.g.; A number is prime or not is a decidable problem.
A language is Semi–Decidable or Recursive Enumerable if a turing machine can be constructed which accepts the strings which are part of language and it may loop forever for strings which are not part of language.
A problem is undecidable if we can’t construct an algorithms and Turing machine which can give yes or no answer. e.g.; Whether a CFG is ambiguous or not is undecidable.
Countability :
Set of all strings over any finite alphabet are countable.
Every subset of countable set is either finite or countable.
Set of all Turing Machines are countable.
The set of all languages that are not recursive enumerable is Uncountable.
Marketing
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Boyer-Moore Majority Voting Algorithm
Introduction of Pushdown Automata
Difference between Mealy machine and Moore machine
Construct Pushdown Automata for given languages
Converting Context Free Grammar to Chomsky Normal Form
Conversion from NFA to DFA
Minimization of DFA
Recursive and Recursive Enumerable Languages in TOC
Variation of Turing Machine
Design 101 sequence detector (Mealy machine) | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 98,
"s": 54,
"text": "See Last Minute Notes on all subjects here."
},
{
"code": null,
"e": 213,
"s": 98,
"text": "We will discuss the important key points useful for GATE exams in summarized form. For details you may refer this."
},
{
"code": null,
"e": 502,
"s": 215,
"text": "Finite Automata: It is used to recognize patterns of specific type input. It is the most restricted type of automata which can accept only regular languages (languages which can be expressed by regular expression using OR (+), Concatenation (.), Kleene Closure(*) like a*b*, (a+b) etc.)"
},
{
"code": null,
"e": 735,
"s": 504,
"text": "Deterministic FA and Non-Deterministic FA: In deterministic FA, there is only one move from every state on every input symbol but in Non-Deterministic FA, there can be zero or more than one move from one state for an input symbol."
},
{
"code": null,
"e": 741,
"s": 735,
"text": "Note:"
},
{
"code": null,
"e": 785,
"s": 741,
"text": "Language accepted by NDFA and DFA are same."
},
{
"code": null,
"e": 816,
"s": 785,
"text": "Power of NDFA and DFA is same."
},
{
"code": null,
"e": 896,
"s": 816,
"text": "No. of states in NDFA is less than or equal to no. of states in equivalent DFA."
},
{
"code": null,
"e": 975,
"s": 896,
"text": "For NFA with n-states, in worst case, the maximum states possible in DFA is 2n"
},
{
"code": null,
"e": 1024,
"s": 975,
"text": "Every NFA can be converted to corresponding DFA."
},
{
"code": null,
"e": 1060,
"s": 1024,
"text": " Identities of Regular Expression :"
},
{
"code": null,
"e": 1146,
"s": 1060,
"text": "Φ + R = R + Φ = RΦ * R = R * Φ = Φε * R = R * ε = Rε* = εΦ* = εε + RR* = R*R + ε = R*"
},
{
"code": null,
"e": 1223,
"s": 1146,
"text": "(a+b)* = (a* + b*)* = (a* b*)* = (a* + b)* = (a + b*)* = a*(ba*)* = b*(ab*)*"
},
{
"code": null,
"e": 1649,
"s": 1223,
"text": "Moore Machine: Moore machines are finite state machines with output value and its output depends only on present state.Mealy Machine: Mealy machines are also finite state machines with output value and its output depends on present state and current input symbol. Push Down Automata: Pushdown Automata has extra memory called stack which gives more power than Finite automata. It is used to recognize context free languages."
},
{
"code": null,
"e": 1874,
"s": 1651,
"text": "Deterministic and Non-Deterministic PDA: In deterministic PDA, there is only one move from every state on every input symbol but in Non-Deterministic PDA, there can be more than one move from one state for an input symbol."
},
{
"code": null,
"e": 1880,
"s": 1874,
"text": "Note:"
},
{
"code": null,
"e": 1913,
"s": 1880,
"text": "Power of NPDA is more than DPDA."
},
{
"code": null,
"e": 1977,
"s": 1913,
"text": "It is not possible to convert every NPDA to corresponding DPDA."
},
{
"code": null,
"e": 2043,
"s": 1977,
"text": "Language accepted by DPDA is subset of language accepted by NPDA."
},
{
"code": null,
"e": 2196,
"s": 2043,
"text": "The languages accepted by DPDA are called DCFL (Deterministic Context Free Languages) which are subset of NCFL (Non Deterministic CFL) accepted by NPDA."
},
{
"code": null,
"e": 2343,
"s": 2198,
"text": "Linear Bound Automata: Linear Bound Automata has finite amount of memory called tape which can be used to recognize Context Sensitive Languages."
},
{
"code": null,
"e": 2389,
"s": 2343,
"text": "LBA is more powerful than Push down automata."
},
{
"code": null,
"e": 2411,
"s": 2389,
"text": " FA < PDA < LBA < TM "
},
{
"code": null,
"e": 2524,
"s": 2413,
"text": "Turing Machine: Turing machine has infinite size tape and it is used to accept Recursive Enumerable Languages."
},
{
"code": null,
"e": 2596,
"s": 2524,
"text": "Turing Machine can move in both directions. Also, it doesn’t accept ε ."
},
{
"code": null,
"e": 2677,
"s": 2596,
"text": "If the string inserted in not in language, machine will halt in non-final state."
},
{
"code": null,
"e": 2936,
"s": 2679,
"text": "Deterministic and Non-Deterministic Turing Machines: In deterministic turing machine, there is only one move from every state on every input symbol but in Non-Deterministic turing machine, there can be more than one move from one state for an input symbol."
},
{
"code": null,
"e": 2942,
"s": 2936,
"text": "Note:"
},
{
"code": null,
"e": 3000,
"s": 2942,
"text": "Language accepted by NTM, multi-tape TM and DTM are same."
},
{
"code": null,
"e": 3045,
"s": 3000,
"text": "Power of NTM, Multi-Tape TM and DTM is same."
},
{
"code": null,
"e": 3094,
"s": 3045,
"text": "Every NTM can be converted to corresponding DTM."
},
{
"code": null,
"e": 3135,
"s": 3098,
"text": "Chomsky Classification of Languages:"
},
{
"code": null,
"e": 3151,
"s": 3135,
"text": "A→ρ where A ∈ N"
},
{
"code": null,
"e": 3166,
"s": 3151,
"text": "and ρ ∈ (T∪N)*"
},
{
"code": null,
"e": 3229,
"s": 3166,
"text": "α →β where α, β ∈ (T∪N)* and α contains atleast 1 non-terminal"
},
{
"code": null,
"e": 3279,
"s": 3229,
"text": "Relationship between these can be represented as:"
},
{
"code": null,
"e": 3317,
"s": 3281,
"text": "Decidable and Undecidable Problems:"
},
{
"code": null,
"e": 3521,
"s": 3317,
"text": "A language is Decidable or Recursive if a Turing machine can be constructed which accepts the strings which are part of language and rejects others. e.g.; A number is prime or not is a decidable problem."
},
{
"code": null,
"e": 3734,
"s": 3521,
"text": "A language is Semi–Decidable or Recursive Enumerable if a turing machine can be constructed which accepts the strings which are part of language and it may loop forever for strings which are not part of language."
},
{
"code": null,
"e": 3903,
"s": 3734,
"text": "A problem is undecidable if we can’t construct an algorithms and Turing machine which can give yes or no answer. e.g.; Whether a CFG is ambiguous or not is undecidable."
},
{
"code": null,
"e": 3919,
"s": 3903,
"text": " Countability :"
},
{
"code": null,
"e": 3978,
"s": 3919,
"text": "Set of all strings over any finite alphabet are countable."
},
{
"code": null,
"e": 4039,
"s": 3978,
"text": "Every subset of countable set is either finite or countable."
},
{
"code": null,
"e": 4081,
"s": 4039,
"text": "Set of all Turing Machines are countable."
},
{
"code": null,
"e": 4156,
"s": 4081,
"text": "The set of all languages that are not recursive enumerable is Uncountable."
},
{
"code": null,
"e": 4166,
"s": 4156,
"text": "Marketing"
},
{
"code": null,
"e": 4199,
"s": 4166,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 4297,
"s": 4199,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4335,
"s": 4297,
"text": "Boyer-Moore Majority Voting Algorithm"
},
{
"code": null,
"e": 4369,
"s": 4335,
"text": "Introduction of Pushdown Automata"
},
{
"code": null,
"e": 4420,
"s": 4369,
"text": "Difference between Mealy machine and Moore machine"
},
{
"code": null,
"e": 4468,
"s": 4420,
"text": "Construct Pushdown Automata for given languages"
},
{
"code": null,
"e": 4523,
"s": 4468,
"text": "Converting Context Free Grammar to Chomsky Normal Form"
},
{
"code": null,
"e": 4550,
"s": 4523,
"text": "Conversion from NFA to DFA"
},
{
"code": null,
"e": 4570,
"s": 4550,
"text": "Minimization of DFA"
},
{
"code": null,
"e": 4622,
"s": 4570,
"text": "Recursive and Recursive Enumerable Languages in TOC"
},
{
"code": null,
"e": 4650,
"s": 4622,
"text": "Variation of Turing Machine"
}
] |
Draw Rainbow using Turtle Graphics in Python | 15 Oct, 2020
Turtle is an inbuilt module in Python. It provides:
Drawing using a screen (cardboard).Turtle (pen).
Drawing using a screen (cardboard).
Turtle (pen).
To draw something on the screen, we need to move the turtle (pen), and to move the turtle, there are some functions like the forward(), backward(), etc.
Prerequisite: Turtle Programming Basics
In this section, we will discuss how to draw a Rainbow using two different ways using Turtle Graphics.
Approach:
Import Turtle.Set screenMake Turtle ObjectDefine colors used for drawingLoop to draw semi-circles oriented by 180-degree position.
Import Turtle.
Set screen
Make Turtle Object
Define colors used for drawing
Loop to draw semi-circles oriented by 180-degree position.
Example 1:
python3
# Import turtle packageimport turtle # Creating a turtle screen objectsc = turtle.Screen() # Creating a turtle object(pen)pen = turtle.Turtle() # Defining a method to form a semicircle# with a dynamic radius and colordef semi_circle(col, rad, val): # Set the fill color of the semicircle pen.color(col) # Draw a circle pen.circle(rad, -180) # Move the turtle to air pen.up() # Move the turtle to a given position pen.setpos(val, 0) # Move the turtle to the ground pen.down() pen.right(180) # Set the colors for drawingcol = ['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red'] # Setup the screen featuressc.setup(600, 600) # Set the screen color to blacksc.bgcolor('black') # Setup the turtle featurespen.right(90)pen.width(10)pen.speed(7) # Loop to draw 7 semicirclesfor i in range(7): semi_circle(col[i], 10*( i + 8), -10*(i + 1)) # Hide the turtlepen.hideturtle()
Output:
Example 2:
Python3
import turtle mypen= turtle.Turtle()mypen.shape('turtle')mypen.speed(10) window= turtle.Screen()window.bgcolor('white')rainbow= ['red','orange','yellow','green','blue','indigo','violet']size= 180mypen.penup()mypen.goto(0,-180)for color in rainbow: mypen.color(color) mypen.fillcolor(color) mypen.begin_fill() mypen.circle(size) mypen.end_fill() size-=20 turtle.done()
Output:
pulkitagarwal03pulkit
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 107,
"s": 54,
"text": "Turtle is an inbuilt module in Python. It provides: "
},
{
"code": null,
"e": 156,
"s": 107,
"text": "Drawing using a screen (cardboard).Turtle (pen)."
},
{
"code": null,
"e": 192,
"s": 156,
"text": "Drawing using a screen (cardboard)."
},
{
"code": null,
"e": 206,
"s": 192,
"text": "Turtle (pen)."
},
{
"code": null,
"e": 359,
"s": 206,
"text": "To draw something on the screen, we need to move the turtle (pen), and to move the turtle, there are some functions like the forward(), backward(), etc."
},
{
"code": null,
"e": 399,
"s": 359,
"text": "Prerequisite: Turtle Programming Basics"
},
{
"code": null,
"e": 502,
"s": 399,
"text": "In this section, we will discuss how to draw a Rainbow using two different ways using Turtle Graphics."
},
{
"code": null,
"e": 513,
"s": 502,
"text": "Approach: "
},
{
"code": null,
"e": 644,
"s": 513,
"text": "Import Turtle.Set screenMake Turtle ObjectDefine colors used for drawingLoop to draw semi-circles oriented by 180-degree position."
},
{
"code": null,
"e": 659,
"s": 644,
"text": "Import Turtle."
},
{
"code": null,
"e": 670,
"s": 659,
"text": "Set screen"
},
{
"code": null,
"e": 689,
"s": 670,
"text": "Make Turtle Object"
},
{
"code": null,
"e": 720,
"s": 689,
"text": "Define colors used for drawing"
},
{
"code": null,
"e": 779,
"s": 720,
"text": "Loop to draw semi-circles oriented by 180-degree position."
},
{
"code": null,
"e": 790,
"s": 779,
"text": "Example 1:"
},
{
"code": null,
"e": 798,
"s": 790,
"text": "python3"
},
{
"code": "# Import turtle packageimport turtle # Creating a turtle screen objectsc = turtle.Screen() # Creating a turtle object(pen)pen = turtle.Turtle() # Defining a method to form a semicircle# with a dynamic radius and colordef semi_circle(col, rad, val): # Set the fill color of the semicircle pen.color(col) # Draw a circle pen.circle(rad, -180) # Move the turtle to air pen.up() # Move the turtle to a given position pen.setpos(val, 0) # Move the turtle to the ground pen.down() pen.right(180) # Set the colors for drawingcol = ['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red'] # Setup the screen featuressc.setup(600, 600) # Set the screen color to blacksc.bgcolor('black') # Setup the turtle featurespen.right(90)pen.width(10)pen.speed(7) # Loop to draw 7 semicirclesfor i in range(7): semi_circle(col[i], 10*( i + 8), -10*(i + 1)) # Hide the turtlepen.hideturtle()",
"e": 1731,
"s": 798,
"text": null
},
{
"code": null,
"e": 1739,
"s": 1731,
"text": "Output:"
},
{
"code": null,
"e": 1750,
"s": 1739,
"text": "Example 2:"
},
{
"code": null,
"e": 1758,
"s": 1750,
"text": "Python3"
},
{
"code": "import turtle mypen= turtle.Turtle()mypen.shape('turtle')mypen.speed(10) window= turtle.Screen()window.bgcolor('white')rainbow= ['red','orange','yellow','green','blue','indigo','violet']size= 180mypen.penup()mypen.goto(0,-180)for color in rainbow: mypen.color(color) mypen.fillcolor(color) mypen.begin_fill() mypen.circle(size) mypen.end_fill() size-=20 turtle.done()",
"e": 2144,
"s": 1758,
"text": null
},
{
"code": null,
"e": 2152,
"s": 2144,
"text": "Output:"
},
{
"code": null,
"e": 2174,
"s": 2152,
"text": "pulkitagarwal03pulkit"
},
{
"code": null,
"e": 2188,
"s": 2174,
"text": "Python-turtle"
},
{
"code": null,
"e": 2195,
"s": 2188,
"text": "Python"
}
] |
strings.Compare() Function in Golang with Examples | 21 Apr, 2020
The Compare() function is an inbuilt function in the Golang programming language which is used to compare two strings. It is used to compare two strings in lexicographical order (order in which the words are arranged alphabetically, similar to the way we search words in dictionary) or to find out if the strings are equal or not. It returns an integer value as follows:
Syntax:
func Compare(s1, s2 string) int
Returns 0 if the strings are equal (s1==s2)
Returns 1 if string 1 is greater than string 2 (s1 > s2)
Returns -1 is string 1 is lesser than string 2 (s1 < s2)
Example 1:
// Golang program to illustrate the use of// the strings.Compare() Functionpackage main import ( "fmt" "strings") func main() { var s1 = "Geeks" var s2 = "GeeksforGeeks" var s3 = "Geeks" // using the function fmt.Println(strings.Compare(s1, s2)) fmt.Println(strings.Compare(s2, s3)) fmt.Println(strings.Compare(s3, s1)) }
Output:
-1
1
0
Explanation: The first output comes -1 as the first string is “Geeks” which is lexicographically lesser than the second string “GeeksforGeeks”. The second output comes 1 as the first string is “GeeksforGeeks” which is lexicographically greater than the second string “Geeks”. The third output comes as 0 as the first string is “Geeks” which is equal to the second string “Geeks”.
Example 2:
// Golang program to illustrate the use of// the strings.Compare() Functionpackage main import ( "fmt" "strings") func main() { var s1 = "apple" var s2 = "Apple" var s3 = "Apricot" // using the function fmt.Println(strings.Compare(s1, s2)) fmt.Println(strings.Compare(s2, s3)) fmt.Println(strings.Compare(s3, s1)) }
Output:
1
-1
-1
Explanation: The first output comes 1 as the first string is “apple” which is lexicographically greater than the second string “Apple” as the characters are compared sequentially from left to right using the Unicode Character Set and the ASCII value of ‘a’ is 97 and that of ‘A’ is 65. Therefore apple is greater than Apple.The second output comes -1 as the first string is “Apple” which is lexicographically lesser than the second string “Apricot”. The third output comes as -1 as the first string is “Apricot” which is lexicographically lesser than the second string “apple” as ‘A’ is lesser than ‘a’.
Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Constants- Go Language
Time Durations in Golang
Loops in Go Language
How to iterate over an Array using for loop in Golang?
Structures in Golang
Strings in Golang
Go Variables
time.Parse() Function in Golang With Examples
Class and Object in Golang | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 399,
"s": 28,
"text": "The Compare() function is an inbuilt function in the Golang programming language which is used to compare two strings. It is used to compare two strings in lexicographical order (order in which the words are arranged alphabetically, similar to the way we search words in dictionary) or to find out if the strings are equal or not. It returns an integer value as follows:"
},
{
"code": null,
"e": 407,
"s": 399,
"text": "Syntax:"
},
{
"code": null,
"e": 439,
"s": 407,
"text": "func Compare(s1, s2 string) int"
},
{
"code": null,
"e": 483,
"s": 439,
"text": "Returns 0 if the strings are equal (s1==s2)"
},
{
"code": null,
"e": 540,
"s": 483,
"text": "Returns 1 if string 1 is greater than string 2 (s1 > s2)"
},
{
"code": null,
"e": 597,
"s": 540,
"text": "Returns -1 is string 1 is lesser than string 2 (s1 < s2)"
},
{
"code": null,
"e": 608,
"s": 597,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the use of// the strings.Compare() Functionpackage main import ( \"fmt\" \"strings\") func main() { var s1 = \"Geeks\" var s2 = \"GeeksforGeeks\" var s3 = \"Geeks\" // using the function fmt.Println(strings.Compare(s1, s2)) fmt.Println(strings.Compare(s2, s3)) fmt.Println(strings.Compare(s3, s1)) }",
"e": 964,
"s": 608,
"text": null
},
{
"code": null,
"e": 972,
"s": 964,
"text": "Output:"
},
{
"code": null,
"e": 980,
"s": 972,
"text": "-1\n1\n0\n"
},
{
"code": null,
"e": 1360,
"s": 980,
"text": "Explanation: The first output comes -1 as the first string is “Geeks” which is lexicographically lesser than the second string “GeeksforGeeks”. The second output comes 1 as the first string is “GeeksforGeeks” which is lexicographically greater than the second string “Geeks”. The third output comes as 0 as the first string is “Geeks” which is equal to the second string “Geeks”."
},
{
"code": null,
"e": 1371,
"s": 1360,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the use of// the strings.Compare() Functionpackage main import ( \"fmt\" \"strings\") func main() { var s1 = \"apple\" var s2 = \"Apple\" var s3 = \"Apricot\" // using the function fmt.Println(strings.Compare(s1, s2)) fmt.Println(strings.Compare(s2, s3)) fmt.Println(strings.Compare(s3, s1)) }",
"e": 1725,
"s": 1371,
"text": null
},
{
"code": null,
"e": 1733,
"s": 1725,
"text": "Output:"
},
{
"code": null,
"e": 1742,
"s": 1733,
"text": "1\n-1\n-1\n"
},
{
"code": null,
"e": 2346,
"s": 1742,
"text": "Explanation: The first output comes 1 as the first string is “apple” which is lexicographically greater than the second string “Apple” as the characters are compared sequentially from left to right using the Unicode Character Set and the ASCII value of ‘a’ is 97 and that of ‘A’ is 65. Therefore apple is greater than Apple.The second output comes -1 as the first string is “Apple” which is lexicographically lesser than the second string “Apricot”. The third output comes as -1 as the first string is “Apricot” which is lexicographically lesser than the second string “apple” as ‘A’ is lesser than ‘a’."
},
{
"code": null,
"e": 2360,
"s": 2346,
"text": "Golang-String"
},
{
"code": null,
"e": 2367,
"s": 2360,
"text": "Picked"
},
{
"code": null,
"e": 2379,
"s": 2367,
"text": "Go Language"
},
{
"code": null,
"e": 2477,
"s": 2379,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2506,
"s": 2477,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 2529,
"s": 2506,
"text": "Constants- Go Language"
},
{
"code": null,
"e": 2554,
"s": 2529,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 2575,
"s": 2554,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 2630,
"s": 2575,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 2651,
"s": 2630,
"text": "Structures in Golang"
},
{
"code": null,
"e": 2669,
"s": 2651,
"text": "Strings in Golang"
},
{
"code": null,
"e": 2682,
"s": 2669,
"text": "Go Variables"
},
{
"code": null,
"e": 2728,
"s": 2682,
"text": "time.Parse() Function in Golang With Examples"
}
] |
Node.js fs.createReadStream() Method | 11 Oct, 2021
The createReadStream() method is an inbuilt application programming interface of fs module which allow you to open up a file/stream and read the data present in it.Syntax:
fs.createReadStream( path, options )
Parameters: This method accept two parameters as mentioned above and described below:
path: This parameter holds the path of the file where to read the file. It can be string, buffer or URL.
options: It is an optional parameter that holds string or object.
Return Value: This method returns the fs.ReadStream object.Below examples illustrate the createReadStream() method in Node.js:Example 1:
javascript
// Node.js program to demonstrate the // fs.createReadStream() method // Include fs modulelet fs = require('fs'), // Use fs.createReadStream() method// to read the filereader = fs.createReadStream('input.txt'); // Read and display the file data on consolereader.on('data', function (chunk) { console.log(chunk.toString());});
Output:
input.txt file data:
GeeksforGeeks: A computer science portal for geeks
Example 2:
javascript
// Node.js program to demonstrate the // fs.createReadStream() method // Include fs modulelet fs = require('fs'), // Use fs.createReadStream() method// to read the filereader = fs.createReadStream('input.txt', { flag: 'a+', encoding: 'UTF-8', start: 5, end: 64, highWaterMark: 16}); // Read and display the file data on consolereader.on('data', function (chunk) { console.log(chunk);});
Output:
forGeeks: A comp
uter science por
tal for geeks
Reference: https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options
simranarora5sos
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 202,
"s": 28,
"text": "The createReadStream() method is an inbuilt application programming interface of fs module which allow you to open up a file/stream and read the data present in it.Syntax: "
},
{
"code": null,
"e": 239,
"s": 202,
"text": "fs.createReadStream( path, options )"
},
{
"code": null,
"e": 327,
"s": 239,
"text": "Parameters: This method accept two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 432,
"s": 327,
"text": "path: This parameter holds the path of the file where to read the file. It can be string, buffer or URL."
},
{
"code": null,
"e": 498,
"s": 432,
"text": "options: It is an optional parameter that holds string or object."
},
{
"code": null,
"e": 637,
"s": 498,
"text": "Return Value: This method returns the fs.ReadStream object.Below examples illustrate the createReadStream() method in Node.js:Example 1: "
},
{
"code": null,
"e": 648,
"s": 637,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the // fs.createReadStream() method // Include fs modulelet fs = require('fs'), // Use fs.createReadStream() method// to read the filereader = fs.createReadStream('input.txt'); // Read and display the file data on consolereader.on('data', function (chunk) { console.log(chunk.toString());});",
"e": 981,
"s": 648,
"text": null
},
{
"code": null,
"e": 991,
"s": 981,
"text": "Output: "
},
{
"code": null,
"e": 1063,
"s": 991,
"text": "input.txt file data:\nGeeksforGeeks: A computer science portal for geeks"
},
{
"code": null,
"e": 1076,
"s": 1063,
"text": "Example 2: "
},
{
"code": null,
"e": 1087,
"s": 1076,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the // fs.createReadStream() method // Include fs modulelet fs = require('fs'), // Use fs.createReadStream() method// to read the filereader = fs.createReadStream('input.txt', { flag: 'a+', encoding: 'UTF-8', start: 5, end: 64, highWaterMark: 16}); // Read and display the file data on consolereader.on('data', function (chunk) { console.log(chunk);});",
"e": 1496,
"s": 1087,
"text": null
},
{
"code": null,
"e": 1506,
"s": 1496,
"text": "Output: "
},
{
"code": null,
"e": 1554,
"s": 1506,
"text": "forGeeks: A comp\nuter science por\ntal for geeks"
},
{
"code": null,
"e": 1633,
"s": 1554,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options "
},
{
"code": null,
"e": 1649,
"s": 1633,
"text": "simranarora5sos"
},
{
"code": null,
"e": 1667,
"s": 1649,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 1674,
"s": 1667,
"text": "Picked"
},
{
"code": null,
"e": 1682,
"s": 1674,
"text": "Node.js"
},
{
"code": null,
"e": 1699,
"s": 1682,
"text": "Web Technologies"
}
] |
How to read a file line by line using node.js ? | 20 May, 2020
The ability to read a file line by line allows us to read large files without entirely storing it to the memory. It is useful in saving resources and improves the efficiency of the application. It allows us to look for the information that is required and once the relevant information is found, we can stop the search process and can prevent unwanted memory usage.
We will achieve the target by using the Readline Module and Line-Reader Module.
Method 1: Using the Readline Module: Readline is a native module of Node.js, it was developed specifically for reading the content line by line from any readable stream. It can be used to read data from the command line.Since the module is the native module of Node.js, it doesn’t require any installation and can be imported as
const readline = require('readline');
Since readline module works only with Readable streams, so we need to first create a readable stream using the fs module.
const file = readline.createInterface({
input: fs.createReadStream('source_to_file'),
output: process.stdout,
terminal: false
});
Now, listen for the line event on the file object. The event will trigger whenever a new line is read from the stream:
file.on('line', (line) => {
console.log(line);
});
Example:
// Importing the Required Modulesconst fs = require('fs');const readline = require('readline'); // Creating a readable stream from file// readline module reads line by line // but from a readable stream only.const file = readline.createInterface({ input: fs.createReadStream('gfg.txt'), output: process.stdout, terminal: false}); // Printing the content of file line by// line to console by listening on the// line event which will triggered// whenever a new line is read from// the streamfile.on('line', (line) => { console.log(line);});
Output:
Method 2: Using Line-reader Module: The line-reader module is an open-source module for reading file line by line in Node.js. It is not the native module, so you need to install it using npm(Node Package Manager) using the command:
npm install line-reader --save
The line-reader module provides eachLine() method which reads the file line by line. It had got a callback function which got two arguments: the line content and a boolean value that stores, whether the line read, was the last line of the file.
const lineReader = require('line-reader');
lineReader.eachLine('source-to-file', (line, last) => {
console.log(line);
});
Example:
// Importing required librariesconst lineReader = require('line-reader'); // eachLine() method call on gfg.txt// It got a callback function// Printing content of file line by line// on the consolelineReader.eachLine('gfg.txt', (line, last) => { console.log(line);});
Output:
Node.js-Misc
Picked
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
JWT Authentication with Node.js
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 ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 May, 2020"
},
{
"code": null,
"e": 394,
"s": 28,
"text": "The ability to read a file line by line allows us to read large files without entirely storing it to the memory. It is useful in saving resources and improves the efficiency of the application. It allows us to look for the information that is required and once the relevant information is found, we can stop the search process and can prevent unwanted memory usage."
},
{
"code": null,
"e": 474,
"s": 394,
"text": "We will achieve the target by using the Readline Module and Line-Reader Module."
},
{
"code": null,
"e": 803,
"s": 474,
"text": "Method 1: Using the Readline Module: Readline is a native module of Node.js, it was developed specifically for reading the content line by line from any readable stream. It can be used to read data from the command line.Since the module is the native module of Node.js, it doesn’t require any installation and can be imported as"
},
{
"code": null,
"e": 841,
"s": 803,
"text": "const readline = require('readline');"
},
{
"code": null,
"e": 963,
"s": 841,
"text": "Since readline module works only with Readable streams, so we need to first create a readable stream using the fs module."
},
{
"code": null,
"e": 1106,
"s": 963,
"text": "const file = readline.createInterface({\n input: fs.createReadStream('source_to_file'),\n output: process.stdout,\n terminal: false\n});\n"
},
{
"code": null,
"e": 1225,
"s": 1106,
"text": "Now, listen for the line event on the file object. The event will trigger whenever a new line is read from the stream:"
},
{
"code": null,
"e": 1281,
"s": 1225,
"text": "file.on('line', (line) => {\n console.log(line);\n});\n"
},
{
"code": null,
"e": 1290,
"s": 1281,
"text": "Example:"
},
{
"code": "// Importing the Required Modulesconst fs = require('fs');const readline = require('readline'); // Creating a readable stream from file// readline module reads line by line // but from a readable stream only.const file = readline.createInterface({ input: fs.createReadStream('gfg.txt'), output: process.stdout, terminal: false}); // Printing the content of file line by// line to console by listening on the// line event which will triggered// whenever a new line is read from// the streamfile.on('line', (line) => { console.log(line);});",
"e": 1844,
"s": 1290,
"text": null
},
{
"code": null,
"e": 1852,
"s": 1844,
"text": "Output:"
},
{
"code": null,
"e": 2084,
"s": 1852,
"text": "Method 2: Using Line-reader Module: The line-reader module is an open-source module for reading file line by line in Node.js. It is not the native module, so you need to install it using npm(Node Package Manager) using the command:"
},
{
"code": null,
"e": 2115,
"s": 2084,
"text": "npm install line-reader --save"
},
{
"code": null,
"e": 2360,
"s": 2115,
"text": "The line-reader module provides eachLine() method which reads the file line by line. It had got a callback function which got two arguments: the line content and a boolean value that stores, whether the line read, was the last line of the file."
},
{
"code": null,
"e": 2488,
"s": 2360,
"text": "const lineReader = require('line-reader');\n\nlineReader.eachLine('source-to-file', (line, last) => {\n console.log(line);\n});\n"
},
{
"code": null,
"e": 2497,
"s": 2488,
"text": "Example:"
},
{
"code": "// Importing required librariesconst lineReader = require('line-reader'); // eachLine() method call on gfg.txt// It got a callback function// Printing content of file line by line// on the consolelineReader.eachLine('gfg.txt', (line, last) => { console.log(line);});",
"e": 2768,
"s": 2497,
"text": null
},
{
"code": null,
"e": 2776,
"s": 2768,
"text": "Output:"
},
{
"code": null,
"e": 2789,
"s": 2776,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 2796,
"s": 2789,
"text": "Picked"
},
{
"code": null,
"e": 2804,
"s": 2796,
"text": "Node.js"
},
{
"code": null,
"e": 2821,
"s": 2804,
"text": "Web Technologies"
},
{
"code": null,
"e": 2848,
"s": 2821,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2946,
"s": 2848,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3003,
"s": 2946,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 3057,
"s": 3003,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 3097,
"s": 3057,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 3132,
"s": 3097,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 3164,
"s": 3132,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 3226,
"s": 3164,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3287,
"s": 3226,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3337,
"s": 3287,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3380,
"s": 3337,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Variables in LISP | 16 Oct, 2021
Similar to other languages, in LISP variables are named places that store a particular value, but they are not declared the way you declare variables in C++ or Java i.e you don’t need to mention data-type of variables when declaring them as LISP is dynamically typed.
LISP supports two types of variables:
Local variablesGlobal variables
Local variables
Global variables
They are also called Lexical variables, these variables are defined inside a particular function and only the code within the binding form can refer to them as they can not be accessed outside of that function. Parameters of the functions are also local variables.
Defining a local variable:
New local variables can be created using the special operator LET. These variables then can be used within the body of the LET. The syntax for creating a variable with LET is:
(let (variable)
body-of-expressions)
A let expression has two parts
The first part consists of instructions for creating a variable and assigning values to them
The second part consists of a list of s-expressions
Now let’s create local variables using the above-mentioned syntax
Lisp
(let ((x 10) (y 20) z) (format t "Local Variables :~%") (format t "x = ~a, y = ~a & z=~a~%" x y z))
Here we have assigned x and y with initial values and for z no value is provided, hence NIL will be set as z’s default value.
Output :
Local Variables :
x = 10, y = 20 & z=NIL
These are the variables that have a global scope i.e. you can call access them from anywhere in the program. In LISP global variables are also called Dynamic variables.
Defining a global variable:
New global variables can be defined using DEFVAR and DEFPARAMETER construct. The difference between both of them is that DEFPARAMETER always assigns initial value and DEFVAR form can be used to create a global variable without giving it a value.
The syntax for creating global variables is:
(defvar *name* initial-value
"Documentation string")
(defparameter *name* initial-value
"Documentation string")
Example:
Let’s create a global variable that holds the rate of the pencil as *pencil-rate*, and with help of one function calculate the total bill by multiplying the total number of pencils with our global variable *pencil-rate*.
Lisp
(defparameter *pencil-rate* 10 "Pencil rate is set to 10") (defun calc-bill (n) "Calculates the total bill by multiplying the number of pencils with its global rate" (* *pencil-rate* n)) (write (calc-bill 20))
Output:
200
It is a proper naming convention to define global variables to start and end with asterisks because as global variables can be accessed anywhere in the program, there can be local variables with the same name, hence for avoiding this possibility by accident this naming convention is used. Example. *global*
LISP-Basics
Picked
LISP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Oct, 2021"
},
{
"code": null,
"e": 296,
"s": 28,
"text": "Similar to other languages, in LISP variables are named places that store a particular value, but they are not declared the way you declare variables in C++ or Java i.e you don’t need to mention data-type of variables when declaring them as LISP is dynamically typed."
},
{
"code": null,
"e": 334,
"s": 296,
"text": "LISP supports two types of variables:"
},
{
"code": null,
"e": 366,
"s": 334,
"text": "Local variablesGlobal variables"
},
{
"code": null,
"e": 382,
"s": 366,
"text": "Local variables"
},
{
"code": null,
"e": 399,
"s": 382,
"text": "Global variables"
},
{
"code": null,
"e": 664,
"s": 399,
"text": "They are also called Lexical variables, these variables are defined inside a particular function and only the code within the binding form can refer to them as they can not be accessed outside of that function. Parameters of the functions are also local variables."
},
{
"code": null,
"e": 691,
"s": 664,
"text": "Defining a local variable:"
},
{
"code": null,
"e": 867,
"s": 691,
"text": "New local variables can be created using the special operator LET. These variables then can be used within the body of the LET. The syntax for creating a variable with LET is:"
},
{
"code": null,
"e": 906,
"s": 867,
"text": "(let (variable)\n body-of-expressions)"
},
{
"code": null,
"e": 938,
"s": 906,
"text": "A let expression has two parts "
},
{
"code": null,
"e": 1031,
"s": 938,
"text": "The first part consists of instructions for creating a variable and assigning values to them"
},
{
"code": null,
"e": 1083,
"s": 1031,
"text": "The second part consists of a list of s-expressions"
},
{
"code": null,
"e": 1149,
"s": 1083,
"text": "Now let’s create local variables using the above-mentioned syntax"
},
{
"code": null,
"e": 1154,
"s": 1149,
"text": "Lisp"
},
{
"code": "(let ((x 10) (y 20) z) (format t \"Local Variables :~%\") (format t \"x = ~a, y = ~a & z=~a~%\" x y z))",
"e": 1256,
"s": 1154,
"text": null
},
{
"code": null,
"e": 1382,
"s": 1256,
"text": "Here we have assigned x and y with initial values and for z no value is provided, hence NIL will be set as z’s default value."
},
{
"code": null,
"e": 1392,
"s": 1382,
"text": "Output : "
},
{
"code": null,
"e": 1433,
"s": 1392,
"text": "Local Variables :\nx = 10, y = 20 & z=NIL"
},
{
"code": null,
"e": 1602,
"s": 1433,
"text": "These are the variables that have a global scope i.e. you can call access them from anywhere in the program. In LISP global variables are also called Dynamic variables."
},
{
"code": null,
"e": 1630,
"s": 1602,
"text": "Defining a global variable:"
},
{
"code": null,
"e": 1876,
"s": 1630,
"text": "New global variables can be defined using DEFVAR and DEFPARAMETER construct. The difference between both of them is that DEFPARAMETER always assigns initial value and DEFVAR form can be used to create a global variable without giving it a value."
},
{
"code": null,
"e": 1921,
"s": 1876,
"text": "The syntax for creating global variables is:"
},
{
"code": null,
"e": 2042,
"s": 1921,
"text": "(defvar *name* initial-value\n \"Documentation string\")\n \n(defparameter *name* initial-value\n \"Documentation string\") "
},
{
"code": null,
"e": 2051,
"s": 2042,
"text": "Example:"
},
{
"code": null,
"e": 2273,
"s": 2051,
"text": "Let’s create a global variable that holds the rate of the pencil as *pencil-rate*, and with help of one function calculate the total bill by multiplying the total number of pencils with our global variable *pencil-rate*."
},
{
"code": null,
"e": 2278,
"s": 2273,
"text": "Lisp"
},
{
"code": "(defparameter *pencil-rate* 10 \"Pencil rate is set to 10\") (defun calc-bill (n) \"Calculates the total bill by multiplying the number of pencils with its global rate\" (* *pencil-rate* n)) (write (calc-bill 20))",
"e": 2493,
"s": 2278,
"text": null
},
{
"code": null,
"e": 2501,
"s": 2493,
"text": "Output:"
},
{
"code": null,
"e": 2505,
"s": 2501,
"text": "200"
},
{
"code": null,
"e": 2813,
"s": 2505,
"text": "It is a proper naming convention to define global variables to start and end with asterisks because as global variables can be accessed anywhere in the program, there can be local variables with the same name, hence for avoiding this possibility by accident this naming convention is used. Example. *global*"
},
{
"code": null,
"e": 2825,
"s": 2813,
"text": "LISP-Basics"
},
{
"code": null,
"e": 2832,
"s": 2825,
"text": "Picked"
},
{
"code": null,
"e": 2837,
"s": 2832,
"text": "LISP"
}
] |
How to calculate and plot the derivative of a function using Python – Matplotlib ? | 24 Feb, 2021
In this article, we will plot the derivative of a function using matplotlib and python. For this we are using some modules in python which are as follows:
Matplotlib: Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays.
NumPy: It is a python library that is used for working with arrays, it also supports large multi-dimensional arrays and matrices, it also has several mathematical functions.
SciPy: Python has a library named as SciPy that is used for mathematical, scientific, and engineering calculations. This library depends on NumPy, and provides various numerical operations.
To plot the derivative of a function first, we have to calculate it. The scipy.misc library has a derivative() function which accepts one argument as a function and the other is the variable w.r.t which we will differentiate the function. So we will make a method named function() that will return the original function and a second method named deriv() that will return the derivative of that function.
After this calculation of the derivative of the input function, we will use the NumPy linspace() function which sets the range of the x-axis. The plot() function will be used to plot the function and also the derivative of that function.
Approach:
Import the modules required.
Define methods for function and its derivative
Use NumPy linspace function to make x-axis spacing.
Plot the function and its derivative
Change the limits of axis using gca() function
Plot the text using text() function
Example 1: (Derivative of cubic)
In this example, we will give the function f(x)=2x3+x+3 as input, then calculate the derivative and plot both the function and its derivative.
Python3
# importing the libraryimport matplotlib.pyplot as pltfrom scipy.misc import derivativeimport numpy as np # defining the functiondef function(x): return 2*x*x*x+x+3 # calculating its derivativedef deriv(x): return derivative(function, x) # defininf x-axis intervalsy = np.linspace(-6, 6) # plotting the functionplt.plot(y, function(y), color='purple', label='Function') # plotting its derivativeplt.plot(y, deriv(y), color='green', label='Derivative') # formattingplt.legend(loc='upper left')plt.grid(True)
Output:
Example 2: (Derivative of Poly degree polynomial)
In this example, we will give the function f(x)=x4+x2+5 as input, then calculate the derivative and plot both the function and its derivative.
Python3
# importing the libraryimport matplotlib.pyplot as pltfrom scipy.misc import derivativeimport numpy as np # defining the functiondef function(x): return x*x*x*x+x*x+5 # calculating its derivativedef deriv(x): return derivative(function, x) # defininf x-axis intervalsy = np.linspace(-15, 15) # plotting the functionplt.plot(y, function(y), color='red', label='Function') # plotting its derivativeplt.plot(y, deriv(y), color='green', label='Derivative') # formattingplt.legend(loc='upper left')plt.grid(True)
Output:
Example 3: (Derivative of quadratic with formatting by text)
In this example, we will plot the derivative of f(x)=4x2+x+1. Also, we will use some formatting using the gca() function that will change the limits of the axis so that both x, y axes intersect at the origin. The text() function which comes under matplotlib library plots the text on the graph and takes an argument as (x, y) coordinates. We will also do some formatting.
Python3
# importing modulesimport matplotlib.pyplot as pltfrom scipy.misc import derivativeimport numpy as np # method to return functiondef function(x): return 4*x**2+x+1 # method to return its derivativedef deriv(x): return derivative(function, x) #range in x-axisy = np.linspace(-6, 6) # plotting functionplt.plot(y, function(y), color='brown', label='Function') # plotting its derivativeplt.plot(y, deriv(y), color='blue', label='Derivative') # changing limits of y-axisplt.gca().spines['left'].set_position('zero',) # changing limits of x-axisplt.gca().spines['bottom'].set_position('zero',)plt.legend(loc='upper left') # plotting text in the graphplt.text(5.0, 1.0, r"$f'(x)=8x+1$", horizontalalignment='center', fontsize=18, color='blue') plt.text(-4.4, 25.0, r'$f(x)=4x^2+x+1$', horizontalalignment='center', fontsize=18, color='brown')plt.grid(True)
Output:
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 209,
"s": 54,
"text": "In this article, we will plot the derivative of a function using matplotlib and python. For this we are using some modules in python which are as follows:"
},
{
"code": null,
"e": 376,
"s": 209,
"text": "Matplotlib: Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays."
},
{
"code": null,
"e": 550,
"s": 376,
"text": "NumPy: It is a python library that is used for working with arrays, it also supports large multi-dimensional arrays and matrices, it also has several mathematical functions."
},
{
"code": null,
"e": 740,
"s": 550,
"text": "SciPy: Python has a library named as SciPy that is used for mathematical, scientific, and engineering calculations. This library depends on NumPy, and provides various numerical operations."
},
{
"code": null,
"e": 1144,
"s": 740,
"text": "To plot the derivative of a function first, we have to calculate it. The scipy.misc library has a derivative() function which accepts one argument as a function and the other is the variable w.r.t which we will differentiate the function. So we will make a method named function() that will return the original function and a second method named deriv() that will return the derivative of that function."
},
{
"code": null,
"e": 1382,
"s": 1144,
"text": "After this calculation of the derivative of the input function, we will use the NumPy linspace() function which sets the range of the x-axis. The plot() function will be used to plot the function and also the derivative of that function."
},
{
"code": null,
"e": 1392,
"s": 1382,
"text": "Approach:"
},
{
"code": null,
"e": 1421,
"s": 1392,
"text": "Import the modules required."
},
{
"code": null,
"e": 1468,
"s": 1421,
"text": "Define methods for function and its derivative"
},
{
"code": null,
"e": 1520,
"s": 1468,
"text": "Use NumPy linspace function to make x-axis spacing."
},
{
"code": null,
"e": 1557,
"s": 1520,
"text": "Plot the function and its derivative"
},
{
"code": null,
"e": 1604,
"s": 1557,
"text": "Change the limits of axis using gca() function"
},
{
"code": null,
"e": 1640,
"s": 1604,
"text": "Plot the text using text() function"
},
{
"code": null,
"e": 1674,
"s": 1640,
"text": "Example 1: (Derivative of cubic) "
},
{
"code": null,
"e": 1817,
"s": 1674,
"text": "In this example, we will give the function f(x)=2x3+x+3 as input, then calculate the derivative and plot both the function and its derivative."
},
{
"code": null,
"e": 1825,
"s": 1817,
"text": "Python3"
},
{
"code": "# importing the libraryimport matplotlib.pyplot as pltfrom scipy.misc import derivativeimport numpy as np # defining the functiondef function(x): return 2*x*x*x+x+3 # calculating its derivativedef deriv(x): return derivative(function, x) # defininf x-axis intervalsy = np.linspace(-6, 6) # plotting the functionplt.plot(y, function(y), color='purple', label='Function') # plotting its derivativeplt.plot(y, deriv(y), color='green', label='Derivative') # formattingplt.legend(loc='upper left')plt.grid(True)",
"e": 2344,
"s": 1825,
"text": null
},
{
"code": null,
"e": 2352,
"s": 2344,
"text": "Output:"
},
{
"code": null,
"e": 2403,
"s": 2352,
"text": "Example 2: (Derivative of Poly degree polynomial) "
},
{
"code": null,
"e": 2546,
"s": 2403,
"text": "In this example, we will give the function f(x)=x4+x2+5 as input, then calculate the derivative and plot both the function and its derivative."
},
{
"code": null,
"e": 2554,
"s": 2546,
"text": "Python3"
},
{
"code": "# importing the libraryimport matplotlib.pyplot as pltfrom scipy.misc import derivativeimport numpy as np # defining the functiondef function(x): return x*x*x*x+x*x+5 # calculating its derivativedef deriv(x): return derivative(function, x) # defininf x-axis intervalsy = np.linspace(-15, 15) # plotting the functionplt.plot(y, function(y), color='red', label='Function') # plotting its derivativeplt.plot(y, deriv(y), color='green', label='Derivative') # formattingplt.legend(loc='upper left')plt.grid(True)",
"e": 3076,
"s": 2554,
"text": null
},
{
"code": null,
"e": 3084,
"s": 3076,
"text": "Output:"
},
{
"code": null,
"e": 3146,
"s": 3084,
"text": "Example 3: (Derivative of quadratic with formatting by text) "
},
{
"code": null,
"e": 3518,
"s": 3146,
"text": "In this example, we will plot the derivative of f(x)=4x2+x+1. Also, we will use some formatting using the gca() function that will change the limits of the axis so that both x, y axes intersect at the origin. The text() function which comes under matplotlib library plots the text on the graph and takes an argument as (x, y) coordinates. We will also do some formatting."
},
{
"code": null,
"e": 3526,
"s": 3518,
"text": "Python3"
},
{
"code": "# importing modulesimport matplotlib.pyplot as pltfrom scipy.misc import derivativeimport numpy as np # method to return functiondef function(x): return 4*x**2+x+1 # method to return its derivativedef deriv(x): return derivative(function, x) #range in x-axisy = np.linspace(-6, 6) # plotting functionplt.plot(y, function(y), color='brown', label='Function') # plotting its derivativeplt.plot(y, deriv(y), color='blue', label='Derivative') # changing limits of y-axisplt.gca().spines['left'].set_position('zero',) # changing limits of x-axisplt.gca().spines['bottom'].set_position('zero',)plt.legend(loc='upper left') # plotting text in the graphplt.text(5.0, 1.0, r\"$f'(x)=8x+1$\", horizontalalignment='center', fontsize=18, color='blue') plt.text(-4.4, 25.0, r'$f(x)=4x^2+x+1$', horizontalalignment='center', fontsize=18, color='brown')plt.grid(True)",
"e": 4408,
"s": 3526,
"text": null
},
{
"code": null,
"e": 4416,
"s": 4408,
"text": "Output:"
},
{
"code": null,
"e": 4423,
"s": 4416,
"text": "Picked"
},
{
"code": null,
"e": 4441,
"s": 4423,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 4465,
"s": 4441,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 4472,
"s": 4465,
"text": "Python"
},
{
"code": null,
"e": 4491,
"s": 4472,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4589,
"s": 4491,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4607,
"s": 4589,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4649,
"s": 4607,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4671,
"s": 4649,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4706,
"s": 4671,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4732,
"s": 4706,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4764,
"s": 4732,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4793,
"s": 4764,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4823,
"s": 4793,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 4850,
"s": 4823,
"text": "Python Classes and Objects"
}
] |
Scala List filterNot() method with example | 26 Jul, 2019
The filterNot() method is utilized to select all elements of the list which does not satisfies a stated predicate.
Method Definition: def filterNot(p: (A) => Boolean): List[A]
Return Type: It returns a new list consisting all the elements of the list which does not satisfies the given predicate.
Example #1:
// Scala program of filterNot()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(5, 12, 3, 13) // Applying filterNot method val result = m1.filterNot(_ < 10) // Displays output println(result) }}
List(12, 13)
Example #2:
// Scala program of filterNot()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(5, 12, 3, 13) // Applying filterNot method val result = m1.filterNot(_ < 3) // Displays output println(result) }}
List(5, 12, 3, 13)
Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jul, 2019"
},
{
"code": null,
"e": 143,
"s": 28,
"text": "The filterNot() method is utilized to select all elements of the list which does not satisfies a stated predicate."
},
{
"code": null,
"e": 204,
"s": 143,
"text": "Method Definition: def filterNot(p: (A) => Boolean): List[A]"
},
{
"code": null,
"e": 325,
"s": 204,
"text": "Return Type: It returns a new list consisting all the elements of the list which does not satisfies the given predicate."
},
{
"code": null,
"e": 337,
"s": 325,
"text": "Example #1:"
},
{
"code": "// Scala program of filterNot()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(5, 12, 3, 13) // Applying filterNot method val result = m1.filterNot(_ < 10) // Displays output println(result) }}",
"e": 692,
"s": 337,
"text": null
},
{
"code": null,
"e": 706,
"s": 692,
"text": "List(12, 13)\n"
},
{
"code": null,
"e": 718,
"s": 706,
"text": "Example #2:"
},
{
"code": "// Scala program of filterNot()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(5, 12, 3, 13) // Applying filterNot method val result = m1.filterNot(_ < 3) // Displays output println(result) }}",
"e": 1072,
"s": 718,
"text": null
},
{
"code": null,
"e": 1092,
"s": 1072,
"text": "List(5, 12, 3, 13)\n"
},
{
"code": null,
"e": 1098,
"s": 1092,
"text": "Scala"
},
{
"code": null,
"e": 1109,
"s": 1098,
"text": "Scala-list"
},
{
"code": null,
"e": 1122,
"s": 1109,
"text": "Scala-Method"
},
{
"code": null,
"e": 1128,
"s": 1122,
"text": "Scala"
}
] |
Python | How to lock Critical Sections | 24 Jun, 2019
This article aims how to lock the threads and critical sections in the given program to avoid race conditions. So, using Lock object in the threading library to make mutable objects safe to use by multiple threads.
Code #1 :
import threading class counter_share: ''' multiple threads can share. ''' def __init__(self, initial_key = 0): self._key = initial_key self._key_lock = threading.Lock() def incr(self, delta = 1): with self._key_lock: # Increasing the counter with lock self._key += delta def decr(self, delta = 1): with self._key_lock: # Decreasing the counter with lock self._key -= delta
Using a with statement along with the lock ensures the mutual exclusion. By exclusion, it is meant that at a time only one thread (under with statement) is allowed to execute the block of a statement.The lock for the duration of intended statements is acquired and is released when the control flow exits the indented block. Thread scheduling is inherently nondeterministic. Because of this, randomly corrupted data and ‘race condition’ can result as there is a failure to use locks. So, whenever a shared mutable state is accessed by multiple threads, locks should always be used to avoid this.
In older Python code, it is common to see locks explicitly acquired and released.
Code #2 : Variant of code 1
import threading class counter_share: # multiple threads can share counter objects def __init__(self, initial_key = 0): self._key = initial_key self._key_lock = threading.Lock() def incr(self, delta = 1): # Increasing the counter with lock self._key_lock.acquire() self._key += delta self._key_lock.release() def decr(self, delta = 1): # Decreasing the counter with lock self._key_lock.acquire() self._key -= delta self._key_lock.release()
In situations where release() method is not called or while holding a lock no exception is raised, the with statement is much less prone to error.
Each thread in a program is not allowed to acquire one lock at a time, this can potentially avoid the cases of deadlock. Introduce more advanced deadlock avoidance into the program if it is not possible.
Synchronization primitives, such as RLock and Semaphore objects are found in the threading library.
Except the simple module locking, there is some more special purpose being solved :
An RLock or re-entrant lock object is a lock that can be acquired multiple times by the same thread.
It implements code primarily on the basis of locking or synchronization a construct known as a “monitor.” Only one thread is allowed to use an entire function or the methods of a class while the lock is held, with this type of locking.
Code #3 : Implementing the SharedCounter class.
import threading class counter_share: # multiple threads can share counter objects _lock = threading.RLock() def __init__(self, initial_key = 0): self._key = initial_key def incr(self, delta = 1): # Increasing the counter with lock with SharedCounter._lock: self._key += delta def decr(self, delta = 1): # Decreasing the counter with lock with SharedCounter._lock: self.incr(-delta)
The lock is meant to synchronize the methods of the class, inspite of lock being tied to the per-instance mutable state.
There is just a single class-level lock shared by all instances of the class in this code variant.
Only one thread is allowed to be using the methods of the class at once is ensured.
it is OK for methods to call other methods that also use the lock if they already have the locks. (for example the decr() method).
If there are a large number of counters, it is much more memory-efficient. However, it may cause more lock contention in programs that use a large number of threads and make frequent counter updates.
A Semaphore item is a synchronization crude dependent on a mutual counter. The counter is increased upon the finish of the with square. On the off chance that the counter is zero, advance is obstructed until the counter is increased by another string. On the off chance that the counter is nonzero, the with explanation decrements the tally and a string is permitted to continue.Rather than straightforward locking, Semaphore items are increasingly valuable for applications including motioning between strings or throttling. Despite the fact that a semaphore can be utilized in a similar way as a standard Lock, the additional multifaceted nature in usage contrarily impacts execution.
Code #4 : To limit the amount of concurrency in a part of code, use a semaphore.
from threading import Semaphoreimport urllib.request # five threads are allowed to run at once (at max)_fetch_url_sema = Semaphore(5) def fetch_url(url): with _fetch_url_sema: return urllib.request.urlopen(url)
python-utility
Operating Systems
Python
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jun, 2019"
},
{
"code": null,
"e": 243,
"s": 28,
"text": "This article aims how to lock the threads and critical sections in the given program to avoid race conditions. So, using Lock object in the threading library to make mutable objects safe to use by multiple threads."
},
{
"code": null,
"e": 253,
"s": 243,
"text": "Code #1 :"
},
{
"code": "import threading class counter_share: ''' multiple threads can share. ''' def __init__(self, initial_key = 0): self._key = initial_key self._key_lock = threading.Lock() def incr(self, delta = 1): with self._key_lock: # Increasing the counter with lock self._key += delta def decr(self, delta = 1): with self._key_lock: # Decreasing the counter with lock self._key -= delta",
"e": 737,
"s": 253,
"text": null
},
{
"code": null,
"e": 1333,
"s": 737,
"text": "Using a with statement along with the lock ensures the mutual exclusion. By exclusion, it is meant that at a time only one thread (under with statement) is allowed to execute the block of a statement.The lock for the duration of intended statements is acquired and is released when the control flow exits the indented block. Thread scheduling is inherently nondeterministic. Because of this, randomly corrupted data and ‘race condition’ can result as there is a failure to use locks. So, whenever a shared mutable state is accessed by multiple threads, locks should always be used to avoid this."
},
{
"code": null,
"e": 1415,
"s": 1333,
"text": "In older Python code, it is common to see locks explicitly acquired and released."
},
{
"code": null,
"e": 1443,
"s": 1415,
"text": "Code #2 : Variant of code 1"
},
{
"code": "import threading class counter_share: # multiple threads can share counter objects def __init__(self, initial_key = 0): self._key = initial_key self._key_lock = threading.Lock() def incr(self, delta = 1): # Increasing the counter with lock self._key_lock.acquire() self._key += delta self._key_lock.release() def decr(self, delta = 1): # Decreasing the counter with lock self._key_lock.acquire() self._key -= delta self._key_lock.release()",
"e": 1986,
"s": 1443,
"text": null
},
{
"code": null,
"e": 2133,
"s": 1986,
"text": "In situations where release() method is not called or while holding a lock no exception is raised, the with statement is much less prone to error."
},
{
"code": null,
"e": 2337,
"s": 2133,
"text": "Each thread in a program is not allowed to acquire one lock at a time, this can potentially avoid the cases of deadlock. Introduce more advanced deadlock avoidance into the program if it is not possible."
},
{
"code": null,
"e": 2437,
"s": 2337,
"text": "Synchronization primitives, such as RLock and Semaphore objects are found in the threading library."
},
{
"code": null,
"e": 2521,
"s": 2437,
"text": "Except the simple module locking, there is some more special purpose being solved :"
},
{
"code": null,
"e": 2622,
"s": 2521,
"text": "An RLock or re-entrant lock object is a lock that can be acquired multiple times by the same thread."
},
{
"code": null,
"e": 2858,
"s": 2622,
"text": "It implements code primarily on the basis of locking or synchronization a construct known as a “monitor.” Only one thread is allowed to use an entire function or the methods of a class while the lock is held, with this type of locking."
},
{
"code": null,
"e": 2906,
"s": 2858,
"text": "Code #3 : Implementing the SharedCounter class."
},
{
"code": "import threading class counter_share: # multiple threads can share counter objects _lock = threading.RLock() def __init__(self, initial_key = 0): self._key = initial_key def incr(self, delta = 1): # Increasing the counter with lock with SharedCounter._lock: self._key += delta def decr(self, delta = 1): # Decreasing the counter with lock with SharedCounter._lock: self.incr(-delta)",
"e": 3392,
"s": 2906,
"text": null
},
{
"code": null,
"e": 3513,
"s": 3392,
"text": "The lock is meant to synchronize the methods of the class, inspite of lock being tied to the per-instance mutable state."
},
{
"code": null,
"e": 3612,
"s": 3513,
"text": "There is just a single class-level lock shared by all instances of the class in this code variant."
},
{
"code": null,
"e": 3696,
"s": 3612,
"text": "Only one thread is allowed to be using the methods of the class at once is ensured."
},
{
"code": null,
"e": 3827,
"s": 3696,
"text": "it is OK for methods to call other methods that also use the lock if they already have the locks. (for example the decr() method)."
},
{
"code": null,
"e": 4027,
"s": 3827,
"text": "If there are a large number of counters, it is much more memory-efficient. However, it may cause more lock contention in programs that use a large number of threads and make frequent counter updates."
},
{
"code": null,
"e": 4714,
"s": 4027,
"text": "A Semaphore item is a synchronization crude dependent on a mutual counter. The counter is increased upon the finish of the with square. On the off chance that the counter is zero, advance is obstructed until the counter is increased by another string. On the off chance that the counter is nonzero, the with explanation decrements the tally and a string is permitted to continue.Rather than straightforward locking, Semaphore items are increasingly valuable for applications including motioning between strings or throttling. Despite the fact that a semaphore can be utilized in a similar way as a standard Lock, the additional multifaceted nature in usage contrarily impacts execution."
},
{
"code": null,
"e": 4795,
"s": 4714,
"text": "Code #4 : To limit the amount of concurrency in a part of code, use a semaphore."
},
{
"code": "from threading import Semaphoreimport urllib.request # five threads are allowed to run at once (at max)_fetch_url_sema = Semaphore(5) def fetch_url(url): with _fetch_url_sema: return urllib.request.urlopen(url)",
"e": 5018,
"s": 4795,
"text": null
},
{
"code": null,
"e": 5033,
"s": 5018,
"text": "python-utility"
},
{
"code": null,
"e": 5051,
"s": 5033,
"text": "Operating Systems"
},
{
"code": null,
"e": 5058,
"s": 5051,
"text": "Python"
},
{
"code": null,
"e": 5076,
"s": 5058,
"text": "Operating Systems"
}
] |
Notifications in Android with Example | 01 Jan, 2021
Notification is a kind of message, alert, or status of an application (probably running in the background) that is visible or available in the Android’s UI elements. This application could be running in the background but not in use by the user. The purpose of a notification is to notify the user about a process that was initiated in the application either by the user or the system. This article could help someone who’s trying hard to create a notification for developmental purposes.
Notifications could be of various formats and designs depending upon the developer. In General, one must have witnessed these four types of notifications:
Status Bar Notification (appears in the same layout as the current time, battery percentage)Notification drawer Notification (appears in the drop-down menu)Heads-Up Notification (appears on the overlay screen, ex: Whatsapp notification, OTP messages)Lock-Screen Notification (I guess you know it)
Status Bar Notification (appears in the same layout as the current time, battery percentage)
Notification drawer Notification (appears in the drop-down menu)
Heads-Up Notification (appears on the overlay screen, ex: Whatsapp notification, OTP messages)
Lock-Screen Notification (I guess you know it)
In this article, we will be discussing how to produce notifications in Kotlin.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. In this step, we are going to design our layout page. Here, we will use the RelativeLayout to get the Scroll View from the Kotlin file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Send Notification" /> </RelativeLayout>
Step 3: Create a new empty activity
Reference article: How to Create Constructor, Getter/Setter Methods and New Activity in Android Studio using Shortcuts?
Name the activity as afterNotification. When someone clicks on the notification, this activity will open up in our app that is the user will be redirected to this page. Below is the code for the activity_after_notification.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".afterNotification"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Welcome To GeeksforGeeks" android:textSize="15sp" android:textStyle="bold" /> </RelativeLayout>
Note 1: Without configuring Notification Channels, you cannot build notification for applications with Android API >=26. For them generating a notification channel is mandatory. Apps with API<26 don’t need notification channels they just need notification builder. Each channel is supposed to have a particular behavior that will be applicable to all the notifications which are a part of it. Every channel will, therefore, have a Channel ID which basically will act as a unique identifier for this Channel which will be useful if the user wants to differentiate a particular notification channel. In contrast, the Notification builder provides a convenient way to set the various fields of a Notification and generate content views using the platform’s notification layout template but is not able to target a particular notification channel.
Note 2: If you have referred any other documentation or any other blog before this one, you might have noticed them appealing to implement the following dependency“com.android.support:support-compat:28.0.0”. What I’ve personally experienced is that there’s no need to implement it, things go far and good without this also.
Step 5: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.app.Notificationimport android.app.NotificationChannelimport android.app.NotificationManagerimport android.app.PendingIntentimport android.content.Contextimport android.content.Intentimport android.graphics.BitmapFactoryimport android.graphics.Colorimport android.os.Buildimport android.os.Bundleimport android.widget.Buttonimport android.widget.RemoteViewsimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // declaring variables lateinit var notificationManager: NotificationManager lateinit var notificationChannel: NotificationChannel lateinit var builder: Notification.Builder private val channelId = "i.apps.notifications" private val description = "Test notification" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // accessing button val btn = findViewById<Button>(R.id.btn) // it is a class to notify the user of events that happen. // This is how you tell the user that something has happened in the // background. notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // onClick listener for the button btn.setOnClickListener { // pendingIntent is an intent for future use i.e after // the notification is clicked, this intent will come into action val intent = Intent(this, afterNotification::class.java) // FLAG_UPDATE_CURRENT specifies that if a previous // PendingIntent already exists, then the current one // will update it with the latest intent // 0 is the request code, using it later with the // same method again will get back the same pending // intent for future reference // intent passed here is to our afterNotification class val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) // RemoteViews are used to use the content of // some different layout apart from the current activity layout val contentView = RemoteViews(packageName, R.layout.activity_after_notification) // checking if android version is greater than oreo(API 26) or not if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationChannel = NotificationChannel(channelId, description, NotificationManager.IMPORTANCE_HIGH) notificationChannel.enableLights(true) notificationChannel.lightColor = Color.GREEN notificationChannel.enableVibration(false) notificationManager.createNotificationChannel(notificationChannel) builder = Notification.Builder(this, channelId) .setContent(contentView) .setSmallIcon(R.drawable.ic_launcher_background) .setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.ic_launcher_background)) .setContentIntent(pendingIntent) } else { builder = Notification.Builder(this) .setContent(contentView) .setSmallIcon(R.drawable.ic_launcher_background) .setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.ic_launcher_background)) .setContentIntent(pendingIntent) } notificationManager.notify(1234, builder.build()) } }}
With this, we have now successfully created a “Notification” for our application. Note that the parameters listed in the above code are required and the absence of any single parameter could result in crashing or not starting the application. The content title, content text, small icon are customizable parameters but are mandatory also. One can change their values according to the requirement.
aashaypawar
omrisarig13
Kotlin Android
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android RecyclerView in Kotlin
Kotlin constructor
Broadcast Receiver in Android With Example
Retrofit with Kotlin Coroutine in Android
Content Providers in Android with Example
Kotlin Setters and Getters
How to Add and Customize Back Button of Action Bar in Android?
Android Menus
How to Change the Color of Status Bar in an Android App?
Kotlin Higher-Order Functions | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jan, 2021"
},
{
"code": null,
"e": 542,
"s": 52,
"text": "Notification is a kind of message, alert, or status of an application (probably running in the background) that is visible or available in the Android’s UI elements. This application could be running in the background but not in use by the user. The purpose of a notification is to notify the user about a process that was initiated in the application either by the user or the system. This article could help someone who’s trying hard to create a notification for developmental purposes. "
},
{
"code": null,
"e": 697,
"s": 542,
"text": "Notifications could be of various formats and designs depending upon the developer. In General, one must have witnessed these four types of notifications:"
},
{
"code": null,
"e": 994,
"s": 697,
"text": "Status Bar Notification (appears in the same layout as the current time, battery percentage)Notification drawer Notification (appears in the drop-down menu)Heads-Up Notification (appears on the overlay screen, ex: Whatsapp notification, OTP messages)Lock-Screen Notification (I guess you know it)"
},
{
"code": null,
"e": 1087,
"s": 994,
"text": "Status Bar Notification (appears in the same layout as the current time, battery percentage)"
},
{
"code": null,
"e": 1152,
"s": 1087,
"text": "Notification drawer Notification (appears in the drop-down menu)"
},
{
"code": null,
"e": 1247,
"s": 1152,
"text": "Heads-Up Notification (appears on the overlay screen, ex: Whatsapp notification, OTP messages)"
},
{
"code": null,
"e": 1294,
"s": 1247,
"text": "Lock-Screen Notification (I guess you know it)"
},
{
"code": null,
"e": 1374,
"s": 1294,
"text": "In this article, we will be discussing how to produce notifications in Kotlin. "
},
{
"code": null,
"e": 1403,
"s": 1374,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1567,
"s": 1403,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 1615,
"s": 1567,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1867,
"s": 1615,
"text": "Go to the activity_main.xml file and refer to the following code. In this step, we are going to design our layout page. Here, we will use the RelativeLayout to get the Scroll View from the Kotlin file. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 1871,
"s": 1867,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/btn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Send Notification\" /> </RelativeLayout>",
"e": 2383,
"s": 1871,
"text": null
},
{
"code": null,
"e": 2419,
"s": 2383,
"text": "Step 3: Create a new empty activity"
},
{
"code": null,
"e": 2540,
"s": 2419,
"text": "Reference article: How to Create Constructor, Getter/Setter Methods and New Activity in Android Studio using Shortcuts? "
},
{
"code": null,
"e": 2773,
"s": 2540,
"text": "Name the activity as afterNotification. When someone clicks on the notification, this activity will open up in our app that is the user will be redirected to this page. Below is the code for the activity_after_notification.xml file."
},
{
"code": null,
"e": 2777,
"s": 2773,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".afterNotification\"> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Welcome To GeeksforGeeks\" android:textSize=\"15sp\" android:textStyle=\"bold\" /> </RelativeLayout>",
"e": 3371,
"s": 2777,
"text": null
},
{
"code": null,
"e": 4216,
"s": 3371,
"text": "Note 1: Without configuring Notification Channels, you cannot build notification for applications with Android API >=26. For them generating a notification channel is mandatory. Apps with API<26 don’t need notification channels they just need notification builder. Each channel is supposed to have a particular behavior that will be applicable to all the notifications which are a part of it. Every channel will, therefore, have a Channel ID which basically will act as a unique identifier for this Channel which will be useful if the user wants to differentiate a particular notification channel. In contrast, the Notification builder provides a convenient way to set the various fields of a Notification and generate content views using the platform’s notification layout template but is not able to target a particular notification channel. "
},
{
"code": null,
"e": 4540,
"s": 4216,
"text": "Note 2: If you have referred any other documentation or any other blog before this one, you might have noticed them appealing to implement the following dependency“com.android.support:support-compat:28.0.0”. What I’ve personally experienced is that there’s no need to implement it, things go far and good without this also."
},
{
"code": null,
"e": 4586,
"s": 4540,
"text": "Step 5: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 4772,
"s": 4586,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 4779,
"s": 4772,
"text": "Kotlin"
},
{
"code": "import android.app.Notificationimport android.app.NotificationChannelimport android.app.NotificationManagerimport android.app.PendingIntentimport android.content.Contextimport android.content.Intentimport android.graphics.BitmapFactoryimport android.graphics.Colorimport android.os.Buildimport android.os.Bundleimport android.widget.Buttonimport android.widget.RemoteViewsimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // declaring variables lateinit var notificationManager: NotificationManager lateinit var notificationChannel: NotificationChannel lateinit var builder: Notification.Builder private val channelId = \"i.apps.notifications\" private val description = \"Test notification\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // accessing button val btn = findViewById<Button>(R.id.btn) // it is a class to notify the user of events that happen. // This is how you tell the user that something has happened in the // background. notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // onClick listener for the button btn.setOnClickListener { // pendingIntent is an intent for future use i.e after // the notification is clicked, this intent will come into action val intent = Intent(this, afterNotification::class.java) // FLAG_UPDATE_CURRENT specifies that if a previous // PendingIntent already exists, then the current one // will update it with the latest intent // 0 is the request code, using it later with the // same method again will get back the same pending // intent for future reference // intent passed here is to our afterNotification class val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) // RemoteViews are used to use the content of // some different layout apart from the current activity layout val contentView = RemoteViews(packageName, R.layout.activity_after_notification) // checking if android version is greater than oreo(API 26) or not if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationChannel = NotificationChannel(channelId, description, NotificationManager.IMPORTANCE_HIGH) notificationChannel.enableLights(true) notificationChannel.lightColor = Color.GREEN notificationChannel.enableVibration(false) notificationManager.createNotificationChannel(notificationChannel) builder = Notification.Builder(this, channelId) .setContent(contentView) .setSmallIcon(R.drawable.ic_launcher_background) .setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.ic_launcher_background)) .setContentIntent(pendingIntent) } else { builder = Notification.Builder(this) .setContent(contentView) .setSmallIcon(R.drawable.ic_launcher_background) .setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.ic_launcher_background)) .setContentIntent(pendingIntent) } notificationManager.notify(1234, builder.build()) } }}",
"e": 8377,
"s": 4779,
"text": null
},
{
"code": null,
"e": 8774,
"s": 8377,
"text": "With this, we have now successfully created a “Notification” for our application. Note that the parameters listed in the above code are required and the absence of any single parameter could result in crashing or not starting the application. The content title, content text, small icon are customizable parameters but are mandatory also. One can change their values according to the requirement."
},
{
"code": null,
"e": 8786,
"s": 8774,
"text": "aashaypawar"
},
{
"code": null,
"e": 8798,
"s": 8786,
"text": "omrisarig13"
},
{
"code": null,
"e": 8813,
"s": 8798,
"text": "Kotlin Android"
},
{
"code": null,
"e": 8820,
"s": 8813,
"text": "Picked"
},
{
"code": null,
"e": 8827,
"s": 8820,
"text": "Kotlin"
},
{
"code": null,
"e": 8925,
"s": 8827,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8956,
"s": 8925,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 8975,
"s": 8956,
"text": "Kotlin constructor"
},
{
"code": null,
"e": 9018,
"s": 8975,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 9060,
"s": 9018,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 9102,
"s": 9060,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 9129,
"s": 9102,
"text": "Kotlin Setters and Getters"
},
{
"code": null,
"e": 9192,
"s": 9129,
"text": "How to Add and Customize Back Button of Action Bar in Android?"
},
{
"code": null,
"e": 9206,
"s": 9192,
"text": "Android Menus"
},
{
"code": null,
"e": 9263,
"s": 9206,
"text": "How to Change the Color of Status Bar in an Android App?"
}
] |
Program for n’th node from the end of a Linked List | 15 Jun, 2022
Given a Linked List and a number n, write a function that returns the value at the n’th node from the end of the Linked List.For example, if the input is below list and n = 3, then output is “B”
Method 1 (Use length of linked list) 1) Calculate the length of the Linked List. Let the length be len. 2) Print the (len – n + 1)th node from the beginning of the Linked List.
Double pointer concept: First pointer is used to store the address of the variable and the second pointer is used to store the address of the first pointer. If we wish to change the value of a variable by a function, we pass a pointer to it. And if we wish to change the value of a pointer (i. e., it should start pointing to something else), we pass the pointer to a pointer.
Below is the implementation of the above approach:
C++14
C
Java
Python3
C#
Javascript
// Simple C++ program to find n'th node from end#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Function to get the nth node from the last of a linked list*/void printNthFromLast(struct Node* head, int n){ int len = 0, i; struct Node* temp = head; // count the number of nodes in Linked List while (temp != NULL) { temp = temp->next; len++; } // check if value of n is not // more than length of the linked list if (len < n) return; temp = head; // get the (len-n+1)th node from the beginning for (i = 1; i < len - n + 1; i++) temp = temp->next; cout << temp->data; return;} void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Driver Codeint main(){ /* Start with the empty list */ struct Node* head = NULL; // create linked 35->15->4->20 push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 35); printNthFromLast(head, 4); return 0;}
// Simple C++ program to find n'th node from end#include <stdio.h>#include <stdlib.h> /* Link list node */typedef struct Node { int data; struct Node* next;}Node; /* Function to get the nth node from the last of a linked list*/void printNthFromLast(Node* head, int n){ int len = 0, i; Node* temp = head; // count the number of nodes in Linked List while (temp != NULL) { temp = temp->next; len++; } // check if value of n is not // more than length of the linked list if (len < n) return; temp = head; // get the (len-n+1)th node from the beginning for (i = 1; i < len - n + 1; i++) temp = temp->next; printf("%d",temp->data); return;} void push(struct Node** head_ref, int new_data){ /* allocate node */ Node* new_node = (Node *)malloc(sizeof(Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Driver Codeint main(){ /* Start with the empty list */ struct Node* head = NULL; // create linked 35->15->4->20 push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 35); printNthFromLast(head, 4); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Simple Java program to find n'th node from end of linked listclass LinkedList { Node head; // head of the list /* Linked List node */ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to get the nth node from the last of a linked list */ void printNthFromLast(int n) { int len = 0; Node temp = head; // 1) count the number of nodes in Linked List while (temp != null) { temp = temp.next; len++; } // check if value of n is not more than length of // the linked list if (len < n) return; temp = head; // 2) get the (len-n+1)th node from the beginning for (int i = 1; i < len - n + 1; i++) temp = temp.next; System.out.println(temp.data); } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /*Driver program to test above methods */ public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(35); llist.printNthFromLast(4); }} // This code is contributed by Rajat Mishra
# Simple Python3 program to find# n'th node from endclass Node: def __init__(self, new_data): self.data = new_data self.next = None class LinkedList: def __init__(self): self.head = None # createNode and make linked list def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Function to get the nth node from # the last of a linked list def printNthFromLast(self, n): temp = self.head # used temp variable length = 0 while temp is not None: temp = temp.next length += 1 # print count if n > length: # if entered location is greater # than length of linked list print('Location is greater than the' + ' length of LinkedList') return temp = self.head for i in range(0, length - n): temp = temp.next print(temp.data) # Driver Code llist = LinkedList()llist.push(20)llist.push(4)llist.push(15)llist.push(35)llist.printNthFromLast(4) # This code is contributed by Yogesh Joshi
// C# program to find n'th node from end of linked listusing System; public class LinkedList{ public Node head; // head of the list /* Linked List node */ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Function to get the nth node from the last of a linked list */ void printNthFromLast(int n) { int len = 0; Node temp = head; // 1) count the number of nodes in Linked List while (temp != null) { temp = temp.next; len++; } // check if value of n is not more than length of // the linked list if (len < n) return; temp = head; // 2) get the (len-n+1)th node from the beginning for (int i = 1; i < len - n + 1; i++) temp = temp.next; Console.WriteLine(temp.data); } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /*Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(35); llist.printNthFromLast(4); }} // This code is contributed by Rajput-Ji
<script> // Simple Javascript program to find n'th node from end of linked list /* Linked List node */ class Node { constructor(d) { this.data = d; this.next = null; } } /* Function to get the nth node from the last of a linked list */ class LinkedList { constructor(d){ this.head = d; } printNthFromLast(n) { let len = 0; let temp = this.head; // 1) count the number of nodes in Linked List while (temp != null) { temp = temp.next; len++; } // check if value of n is not more than length of // the linked list if (len < n) return; temp = this.head; // 2) get the (len-n+1)th node from the beginning for (let i = 1; i < len - n + 1; i++) temp = temp.next; document.write(temp.data); } /* Inserts a new Node at front of the list. */ push(new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ let new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = this.head; /* 4. Move the head to point to new Node */ this.head = new_node; } } /*Driver program to test above methods */ let llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(35); llist.printNthFromLast(4); // This code is contributed by Saurabh Jaiswal </script>
35
Time complexity: O(n) where n is size of the linked list
Auxiliary Space: O(1)
Following is a recursive C code for the same method. Thanks to Anuj Bansal for providing following code.
Implementation:
C++
C
Java
Python3
C#
Javascript
void printNthFromLast(struct Node* head, int n){ int i = 0; if (head == NULL) return; printNthFromLast(head->next, n); if (++i == n) cout<<head->data;}
void printNthFromLast(struct Node* head, int n){ static int i = 0; if (head == NULL) return; printNthFromLast(head->next, n); if (++i == n) printf("%d", head->data);}
static void printNthFromLast(Node head, int n){ int i = 0; if (head == null) return; printNthFromLast(head.next, n); if (++i == n) System.out.print(head.data);} // This code is contributed by rutvik_56.
def printNthFromLast(head, n): i = 0 if (head == None) return printNthFromLast(head.next, n); i+=1 if (i == n): print(head.data) # This code is contributed by sunils0ni.
static void printNthFromLast(Node head, int n){ static int i = 0; if (head == null) return; printNthFromLast(head.next, n); if (++i == n) Console.Write(head.data);} // This code is contributed by pratham76.
<script>function printNthFromLast(head , n){ function i = 0; if (head == null) return; printNthFromLast(head.next, n); if (++i == n) document.write(head.data);} // This code is contributed by gauravrajput1</script>
Time Complexity: O(n) where n is the length of linked list.
Method 2 (Use two pointers) Maintain two pointers – reference pointer and main pointer. Initialize both reference and main pointers to head. First, move the reference pointer to n nodes from head. Now move both pointers one by one until the reference pointer reaches the end. Now the main pointer will point to nth node from the end. Return the main pointer.Below image is a dry run of the above approach:
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find n-th node// from the end of the linked list. #include <bits/stdc++.h>using namespace std; struct node { int data; node* next; node(int val) { data = val; next = NULL; }}; struct llist { node* head; llist() { head = NULL; } // insert operation at the beginning of the list. void insertAtBegin(int val) { node* newNode = new node(val); newNode->next = head; head = newNode; } // finding n-th node from the end. void nthFromEnd(int n) { // create two pointers main_ptr and ref_ptr // initially pointing to head. node* main_ptr = head; node* ref_ptr = head; // if list is empty, return if (head == NULL) { cout << "List is empty" << endl; return; } // move ref_ptr to the n-th node from beginning. for (int i = 1; i < n; i++) { ref_ptr = ref_ptr->next; if (ref_ptr == NULL) { cout << n << " is greater than no. of nodes in " "the list" << endl; return; } } // move ref_ptr and main_ptr by one node until // ref_ptr reaches end of the list. while (ref_ptr != NULL && ref_ptr->next != NULL) { ref_ptr = ref_ptr->next; main_ptr = main_ptr->next; } cout << "Node no. " << n << " from end is: " << main_ptr->data << endl; } void displaylist() { node* temp = head; while (temp != NULL) { cout << temp->data << "->"; temp = temp->next; } cout << "NULL" << endl; }}; int main(){ llist ll; for (int i = 60; i >= 10; i -= 10) ll.insertAtBegin(i); ll.displaylist(); for (int i = 1; i <= 7; i++) ll.nthFromEnd(i); return 0;} // This code is contributed by sandeepkrsuman.
// Java program to find n'th// node from end using slow and// fast pointersclass LinkedList{ Node head; // head of the list /* Linked List node */ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to get the nth node from end of list */ void printNthFromLast(int n) { Node main_ptr = head; Node ref_ptr = head; int count = 0; if (head != null) { while (count < n) { if (ref_ptr == null) { System.out.println(n + " is greater than the no " + " of nodes in the list"); return; } ref_ptr = ref_ptr.next; count++; } if(ref_ptr == null) { if(head != null) System.out.println("Node no. " + n + " from last is " + head.data); } else { while (ref_ptr != null) { main_ptr = main_ptr.next; ref_ptr = ref_ptr.next; } System.out.println("Node no. " + n + " from last is " + main_ptr.data); } } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /*Driver program to test above methods */ public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(35); llist.printNthFromLast(4); }}// This code is contributed by Rajat Mishra
# Python program to find n'th node from end using slow# and fast pointer # Node classclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printNthFromLast(self, n): main_ptr = self.head ref_ptr = self.head count = 0 if(self.head is not None): while(count < n ): if(ref_ptr is None): print ("% d is greater than the no. pf nodes in list" %(n)) return ref_ptr = ref_ptr.next count += 1 if(ref_ptr is None): self.head = self.head.next if(self.head is not None): print("Node no. % d from last is % d " %(n, main_ptr.data)) else: while(ref_ptr is not None): main_ptr = main_ptr.next ref_ptr = ref_ptr.next print ("Node no. % d from last is % d " %(n, main_ptr.data)) if __name__ == '__main__': llist = LinkedList() llist.push(20) llist.push(4) llist.push(15) llist.push(35) llist.printNthFromLast(4) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// C# program to find n'th node from end using slow and// fast pointerspublicusing System; public class LinkedList{ Node head; // head of the list /* Linked List node */ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Function to get the nth node from end of list */ void printNthFromLast(int n) { Node main_ptr = head; Node ref_ptr = head; int count = 0; if (head != null) { while (count < n) { if (ref_ptr == null) { Console.WriteLine(n + " is greater than the no " + " of nodes in the list"); return; } ref_ptr = ref_ptr.next; count++; } if(ref_ptr == null) { head = head.next; if(head != null) Console.WriteLine("Node no. " + n + " from last is " + main_ptr.data); } else { while (ref_ptr != null) { main_ptr = main_ptr.next; ref_ptr = ref_ptr.next; } Console.WriteLine("Node no. " + n + " from last is " + main_ptr.data); } } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /*Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(35); llist.printNthFromLast(4); }} /* This code is contributed by PrinciRaj1992 */
<script>// javascript program to find n'th// node from end using slow and// fast pointersvar head; // head of the list /* Linked List node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* * Function to get the nth node from end of list */ function printNthFromLast(n) { var main_ptr = head; var ref_ptr = head; var count = 0; if (head != null) { while (count < n) { if (ref_ptr == null) { document.write(n + " is greater than the no " + " of nodes in the list"); return; } ref_ptr = ref_ptr.next; count++; } if (ref_ptr == null) { if (head != null) document.write("Node no. " + n + " from last is " + head.data); } else { while (ref_ptr != null) { main_ptr = main_ptr.next; ref_ptr = ref_ptr.next; } document.write("Node no. " + n + " from last is " + main_ptr.data); } } } /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Driver program to test above methods */ push(20); push(4); push(15); push(35); printNthFromLast(4); // This code is contributed by Rajput-Ji</script>
Output
10->20->30->40->50->60->NULL
Node no. 1 from end is: 60
Node no. 2 from end is: 50
Node no. 3 from end is: 40
Node no. 4 from end is: 30
Node no. 5 from end is: 20
Node no. 6 from end is: 10
7 is greater than no. of nodes in the list
Time Complexity: O(n) where n is the length of linked list.
Auxiliary Space: O(1)Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.
HRX
anurag singh 21
joshiyogesh
princiraj1992
Rajput-Ji
Akanksha_Rai
kallemshivashekarreddy625
abpb9114
rutvik_56
pratham76
aakarshitrekhi
rs4411863
sunils0ni
GauravRajput1
_saurabh_jaiswal
sandeepkrsuman
simmytarika5
amartyaghoshgfg
adityakumar129
technophpfij
hardikkoriintern
Accolite
Adobe
Amazon
Citicorp
Epic Systems
FactSet
Hike
Linked Lists
MAQ Software
Monotype Solutions
Python-Data-Structures
Qualcomm
Snapdeal
Linked List
Accolite
Amazon
Snapdeal
FactSet
Hike
MAQ Software
Adobe
Qualcomm
Epic Systems
Citicorp
Monotype Solutions
Linked List
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": 247,
"s": 52,
"text": "Given a Linked List and a number n, write a function that returns the value at the n’th node from the end of the Linked List.For example, if the input is below list and n = 3, then output is “B”"
},
{
"code": null,
"e": 425,
"s": 247,
"text": "Method 1 (Use length of linked list) 1) Calculate the length of the Linked List. Let the length be len. 2) Print the (len – n + 1)th node from the beginning of the Linked List. "
},
{
"code": null,
"e": 802,
"s": 425,
"text": "Double pointer concept: First pointer is used to store the address of the variable and the second pointer is used to store the address of the first pointer. If we wish to change the value of a variable by a function, we pass a pointer to it. And if we wish to change the value of a pointer (i. e., it should start pointing to something else), we pass the pointer to a pointer."
},
{
"code": null,
"e": 853,
"s": 802,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 859,
"s": 853,
"text": "C++14"
},
{
"code": null,
"e": 861,
"s": 859,
"text": "C"
},
{
"code": null,
"e": 866,
"s": 861,
"text": "Java"
},
{
"code": null,
"e": 874,
"s": 866,
"text": "Python3"
},
{
"code": null,
"e": 877,
"s": 874,
"text": "C#"
},
{
"code": null,
"e": 888,
"s": 877,
"text": "Javascript"
},
{
"code": "// Simple C++ program to find n'th node from end#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Function to get the nth node from the last of a linked list*/void printNthFromLast(struct Node* head, int n){ int len = 0, i; struct Node* temp = head; // count the number of nodes in Linked List while (temp != NULL) { temp = temp->next; len++; } // check if value of n is not // more than length of the linked list if (len < n) return; temp = head; // get the (len-n+1)th node from the beginning for (i = 1; i < len - n + 1; i++) temp = temp->next; cout << temp->data; return;} void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Driver Codeint main(){ /* Start with the empty list */ struct Node* head = NULL; // create linked 35->15->4->20 push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 35); printNthFromLast(head, 4); return 0;}",
"e": 2180,
"s": 888,
"text": null
},
{
"code": "// Simple C++ program to find n'th node from end#include <stdio.h>#include <stdlib.h> /* Link list node */typedef struct Node { int data; struct Node* next;}Node; /* Function to get the nth node from the last of a linked list*/void printNthFromLast(Node* head, int n){ int len = 0, i; Node* temp = head; // count the number of nodes in Linked List while (temp != NULL) { temp = temp->next; len++; } // check if value of n is not // more than length of the linked list if (len < n) return; temp = head; // get the (len-n+1)th node from the beginning for (i = 1; i < len - n + 1; i++) temp = temp->next; printf(\"%d\",temp->data); return;} void push(struct Node** head_ref, int new_data){ /* allocate node */ Node* new_node = (Node *)malloc(sizeof(Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Driver Codeint main(){ /* Start with the empty list */ struct Node* head = NULL; // create linked 35->15->4->20 push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 35); printNthFromLast(head, 4); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 3551,
"s": 2180,
"text": null
},
{
"code": "// Simple Java program to find n'th node from end of linked listclass LinkedList { Node head; // head of the list /* Linked List node */ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to get the nth node from the last of a linked list */ void printNthFromLast(int n) { int len = 0; Node temp = head; // 1) count the number of nodes in Linked List while (temp != null) { temp = temp.next; len++; } // check if value of n is not more than length of // the linked list if (len < n) return; temp = head; // 2) get the (len-n+1)th node from the beginning for (int i = 1; i < len - n + 1; i++) temp = temp.next; System.out.println(temp.data); } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /*Driver program to test above methods */ public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(35); llist.printNthFromLast(4); }} // This code is contributed by Rajat Mishra",
"e": 5127,
"s": 3551,
"text": null
},
{
"code": "# Simple Python3 program to find# n'th node from endclass Node: def __init__(self, new_data): self.data = new_data self.next = None class LinkedList: def __init__(self): self.head = None # createNode and make linked list def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Function to get the nth node from # the last of a linked list def printNthFromLast(self, n): temp = self.head # used temp variable length = 0 while temp is not None: temp = temp.next length += 1 # print count if n > length: # if entered location is greater # than length of linked list print('Location is greater than the' + ' length of LinkedList') return temp = self.head for i in range(0, length - n): temp = temp.next print(temp.data) # Driver Code llist = LinkedList()llist.push(20)llist.push(4)llist.push(15)llist.push(35)llist.printNthFromLast(4) # This code is contributed by Yogesh Joshi",
"e": 6296,
"s": 5127,
"text": null
},
{
"code": "// C# program to find n'th node from end of linked listusing System; public class LinkedList{ public Node head; // head of the list /* Linked List node */ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Function to get the nth node from the last of a linked list */ void printNthFromLast(int n) { int len = 0; Node temp = head; // 1) count the number of nodes in Linked List while (temp != null) { temp = temp.next; len++; } // check if value of n is not more than length of // the linked list if (len < n) return; temp = head; // 2) get the (len-n+1)th node from the beginning for (int i = 1; i < len - n + 1; i++) temp = temp.next; Console.WriteLine(temp.data); } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /*Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(35); llist.printNthFromLast(4); }} // This code is contributed by Rajput-Ji",
"e": 7894,
"s": 6296,
"text": null
},
{
"code": "<script> // Simple Javascript program to find n'th node from end of linked list /* Linked List node */ class Node { constructor(d) { this.data = d; this.next = null; } } /* Function to get the nth node from the last of a linked list */ class LinkedList { constructor(d){ this.head = d; } printNthFromLast(n) { let len = 0; let temp = this.head; // 1) count the number of nodes in Linked List while (temp != null) { temp = temp.next; len++; } // check if value of n is not more than length of // the linked list if (len < n) return; temp = this.head; // 2) get the (len-n+1)th node from the beginning for (let i = 1; i < len - n + 1; i++) temp = temp.next; document.write(temp.data); } /* Inserts a new Node at front of the list. */ push(new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ let new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = this.head; /* 4. Move the head to point to new Node */ this.head = new_node; } } /*Driver program to test above methods */ let llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(35); llist.printNthFromLast(4); // This code is contributed by Saurabh Jaiswal </script>",
"e": 9343,
"s": 7894,
"text": null
},
{
"code": null,
"e": 9346,
"s": 9343,
"text": "35"
},
{
"code": null,
"e": 9403,
"s": 9346,
"text": "Time complexity: O(n) where n is size of the linked list"
},
{
"code": null,
"e": 9425,
"s": 9403,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9530,
"s": 9425,
"text": "Following is a recursive C code for the same method. Thanks to Anuj Bansal for providing following code."
},
{
"code": null,
"e": 9546,
"s": 9530,
"text": "Implementation:"
},
{
"code": null,
"e": 9550,
"s": 9546,
"text": "C++"
},
{
"code": null,
"e": 9552,
"s": 9550,
"text": "C"
},
{
"code": null,
"e": 9557,
"s": 9552,
"text": "Java"
},
{
"code": null,
"e": 9565,
"s": 9557,
"text": "Python3"
},
{
"code": null,
"e": 9568,
"s": 9565,
"text": "C#"
},
{
"code": null,
"e": 9579,
"s": 9568,
"text": "Javascript"
},
{
"code": "void printNthFromLast(struct Node* head, int n){ int i = 0; if (head == NULL) return; printNthFromLast(head->next, n); if (++i == n) cout<<head->data;}",
"e": 9757,
"s": 9579,
"text": null
},
{
"code": "void printNthFromLast(struct Node* head, int n){ static int i = 0; if (head == NULL) return; printNthFromLast(head->next, n); if (++i == n) printf(\"%d\", head->data);}",
"e": 9950,
"s": 9757,
"text": null
},
{
"code": "static void printNthFromLast(Node head, int n){ int i = 0; if (head == null) return; printNthFromLast(head.next, n); if (++i == n) System.out.print(head.data);} // This code is contributed by rutvik_56.",
"e": 10181,
"s": 9950,
"text": null
},
{
"code": "def printNthFromLast(head, n): i = 0 if (head == None) return printNthFromLast(head.next, n); i+=1 if (i == n): print(head.data) # This code is contributed by sunils0ni.",
"e": 10394,
"s": 10181,
"text": null
},
{
"code": "static void printNthFromLast(Node head, int n){ static int i = 0; if (head == null) return; printNthFromLast(head.next, n); if (++i == n) Console.Write(head.data);} // This code is contributed by pratham76.",
"e": 10629,
"s": 10394,
"text": null
},
{
"code": "<script>function printNthFromLast(head , n){ function i = 0; if (head == null) return; printNthFromLast(head.next, n); if (++i == n) document.write(head.data);} // This code is contributed by gauravrajput1</script>",
"e": 10873,
"s": 10629,
"text": null
},
{
"code": null,
"e": 10934,
"s": 10873,
"text": "Time Complexity: O(n) where n is the length of linked list. "
},
{
"code": null,
"e": 11341,
"s": 10934,
"text": "Method 2 (Use two pointers) Maintain two pointers – reference pointer and main pointer. Initialize both reference and main pointers to head. First, move the reference pointer to n nodes from head. Now move both pointers one by one until the reference pointer reaches the end. Now the main pointer will point to nth node from the end. Return the main pointer.Below image is a dry run of the above approach: "
},
{
"code": null,
"e": 11393,
"s": 11341,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 11397,
"s": 11393,
"text": "C++"
},
{
"code": null,
"e": 11402,
"s": 11397,
"text": "Java"
},
{
"code": null,
"e": 11410,
"s": 11402,
"text": "Python3"
},
{
"code": null,
"e": 11413,
"s": 11410,
"text": "C#"
},
{
"code": null,
"e": 11424,
"s": 11413,
"text": "Javascript"
},
{
"code": "// C++ program to find n-th node// from the end of the linked list. #include <bits/stdc++.h>using namespace std; struct node { int data; node* next; node(int val) { data = val; next = NULL; }}; struct llist { node* head; llist() { head = NULL; } // insert operation at the beginning of the list. void insertAtBegin(int val) { node* newNode = new node(val); newNode->next = head; head = newNode; } // finding n-th node from the end. void nthFromEnd(int n) { // create two pointers main_ptr and ref_ptr // initially pointing to head. node* main_ptr = head; node* ref_ptr = head; // if list is empty, return if (head == NULL) { cout << \"List is empty\" << endl; return; } // move ref_ptr to the n-th node from beginning. for (int i = 1; i < n; i++) { ref_ptr = ref_ptr->next; if (ref_ptr == NULL) { cout << n << \" is greater than no. of nodes in \" \"the list\" << endl; return; } } // move ref_ptr and main_ptr by one node until // ref_ptr reaches end of the list. while (ref_ptr != NULL && ref_ptr->next != NULL) { ref_ptr = ref_ptr->next; main_ptr = main_ptr->next; } cout << \"Node no. \" << n << \" from end is: \" << main_ptr->data << endl; } void displaylist() { node* temp = head; while (temp != NULL) { cout << temp->data << \"->\"; temp = temp->next; } cout << \"NULL\" << endl; }}; int main(){ llist ll; for (int i = 60; i >= 10; i -= 10) ll.insertAtBegin(i); ll.displaylist(); for (int i = 1; i <= 7; i++) ll.nthFromEnd(i); return 0;} // This code is contributed by sandeepkrsuman.",
"e": 13369,
"s": 11424,
"text": null
},
{
"code": "// Java program to find n'th// node from end using slow and// fast pointersclass LinkedList{ Node head; // head of the list /* Linked List node */ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to get the nth node from end of list */ void printNthFromLast(int n) { Node main_ptr = head; Node ref_ptr = head; int count = 0; if (head != null) { while (count < n) { if (ref_ptr == null) { System.out.println(n + \" is greater than the no \" + \" of nodes in the list\"); return; } ref_ptr = ref_ptr.next; count++; } if(ref_ptr == null) { if(head != null) System.out.println(\"Node no. \" + n + \" from last is \" + head.data); } else { while (ref_ptr != null) { main_ptr = main_ptr.next; ref_ptr = ref_ptr.next; } System.out.println(\"Node no. \" + n + \" from last is \" + main_ptr.data); } } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /*Driver program to test above methods */ public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(35); llist.printNthFromLast(4); }}// This code is contributed by Rajat Mishra",
"e": 15532,
"s": 13369,
"text": null
},
{
"code": "# Python program to find n'th node from end using slow# and fast pointer # Node classclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printNthFromLast(self, n): main_ptr = self.head ref_ptr = self.head count = 0 if(self.head is not None): while(count < n ): if(ref_ptr is None): print (\"% d is greater than the no. pf nodes in list\" %(n)) return ref_ptr = ref_ptr.next count += 1 if(ref_ptr is None): self.head = self.head.next if(self.head is not None): print(\"Node no. % d from last is % d \" %(n, main_ptr.data)) else: while(ref_ptr is not None): main_ptr = main_ptr.next ref_ptr = ref_ptr.next print (\"Node no. % d from last is % d \" %(n, main_ptr.data)) if __name__ == '__main__': llist = LinkedList() llist.push(20) llist.push(4) llist.push(15) llist.push(35) llist.printNthFromLast(4) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 17088,
"s": 15532,
"text": null
},
{
"code": "// C# program to find n'th node from end using slow and// fast pointerspublicusing System; public class LinkedList{ Node head; // head of the list /* Linked List node */ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Function to get the nth node from end of list */ void printNthFromLast(int n) { Node main_ptr = head; Node ref_ptr = head; int count = 0; if (head != null) { while (count < n) { if (ref_ptr == null) { Console.WriteLine(n + \" is greater than the no \" + \" of nodes in the list\"); return; } ref_ptr = ref_ptr.next; count++; } if(ref_ptr == null) { head = head.next; if(head != null) Console.WriteLine(\"Node no. \" + n + \" from last is \" + main_ptr.data); } else { while (ref_ptr != null) { main_ptr = main_ptr.next; ref_ptr = ref_ptr.next; } Console.WriteLine(\"Node no. \" + n + \" from last is \" + main_ptr.data); } } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /*Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(35); llist.printNthFromLast(4); }} /* This code is contributed by PrinciRaj1992 */",
"e": 18921,
"s": 17088,
"text": null
},
{
"code": "<script>// javascript program to find n'th// node from end using slow and// fast pointersvar head; // head of the list /* Linked List node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* * Function to get the nth node from end of list */ function printNthFromLast(n) { var main_ptr = head; var ref_ptr = head; var count = 0; if (head != null) { while (count < n) { if (ref_ptr == null) { document.write(n + \" is greater than the no \" + \" of nodes in the list\"); return; } ref_ptr = ref_ptr.next; count++; } if (ref_ptr == null) { if (head != null) document.write(\"Node no. \" + n + \" from last is \" + head.data); } else { while (ref_ptr != null) { main_ptr = main_ptr.next; ref_ptr = ref_ptr.next; } document.write(\"Node no. \" + n + \" from last is \" + main_ptr.data); } } } /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Driver program to test above methods */ push(20); push(4); push(15); push(35); printNthFromLast(4); // This code is contributed by Rajput-Ji</script>",
"e": 20699,
"s": 18921,
"text": null
},
{
"code": null,
"e": 20706,
"s": 20699,
"text": "Output"
},
{
"code": null,
"e": 20940,
"s": 20706,
"text": "10->20->30->40->50->60->NULL\nNode no. 1 from end is: 60\nNode no. 2 from end is: 50\nNode no. 3 from end is: 40\nNode no. 4 from end is: 30\nNode no. 5 from end is: 20\nNode no. 6 from end is: 10\n7 is greater than no. of nodes in the list"
},
{
"code": null,
"e": 21000,
"s": 20940,
"text": "Time Complexity: O(n) where n is the length of linked list."
},
{
"code": null,
"e": 21139,
"s": 21000,
"text": "Auxiliary Space: O(1)Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem."
},
{
"code": null,
"e": 21143,
"s": 21139,
"text": "HRX"
},
{
"code": null,
"e": 21159,
"s": 21143,
"text": "anurag singh 21"
},
{
"code": null,
"e": 21171,
"s": 21159,
"text": "joshiyogesh"
},
{
"code": null,
"e": 21185,
"s": 21171,
"text": "princiraj1992"
},
{
"code": null,
"e": 21195,
"s": 21185,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 21208,
"s": 21195,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 21234,
"s": 21208,
"text": "kallemshivashekarreddy625"
},
{
"code": null,
"e": 21243,
"s": 21234,
"text": "abpb9114"
},
{
"code": null,
"e": 21253,
"s": 21243,
"text": "rutvik_56"
},
{
"code": null,
"e": 21263,
"s": 21253,
"text": "pratham76"
},
{
"code": null,
"e": 21278,
"s": 21263,
"text": "aakarshitrekhi"
},
{
"code": null,
"e": 21288,
"s": 21278,
"text": "rs4411863"
},
{
"code": null,
"e": 21298,
"s": 21288,
"text": "sunils0ni"
},
{
"code": null,
"e": 21312,
"s": 21298,
"text": "GauravRajput1"
},
{
"code": null,
"e": 21329,
"s": 21312,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 21344,
"s": 21329,
"text": "sandeepkrsuman"
},
{
"code": null,
"e": 21357,
"s": 21344,
"text": "simmytarika5"
},
{
"code": null,
"e": 21373,
"s": 21357,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 21388,
"s": 21373,
"text": "adityakumar129"
},
{
"code": null,
"e": 21401,
"s": 21388,
"text": "technophpfij"
},
{
"code": null,
"e": 21418,
"s": 21401,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 21427,
"s": 21418,
"text": "Accolite"
},
{
"code": null,
"e": 21433,
"s": 21427,
"text": "Adobe"
},
{
"code": null,
"e": 21440,
"s": 21433,
"text": "Amazon"
},
{
"code": null,
"e": 21449,
"s": 21440,
"text": "Citicorp"
},
{
"code": null,
"e": 21462,
"s": 21449,
"text": "Epic Systems"
},
{
"code": null,
"e": 21470,
"s": 21462,
"text": "FactSet"
},
{
"code": null,
"e": 21475,
"s": 21470,
"text": "Hike"
},
{
"code": null,
"e": 21488,
"s": 21475,
"text": "Linked Lists"
},
{
"code": null,
"e": 21501,
"s": 21488,
"text": "MAQ Software"
},
{
"code": null,
"e": 21520,
"s": 21501,
"text": "Monotype Solutions"
},
{
"code": null,
"e": 21543,
"s": 21520,
"text": "Python-Data-Structures"
},
{
"code": null,
"e": 21552,
"s": 21543,
"text": "Qualcomm"
},
{
"code": null,
"e": 21561,
"s": 21552,
"text": "Snapdeal"
},
{
"code": null,
"e": 21573,
"s": 21561,
"text": "Linked List"
},
{
"code": null,
"e": 21582,
"s": 21573,
"text": "Accolite"
},
{
"code": null,
"e": 21589,
"s": 21582,
"text": "Amazon"
},
{
"code": null,
"e": 21598,
"s": 21589,
"text": "Snapdeal"
},
{
"code": null,
"e": 21606,
"s": 21598,
"text": "FactSet"
},
{
"code": null,
"e": 21611,
"s": 21606,
"text": "Hike"
},
{
"code": null,
"e": 21624,
"s": 21611,
"text": "MAQ Software"
},
{
"code": null,
"e": 21630,
"s": 21624,
"text": "Adobe"
},
{
"code": null,
"e": 21639,
"s": 21630,
"text": "Qualcomm"
},
{
"code": null,
"e": 21652,
"s": 21639,
"text": "Epic Systems"
},
{
"code": null,
"e": 21661,
"s": 21652,
"text": "Citicorp"
},
{
"code": null,
"e": 21680,
"s": 21661,
"text": "Monotype Solutions"
},
{
"code": null,
"e": 21692,
"s": 21680,
"text": "Linked List"
}
] |
How to set the cursor to wait in JavaScript ? | 18 Aug, 2021
In JavaScript, we could easily set the cursor to wait. In this article, we will see how we are going to do this. Actually, it’s quite an easy task, there is a CSS cursor property and it has some values and one of the values is wait. We will use the [cursor: wait] property of CSS and control its behavior using JavaScript.
Setting the cursor to the wait could be useful in many cases, for example, if we click on the complete payment button in some payment transaction page then we should make the cursor to the wait just after the button get clicked, to prevent the unwanted click on anywhere on the page until the transaction is completed.
Example 1: In this example, we will create a button, when the button gets clicked then the cursor will be waiting. For this, we will use the addEventListener() function of JavaScript. With the help of this, we could control the behavior of events like click, hover, etc.
HTML
<!DOCTYPE html><html lang="en"> <head> <Style> * { margin: 0px; padding: 0px; box-sizing: border-box; } .box { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: rgb(36, 36, 36); } #btn { height: 50px; width: 100px; border-radius: 10px; border: none; outline: none; background-color: rgb(2, 151, 2); font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif; font-size: 1.1rem; } </Style></head> <body> <div class="box"> <button id="btn">Click me</button> </div> <script> document.getElementById("btn") .addEventListener("click", function() { document.body.style.cursor = "wait"; document.getElementById("btn") .style.backgroundColor = "gray"; document.getElementById("btn") .style.cursor = "wait"; }); </script></body> </html>
Output:
Example 2: For this example, we will use the same JavaScript’s addEventListener() method, use the hover event, and specify where the cursor should go to wait. In this case, we have created two containers, The cursor will work fine in the first container but on the second one, the cursor will go to the wait.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <Style> body { margin: 0px; padding: 0px; box-sizing: border-box; } .box { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: rgb(36, 36, 36); } #box1 { height: 100px; width: 100px; border-radius: 50%; background-color: Green; } #box2 { height: 100px; width: 100px; border-radius: 50%; background-color: rgb(102, 11, 3); margin: 5px; cursor: wait; } </Style></head> <body> <div class="box"> <div id="box1"></div> <div id="box2"></div> </div> <script> document.getElementById("box2") .addEventListener("hover", function() { document.getElementById("box2") .style.cursor = "wait"; }); </script></body> </html>
Output:
CSS-Properties
JavaScript-Events
JavaScript-Questions
Picked
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 352,
"s": 28,
"text": "In JavaScript, we could easily set the cursor to wait. In this article, we will see how we are going to do this. Actually, it’s quite an easy task, there is a CSS cursor property and it has some values and one of the values is wait. We will use the [cursor: wait] property of CSS and control its behavior using JavaScript. "
},
{
"code": null,
"e": 671,
"s": 352,
"text": "Setting the cursor to the wait could be useful in many cases, for example, if we click on the complete payment button in some payment transaction page then we should make the cursor to the wait just after the button get clicked, to prevent the unwanted click on anywhere on the page until the transaction is completed."
},
{
"code": null,
"e": 942,
"s": 671,
"text": "Example 1: In this example, we will create a button, when the button gets clicked then the cursor will be waiting. For this, we will use the addEventListener() function of JavaScript. With the help of this, we could control the behavior of events like click, hover, etc."
},
{
"code": null,
"e": 947,
"s": 942,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <Style> * { margin: 0px; padding: 0px; box-sizing: border-box; } .box { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: rgb(36, 36, 36); } #btn { height: 50px; width: 100px; border-radius: 10px; border: none; outline: none; background-color: rgb(2, 151, 2); font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif; font-size: 1.1rem; } </Style></head> <body> <div class=\"box\"> <button id=\"btn\">Click me</button> </div> <script> document.getElementById(\"btn\") .addEventListener(\"click\", function() { document.body.style.cursor = \"wait\"; document.getElementById(\"btn\") .style.backgroundColor = \"gray\"; document.getElementById(\"btn\") .style.cursor = \"wait\"; }); </script></body> </html>",
"e": 2131,
"s": 947,
"text": null
},
{
"code": null,
"e": 2139,
"s": 2131,
"text": "Output:"
},
{
"code": null,
"e": 2448,
"s": 2139,
"text": "Example 2: For this example, we will use the same JavaScript’s addEventListener() method, use the hover event, and specify where the cursor should go to wait. In this case, we have created two containers, The cursor will work fine in the first container but on the second one, the cursor will go to the wait."
},
{
"code": null,
"e": 2453,
"s": 2448,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <Style> body { margin: 0px; padding: 0px; box-sizing: border-box; } .box { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: rgb(36, 36, 36); } #box1 { height: 100px; width: 100px; border-radius: 50%; background-color: Green; } #box2 { height: 100px; width: 100px; border-radius: 50%; background-color: rgb(102, 11, 3); margin: 5px; cursor: wait; } </Style></head> <body> <div class=\"box\"> <div id=\"box1\"></div> <div id=\"box2\"></div> </div> <script> document.getElementById(\"box2\") .addEventListener(\"hover\", function() { document.getElementById(\"box2\") .style.cursor = \"wait\"; }); </script></body> </html>",
"e": 3694,
"s": 2453,
"text": null
},
{
"code": null,
"e": 3703,
"s": 3694,
"text": "Output: "
},
{
"code": null,
"e": 3718,
"s": 3703,
"text": "CSS-Properties"
},
{
"code": null,
"e": 3736,
"s": 3718,
"text": "JavaScript-Events"
},
{
"code": null,
"e": 3757,
"s": 3736,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 3764,
"s": 3757,
"text": "Picked"
},
{
"code": null,
"e": 3768,
"s": 3764,
"text": "CSS"
},
{
"code": null,
"e": 3773,
"s": 3768,
"text": "HTML"
},
{
"code": null,
"e": 3784,
"s": 3773,
"text": "JavaScript"
},
{
"code": null,
"e": 3801,
"s": 3784,
"text": "Web Technologies"
},
{
"code": null,
"e": 3806,
"s": 3801,
"text": "HTML"
},
{
"code": null,
"e": 3904,
"s": 3806,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3943,
"s": 3904,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3982,
"s": 3943,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 4021,
"s": 3982,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 4050,
"s": 4021,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 4087,
"s": 4050,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 4111,
"s": 4087,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 4164,
"s": 4111,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4224,
"s": 4164,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 4285,
"s": 4224,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
GATE | GATE CS 2019 | Question 42 | 18 Feb, 2019
Assume that in a certain computer, the virtual addresses are 64 bits long and the physical addresses are 48 bits long. The memory is word addressable. The page size is 8k Band the word size is 4 bytes. The Translation Look-aside Buffer (TLB) in the address translation path has 128 valid entries. At most how many distinct virtual addresses can be translated without any TLB miss?(A) 16 x 210(B) 8 x 220(C) 4 x 220(D) 256 x 210Answer: (D)Explanation:
Number of words in a page
= Page size / word size
= 8 KB / 4 B
= 2 K
= 2 * 210
Since TLB can hold 128 valid entries, therefore, TLB can translate
= 128 * number of words in page
= 128 * 2 * 210
= 256 * 210 addresses with TLB hit
So, option (D) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Feb, 2019"
},
{
"code": null,
"e": 479,
"s": 28,
"text": "Assume that in a certain computer, the virtual addresses are 64 bits long and the physical addresses are 48 bits long. The memory is word addressable. The page size is 8k Band the word size is 4 bytes. The Translation Look-aside Buffer (TLB) in the address translation path has 128 valid entries. At most how many distinct virtual addresses can be translated without any TLB miss?(A) 16 x 210(B) 8 x 220(C) 4 x 220(D) 256 x 210Answer: (D)Explanation:"
},
{
"code": null,
"e": 561,
"s": 479,
"text": "Number of words in a page \n= Page size / word size\n= 8 KB / 4 B \n= 2 K\n= 2 * 210 "
},
{
"code": null,
"e": 628,
"s": 561,
"text": "Since TLB can hold 128 valid entries, therefore, TLB can translate"
},
{
"code": null,
"e": 713,
"s": 628,
"text": "= 128 * number of words in page \n= 128 * 2 * 210\n= 256 * 210 addresses with TLB hit "
},
{
"code": null,
"e": 761,
"s": 713,
"text": "So, option (D) is correct.Quiz of this Question"
},
{
"code": null,
"e": 766,
"s": 761,
"text": "GATE"
}
] |
Remove duplicate elements in an Array using STL in C++ | 31 May, 2022
Given an array, the task is to remove the duplicate elements from the array using STL in C++ Examples:
Input: arr[] = {2, 2, 2, 2, 2}
Output: arr[] = {2}
Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}
Output: arr[] = {1, 2, 3, 4, 5}
Approach: This can be done using set in standard template library. Set type variable in STL automatically removes duplicating element when we store the element in it. Below is the implementation of the above approach:
CPP
// C++ program to remove the// duplicate elements from the array// using STL in C++ #include <bits/stdc++.h>using namespace std; // Function to remove duplicate elementsvoid removeDuplicates(int arr[], int n){ int i; // Initialise a set // to store the array values set<int> s; // Insert the array elements // into the set for (i = 0; i < n; i++) { // insert into set s.insert(arr[i]); } set<int>::iterator it; // Print the array with duplicates removed cout << "\nAfter removing duplicates:\n"; for (it = s.begin(); it != s.end(); ++it) cout << *it << ", "; cout << '\n';} // Driver codeint main(){ int arr[] = { 4, 2, 3, 3, 2, 4 }; int n = sizeof(arr) / sizeof(arr[0]); // Print array cout << "\nBefore removing duplicates:\n"; for (int i = 0; i < n; i++) cout << arr[i] << " "; // call removeDuplicates() removeDuplicates(arr, n); return 0;}
Before removing duplicates:
4 2 3 3 2 4
After removing duplicates:
2, 3, 4,
Time Complexity : O(NlogN)
Space Complexity : O(N)
tausifsiddiqui
cpp-array
STL
Arrays
C++
Arrays
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 155,
"s": 52,
"text": "Given an array, the task is to remove the duplicate elements from the array using STL in C++ Examples:"
},
{
"code": null,
"e": 282,
"s": 155,
"text": "Input: arr[] = {2, 2, 2, 2, 2}\nOutput: arr[] = {2}\n\nInput: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}\nOutput: arr[] = {1, 2, 3, 4, 5}"
},
{
"code": null,
"e": 501,
"s": 282,
"text": "Approach: This can be done using set in standard template library. Set type variable in STL automatically removes duplicating element when we store the element in it. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 505,
"s": 501,
"text": "CPP"
},
{
"code": "// C++ program to remove the// duplicate elements from the array// using STL in C++ #include <bits/stdc++.h>using namespace std; // Function to remove duplicate elementsvoid removeDuplicates(int arr[], int n){ int i; // Initialise a set // to store the array values set<int> s; // Insert the array elements // into the set for (i = 0; i < n; i++) { // insert into set s.insert(arr[i]); } set<int>::iterator it; // Print the array with duplicates removed cout << \"\\nAfter removing duplicates:\\n\"; for (it = s.begin(); it != s.end(); ++it) cout << *it << \", \"; cout << '\\n';} // Driver codeint main(){ int arr[] = { 4, 2, 3, 3, 2, 4 }; int n = sizeof(arr) / sizeof(arr[0]); // Print array cout << \"\\nBefore removing duplicates:\\n\"; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; // call removeDuplicates() removeDuplicates(arr, n); return 0;}",
"e": 1451,
"s": 505,
"text": null
},
{
"code": null,
"e": 1528,
"s": 1451,
"text": "Before removing duplicates:\n4 2 3 3 2 4 \nAfter removing duplicates:\n2, 3, 4,"
},
{
"code": null,
"e": 1555,
"s": 1528,
"text": "Time Complexity : O(NlogN)"
},
{
"code": null,
"e": 1580,
"s": 1555,
"text": "Space Complexity : O(N) "
},
{
"code": null,
"e": 1595,
"s": 1580,
"text": "tausifsiddiqui"
},
{
"code": null,
"e": 1605,
"s": 1595,
"text": "cpp-array"
},
{
"code": null,
"e": 1609,
"s": 1605,
"text": "STL"
},
{
"code": null,
"e": 1616,
"s": 1609,
"text": "Arrays"
},
{
"code": null,
"e": 1620,
"s": 1616,
"text": "C++"
},
{
"code": null,
"e": 1627,
"s": 1620,
"text": "Arrays"
},
{
"code": null,
"e": 1631,
"s": 1627,
"text": "STL"
},
{
"code": null,
"e": 1635,
"s": 1631,
"text": "CPP"
}
] |
K-th Largest Sum Contiguous Subarray | 07 Mar, 2022
Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers which has negative and positive numbers.
Examples:
Input: a[] = {20, -5, -1}
k = 3
Output: 14
Explanation: All sum of contiguous
subarrays are (20, 15, 14, -5, -6, -1)
so the 3rd largest sum is 14.
Input: a[] = {10, -10, 20, -40}
k = 6
Output: -10
Explanation: The 6th largest sum among
sum of all contiguous subarrays is -10.
A brute force approach is to store all the contiguous sums in another array and sort it and print the k-th largest. But in the case of the number of elements being large, the array in which we store the contiguous sums will run out of memory as the number of contiguous subarrays will be large (quadratic order)
An efficient approach is to store the pre-sum of the array in a sum[] array. We can find sum of contiguous subarray from index i to j as sum[j]-sum[i-1]
Now for storing the Kth largest sum, use a min heap (priority queue) in which we push the contiguous sums till we get K elements, once we have our K elements, check if the element is greater than the Kth element it is inserted to the min heap with popping out the top element in the min-heap, else not inserted. In the end, the top element in the min-heap will be your answer.
Below is the implementation of the above approach.
C++
Java
Python3
C#
JavaScript
// CPP program to find the k-th largest sum// of subarray#include <bits/stdc++.h>using namespace std; // function to calculate kth largest element// in contiguous subarray sumint kthLargestSum(int arr[], int n, int k){ // array to store prefix sums int sum[n + 1]; sum[0] = 0; sum[1] = arr[0]; for (int i = 2; i <= n; i++) sum[i] = sum[i - 1] + arr[i - 1]; // priority_queue of min heap priority_queue<int, vector<int>, greater<int> > Q; // loop to calculate the contiguous subarray // sum position-wise for (int i = 1; i <= n; i++) { // loop to traverse all positions that // form contiguous subarray for (int j = i; j <= n; j++) { // calculates the contiguous subarray // sum from j to i index int x = sum[j] - sum[i - 1]; // if queue has less then k elements, // then simply push it if (Q.size() < k) Q.push(x); else { // it the min heap has equal to // k elements then just check // if the largest kth element is // smaller than x then insert // else its of no use if (Q.top() < x) { Q.pop(); Q.push(x); } } } } // the top element will be then kth // largest element return Q.top();} // Driver program to test above functionint main(){ int a[] = { 10, -10, 20, -40 }; int n = sizeof(a) / sizeof(a[0]); int k = 6; // calls the function to find out the // k-th largest sum cout << kthLargestSum(a, n, k); return 0;}
// Java program to find the k-th// largest sum of subarrayimport java.util.*; class KthLargestSumSubArray{ // function to calculate kth largest // element in contiguous subarray sum static int kthLargestSum(int arr[], int n, int k) { // array to store prefix sums int sum[] = new int[n + 1]; sum[0] = 0; sum[1] = arr[0]; for (int i = 2; i <= n; i++) sum[i] = sum[i - 1] + arr[i - 1]; // priority_queue of min heap PriorityQueue<Integer> Q = new PriorityQueue<Integer> (); // loop to calculate the contiguous subarray // sum position-wise for (int i = 1; i <= n; i++) { // loop to traverse all positions that // form contiguous subarray for (int j = i; j <= n; j++) { // calculates the contiguous subarray // sum from j to i index int x = sum[j] - sum[i - 1]; // if queue has less then k elements, // then simply push it if (Q.size() < k) Q.add(x); else { // it the min heap has equal to // k elements then just check // if the largest kth element is // smaller than x then insert // else its of no use if (Q.peek() < x) { Q.poll(); Q.add(x); } } } } // the top element will be then kth // largest element return Q.poll(); } // Driver Code public static void main(String[] args) { int a[] = new int[]{ 10, -10, 20, -40 }; int n = a.length; int k = 6; // calls the function to find out the // k-th largest sum System.out.println(kthLargestSum(a, n, k)); }} /* This code is contributed by Danish Kaleem */
# Python program to find the k-th largest sum# of subarrayimport heapq # function to calculate kth largest element# in contiguous subarray sumdef kthLargestSum(arr, n, k): # array to store prefix sums sum = [] sum.append(0) sum.append(arr[0]) for i in range(2, n + 1): sum.append(sum[i - 1] + arr[i - 1]) # priority_queue of min heap Q = [] heapq.heapify(Q) # loop to calculate the contiguous subarray # sum position-wise for i in range(1, n + 1): # loop to traverse all positions that # form contiguous subarray for j in range(i, n + 1): x = sum[j] - sum[i - 1] # if queue has less then k elements, # then simply push it if len(Q) < k: heapq.heappush(Q, x) else: # it the min heap has equal to # k elements then just check # if the largest kth element is # smaller than x then insert # else its of no use if Q[0] < x: heapq.heappop(Q) heapq.heappush(Q, x) # the top element will be then kth # largest element return Q[0] # Driver program to test above functiona = [10,-10,20,-40]n = len(a)k = 6 # calls the function to find out the# k-th largest sumprint(kthLargestSum(a,n,k)) # This code is contributed by Kumar Suman
// C# program to find the k-th// largest sum of subarrayusing System;using System.Collections.Generic;public class KthLargestSumSubArray{ // function to calculate kth largest // element in contiguous subarray sum static int kthLargestSum(int []arr, int n, int k) { // array to store prefix sums int []sum = new int[n + 1]; sum[0] = 0; sum[1] = arr[0]; for (int i = 2; i <= n; i++) sum[i] = sum[i - 1] + arr[i - 1]; // priority_queue of min heap List<int> Q = new List<int> (); // loop to calculate the contiguous subarray // sum position-wise for (int i = 1; i <= n; i++) { // loop to traverse all positions that // form contiguous subarray for (int j = i; j <= n; j++) { // calculates the contiguous subarray // sum from j to i index int x = sum[j] - sum[i - 1]; // if queue has less then k elements, // then simply push it if (Q.Count < k) Q.Add(x); else { // it the min heap has equal to // k elements then just check // if the largest kth element is // smaller than x then insert // else its of no use Q.Sort(); if (Q[0] < x) { Q.RemoveAt(0); Q.Add(x); } } Q.Sort(); } } // the top element will be then kth // largest element return Q[0]; } // Driver Code public static void Main(String[] args) { int []a = new int[]{ 10, -10, 20, -40 }; int n = a.Length; int k = 6; // calls the function to find out the // k-th largest sum Console.WriteLine(kthLargestSum(a, n, k)); }} // This code contributed by Rajput-Ji
<script> // Javascript program to find the k-th largest sum// of subarray // function to calculate kth largest element// in contiguous subarray sumfunction kthLargestSum(arr, n, k){ // array to store prefix sums var sum = new Array(n + 1); sum[0] = 0; sum[1] = arr[0]; for (var i = 2; i <= n; i++) sum[i] = sum[i - 1] + arr[i - 1]; // priority_queue of min heap var Q = []; // loop to calculate the contiguous subarray // sum position-wise for (var i = 1; i <= n; i++) { // loop to traverse all positions that // form contiguous subarray for (var j = i; j <= n; j++) { // calculates the contiguous subarray // sum from j to i index var x = sum[j] - sum[i - 1]; // if queue has less then k elements, // then simply push it if (Q.length < k) Q.push(x); else { // it the min heap has equal to // k elements then just check // if the largest kth element is // smaller than x then insert // else its of no use Q.sort(); if (Q[0] < x) { Q.pop(); Q.push(x); } } Q.sort(); } } // the top element will be then kth // largest element return Q[0];} // Driver program to test above functionvar a = [ 10, -10, 20, -40 ];var n = a.length;var k = 6; // calls the function to find out the// k-th largest sumdocument.write(kthLargestSum(a, n, k));</script>
Output:
-10
Time complexity: O(n^2 log (k)) Auxiliary Space : O(k) for min-heap and we can store the sum array in the array itself as it is of no use.This article is contributed by Raja Vikramaditya. 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.
PravinAgre
Akanksha_Rai
ks120198
pleasehireme
Rajput-Ji
clintra
avtarkumar719
SHUBHAMSINGH10
shashikantg
simmytarika5
arorakashish0911
Order-Statistics
subarray
subarray-sum
Arrays
Heap
Arrays
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 219,
"s": 54,
"text": "Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers which has negative and positive numbers."
},
{
"code": null,
"e": 230,
"s": 219,
"text": "Examples: "
},
{
"code": null,
"e": 531,
"s": 230,
"text": "Input: a[] = {20, -5, -1} \n k = 3\nOutput: 14\nExplanation: All sum of contiguous \nsubarrays are (20, 15, 14, -5, -6, -1) \nso the 3rd largest sum is 14.\n\nInput: a[] = {10, -10, 20, -40} \n k = 6\nOutput: -10 \nExplanation: The 6th largest sum among \nsum of all contiguous subarrays is -10."
},
{
"code": null,
"e": 843,
"s": 531,
"text": "A brute force approach is to store all the contiguous sums in another array and sort it and print the k-th largest. But in the case of the number of elements being large, the array in which we store the contiguous sums will run out of memory as the number of contiguous subarrays will be large (quadratic order)"
},
{
"code": null,
"e": 997,
"s": 843,
"text": "An efficient approach is to store the pre-sum of the array in a sum[] array. We can find sum of contiguous subarray from index i to j as sum[j]-sum[i-1] "
},
{
"code": null,
"e": 1374,
"s": 997,
"text": "Now for storing the Kth largest sum, use a min heap (priority queue) in which we push the contiguous sums till we get K elements, once we have our K elements, check if the element is greater than the Kth element it is inserted to the min heap with popping out the top element in the min-heap, else not inserted. In the end, the top element in the min-heap will be your answer."
},
{
"code": null,
"e": 1427,
"s": 1374,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 1431,
"s": 1427,
"text": "C++"
},
{
"code": null,
"e": 1436,
"s": 1431,
"text": "Java"
},
{
"code": null,
"e": 1444,
"s": 1436,
"text": "Python3"
},
{
"code": null,
"e": 1447,
"s": 1444,
"text": "C#"
},
{
"code": null,
"e": 1458,
"s": 1447,
"text": "JavaScript"
},
{
"code": "// CPP program to find the k-th largest sum// of subarray#include <bits/stdc++.h>using namespace std; // function to calculate kth largest element// in contiguous subarray sumint kthLargestSum(int arr[], int n, int k){ // array to store prefix sums int sum[n + 1]; sum[0] = 0; sum[1] = arr[0]; for (int i = 2; i <= n; i++) sum[i] = sum[i - 1] + arr[i - 1]; // priority_queue of min heap priority_queue<int, vector<int>, greater<int> > Q; // loop to calculate the contiguous subarray // sum position-wise for (int i = 1; i <= n; i++) { // loop to traverse all positions that // form contiguous subarray for (int j = i; j <= n; j++) { // calculates the contiguous subarray // sum from j to i index int x = sum[j] - sum[i - 1]; // if queue has less then k elements, // then simply push it if (Q.size() < k) Q.push(x); else { // it the min heap has equal to // k elements then just check // if the largest kth element is // smaller than x then insert // else its of no use if (Q.top() < x) { Q.pop(); Q.push(x); } } } } // the top element will be then kth // largest element return Q.top();} // Driver program to test above functionint main(){ int a[] = { 10, -10, 20, -40 }; int n = sizeof(a) / sizeof(a[0]); int k = 6; // calls the function to find out the // k-th largest sum cout << kthLargestSum(a, n, k); return 0;}",
"e": 3163,
"s": 1458,
"text": null
},
{
"code": "// Java program to find the k-th// largest sum of subarrayimport java.util.*; class KthLargestSumSubArray{ // function to calculate kth largest // element in contiguous subarray sum static int kthLargestSum(int arr[], int n, int k) { // array to store prefix sums int sum[] = new int[n + 1]; sum[0] = 0; sum[1] = arr[0]; for (int i = 2; i <= n; i++) sum[i] = sum[i - 1] + arr[i - 1]; // priority_queue of min heap PriorityQueue<Integer> Q = new PriorityQueue<Integer> (); // loop to calculate the contiguous subarray // sum position-wise for (int i = 1; i <= n; i++) { // loop to traverse all positions that // form contiguous subarray for (int j = i; j <= n; j++) { // calculates the contiguous subarray // sum from j to i index int x = sum[j] - sum[i - 1]; // if queue has less then k elements, // then simply push it if (Q.size() < k) Q.add(x); else { // it the min heap has equal to // k elements then just check // if the largest kth element is // smaller than x then insert // else its of no use if (Q.peek() < x) { Q.poll(); Q.add(x); } } } } // the top element will be then kth // largest element return Q.poll(); } // Driver Code public static void main(String[] args) { int a[] = new int[]{ 10, -10, 20, -40 }; int n = a.length; int k = 6; // calls the function to find out the // k-th largest sum System.out.println(kthLargestSum(a, n, k)); }} /* This code is contributed by Danish Kaleem */",
"e": 5206,
"s": 3163,
"text": null
},
{
"code": "# Python program to find the k-th largest sum# of subarrayimport heapq # function to calculate kth largest element# in contiguous subarray sumdef kthLargestSum(arr, n, k): # array to store prefix sums sum = [] sum.append(0) sum.append(arr[0]) for i in range(2, n + 1): sum.append(sum[i - 1] + arr[i - 1]) # priority_queue of min heap Q = [] heapq.heapify(Q) # loop to calculate the contiguous subarray # sum position-wise for i in range(1, n + 1): # loop to traverse all positions that # form contiguous subarray for j in range(i, n + 1): x = sum[j] - sum[i - 1] # if queue has less then k elements, # then simply push it if len(Q) < k: heapq.heappush(Q, x) else: # it the min heap has equal to # k elements then just check # if the largest kth element is # smaller than x then insert # else its of no use if Q[0] < x: heapq.heappop(Q) heapq.heappush(Q, x) # the top element will be then kth # largest element return Q[0] # Driver program to test above functiona = [10,-10,20,-40]n = len(a)k = 6 # calls the function to find out the# k-th largest sumprint(kthLargestSum(a,n,k)) # This code is contributed by Kumar Suman",
"e": 6641,
"s": 5206,
"text": null
},
{
"code": "// C# program to find the k-th// largest sum of subarrayusing System;using System.Collections.Generic;public class KthLargestSumSubArray{ // function to calculate kth largest // element in contiguous subarray sum static int kthLargestSum(int []arr, int n, int k) { // array to store prefix sums int []sum = new int[n + 1]; sum[0] = 0; sum[1] = arr[0]; for (int i = 2; i <= n; i++) sum[i] = sum[i - 1] + arr[i - 1]; // priority_queue of min heap List<int> Q = new List<int> (); // loop to calculate the contiguous subarray // sum position-wise for (int i = 1; i <= n; i++) { // loop to traverse all positions that // form contiguous subarray for (int j = i; j <= n; j++) { // calculates the contiguous subarray // sum from j to i index int x = sum[j] - sum[i - 1]; // if queue has less then k elements, // then simply push it if (Q.Count < k) Q.Add(x); else { // it the min heap has equal to // k elements then just check // if the largest kth element is // smaller than x then insert // else its of no use Q.Sort(); if (Q[0] < x) { Q.RemoveAt(0); Q.Add(x); } } Q.Sort(); } } // the top element will be then kth // largest element return Q[0]; } // Driver Code public static void Main(String[] args) { int []a = new int[]{ 10, -10, 20, -40 }; int n = a.Length; int k = 6; // calls the function to find out the // k-th largest sum Console.WriteLine(kthLargestSum(a, n, k)); }} // This code contributed by Rajput-Ji",
"e": 8348,
"s": 6641,
"text": null
},
{
"code": "<script> // Javascript program to find the k-th largest sum// of subarray // function to calculate kth largest element// in contiguous subarray sumfunction kthLargestSum(arr, n, k){ // array to store prefix sums var sum = new Array(n + 1); sum[0] = 0; sum[1] = arr[0]; for (var i = 2; i <= n; i++) sum[i] = sum[i - 1] + arr[i - 1]; // priority_queue of min heap var Q = []; // loop to calculate the contiguous subarray // sum position-wise for (var i = 1; i <= n; i++) { // loop to traverse all positions that // form contiguous subarray for (var j = i; j <= n; j++) { // calculates the contiguous subarray // sum from j to i index var x = sum[j] - sum[i - 1]; // if queue has less then k elements, // then simply push it if (Q.length < k) Q.push(x); else { // it the min heap has equal to // k elements then just check // if the largest kth element is // smaller than x then insert // else its of no use Q.sort(); if (Q[0] < x) { Q.pop(); Q.push(x); } } Q.sort(); } } // the top element will be then kth // largest element return Q[0];} // Driver program to test above functionvar a = [ 10, -10, 20, -40 ];var n = a.length;var k = 6; // calls the function to find out the// k-th largest sumdocument.write(kthLargestSum(a, n, k));</script>",
"e": 9992,
"s": 8348,
"text": null
},
{
"code": null,
"e": 10000,
"s": 9992,
"text": "Output:"
},
{
"code": null,
"e": 10004,
"s": 10000,
"text": "-10"
},
{
"code": null,
"e": 10567,
"s": 10004,
"text": "Time complexity: O(n^2 log (k)) Auxiliary Space : O(k) for min-heap and we can store the sum array in the array itself as it is of no use.This article is contributed by Raja Vikramaditya. 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": 10578,
"s": 10567,
"text": "PravinAgre"
},
{
"code": null,
"e": 10591,
"s": 10578,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 10600,
"s": 10591,
"text": "ks120198"
},
{
"code": null,
"e": 10613,
"s": 10600,
"text": "pleasehireme"
},
{
"code": null,
"e": 10623,
"s": 10613,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 10631,
"s": 10623,
"text": "clintra"
},
{
"code": null,
"e": 10645,
"s": 10631,
"text": "avtarkumar719"
},
{
"code": null,
"e": 10660,
"s": 10645,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 10672,
"s": 10660,
"text": "shashikantg"
},
{
"code": null,
"e": 10685,
"s": 10672,
"text": "simmytarika5"
},
{
"code": null,
"e": 10702,
"s": 10685,
"text": "arorakashish0911"
},
{
"code": null,
"e": 10719,
"s": 10702,
"text": "Order-Statistics"
},
{
"code": null,
"e": 10728,
"s": 10719,
"text": "subarray"
},
{
"code": null,
"e": 10741,
"s": 10728,
"text": "subarray-sum"
},
{
"code": null,
"e": 10748,
"s": 10741,
"text": "Arrays"
},
{
"code": null,
"e": 10753,
"s": 10748,
"text": "Heap"
},
{
"code": null,
"e": 10760,
"s": 10753,
"text": "Arrays"
},
{
"code": null,
"e": 10765,
"s": 10760,
"text": "Heap"
}
] |
Understanding Monte Carlo Simulation Through Basketball | by Vinicius Monteiro | Towards Data Science | Monte Carlo Simulation is a type of simulation where the events are chosen to happen randomly. By iterating and trying out various outcomes many times, arbitrarily, it gives great confidence in the result. [1] The name comes from Monte Carlo, located in Monaco, known for its strong gambling activity.
Let’s use a simple example, a coin toss. Suppose we don’t know, and it’s not easy to calculate the percentage of landing heads or tails. If you toss the coin 10 times and 9 out of 10 it lands on heads, does it mean it’s 90% heads and 10% tails? Of course not. It was merely luck.
The way to increase the confidence on the correct percentage of each side is to throw a lot more times than 10, let’s say 500 times. The count of tails and heads should come out more evenly.
For a coin toss, definitely, there is no need to do such a simulation to know the result. However, often, there are complex use cases with many variables and paths, which is hard to calculate the probability. That’s where Monte Carlo Simulation can be a powerful tool. It can predict something with accuracy by letting the scenario, with all the conditions, evolve randomly. It’s used in Project Management, Artificial Intelligence and to help to make decisions in general.
To provide you with a better perspective on what I’ve explained and to have some fun, I’m going to demonstrate how it works through a specific scenario that can happen at the end of a game of basketball.
Basketball is a complex sport (isn’t it just about putting a ball in a basket?!). It has many constraints and conditions that are constantly being analysed to make the best decision. Players and coaches are always watching for the right position on the court, time on the clock, the number of fouls, timeouts left and more. There are a lot of variables that come into play, literally.
It’s often compared to Chess as some characteristics are similar. For example, each player/piece has its role and function. Many both games are about opening lines and creating space, misleading. ‘fakes’ are also key. Both games make extensive use of set plays that explore these aspects.
The most crucial part of the game, without a doubt, is the end when scores are closed, within two or three points difference, for example. A team can win or lose in a blink of an eye, forcing players and coaches to get the most creative.
A common situation is: A team is down by three points, with 30 seconds left on the clock — is it better to try to take the three (a longer, hence more difficult shot) to tie and go to overtime, OR to try a quick two (usually shorter, easier shot), try to intentionally foul a bad free throw shooter in next possession — hoping that he/she misses one-shot or both — and go for another quick easier two and possibly win the game, or go to overtime?
Salman Khan, from Khan Academy, addressed exactly this situation [2]. Lebron James asked a question, for which Salman Khan answered and demonstrated the best decision using Monte Carlo simulation.
In this post, I’ll do the same, but with one minor difference. I’m going to take into account that according to NBA rules, a player can’t simply intentionally foul ANY player from the other team with under two minutes left in the game. It has to be the one with the ball. Otherwise, there are consequences.
With under two minutes left in the game (and from 2016, at the end of any quarter), if a player fouls another player that is away from the ball, the team is awarded one free throw and retains possession of the ball, there is no opportunity for the rebound. It’s crucial to emphasize that the TEAM is awarded one free throw — this means that the team can select any player on the floor to attempt the shot (most likely a high percentage free throw shooter) [3].
In general, the algorithm mimics the real game. It randomly tests different combinations of plays inside a loop and counts how many times the team won by taking the three or the two-plus intentional foul. The bigger number of trials / the loop, the more reliable the results are. There is a threshold for which increasing the number of trials doesn’t make much difference; the program will take longer to finish without adding much value.
Overall the code is divided into five sections:
It starts by defining the average of various attributes, such as free throw percentage, rebound, two and three-shot percentage, etc.
Definition of the logic that takes the three and misses it or makes it, and if it makes, whether it wins in overtime or not.
The logic for taking the two-plus intentionally fouling. It tests if it makes or misses the two if the opponent makes one or two free throws, grabs the rebound, etc.
It counts how many times the team wins by taking the three and how many times by taking the two.
It prints the result.
Here you can see the result without considering the foul-away-from-the-ball rule. Taking the three is just about better.
Wins taking the three: 1314Wins taking the two: 1151
By tweaking it a little bit, the opponent’s free throw percentage, from 65% to 40%, for example, taking the two, becomes the best option. This is maybe even more realistic, assuming that the player fouled can be the one away from the ball. It’s not uncommon to have such a bad free throw shooter in a team.
Wins taking the three: 1331Wins taking the two: 1564
To consider the rule and penalty that awards one free throw shot and retaining the ball, I added a small change in sim_take_two. In the while loop, I added the logic to check if the bad free throw shooter has the ball or not. If he/she does it, the normal two free throws plus rebound flow is followed. Otherwise (if fouled away from the ball), a team player attempts one shot and retains the possession. See below the snippet and full code.
For this scenario, it’s assumed that the team has a 40% free throw shooter on the floor that might end up with the ball and a high percentage one that the team would select to shoot the free throw if the foul is away from the ball.
Another significant constraint is the percentage that the ball is inbounded to the bad free throw shooter. The losing team would have to work really hard to force this situation. I was generous and set it to a 50% chance to happen.
Wins taking the three: 1326Wins taking the two: 776
With this rule, it becomes almost illogical for the team to try to win by going for the quick two-plus intentional foul under two minutes. The fact that the current winning team gets to retain the ball is a great advantage. It’s an effective rule to stop ‘Hack-a-Shaq’. Named after one of the worst free-throw shooters: Shaquille O’neal. Also, because the team can select any player to attempt the shot, it is even harder. If that weren’t the case, it would be less impossible. But still, the bad free throw shooter would have to have as low as a 15% average to make sense — Below is the result following this logic.
Wins taking the three: 1311Wins taking the two: 1360
What’s the answer? Is it better to take the three or quick two-plus intentional foul? It is definitely better to take the three. Especially considering the away-from-the-ball rule. Without considering this rule, if the team has a terrible free-throw shooter, bad as 40%, for example. Then taking the two-plus intentional foul could be considered. It depends on other variables as well, such as rebound percentage. Lastly, considering how the NBA game has evolved to have more prolific three-point shooters, it’s natural to favour shooting the three.
[1] Sampling and Monte Carlo Simulation https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/unit-2/lecture-14-sampling-and-monte-carlo-simulation/
[2] Monte Carlo Simulation to Answer LeBron’s Question. https://www.youtube.com/watch?v=-fCVxTTAtFQ
[3] 2019 / 2020 NBA Rulebook https://official.nba.com/rulebook/ | [
{
"code": null,
"e": 474,
"s": 172,
"text": "Monte Carlo Simulation is a type of simulation where the events are chosen to happen randomly. By iterating and trying out various outcomes many times, arbitrarily, it gives great confidence in the result. [1] The name comes from Monte Carlo, located in Monaco, known for its strong gambling activity."
},
{
"code": null,
"e": 754,
"s": 474,
"text": "Let’s use a simple example, a coin toss. Suppose we don’t know, and it’s not easy to calculate the percentage of landing heads or tails. If you toss the coin 10 times and 9 out of 10 it lands on heads, does it mean it’s 90% heads and 10% tails? Of course not. It was merely luck."
},
{
"code": null,
"e": 945,
"s": 754,
"text": "The way to increase the confidence on the correct percentage of each side is to throw a lot more times than 10, let’s say 500 times. The count of tails and heads should come out more evenly."
},
{
"code": null,
"e": 1419,
"s": 945,
"text": "For a coin toss, definitely, there is no need to do such a simulation to know the result. However, often, there are complex use cases with many variables and paths, which is hard to calculate the probability. That’s where Monte Carlo Simulation can be a powerful tool. It can predict something with accuracy by letting the scenario, with all the conditions, evolve randomly. It’s used in Project Management, Artificial Intelligence and to help to make decisions in general."
},
{
"code": null,
"e": 1623,
"s": 1419,
"text": "To provide you with a better perspective on what I’ve explained and to have some fun, I’m going to demonstrate how it works through a specific scenario that can happen at the end of a game of basketball."
},
{
"code": null,
"e": 2008,
"s": 1623,
"text": "Basketball is a complex sport (isn’t it just about putting a ball in a basket?!). It has many constraints and conditions that are constantly being analysed to make the best decision. Players and coaches are always watching for the right position on the court, time on the clock, the number of fouls, timeouts left and more. There are a lot of variables that come into play, literally."
},
{
"code": null,
"e": 2297,
"s": 2008,
"text": "It’s often compared to Chess as some characteristics are similar. For example, each player/piece has its role and function. Many both games are about opening lines and creating space, misleading. ‘fakes’ are also key. Both games make extensive use of set plays that explore these aspects."
},
{
"code": null,
"e": 2535,
"s": 2297,
"text": "The most crucial part of the game, without a doubt, is the end when scores are closed, within two or three points difference, for example. A team can win or lose in a blink of an eye, forcing players and coaches to get the most creative."
},
{
"code": null,
"e": 2982,
"s": 2535,
"text": "A common situation is: A team is down by three points, with 30 seconds left on the clock — is it better to try to take the three (a longer, hence more difficult shot) to tie and go to overtime, OR to try a quick two (usually shorter, easier shot), try to intentionally foul a bad free throw shooter in next possession — hoping that he/she misses one-shot or both — and go for another quick easier two and possibly win the game, or go to overtime?"
},
{
"code": null,
"e": 3179,
"s": 2982,
"text": "Salman Khan, from Khan Academy, addressed exactly this situation [2]. Lebron James asked a question, for which Salman Khan answered and demonstrated the best decision using Monte Carlo simulation."
},
{
"code": null,
"e": 3486,
"s": 3179,
"text": "In this post, I’ll do the same, but with one minor difference. I’m going to take into account that according to NBA rules, a player can’t simply intentionally foul ANY player from the other team with under two minutes left in the game. It has to be the one with the ball. Otherwise, there are consequences."
},
{
"code": null,
"e": 3947,
"s": 3486,
"text": "With under two minutes left in the game (and from 2016, at the end of any quarter), if a player fouls another player that is away from the ball, the team is awarded one free throw and retains possession of the ball, there is no opportunity for the rebound. It’s crucial to emphasize that the TEAM is awarded one free throw — this means that the team can select any player on the floor to attempt the shot (most likely a high percentage free throw shooter) [3]."
},
{
"code": null,
"e": 4386,
"s": 3947,
"text": "In general, the algorithm mimics the real game. It randomly tests different combinations of plays inside a loop and counts how many times the team won by taking the three or the two-plus intentional foul. The bigger number of trials / the loop, the more reliable the results are. There is a threshold for which increasing the number of trials doesn’t make much difference; the program will take longer to finish without adding much value."
},
{
"code": null,
"e": 4434,
"s": 4386,
"text": "Overall the code is divided into five sections:"
},
{
"code": null,
"e": 4567,
"s": 4434,
"text": "It starts by defining the average of various attributes, such as free throw percentage, rebound, two and three-shot percentage, etc."
},
{
"code": null,
"e": 4692,
"s": 4567,
"text": "Definition of the logic that takes the three and misses it or makes it, and if it makes, whether it wins in overtime or not."
},
{
"code": null,
"e": 4858,
"s": 4692,
"text": "The logic for taking the two-plus intentionally fouling. It tests if it makes or misses the two if the opponent makes one or two free throws, grabs the rebound, etc."
},
{
"code": null,
"e": 4955,
"s": 4858,
"text": "It counts how many times the team wins by taking the three and how many times by taking the two."
},
{
"code": null,
"e": 4977,
"s": 4955,
"text": "It prints the result."
},
{
"code": null,
"e": 5098,
"s": 4977,
"text": "Here you can see the result without considering the foul-away-from-the-ball rule. Taking the three is just about better."
},
{
"code": null,
"e": 5151,
"s": 5098,
"text": "Wins taking the three: 1314Wins taking the two: 1151"
},
{
"code": null,
"e": 5458,
"s": 5151,
"text": "By tweaking it a little bit, the opponent’s free throw percentage, from 65% to 40%, for example, taking the two, becomes the best option. This is maybe even more realistic, assuming that the player fouled can be the one away from the ball. It’s not uncommon to have such a bad free throw shooter in a team."
},
{
"code": null,
"e": 5511,
"s": 5458,
"text": "Wins taking the three: 1331Wins taking the two: 1564"
},
{
"code": null,
"e": 5953,
"s": 5511,
"text": "To consider the rule and penalty that awards one free throw shot and retaining the ball, I added a small change in sim_take_two. In the while loop, I added the logic to check if the bad free throw shooter has the ball or not. If he/she does it, the normal two free throws plus rebound flow is followed. Otherwise (if fouled away from the ball), a team player attempts one shot and retains the possession. See below the snippet and full code."
},
{
"code": null,
"e": 6185,
"s": 5953,
"text": "For this scenario, it’s assumed that the team has a 40% free throw shooter on the floor that might end up with the ball and a high percentage one that the team would select to shoot the free throw if the foul is away from the ball."
},
{
"code": null,
"e": 6417,
"s": 6185,
"text": "Another significant constraint is the percentage that the ball is inbounded to the bad free throw shooter. The losing team would have to work really hard to force this situation. I was generous and set it to a 50% chance to happen."
},
{
"code": null,
"e": 6469,
"s": 6417,
"text": "Wins taking the three: 1326Wins taking the two: 776"
},
{
"code": null,
"e": 7086,
"s": 6469,
"text": "With this rule, it becomes almost illogical for the team to try to win by going for the quick two-plus intentional foul under two minutes. The fact that the current winning team gets to retain the ball is a great advantage. It’s an effective rule to stop ‘Hack-a-Shaq’. Named after one of the worst free-throw shooters: Shaquille O’neal. Also, because the team can select any player to attempt the shot, it is even harder. If that weren’t the case, it would be less impossible. But still, the bad free throw shooter would have to have as low as a 15% average to make sense — Below is the result following this logic."
},
{
"code": null,
"e": 7139,
"s": 7086,
"text": "Wins taking the three: 1311Wins taking the two: 1360"
},
{
"code": null,
"e": 7689,
"s": 7139,
"text": "What’s the answer? Is it better to take the three or quick two-plus intentional foul? It is definitely better to take the three. Especially considering the away-from-the-ball rule. Without considering this rule, if the team has a terrible free-throw shooter, bad as 40%, for example. Then taking the two-plus intentional foul could be considered. It depends on other variables as well, such as rebound percentage. Lastly, considering how the NBA game has evolved to have more prolific three-point shooters, it’s natural to favour shooting the three."
},
{
"code": null,
"e": 7924,
"s": 7689,
"text": "[1] Sampling and Monte Carlo Simulation https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/unit-2/lecture-14-sampling-and-monte-carlo-simulation/"
},
{
"code": null,
"e": 8024,
"s": 7924,
"text": "[2] Monte Carlo Simulation to Answer LeBron’s Question. https://www.youtube.com/watch?v=-fCVxTTAtFQ"
}
] |
Recursion in Python, an exploration | by Carlos Brown | Towards Data Science | Recursion is one of those ideas that may seem out of reach, likely from a higher plane of programming existence. Something that A. You don’t really know why it’s a thing and B. You don’t think you would ever need to utilize it. After all, there are no Functional Programming languages in the Top 10 of the TIOBE index as of this writing. Think again, and again...
Perhaps you’re right, recursion is only useful for a coding interview and otherwise FORGET IT. However, I am of the opinion that learning different programming paradigms, and the way in which they parse problems, will ultimately make you a better data scientist/coder. Learning a new paradigm exposes you to new ways of thinking and different ways to structure your code. “This is the way we’ve always done it” won’t be a part of your verbal repertoire with this attitude. Consequently, you’ll learn more and have a better handle on solving the data challenges that come your way. Plus, if you like math like I do, and let’s face it if you are doing data science and don’t like math, then LEAVE NOW (sorry for the tone, I love you), then you will find the exercise enjoyable in its own right.
To introduce recursion, let’s make a simple, hypothetical case that compares solutions. You have an array or list of numbers that need to be squared before they are utilized by the rest of your program. We could use a for loop or list comprehension in python to create the squared version as such.
# Set arraymy_array = [10,11,12,13,14,15]# Method 1# Create a new squared array with for loop (can be considered an anti-pattern)squared_array = []for num in my_array: squared_array.append(num*num)# Method 2# Create a new squared array with list comprehension, a bit more beautiful and concisemy_squared_array = [x*x for x in my_array]
Typically when we loop over values in an imperative language like Python, we are using a for loop or a while loop. These are the constructs we are used to and we use them so often, they are second nature. But what if for and while loops got axed from python tomorrow? Aside from a majority of the world ceasing to function, we have the more pressing issue...how to use recursion now??
We can’t use a list comprehension, so let’s use our new pal recursion to square our array. For this, we need to write a new function.
# Set arraymy_array = [10,11,12,13,14,15]# Define our recursive, squared function that returns a new arraydef squares(an_array, n=None, ret_array=None): if n == None: n = len(an_array) ret_array = [] pos = len(ret_array) squared = an_array[pos] ** 2 ret_array.append(squared) if n-1 == 0: return ret_array else: return squares(an_array, n-1, ret_array)
Ok, that’s a bit ugly and verbose when a list comprehension would suffice, but it shows that we can use recursion in place of a for loop. The function begins by initiating a new array that holds our square values, uses n as a counter to determine where we are as we go over the array by position, then it calls itself until we have gone through the entire array and subsequently have our new squared array.
Think of a recursive function as a bit of code that does not only reside in one place in memory. Sure, the function is defined in one place, but can be called multiple times as data is passed into it. This is termed the Call Stack. Don’t think about it like a Python eating its own tail, though many R users would be cheering. Think about it like a bunch of clones passing a small box, each putting in a coin, then passing the box to the next clone. Ok, maybe now you’re even more confused. Going over the following 3 cases will be helpful to drive this point home and clear any confusion you may have.
Let’s use recursion to do what everyone who has ever touched recursion has done, calculate a factorial. Who else loves discrete mathematics!?
def factorial(num): if num == 1: return 1 return num*factorial(num-1)
A factorial of n (notation as n!) is the product of all positive integers less than n. It is an operation on an arbitrary number defined as n! = n * (n-1) * (n-2)...(1!), where 1! = 1. This is what is called the stopping condition in our code. This idea is very important for recursion because without it, our code could go into an infinite loop, causing “a time paradox, the results of which could cause a chain reaction that would unravel the very fabric of the space time continuum and destroy the entire universe.” — Doc Brown
Say what?
Here’s a helpful way to visualize our factorial func for the case of 4!.
factorial(4) = 4*factorial(3) = 4*3*factorial(2) = 4*3*2*factorial(1) = 4*3*2*1 = 24
Each instance of the factorial function is the same as we have defined in def factorial(), but is a new instance that is taking the results of a previous factorial function instance and passing a new result on, all beginning with the base case of 1, in which case it all rolls up into the final calculation.
Here’s how to use recursion to sum the integers between 0 and n
def sum_n(n): if n == 0: return 0 return n + sum_n(n-1)sum_n(1000)Outputs: 500500
Let’s check our result with the closed form version of the same operation, to make sure we defined our recursive function correctly. Spot checks are always a good idea, because as Richard Feynman said: “The first principle is that you must not fool yourself — and you are the easiest person to fool.” Insert I and myself into the quote to make it personal.
def check_sum(n): return int(n*(n+1)/2)check_sum(1000)Outputs:500500
You have probably seen the formula for compound interest before.
Since we have a number (1+r) that is raised to an exponential, then we can use recursion to calculate our future value FV.
def future_val(pv, rate, t): if t == 0: return pv pv = pv*(1+rate) return future_val(pv, rate, t-1)
The previous function assumes a compounding rate of n=1. That means we only compound once per period t, where t is usually meant to refer to a years time. Let’s extend our example to include different compounding rates, such as monthly.
def future_val_n(pv, rate, t, n): if t == 0: return pv pv = future_val(pv, rate/n, n) return future_val_n(pv, rate, t-1, n)
We’ve been able to recycle our future_val function, and extend it so that we are compounding n times per time period t. Does our function work?
future_val_n(1000, 0.07, 20, 12)Outputs:4038.73# Now we check our value from future_val_nprint(1000*(1+0.07/12)**(20*12))Outputs:4038.73
Remember a few things
We don’t have to have a pure functional language to begin using functional programming techniques in our codePython is not a pure functional language (of course), but borrows many features from them, such as functions as first class objects and list comprehensions to name a couple.
We don’t have to have a pure functional language to begin using functional programming techniques in our code
Python is not a pure functional language (of course), but borrows many features from them, such as functions as first class objects and list comprehensions to name a couple.
Given these two items, we then realize that python has a limit to the number of times a function can be called recursively. This limit is defined here:
sys.getrecursionlimit()Outputs:3000
If we run our sum_n function with n>3000, it will throw a RecursionError even though the function works for a recursion depth less than the limit. This is something to think about when incorporating these types of functions into your python code base.
Now that you know recursion, you will start to see things differently, and perhaps have some creative solutions up your sleeve for your next project. I hope this has been a fun and informative intro to recursion and the functional programming paradigm! | [
{
"code": null,
"e": 535,
"s": 171,
"text": "Recursion is one of those ideas that may seem out of reach, likely from a higher plane of programming existence. Something that A. You don’t really know why it’s a thing and B. You don’t think you would ever need to utilize it. After all, there are no Functional Programming languages in the Top 10 of the TIOBE index as of this writing. Think again, and again..."
},
{
"code": null,
"e": 1328,
"s": 535,
"text": "Perhaps you’re right, recursion is only useful for a coding interview and otherwise FORGET IT. However, I am of the opinion that learning different programming paradigms, and the way in which they parse problems, will ultimately make you a better data scientist/coder. Learning a new paradigm exposes you to new ways of thinking and different ways to structure your code. “This is the way we’ve always done it” won’t be a part of your verbal repertoire with this attitude. Consequently, you’ll learn more and have a better handle on solving the data challenges that come your way. Plus, if you like math like I do, and let’s face it if you are doing data science and don’t like math, then LEAVE NOW (sorry for the tone, I love you), then you will find the exercise enjoyable in its own right."
},
{
"code": null,
"e": 1626,
"s": 1328,
"text": "To introduce recursion, let’s make a simple, hypothetical case that compares solutions. You have an array or list of numbers that need to be squared before they are utilized by the rest of your program. We could use a for loop or list comprehension in python to create the squared version as such."
},
{
"code": null,
"e": 1964,
"s": 1626,
"text": "# Set arraymy_array = [10,11,12,13,14,15]# Method 1# Create a new squared array with for loop (can be considered an anti-pattern)squared_array = []for num in my_array: squared_array.append(num*num)# Method 2# Create a new squared array with list comprehension, a bit more beautiful and concisemy_squared_array = [x*x for x in my_array]"
},
{
"code": null,
"e": 2349,
"s": 1964,
"text": "Typically when we loop over values in an imperative language like Python, we are using a for loop or a while loop. These are the constructs we are used to and we use them so often, they are second nature. But what if for and while loops got axed from python tomorrow? Aside from a majority of the world ceasing to function, we have the more pressing issue...how to use recursion now??"
},
{
"code": null,
"e": 2483,
"s": 2349,
"text": "We can’t use a list comprehension, so let’s use our new pal recursion to square our array. For this, we need to write a new function."
},
{
"code": null,
"e": 2870,
"s": 2483,
"text": "# Set arraymy_array = [10,11,12,13,14,15]# Define our recursive, squared function that returns a new arraydef squares(an_array, n=None, ret_array=None): if n == None: n = len(an_array) ret_array = [] pos = len(ret_array) squared = an_array[pos] ** 2 ret_array.append(squared) if n-1 == 0: return ret_array else: return squares(an_array, n-1, ret_array)"
},
{
"code": null,
"e": 3277,
"s": 2870,
"text": "Ok, that’s a bit ugly and verbose when a list comprehension would suffice, but it shows that we can use recursion in place of a for loop. The function begins by initiating a new array that holds our square values, uses n as a counter to determine where we are as we go over the array by position, then it calls itself until we have gone through the entire array and subsequently have our new squared array."
},
{
"code": null,
"e": 3880,
"s": 3277,
"text": "Think of a recursive function as a bit of code that does not only reside in one place in memory. Sure, the function is defined in one place, but can be called multiple times as data is passed into it. This is termed the Call Stack. Don’t think about it like a Python eating its own tail, though many R users would be cheering. Think about it like a bunch of clones passing a small box, each putting in a coin, then passing the box to the next clone. Ok, maybe now you’re even more confused. Going over the following 3 cases will be helpful to drive this point home and clear any confusion you may have."
},
{
"code": null,
"e": 4022,
"s": 3880,
"text": "Let’s use recursion to do what everyone who has ever touched recursion has done, calculate a factorial. Who else loves discrete mathematics!?"
},
{
"code": null,
"e": 4105,
"s": 4022,
"text": "def factorial(num): if num == 1: return 1 return num*factorial(num-1)"
},
{
"code": null,
"e": 4636,
"s": 4105,
"text": "A factorial of n (notation as n!) is the product of all positive integers less than n. It is an operation on an arbitrary number defined as n! = n * (n-1) * (n-2)...(1!), where 1! = 1. This is what is called the stopping condition in our code. This idea is very important for recursion because without it, our code could go into an infinite loop, causing “a time paradox, the results of which could cause a chain reaction that would unravel the very fabric of the space time continuum and destroy the entire universe.” — Doc Brown"
},
{
"code": null,
"e": 4646,
"s": 4636,
"text": "Say what?"
},
{
"code": null,
"e": 4719,
"s": 4646,
"text": "Here’s a helpful way to visualize our factorial func for the case of 4!."
},
{
"code": null,
"e": 4804,
"s": 4719,
"text": "factorial(4) = 4*factorial(3) = 4*3*factorial(2) = 4*3*2*factorial(1) = 4*3*2*1 = 24"
},
{
"code": null,
"e": 5112,
"s": 4804,
"text": "Each instance of the factorial function is the same as we have defined in def factorial(), but is a new instance that is taking the results of a previous factorial function instance and passing a new result on, all beginning with the base case of 1, in which case it all rolls up into the final calculation."
},
{
"code": null,
"e": 5176,
"s": 5112,
"text": "Here’s how to use recursion to sum the integers between 0 and n"
},
{
"code": null,
"e": 5271,
"s": 5176,
"text": "def sum_n(n): if n == 0: return 0 return n + sum_n(n-1)sum_n(1000)Outputs: 500500"
},
{
"code": null,
"e": 5628,
"s": 5271,
"text": "Let’s check our result with the closed form version of the same operation, to make sure we defined our recursive function correctly. Spot checks are always a good idea, because as Richard Feynman said: “The first principle is that you must not fool yourself — and you are the easiest person to fool.” Insert I and myself into the quote to make it personal."
},
{
"code": null,
"e": 5700,
"s": 5628,
"text": "def check_sum(n): return int(n*(n+1)/2)check_sum(1000)Outputs:500500"
},
{
"code": null,
"e": 5765,
"s": 5700,
"text": "You have probably seen the formula for compound interest before."
},
{
"code": null,
"e": 5888,
"s": 5765,
"text": "Since we have a number (1+r) that is raised to an exponential, then we can use recursion to calculate our future value FV."
},
{
"code": null,
"e": 6004,
"s": 5888,
"text": "def future_val(pv, rate, t): if t == 0: return pv pv = pv*(1+rate) return future_val(pv, rate, t-1)"
},
{
"code": null,
"e": 6241,
"s": 6004,
"text": "The previous function assumes a compounding rate of n=1. That means we only compound once per period t, where t is usually meant to refer to a years time. Let’s extend our example to include different compounding rates, such as monthly."
},
{
"code": null,
"e": 6381,
"s": 6241,
"text": "def future_val_n(pv, rate, t, n): if t == 0: return pv pv = future_val(pv, rate/n, n) return future_val_n(pv, rate, t-1, n)"
},
{
"code": null,
"e": 6525,
"s": 6381,
"text": "We’ve been able to recycle our future_val function, and extend it so that we are compounding n times per time period t. Does our function work?"
},
{
"code": null,
"e": 6662,
"s": 6525,
"text": "future_val_n(1000, 0.07, 20, 12)Outputs:4038.73# Now we check our value from future_val_nprint(1000*(1+0.07/12)**(20*12))Outputs:4038.73"
},
{
"code": null,
"e": 6684,
"s": 6662,
"text": "Remember a few things"
},
{
"code": null,
"e": 6967,
"s": 6684,
"text": "We don’t have to have a pure functional language to begin using functional programming techniques in our codePython is not a pure functional language (of course), but borrows many features from them, such as functions as first class objects and list comprehensions to name a couple."
},
{
"code": null,
"e": 7077,
"s": 6967,
"text": "We don’t have to have a pure functional language to begin using functional programming techniques in our code"
},
{
"code": null,
"e": 7251,
"s": 7077,
"text": "Python is not a pure functional language (of course), but borrows many features from them, such as functions as first class objects and list comprehensions to name a couple."
},
{
"code": null,
"e": 7403,
"s": 7251,
"text": "Given these two items, we then realize that python has a limit to the number of times a function can be called recursively. This limit is defined here:"
},
{
"code": null,
"e": 7439,
"s": 7403,
"text": "sys.getrecursionlimit()Outputs:3000"
},
{
"code": null,
"e": 7691,
"s": 7439,
"text": "If we run our sum_n function with n>3000, it will throw a RecursionError even though the function works for a recursion depth less than the limit. This is something to think about when incorporating these types of functions into your python code base."
}
] |
GATE | GATE CS 2013 | Question 65 - GeeksforGeeks | 13 Aug, 2019
Consider an instruction pipeline with five stages without any branch prediction: Fetch Instruction (FI), Decode Instruction (DI), Fetch Operand (FO), Execute Instruction (EI) and Write Operand (WO). The stage delays for FI, DI, FO, EI and WO are 5 ns, 7 ns, 10 ns, 8 ns and 6 ns, respectively. There are intermediate storage buffers after each stage and the delay of each buffer is 1 ns. A program consisting of 12 instructions I1, I2, I3, ..., I12 is executed in this pipelined processor. Instruction I4 is the only branch instruction and its branch target is I9. If the branch is taken during the execution of this program, the time (in ns) needed to complete the program is
(A) 132(B) 165(C) 176(D) 328Answer: (B)Explanation:
Pipeline will have to be stalled till Ei stage of l4 completes,
as Ei stage will tell whether to take branch or not.
After that l4(WO) and l9(Fi) can go in parallel and later the
following instructions.
So, till l4(Ei) completes : 7 cycles * (10 + 1 ) ns = 77ns
From l4(WO) or l9(Fi) to l12(WO) : 8 cycles * (10 + 1)ns = 88ns
Total = 77 + 88 = 165 ns
Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-IT-2004 | Question 83
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2007 | Question 17
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 64
GATE | GATE-CS-2014-(Set-3) | Question 65 | [
{
"code": null,
"e": 24412,
"s": 24384,
"text": "\n13 Aug, 2019"
},
{
"code": null,
"e": 25089,
"s": 24412,
"text": "Consider an instruction pipeline with five stages without any branch prediction: Fetch Instruction (FI), Decode Instruction (DI), Fetch Operand (FO), Execute Instruction (EI) and Write Operand (WO). The stage delays for FI, DI, FO, EI and WO are 5 ns, 7 ns, 10 ns, 8 ns and 6 ns, respectively. There are intermediate storage buffers after each stage and the delay of each buffer is 1 ns. A program consisting of 12 instructions I1, I2, I3, ..., I12 is executed in this pipelined processor. Instruction I4 is the only branch instruction and its branch target is I9. If the branch is taken during the execution of this program, the time (in ns) needed to complete the program is"
},
{
"code": null,
"e": 25141,
"s": 25089,
"text": "(A) 132(B) 165(C) 176(D) 328Answer: (B)Explanation:"
},
{
"code": null,
"e": 25495,
"s": 25141,
"text": "Pipeline will have to be stalled till Ei stage of l4 completes, \nas Ei stage will tell whether to take branch or not. \n\nAfter that l4(WO) and l9(Fi) can go in parallel and later the\nfollowing instructions.\nSo, till l4(Ei) completes : 7 cycles * (10 + 1 ) ns = 77ns\nFrom l4(WO) or l9(Fi) to l12(WO) : 8 cycles * (10 + 1)ns = 88ns\nTotal = 77 + 88 = 165 ns"
},
{
"code": null,
"e": 25517,
"s": 25495,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25530,
"s": 25517,
"text": "GATE-CS-2013"
},
{
"code": null,
"e": 25548,
"s": 25530,
"text": "GATE-GATE CS 2013"
},
{
"code": null,
"e": 25553,
"s": 25548,
"text": "GATE"
},
{
"code": null,
"e": 25651,
"s": 25553,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25660,
"s": 25651,
"text": "Comments"
},
{
"code": null,
"e": 25673,
"s": 25660,
"text": "Old Comments"
},
{
"code": null,
"e": 25715,
"s": 25673,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 25749,
"s": 25715,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 25783,
"s": 25749,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 25825,
"s": 25783,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 25867,
"s": 25825,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 63"
},
{
"code": null,
"e": 25901,
"s": 25867,
"text": "GATE | GATE-CS-2007 | Question 17"
},
{
"code": null,
"e": 25935,
"s": 25901,
"text": "GATE | GATE-IT-2004 | Question 12"
},
{
"code": null,
"e": 25977,
"s": 25935,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 26011,
"s": 25977,
"text": "GATE | GATE-CS-2007 | Question 64"
}
] |
Shortest Unique prefix for every word | Practice | GeeksforGeeks | Given an array of words, find all shortest unique prefixes to represent each word in the given array. Assume that no word is prefix of another.
Example 1:
Input:
N = 4
arr[] = {"zebra", "dog", "duck", "dove"}
Output: z dog du dov
Explanation:
z => zebra
dog => dog
duck => du
dove => dov
Example 2:
Input:
N = 3
arr[] = {"geeksgeeks", "geeksquiz",
"geeksforgeeks"};
Output: geeksg geeksq geeksf
Explanation:
geeksgeeks => geeksg
geeksquiz => geeksq
geeksforgeeks => geeksf
0
therishabhkumar0012 weeks ago
need help
class tr{ public: int num; tr* children[26]; bool last ; tr(){ num = 1; for(int i=0;i<26;i++)children[i]=NULL; last = false; }};
class Solution{ public: void insert(tr* root, string word){ if(word.size()==0){ root->last=true; return ; } tr *child = new tr; if(root->children[word[0]-'a']==NULL){ root->children[word[0]-'a'] = child; insert(child,word.substr(1)); }else{ root->children[word[0]-'a']->num++; insert(root->children[word[0]-'a'],word.substr(1)); } return ; } void go(tr* root, string temp, vector<string> &ans,string& x){ if(root!=NULL&&temp.size()!=0)x.push_back(temp[0]); else return; if(root->children[temp[0]-'a']->num==1||temp.size()==1){ ans.push_back(x); return ; } go(root->children[temp[0]-'a'],temp.substr(1),ans,x); } vector<string> findPrefixes(string arr[], int n) { vector<string > ans; tr *root = new tr; for(int i=0;i<n;i++)insert(root,arr[i]); string temp=""; for(int i=0;i<n;i++){ go(root,arr[i],ans,temp); temp.clear(); } return ans; } };
giving error(Abort signal from abort(3) (SIGABRT)) at testcase number 10004.
+2
arthurshelby1 month ago
😉✌️🇮🇳❄️
struct Trie{
Trie *dict[26];
int count;
Trie(){
count=0;
for(int i=0;i<26;i++){ //clearing for the next testcase
dict[i]=NULL;
}
}
};
class Solution
{
public:
vector<string>v;
Trie *root=new Trie();
void make(string s )
{
Trie *cur=root;
for(int i=0;i<s.length();i++)
{
if(cur->dict[s[i]-'a']==NULL)
cur->dict[s[i]-'a']=new Trie();
cur->dict[s[i]-'a']->count++;
cur=cur->dict[s[i]-'a'];
}
}
vector<string> findPrefixes(string arr[], int n)
{
//code here
for(int i=0;i<n;i++)
make(arr[i]);
for(int i=0;i<n;i++)
{
Trie *cur=root;
for(int j=0;j<arr[i].size();j++)
{
cur=cur->dict[arr[i][j]-'a'];
if(cur->count==1)
{
v.push_back(arr[i].substr(0,j+1));
break;
}
}
}
return v;
}
};
+1
goelharsh491 month ago
JAVA Efficient Solution
// { Driver Code Starts
//Initial Template for Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[]) throws IOException {
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while (t-- > 0) {
int N = Integer.parseInt(read.readLine());
String arr[] = read.readLine().split(" ");
Solution ob = new Solution();
String[] res = ob.findPrefixes(arr,N);
for(int i=0; i<res.length; i++)
System.out.print(res[i] + " ");
System.out.println();
}
}
}// } Driver Code Ends
//User function Template for Java
class Solution {
static String[] findPrefixes(String[] a, int n) {
Trie root = new Trie();
String[] ans = new String[n];
for(int i=0;i<n;i++){
Trie temp = root;
for(int j = 0;j<a[i].length();j++){
char c = a[i].charAt(j);
if(temp.a[c-'a'] == null )
temp.a[c-'a'] = new Trie();
temp = temp.a[c-'a'];
temp.end++;
}
}
for(int i=0;i<n;i++){
Trie temp = root;
int j = 0;
while(temp.end != 1){
char c = a[i].charAt(j);
temp = temp.a[c-'a'];
j++;
}
ans[i] = a[i].substring(0,j);
}
return ans;
}
}
class Trie{
Trie a[] = new Trie[26];
int end;
}
0
sequeirahansel
This comment was deleted.
0
sequeirahansel
This comment was deleted.
0
anushkay009212 months ago
class TrieNode { TrieNode children [] = new TrieNode [26]; boolean isEndOfWord = false ; }class Solution { static void insert(TrieNode root, String key) { TrieNode node = root ; for( int i = 0; i < key.length(); i++) { if(node.children[key.charAt(i) - 'a'] == null) { TrieNode newNode = new TrieNode (); node.children[key.charAt(i) - 'a'] = newNode; } node = node.children[key.charAt(i) - 'a'] ; } node.isEndOfWord = true;
}
static String search(TrieNode root, String key){ int start = 0; int end = 0; TrieNode node = root ; int count; for( int i = 0; i < key.length(); i++) { count = 0 ; for(int j= 0 ; j < 26 ; j++) { if( node.children [j] != null ) count ++; } if (count > 1 && i!=0 ) end = i ; node = node.children[key.charAt(i) - 'a']; } String prefix = key.substring(start, end +1); return prefix; } static String[] findPrefixes(String[] arr, int N) { TrieNode root = new TrieNode (); for(int i = 0; i< arr.length; i++) { insert (root, arr[i]); } String [] result = new String [N] ; for (int i = 0 ; i < arr.length; i++ ) { result [i] = search(root, arr[i]); } return result ; }};
+1
lindan1232 months ago
struct TrieNode
{
int count;
TrieNode* child[26];
TrieNode()
{
count=0;
for(int i=0;i<26;i++)
{
child[i]=NULL;
}
}
};
class Solution
{
public:
TrieNode* root = new TrieNode();
vector<string> findPrefixes(string arr[], int n)
{
vector<string> vec;
for(int i=0;i<n;i++)
{
maketree(arr[i],root);
}
for(int i=0;i<n;i++)
{
string s = arr[i];
TrieNode* curr = root;
string ans="";
for(int j=0;j<s.length();j++)
{
int ind = s[j]-'a';
curr = curr->child[ind];
if(curr->count==1)
{
vec.push_back(s.substr(0,j+1));
break;
}
}
}
return vec;
}
void maketree(string s,TrieNode* root)
{
TrieNode* curr = root;
for(int i=0;i<s.length();i++)
{
if(curr->child[s[i]-'a']==NULL)
{
curr->child[s[i]-'a'] = new TrieNode();
}
curr->child[s[i]-'a']->count++;
curr = curr->child[s[i]-'a'];
}
}
};
Time Taken : 0.4
Cpp
0
himanshujain4572 months ago
Can Anyone Tell Why Can't Be This Output of TC-1:
z d du do
+3
abhishek2061a2 months ago
Simple C++ Solution using Trie
class Trie{
Trie* child[26];
int startWith;
int endWith;
public:
Trie()
{
fill_n(this->child, 26, nullptr);
startWith = 0;
endWith = 0;
}
void insert(string word)
{
Trie* root = this;
for(char it : word)
{
int i = it-'a';
if(!root->child[i])
root->child[i] = new Trie();
root = root->child[i];
root->startWith++;
}
root->endWith++;
}
string find(string word)
{
Trie* root = this;
string ans;
for(char it : word)
{
ans.push_back(it);
int i = it-'a';
root = root->child[i];
if(root->startWith == 1)
break;
}
return ans;
}
};
class Solution
{
public:
vector<string> findPrefixes(string arr[], int n)
{
//code here
Trie* root = new Trie();
vector<string> ans;
for(int i=0; i<n; i++)
root->insert(arr[i]);
for(int i=0; i<n; i++)
ans.push_back(root->find(arr[i]));
return ans;
}
};
0
mayankkannojia293 months ago
Java 2/5.8
class Node{ char data; int count; HashMap<Character,Node> values; Node(char d){ this.data = d; values = new HashMap<>(); count=1; }}
class Solution { static String[] findPrefixes(String[] str, int N) { HashMap<Character,Node> hash = new HashMap<>(); for(int i = 0;i<N;i++){ Node c = new Node(str[i].charAt(0)); if(hash.containsKey(c.data)){ c = hash.get(c.data); c.count += 1; } else hash.put(c.data,c); for(int j = 1;j<str[i].length();j++){ if(c.values.containsKey(str[i].charAt(j))){ c = c.values.get(str[i].charAt(j)); c.count += 1; } else{ Node temp = new Node(str[i].charAt(j)); c.values.put(str[i].charAt(j),temp); c = temp; } } } String[] b = new String[N]; for(int i = 0;i<N;i++){ Node n = hash.get(str[i].charAt(0)); for(int j = 0;j<str[i].length();j++){ if(n.count == 1){ b[i] = str[i].substring(0,j+1); break; }else if(j != str[i].length()-1) n = n.values.get(str[i].charAt(j+1)); else b[i] = str[i]; } } return b; }};
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": 382,
"s": 238,
"text": "Given an array of words, find all shortest unique prefixes to represent each word in the given array. Assume that no word is prefix of another."
},
{
"code": null,
"e": 393,
"s": 382,
"text": "Example 1:"
},
{
"code": null,
"e": 533,
"s": 393,
"text": "Input: \nN = 4\narr[] = {\"zebra\", \"dog\", \"duck\", \"dove\"}\nOutput: z dog du dov\nExplanation: \nz => zebra \ndog => dog \nduck => du \ndove => dov \n"
},
{
"code": null,
"e": 544,
"s": 533,
"text": "Example 2:"
},
{
"code": null,
"e": 746,
"s": 544,
"text": "Input: \nN = 3\narr[] = {\"geeksgeeks\", \"geeksquiz\",\n \"geeksforgeeks\"};\nOutput: geeksg geeksq geeksf\nExplanation: \ngeeksgeeks => geeksg \ngeeksquiz => geeksq \ngeeksforgeeks => geeksf"
},
{
"code": null,
"e": 748,
"s": 746,
"text": "0"
},
{
"code": null,
"e": 778,
"s": 748,
"text": "therishabhkumar0012 weeks ago"
},
{
"code": null,
"e": 788,
"s": 778,
"text": "need help"
},
{
"code": null,
"e": 947,
"s": 788,
"text": "class tr{ public: int num; tr* children[26]; bool last ; tr(){ num = 1; for(int i=0;i<26;i++)children[i]=NULL; last = false; }};"
},
{
"code": null,
"e": 2025,
"s": 947,
"text": "class Solution{ public: void insert(tr* root, string word){ if(word.size()==0){ root->last=true; return ; } tr *child = new tr; if(root->children[word[0]-'a']==NULL){ root->children[word[0]-'a'] = child; insert(child,word.substr(1)); }else{ root->children[word[0]-'a']->num++; insert(root->children[word[0]-'a'],word.substr(1)); } return ; } void go(tr* root, string temp, vector<string> &ans,string& x){ if(root!=NULL&&temp.size()!=0)x.push_back(temp[0]); else return; if(root->children[temp[0]-'a']->num==1||temp.size()==1){ ans.push_back(x); return ; } go(root->children[temp[0]-'a'],temp.substr(1),ans,x); } vector<string> findPrefixes(string arr[], int n) { vector<string > ans; tr *root = new tr; for(int i=0;i<n;i++)insert(root,arr[i]); string temp=\"\"; for(int i=0;i<n;i++){ go(root,arr[i],ans,temp); temp.clear(); } return ans; } };"
},
{
"code": null,
"e": 2102,
"s": 2025,
"text": "giving error(Abort signal from abort(3) (SIGABRT)) at testcase number 10004."
},
{
"code": null,
"e": 2105,
"s": 2102,
"text": "+2"
},
{
"code": null,
"e": 2129,
"s": 2105,
"text": "arthurshelby1 month ago"
},
{
"code": null,
"e": 3204,
"s": 2129,
"text": "😉✌️🇮🇳❄️\nstruct Trie{\n Trie *dict[26];\n int count;\n Trie(){\n count=0;\n for(int i=0;i<26;i++){ //clearing for the next testcase\n dict[i]=NULL;\n }\n }\n};\nclass Solution\n{\n public:\n vector<string>v;\n Trie *root=new Trie();\n void make(string s )\n {\n Trie *cur=root;\n for(int i=0;i<s.length();i++)\n {\n if(cur->dict[s[i]-'a']==NULL)\n cur->dict[s[i]-'a']=new Trie();\n cur->dict[s[i]-'a']->count++;\n cur=cur->dict[s[i]-'a'];\n }\n }\n vector<string> findPrefixes(string arr[], int n)\n {\n //code here\n for(int i=0;i<n;i++)\n make(arr[i]);\n for(int i=0;i<n;i++)\n {\n Trie *cur=root;\n for(int j=0;j<arr[i].size();j++)\n {\n cur=cur->dict[arr[i][j]-'a'];\n if(cur->count==1)\n {\n v.push_back(arr[i].substr(0,j+1));\n break;\n }\n }\n }\n return v;\n }\n};"
},
{
"code": null,
"e": 3207,
"s": 3204,
"text": "+1"
},
{
"code": null,
"e": 3230,
"s": 3207,
"text": "goelharsh491 month ago"
},
{
"code": null,
"e": 3254,
"s": 3230,
"text": "JAVA Efficient Solution"
},
{
"code": null,
"e": 4966,
"s": 3254,
"text": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n int N = Integer.parseInt(read.readLine());\n \n String arr[] = read.readLine().split(\" \");\n\n Solution ob = new Solution();\n String[] res = ob.findPrefixes(arr,N);\n \n for(int i=0; i<res.length; i++)\n System.out.print(res[i] + \" \");\n System.out.println();\n }\n }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n static String[] findPrefixes(String[] a, int n) {\n Trie root = new Trie();\n String[] ans = new String[n];\n \n for(int i=0;i<n;i++){\n Trie temp = root;\n \n for(int j = 0;j<a[i].length();j++){\n char c = a[i].charAt(j);\n \n if(temp.a[c-'a'] == null )\n temp.a[c-'a'] = new Trie();\n \n temp = temp.a[c-'a'];\n temp.end++;\n }\n }\n \n for(int i=0;i<n;i++){\n Trie temp = root;\n int j = 0;\n \n while(temp.end != 1){\n char c = a[i].charAt(j);\n temp = temp.a[c-'a'];\n j++;\n }\n \n ans[i] = a[i].substring(0,j);\n }\n \n return ans;\n }\n}\n\nclass Trie{\n Trie a[] = new Trie[26];\n int end;\n}"
},
{
"code": null,
"e": 4968,
"s": 4966,
"text": "0"
},
{
"code": null,
"e": 4983,
"s": 4968,
"text": "sequeirahansel"
},
{
"code": null,
"e": 5009,
"s": 4983,
"text": "This comment was deleted."
},
{
"code": null,
"e": 5011,
"s": 5009,
"text": "0"
},
{
"code": null,
"e": 5026,
"s": 5011,
"text": "sequeirahansel"
},
{
"code": null,
"e": 5052,
"s": 5026,
"text": "This comment was deleted."
},
{
"code": null,
"e": 5054,
"s": 5052,
"text": "0"
},
{
"code": null,
"e": 5080,
"s": 5054,
"text": "anushkay009212 months ago"
},
{
"code": null,
"e": 5579,
"s": 5080,
"text": " class TrieNode { TrieNode children [] = new TrieNode [26]; boolean isEndOfWord = false ; }class Solution { static void insert(TrieNode root, String key) { TrieNode node = root ; for( int i = 0; i < key.length(); i++) { if(node.children[key.charAt(i) - 'a'] == null) { TrieNode newNode = new TrieNode (); node.children[key.charAt(i) - 'a'] = newNode; } node = node.children[key.charAt(i) - 'a'] ; } node.isEndOfWord = true;"
},
{
"code": null,
"e": 5581,
"s": 5579,
"text": "}"
},
{
"code": null,
"e": 6408,
"s": 5581,
"text": "static String search(TrieNode root, String key){ int start = 0; int end = 0; TrieNode node = root ; int count; for( int i = 0; i < key.length(); i++) { count = 0 ; for(int j= 0 ; j < 26 ; j++) { if( node.children [j] != null ) count ++; } if (count > 1 && i!=0 ) end = i ; node = node.children[key.charAt(i) - 'a']; } String prefix = key.substring(start, end +1); return prefix; } static String[] findPrefixes(String[] arr, int N) { TrieNode root = new TrieNode (); for(int i = 0; i< arr.length; i++) { insert (root, arr[i]); } String [] result = new String [N] ; for (int i = 0 ; i < arr.length; i++ ) { result [i] = search(root, arr[i]); } return result ; }};"
},
{
"code": null,
"e": 6411,
"s": 6408,
"text": "+1"
},
{
"code": null,
"e": 6433,
"s": 6411,
"text": "lindan1232 months ago"
},
{
"code": null,
"e": 7780,
"s": 6433,
"text": "struct TrieNode\n {\n int count;\n TrieNode* child[26];\n TrieNode()\n {\n count=0;\n for(int i=0;i<26;i++)\n {\n child[i]=NULL;\n }\n }\n };\nclass Solution\n{\n public:\n TrieNode* root = new TrieNode();\n \n vector<string> findPrefixes(string arr[], int n)\n {\n vector<string> vec;\n \n for(int i=0;i<n;i++)\n {\n maketree(arr[i],root);\n }\n \n for(int i=0;i<n;i++)\n {\n string s = arr[i];\n TrieNode* curr = root;\n string ans=\"\";\n for(int j=0;j<s.length();j++)\n {\n int ind = s[j]-'a';\n curr = curr->child[ind];\n if(curr->count==1)\n {\n vec.push_back(s.substr(0,j+1));\n break;\n }\n \n }\n }\n return vec;\n }\n \n void maketree(string s,TrieNode* root)\n {\n TrieNode* curr = root;\n for(int i=0;i<s.length();i++)\n {\n if(curr->child[s[i]-'a']==NULL)\n {\n curr->child[s[i]-'a'] = new TrieNode();\n }\n curr->child[s[i]-'a']->count++;\n curr = curr->child[s[i]-'a'];\n }\n }\n \n \n};"
},
{
"code": null,
"e": 7797,
"s": 7780,
"text": "Time Taken : 0.4"
},
{
"code": null,
"e": 7801,
"s": 7797,
"text": "Cpp"
},
{
"code": null,
"e": 7803,
"s": 7801,
"text": "0"
},
{
"code": null,
"e": 7831,
"s": 7803,
"text": "himanshujain4572 months ago"
},
{
"code": null,
"e": 7881,
"s": 7831,
"text": "Can Anyone Tell Why Can't Be This Output of TC-1:"
},
{
"code": null,
"e": 7892,
"s": 7881,
"text": "z d du do "
},
{
"code": null,
"e": 7895,
"s": 7892,
"text": "+3"
},
{
"code": null,
"e": 7921,
"s": 7895,
"text": "abhishek2061a2 months ago"
},
{
"code": null,
"e": 7952,
"s": 7921,
"text": "Simple C++ Solution using Trie"
},
{
"code": null,
"e": 9150,
"s": 7954,
"text": "class Trie{\n \n Trie* child[26];\n int startWith;\n int endWith;\n \n public:\n \n Trie()\n {\n fill_n(this->child, 26, nullptr);\n startWith = 0;\n endWith = 0;\n }\n \n void insert(string word)\n {\n Trie* root = this;\n \n for(char it : word)\n {\n int i = it-'a';\n \n if(!root->child[i])\n root->child[i] = new Trie();\n \n root = root->child[i];\n root->startWith++;\n }\n \n root->endWith++;\n }\n \n string find(string word)\n {\n Trie* root = this;\n string ans;\n \n for(char it : word)\n {\n ans.push_back(it);\n \n int i = it-'a';\n \n root = root->child[i];\n \n if(root->startWith == 1)\n break;\n }\n \n return ans;\n }\n \n};\n\nclass Solution\n{\n public:\n vector<string> findPrefixes(string arr[], int n)\n {\n //code here\n Trie* root = new Trie();\n vector<string> ans;\n \n for(int i=0; i<n; i++)\n root->insert(arr[i]);\n \n for(int i=0; i<n; i++)\n ans.push_back(root->find(arr[i]));\n \n return ans;\n }\n \n};"
},
{
"code": null,
"e": 9152,
"s": 9150,
"text": "0"
},
{
"code": null,
"e": 9181,
"s": 9152,
"text": "mayankkannojia293 months ago"
},
{
"code": null,
"e": 9192,
"s": 9181,
"text": "Java 2/5.8"
},
{
"code": null,
"e": 9353,
"s": 9192,
"text": "class Node{ char data; int count; HashMap<Character,Node> values; Node(char d){ this.data = d; values = new HashMap<>(); count=1; }}"
},
{
"code": null,
"e": 10538,
"s": 9353,
"text": "class Solution { static String[] findPrefixes(String[] str, int N) { HashMap<Character,Node> hash = new HashMap<>(); for(int i = 0;i<N;i++){ Node c = new Node(str[i].charAt(0)); if(hash.containsKey(c.data)){ c = hash.get(c.data); c.count += 1; } else hash.put(c.data,c); for(int j = 1;j<str[i].length();j++){ if(c.values.containsKey(str[i].charAt(j))){ c = c.values.get(str[i].charAt(j)); c.count += 1; } else{ Node temp = new Node(str[i].charAt(j)); c.values.put(str[i].charAt(j),temp); c = temp; } } } String[] b = new String[N]; for(int i = 0;i<N;i++){ Node n = hash.get(str[i].charAt(0)); for(int j = 0;j<str[i].length();j++){ if(n.count == 1){ b[i] = str[i].substring(0,j+1); break; }else if(j != str[i].length()-1) n = n.values.get(str[i].charAt(j+1)); else b[i] = str[i]; } } return b; }};"
},
{
"code": null,
"e": 10684,
"s": 10538,
"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": 10720,
"s": 10684,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 10730,
"s": 10720,
"text": "\nProblem\n"
},
{
"code": null,
"e": 10740,
"s": 10730,
"text": "\nContest\n"
},
{
"code": null,
"e": 10803,
"s": 10740,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 10951,
"s": 10803,
"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": 11159,
"s": 10951,
"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": 11265,
"s": 11159,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How can we export data to a CSV file whose filename name contains timestamp at which the file is created? | Sometimes we need to export data into a CSV file whose name has a timestamp at which that file is created. It can be done with the help of MySQL prepared statement. To illustrate it we are using the following example −
Example
The queries in the following example will export the data from table ‘student_info’ to the CSV file having a timestamp in its name.
mysql> SET @time_stamp = DATE_FORMAT(NOW(),'_%Y_%m_%d_%H_%i_%s');
Query OK, 0 rows affected (0.00 sec)
mysql> SET @FOLDER = 'C:/mysql/bin/mysql-files';
Query OK, 0 rows affected (0.00 sec)
mysql> SET @FOLDER = 'C:/mysql/bin/mysql-files/';
Query OK, 0 rows affected (0.00 sec)
mysql> SET @PREFIX = 'Student15';
Query OK, 0 rows affected (0.00 sec)
mysql> SET @EXT = '.CSV';
Query OK, 0 rows affected (0.00 sec)
mysql> SET @Command = CONCAT("SELECT * FROM Student_info INTO OUTFILE '",@FOLDER, @PREFIX, @time_stamp, @EXT,"' FIELDS ENCLOSED BY '\"' TERMINATED BY ';'
ESCAPED BY '\"'"," LINES TERMINATED BY '\r\n';");
Query OK, 0 rows affected (0.00 sec)
mysql> PREPARE stmt FROM @command;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute stmt;
Query OK, 6 rows affected (0.07 sec)
The above query will create CSV file name ‘student_2017_12_10_18_52_46.CSV’ i.e. a CSV file with timestamp value, having the following data −
101;"YashPal";"Amritsar";"History"
105;"Gaurav";"Chandigarh";"Literature"
125;"Raman";"Shimla";"Computers"
130;"Ram";"Jhansi";"Computers"
132;"Shyam";"Chandigarh";"Economics"
133;"Mohan";"Delhi";"Computers" | [
{
"code": null,
"e": 1281,
"s": 1062,
"text": "Sometimes we need to export data into a CSV file whose name has a timestamp at which that file is created. It can be done with the help of MySQL prepared statement. To illustrate it we are using the following example −"
},
{
"code": null,
"e": 1289,
"s": 1281,
"text": "Example"
},
{
"code": null,
"e": 1421,
"s": 1289,
"text": "The queries in the following example will export the data from table ‘student_info’ to the CSV file having a timestamp in its name."
},
{
"code": null,
"e": 2228,
"s": 1421,
"text": "mysql> SET @time_stamp = DATE_FORMAT(NOW(),'_%Y_%m_%d_%H_%i_%s');\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> SET @FOLDER = 'C:/mysql/bin/mysql-files';\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> SET @FOLDER = 'C:/mysql/bin/mysql-files/';\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> SET @PREFIX = 'Student15';\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> SET @EXT = '.CSV';\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> SET @Command = CONCAT(\"SELECT * FROM Student_info INTO OUTFILE '\",@FOLDER, @PREFIX, @time_stamp, @EXT,\"' FIELDS ENCLOSED BY '\\\"' TERMINATED BY ';'\nESCAPED BY '\\\"'\",\" LINES TERMINATED BY '\\r\\n';\");\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> PREPARE stmt FROM @command;\nQuery OK, 0 rows affected (0.00 sec)\nStatement prepared\n\nmysql> execute stmt;\nQuery OK, 6 rows affected (0.07 sec)"
},
{
"code": null,
"e": 2370,
"s": 2228,
"text": "The above query will create CSV file name ‘student_2017_12_10_18_52_46.CSV’ i.e. a CSV file with timestamp value, having the following data −"
},
{
"code": null,
"e": 2577,
"s": 2370,
"text": "101;\"YashPal\";\"Amritsar\";\"History\"\n105;\"Gaurav\";\"Chandigarh\";\"Literature\"\n125;\"Raman\";\"Shimla\";\"Computers\"\n130;\"Ram\";\"Jhansi\";\"Computers\"\n132;\"Shyam\";\"Chandigarh\";\"Economics\"\n133;\"Mohan\";\"Delhi\";\"Computers\""
}
] |
What are RMSE and MAE?. A Simple Guide to Evaluation Metrics | by Shwetha Acharya | Towards Data Science | Root Mean Squared Error (RMSE)and Mean Absolute Error (MAE) are metrics used to evaluate a Regression Model. These metrics tell us how accurate our predictions are and, what is the amount of deviation from the actual values.
Technically, RMSE is the Root of the Mean of the Square of Errors and MAE is the Mean of Absolute value of Errors. Here, errors are the differences between the predicted values (values predicted by our regression model) and the actual values of a variable. They are calculated as follows :
On close inspection, you will see that both are average of errors.
Let’s understand this with an example. Say, I want to predict the salary of a data scientist based on the number of years of experience. So, salary is my target variable (Y) and experience is the independent variable(X). I have some random data on X and Y and we will use Linear Regression to predict salary. Let’s use pandas and scikit-learn for data loading and creating linear model.
import pandas as pdfrom sklearn.linear_model import LinearRegressionsal_data={"Exp":[2,2.2, 2.8, 4, 7, 8, 11, 12, 21, 25], "Salary": [7, 8, 11, 15, 22, 29, 37 ,45.7, 49, 52]}#Load data into a pandas Dataframedf=pd.DataFrame(sal_data)df.head(3)
#Selecting X and y variablesX=df[['Experience']]y=df.Salary#Creating a Simple Linear Regression Model to predict salarieslm=LinearRegression()lm.fit(X,y)#Prediction of salaries by the modelyp=lm.predict(X)print(yp)[12.23965934 12.64846842 13.87489568 16.32775018 22.45988645 24.50393187 30.63606813 32.68011355 51.07652234 59.25270403]
Now, we have ‘yp’ — our array of salary prediction and we will evaluate our model by plotting predicted(yp) and actual salary(y). I am using bohek for my visualizations.
from bokeh.plotting import figure, show, output_filep=figure(title="Actual vs Predicted Salary", width=450, height=300)p.title.align = 'center'p.circle(df.Exp, df.Salary)p.line(df.Exp, df.Salary, legend_label='Actual Salary', line_width=3, line_alpha=0.4)p.circle(df.Exp, yp, color="red")p.line(df.Exp,yp, color="red",legend_label='Predicted Salary', line_width=3, line_alpha=0.4)p.xaxis.axis_label = 'Experience'p.yaxis.axis_label = 'Salary'show(p)
From the graph above, we see that there is a gap between predicted and actual data points. Statistically, this gap/difference is called residuals and commonly called error, and is used in RMSE and MAE. Scikit-learn provides metrics library to calculate these values. However, we will compute RMSE and MAE by using the above mathematical expressions. Both methods will give you the same result.
import numpy as npprint(f'Residuals: {y-yp}')np.sqrt(np.mean(np.square(y-yp))) #RMSEnp.mean(abs(y-yp)) #MAE#RMSE/MAE computation using sklearn libraryfrom sklearn.metrics import mean_squared_error, mean_absolute_errornp.sqrt(mean_squared_error(y, yp))mean_absolute_error(y, yp)6.485.68
This is our baseline model. MAE is around 5.7 — which seems to be higher. Now our goal is to improve this model by reducing this error.
Let’s run a polynomial transformation on “experience” (X) with the same model and see if our errors reduce.
from sklearn.preprocessing import PolynomialFeaturespf=PolynomialFeatures() #Linear Equation of degree 2X_poly=pf.fit_transform(X) lm.fit(X_poly, y)yp=lm.predict(X_poly)
I have used Scikit-learn PolynomialFeatures to create a matrix of 1, X, and X2 and passed that as input to my model.
Calculating our error metrics and ....
#RMSE and MAEnp.sqrt(np.mean(np.square(y-yp)))np.mean(abs(y-yp))2.39741.6386
Voilaaa... they are much lower this time. It fits better than our baseline model! Let’s plot y and yp (like how we did before) to check the overlap.
The gap between the 2 lines has reduced. Let’s observe the distribution of residuals or errors(y-yp) using seaborn’s residual plot function
print(y-yp) #residuals[ 0.333921 0.447306 0.84028668 -0.136044 -4.190238 -0.434767 -0.847751 5.488121 -2.584481 1.083648]import seaborn as snssns.residplot(y, yp) plt.show()
We see that residuals tend to concentrate around the x-axis, which makes sense because they are negligible.
There is a third metric — R-Squared score, usually used for regression models. This measures the amount of variation that can be explained by our model i.e. percentage of correct predictions returned by our model. It is also called the coefficient of determination and calculated by the formula:
Let’s compute R2 mathematically using the formula and using sklearn library and compare the values. Both methods should give you the same result.
#Calculating R-Squared manuallya=sum(np.square(y-yp)) # a -> sum of square of residualsb=sum(np.square(y-np.mean(y))) # b -> total sum of sqauresr2_value = 1-(a/b)0.979#calculating r2 using sklearnfrom sklearn.metrics import r2_scoreprint(r2_score(y, yp))0.979
Thus, overall we can interpret that 98% of the model predictions are correct and the variation in the errors is around 2 units. For an ideal model, RMSE/MAE=0 and R2 score = 1, and all the residual points lie on the X-axis. Achieving such a value for any business solution is almost impossible!
Some of the techniques we can use to improve our model accuracy include:
Transform/scale features
Treat outliers (if many)
Add new features/feature engineering
Use different algorithms
Model hyperparameter tuning
In my next article, I will be explaining some of the above concepts in detail. You can refer to my notebook here for the above code. | [
{
"code": null,
"e": 397,
"s": 172,
"text": "Root Mean Squared Error (RMSE)and Mean Absolute Error (MAE) are metrics used to evaluate a Regression Model. These metrics tell us how accurate our predictions are and, what is the amount of deviation from the actual values."
},
{
"code": null,
"e": 687,
"s": 397,
"text": "Technically, RMSE is the Root of the Mean of the Square of Errors and MAE is the Mean of Absolute value of Errors. Here, errors are the differences between the predicted values (values predicted by our regression model) and the actual values of a variable. They are calculated as follows :"
},
{
"code": null,
"e": 754,
"s": 687,
"text": "On close inspection, you will see that both are average of errors."
},
{
"code": null,
"e": 1141,
"s": 754,
"text": "Let’s understand this with an example. Say, I want to predict the salary of a data scientist based on the number of years of experience. So, salary is my target variable (Y) and experience is the independent variable(X). I have some random data on X and Y and we will use Linear Regression to predict salary. Let’s use pandas and scikit-learn for data loading and creating linear model."
},
{
"code": null,
"e": 1395,
"s": 1141,
"text": "import pandas as pdfrom sklearn.linear_model import LinearRegressionsal_data={\"Exp\":[2,2.2, 2.8, 4, 7, 8, 11, 12, 21, 25], \"Salary\": [7, 8, 11, 15, 22, 29, 37 ,45.7, 49, 52]}#Load data into a pandas Dataframedf=pd.DataFrame(sal_data)df.head(3)"
},
{
"code": null,
"e": 1731,
"s": 1395,
"text": "#Selecting X and y variablesX=df[['Experience']]y=df.Salary#Creating a Simple Linear Regression Model to predict salarieslm=LinearRegression()lm.fit(X,y)#Prediction of salaries by the modelyp=lm.predict(X)print(yp)[12.23965934 12.64846842 13.87489568 16.32775018 22.45988645 24.50393187 30.63606813 32.68011355 51.07652234 59.25270403]"
},
{
"code": null,
"e": 1901,
"s": 1731,
"text": "Now, we have ‘yp’ — our array of salary prediction and we will evaluate our model by plotting predicted(yp) and actual salary(y). I am using bohek for my visualizations."
},
{
"code": null,
"e": 2351,
"s": 1901,
"text": "from bokeh.plotting import figure, show, output_filep=figure(title=\"Actual vs Predicted Salary\", width=450, height=300)p.title.align = 'center'p.circle(df.Exp, df.Salary)p.line(df.Exp, df.Salary, legend_label='Actual Salary', line_width=3, line_alpha=0.4)p.circle(df.Exp, yp, color=\"red\")p.line(df.Exp,yp, color=\"red\",legend_label='Predicted Salary', line_width=3, line_alpha=0.4)p.xaxis.axis_label = 'Experience'p.yaxis.axis_label = 'Salary'show(p)"
},
{
"code": null,
"e": 2745,
"s": 2351,
"text": "From the graph above, we see that there is a gap between predicted and actual data points. Statistically, this gap/difference is called residuals and commonly called error, and is used in RMSE and MAE. Scikit-learn provides metrics library to calculate these values. However, we will compute RMSE and MAE by using the above mathematical expressions. Both methods will give you the same result."
},
{
"code": null,
"e": 3048,
"s": 2745,
"text": "import numpy as npprint(f'Residuals: {y-yp}')np.sqrt(np.mean(np.square(y-yp))) #RMSEnp.mean(abs(y-yp)) #MAE#RMSE/MAE computation using sklearn libraryfrom sklearn.metrics import mean_squared_error, mean_absolute_errornp.sqrt(mean_squared_error(y, yp))mean_absolute_error(y, yp)6.485.68"
},
{
"code": null,
"e": 3184,
"s": 3048,
"text": "This is our baseline model. MAE is around 5.7 — which seems to be higher. Now our goal is to improve this model by reducing this error."
},
{
"code": null,
"e": 3292,
"s": 3184,
"text": "Let’s run a polynomial transformation on “experience” (X) with the same model and see if our errors reduce."
},
{
"code": null,
"e": 3466,
"s": 3292,
"text": "from sklearn.preprocessing import PolynomialFeaturespf=PolynomialFeatures() #Linear Equation of degree 2X_poly=pf.fit_transform(X) lm.fit(X_poly, y)yp=lm.predict(X_poly)"
},
{
"code": null,
"e": 3583,
"s": 3466,
"text": "I have used Scikit-learn PolynomialFeatures to create a matrix of 1, X, and X2 and passed that as input to my model."
},
{
"code": null,
"e": 3622,
"s": 3583,
"text": "Calculating our error metrics and ...."
},
{
"code": null,
"e": 3699,
"s": 3622,
"text": "#RMSE and MAEnp.sqrt(np.mean(np.square(y-yp)))np.mean(abs(y-yp))2.39741.6386"
},
{
"code": null,
"e": 3848,
"s": 3699,
"text": "Voilaaa... they are much lower this time. It fits better than our baseline model! Let’s plot y and yp (like how we did before) to check the overlap."
},
{
"code": null,
"e": 3988,
"s": 3848,
"text": "The gap between the 2 lines has reduced. Let’s observe the distribution of residuals or errors(y-yp) using seaborn’s residual plot function"
},
{
"code": null,
"e": 4168,
"s": 3988,
"text": "print(y-yp) #residuals[ 0.333921 0.447306 0.84028668 -0.136044 -4.190238 -0.434767 -0.847751 5.488121 -2.584481 1.083648]import seaborn as snssns.residplot(y, yp) plt.show()"
},
{
"code": null,
"e": 4276,
"s": 4168,
"text": "We see that residuals tend to concentrate around the x-axis, which makes sense because they are negligible."
},
{
"code": null,
"e": 4572,
"s": 4276,
"text": "There is a third metric — R-Squared score, usually used for regression models. This measures the amount of variation that can be explained by our model i.e. percentage of correct predictions returned by our model. It is also called the coefficient of determination and calculated by the formula:"
},
{
"code": null,
"e": 4718,
"s": 4572,
"text": "Let’s compute R2 mathematically using the formula and using sklearn library and compare the values. Both methods should give you the same result."
},
{
"code": null,
"e": 4991,
"s": 4718,
"text": "#Calculating R-Squared manuallya=sum(np.square(y-yp)) # a -> sum of square of residualsb=sum(np.square(y-np.mean(y))) # b -> total sum of sqauresr2_value = 1-(a/b)0.979#calculating r2 using sklearnfrom sklearn.metrics import r2_scoreprint(r2_score(y, yp))0.979"
},
{
"code": null,
"e": 5286,
"s": 4991,
"text": "Thus, overall we can interpret that 98% of the model predictions are correct and the variation in the errors is around 2 units. For an ideal model, RMSE/MAE=0 and R2 score = 1, and all the residual points lie on the X-axis. Achieving such a value for any business solution is almost impossible!"
},
{
"code": null,
"e": 5359,
"s": 5286,
"text": "Some of the techniques we can use to improve our model accuracy include:"
},
{
"code": null,
"e": 5384,
"s": 5359,
"text": "Transform/scale features"
},
{
"code": null,
"e": 5409,
"s": 5384,
"text": "Treat outliers (if many)"
},
{
"code": null,
"e": 5446,
"s": 5409,
"text": "Add new features/feature engineering"
},
{
"code": null,
"e": 5471,
"s": 5446,
"text": "Use different algorithms"
},
{
"code": null,
"e": 5499,
"s": 5471,
"text": "Model hyperparameter tuning"
}
] |
How can I display MySQL query result vertically? | With the use of ego, \G option at end of a statement, we can get the result set in vertical format. Consider the following example −
mysql> Select * from Student where name = 'Aarav'\G
*************************** 1. row ***************************
Name: Aarav
RollNo: 150
Grade: M.SC
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1195,
"s": 1062,
"text": "With the use of ego, \\G option at end of a statement, we can get the result set in vertical format. Consider the following example −"
},
{
"code": null,
"e": 1373,
"s": 1195,
"text": "mysql> Select * from Student where name = 'Aarav'\\G\n*************************** 1. row ***************************\n Name: Aarav\nRollNo: 150\n Grade: M.SC\n1 row in set (0.00 sec)"
}
] |
Systematically Pricing Financial Options With Black Scholes | by Brunna Torino | Towards Data Science | There are two types of vanilla financial options that are traded in the financial markets: American — where you can exercise the option any time until the exercise date — and European — where you have to wait until the exercise date to exercise the option.
The names “American” and “European” don’t actually relate to where the option is traded, or what nationality the company is. The two types of options will only have a significant different in valuation if the stock pays dividends and the time to the exercise date includes the ex-dividend date — when buying a stock will not grant you a right to receive the dividend anymore.
Black-Scholes assumes an European option, but it can be used for American-style options that don’t pay dividends.
The Nobel-winning original Black-Scholes formula states that the price of a call option depends on the cumulative normal distribution, denoted here by N, of a function of the stock’s spot price S, the present value of a risk-free bond trading at a value K (which equals the strike price), the volatility of the stock’s annualised returns and the time from today to the exercise date divided by the number of days in a financial year, denoted here by T.
If you would like to know more about the derivation of the formula, here is a really good resource. In this article, I will focus more on the systematic application of the formula.
To calculate our potential payoffs from the option, we need the historical data of the stock’s price for one year (in this case, June 12th 2018 to June 12th 2019) and data on the price level that the options are currently being traded at so we can compare our results.
The historical data can be obtained from Yahoo Finance: go to Historical Data and download the dataset for one year.
First we need to calculate the volatility input to the Black Scholes model. Traditionally, we use the volatility of the annualised returns of the stock, as calculated below:
The last line will retrieve the table for the call options data with an exercise date of July 24th for the stock.
Below is the same Black Scholes formula described in the start of the article, but now represented by a Python function named black_scholes . Note that the present value formula of the risk-free bond is just the price of the bond K divided by (1 + risk free rate) to the power of the fraction of time T, and we are using the Python function cdf to calculate the cumulative distribution function value of our variables d1 and d2.
Having calculated the volatility (square root of financial market days times the standard deviation of the annualised returns), we can make estimates for all the strike prices we currently have available contracts for. In Tesla’s case, we have 35 different strike prices for call options.
For each strike price, we input the spot price of the stock (972.84 at the moment), loop through the strike prices in the data frame r, the risk-free rate which I am using the 10-year U.S. treasury yield currently at 0.69%.
We output the data frame df_estimate that we can use to calculate how close the Black Scholes model estimates were to the actual price that the options are being traded at in the market:
Has Black Scholes correctly predicted the market value of the options?
Our mean estimation error is 0.49%, with a standard deviation of 2.46 percentage points. Our median is even more promising at around 0.29%. Our standard deviation still seems a bit high, but looking closer at the dataset we can see that there are a few contracts that haven’t been traded at all today which skews the dataset since these prices aren’t as highly updated.
If we only included contracts that have been traded at least once today:
df1 = df_estimate[(df_estimate.Volume != '-')]
We can actually produce much better results for the estimation error:
Here we have a mean estimation error of -0.13% which means the options prices are on average underpricing the options by 0.13% compared to our estimates and our standard deviation is decreased to only 1.8 percentage points.
For curiosity, let’s analyse the few contracts where the black Scholes has made an error larger than 1%:
df1[df1['estimate_error'] > 1]
Most of the contracts have small volumes, being traded only once during the stock market day. Contract number 4 however, has an estimation error of 1.4% with a high volume of 21 contracts and 466 open interests. The strike price is at 850, which means it will make a profit if the stock price gets higher than 850 + 174.65 = $1021.65 whereas at the moment the stock is currently trading at 972.84. That’s only 5.325% climb up in about 31 stock market days which is not a difficult feat for Tesla.
Our estimate is a bit lower, but one reason for the difference could be due to the very large spread on these options, where market makers are exiting with a 6% risk-free profit. This indicates that risk is a lot higher at the moment regarding Tesla options for July 24th, which makes sense considering the low volume of these trades and the proximity of the exercise date.
An important feat of the Yahoo Finance options data is that it shows us the implied volatility of the options prices, which can be calculated by solving the Black Scholes equation backwards for the volatility starting with the option trading price. For this analysis, I didn’t use the implied volatility as an input because I wanted to compare how market players are pricing options vs. the Black Scholes model estimates.
The implied volatility is forward-looking, meaning it can give us a sense of how much future volatility traders are currently pricing in the option, if traders are rational. This last assumption is important when talking about implied volatility since other factors, such as behavioural economics (Tesla is the most shorted stock in the market due to this belief), an irrational risk-averseness during the current pandemic, and other external factors, can all play a role into the pricing of the option that doesn’t necessarily reflect the expected volatility of the stock. | [
{
"code": null,
"e": 429,
"s": 172,
"text": "There are two types of vanilla financial options that are traded in the financial markets: American — where you can exercise the option any time until the exercise date — and European — where you have to wait until the exercise date to exercise the option."
},
{
"code": null,
"e": 805,
"s": 429,
"text": "The names “American” and “European” don’t actually relate to where the option is traded, or what nationality the company is. The two types of options will only have a significant different in valuation if the stock pays dividends and the time to the exercise date includes the ex-dividend date — when buying a stock will not grant you a right to receive the dividend anymore."
},
{
"code": null,
"e": 919,
"s": 805,
"text": "Black-Scholes assumes an European option, but it can be used for American-style options that don’t pay dividends."
},
{
"code": null,
"e": 1372,
"s": 919,
"text": "The Nobel-winning original Black-Scholes formula states that the price of a call option depends on the cumulative normal distribution, denoted here by N, of a function of the stock’s spot price S, the present value of a risk-free bond trading at a value K (which equals the strike price), the volatility of the stock’s annualised returns and the time from today to the exercise date divided by the number of days in a financial year, denoted here by T."
},
{
"code": null,
"e": 1553,
"s": 1372,
"text": "If you would like to know more about the derivation of the formula, here is a really good resource. In this article, I will focus more on the systematic application of the formula."
},
{
"code": null,
"e": 1822,
"s": 1553,
"text": "To calculate our potential payoffs from the option, we need the historical data of the stock’s price for one year (in this case, June 12th 2018 to June 12th 2019) and data on the price level that the options are currently being traded at so we can compare our results."
},
{
"code": null,
"e": 1939,
"s": 1822,
"text": "The historical data can be obtained from Yahoo Finance: go to Historical Data and download the dataset for one year."
},
{
"code": null,
"e": 2113,
"s": 1939,
"text": "First we need to calculate the volatility input to the Black Scholes model. Traditionally, we use the volatility of the annualised returns of the stock, as calculated below:"
},
{
"code": null,
"e": 2227,
"s": 2113,
"text": "The last line will retrieve the table for the call options data with an exercise date of July 24th for the stock."
},
{
"code": null,
"e": 2656,
"s": 2227,
"text": "Below is the same Black Scholes formula described in the start of the article, but now represented by a Python function named black_scholes . Note that the present value formula of the risk-free bond is just the price of the bond K divided by (1 + risk free rate) to the power of the fraction of time T, and we are using the Python function cdf to calculate the cumulative distribution function value of our variables d1 and d2."
},
{
"code": null,
"e": 2945,
"s": 2656,
"text": "Having calculated the volatility (square root of financial market days times the standard deviation of the annualised returns), we can make estimates for all the strike prices we currently have available contracts for. In Tesla’s case, we have 35 different strike prices for call options."
},
{
"code": null,
"e": 3169,
"s": 2945,
"text": "For each strike price, we input the spot price of the stock (972.84 at the moment), loop through the strike prices in the data frame r, the risk-free rate which I am using the 10-year U.S. treasury yield currently at 0.69%."
},
{
"code": null,
"e": 3356,
"s": 3169,
"text": "We output the data frame df_estimate that we can use to calculate how close the Black Scholes model estimates were to the actual price that the options are being traded at in the market:"
},
{
"code": null,
"e": 3427,
"s": 3356,
"text": "Has Black Scholes correctly predicted the market value of the options?"
},
{
"code": null,
"e": 3797,
"s": 3427,
"text": "Our mean estimation error is 0.49%, with a standard deviation of 2.46 percentage points. Our median is even more promising at around 0.29%. Our standard deviation still seems a bit high, but looking closer at the dataset we can see that there are a few contracts that haven’t been traded at all today which skews the dataset since these prices aren’t as highly updated."
},
{
"code": null,
"e": 3870,
"s": 3797,
"text": "If we only included contracts that have been traded at least once today:"
},
{
"code": null,
"e": 3917,
"s": 3870,
"text": "df1 = df_estimate[(df_estimate.Volume != '-')]"
},
{
"code": null,
"e": 3987,
"s": 3917,
"text": "We can actually produce much better results for the estimation error:"
},
{
"code": null,
"e": 4211,
"s": 3987,
"text": "Here we have a mean estimation error of -0.13% which means the options prices are on average underpricing the options by 0.13% compared to our estimates and our standard deviation is decreased to only 1.8 percentage points."
},
{
"code": null,
"e": 4316,
"s": 4211,
"text": "For curiosity, let’s analyse the few contracts where the black Scholes has made an error larger than 1%:"
},
{
"code": null,
"e": 4347,
"s": 4316,
"text": "df1[df1['estimate_error'] > 1]"
},
{
"code": null,
"e": 4844,
"s": 4347,
"text": "Most of the contracts have small volumes, being traded only once during the stock market day. Contract number 4 however, has an estimation error of 1.4% with a high volume of 21 contracts and 466 open interests. The strike price is at 850, which means it will make a profit if the stock price gets higher than 850 + 174.65 = $1021.65 whereas at the moment the stock is currently trading at 972.84. That’s only 5.325% climb up in about 31 stock market days which is not a difficult feat for Tesla."
},
{
"code": null,
"e": 5218,
"s": 4844,
"text": "Our estimate is a bit lower, but one reason for the difference could be due to the very large spread on these options, where market makers are exiting with a 6% risk-free profit. This indicates that risk is a lot higher at the moment regarding Tesla options for July 24th, which makes sense considering the low volume of these trades and the proximity of the exercise date."
},
{
"code": null,
"e": 5640,
"s": 5218,
"text": "An important feat of the Yahoo Finance options data is that it shows us the implied volatility of the options prices, which can be calculated by solving the Black Scholes equation backwards for the volatility starting with the option trading price. For this analysis, I didn’t use the implied volatility as an input because I wanted to compare how market players are pricing options vs. the Black Scholes model estimates."
}
] |
C++ String Library - front | It returns a reference to the first character of the string.
Following is the declaration for std::string::front.
char& front();
const char& front() const;
none
It returns a reference to the first character of the string.
if an exception is thrown, there are no changes in the string.
In below example for std::string::front.
#include <iostream>
#include <string>
int main () {
std::string str ("Sairamkrishna Mammahe");
str.front() = 'A';
std::cout << str << '\n';
return 0;
}
Aairamkrishna Mammahe
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2664,
"s": 2603,
"text": "It returns a reference to the first character of the string."
},
{
"code": null,
"e": 2717,
"s": 2664,
"text": "Following is the declaration for std::string::front."
},
{
"code": null,
"e": 2732,
"s": 2717,
"text": "char& front();"
},
{
"code": null,
"e": 2759,
"s": 2732,
"text": "const char& front() const;"
},
{
"code": null,
"e": 2764,
"s": 2759,
"text": "none"
},
{
"code": null,
"e": 2825,
"s": 2764,
"text": "It returns a reference to the first character of the string."
},
{
"code": null,
"e": 2888,
"s": 2825,
"text": "if an exception is thrown, there are no changes in the string."
},
{
"code": null,
"e": 2929,
"s": 2888,
"text": "In below example for std::string::front."
},
{
"code": null,
"e": 3094,
"s": 2929,
"text": "#include <iostream>\n#include <string>\n\nint main () {\n std::string str (\"Sairamkrishna Mammahe\");\n str.front() = 'A';\n std::cout << str << '\\n';\n return 0;\n}"
},
{
"code": null,
"e": 3117,
"s": 3094,
"text": "Aairamkrishna Mammahe\n"
},
{
"code": null,
"e": 3124,
"s": 3117,
"text": " Print"
},
{
"code": null,
"e": 3135,
"s": 3124,
"text": " Add Notes"
}
] |
How can we map multiple date formats using Jackson in Java? | A Jackson is a Java-based library and it can be useful to convert Java objects to JSON and JSON to Java Object. We can map the multiple date formats in the Jackson library using @JsonFormat annotation, it is a general-purpose annotation used for configuring details of how values of properties are to be serialized. The @JsonFormat has three important fields: shape, pattern, and timezone. The shape field can define structure to use for serialization (JsonFormat.Shape.NUMBER and JsonFormat.Shape.STRING), the pattern field can be used in serialization and deserialization. For date, the pattern contains SimpleDateFormat compatible definition and finally, the timezone field can be used in serialization, default is system default timezone.
@Target(value={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER,TYPE})
@Retention(value=RUNTIME)
public @interface JsonFormat
import java.io.*;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDateformatTest {
final static ObjectMapper mapper = new ObjectMapper();
public static void main(String[] args) throws Exception {
JacksonDateformatTest jacksonDateformat = new JacksonDateformatTest();
jacksonDateformat.dateformat();
}
public void dateformat() throws Exception {
String json = "{\"createDate\":\"1980-12-08\"," + "\"createDateGmt\":\"1980-12-08 3:00 PM GMT+1:00\"}";
Reader reader = new StringReader(json);
Employee employee = mapper.readValue(reader, Employee.class);
System.out.println(employee);
}
}
// Employee class
class Employee implements Serializable {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "IST")
private Date createDate;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z", timezone = "IST")
private Date createDateGmt;
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getCreateDateGmt() {
return createDateGmt;
}
public void setCreateDateGmt(Date createDateGmt) {
this.createDateGmt = createDateGmt;
}
@Override
public String toString() {
return "Employee [\ncreateDate=" + createDate + ", \ncreateDateGmt=" + createDateGmt + "\n]";
}
}
Employee [
createDate=Mon Dec 08 00:00:00 IST 1980,
createDateGmt=Mon Dec 08 07:30:00 IST 1980
] | [
{
"code": null,
"e": 1805,
"s": 1062,
"text": "A Jackson is a Java-based library and it can be useful to convert Java objects to JSON and JSON to Java Object. We can map the multiple date formats in the Jackson library using @JsonFormat annotation, it is a general-purpose annotation used for configuring details of how values of properties are to be serialized. The @JsonFormat has three important fields: shape, pattern, and timezone. The shape field can define structure to use for serialization (JsonFormat.Shape.NUMBER and JsonFormat.Shape.STRING), the pattern field can be used in serialization and deserialization. For date, the pattern contains SimpleDateFormat compatible definition and finally, the timezone field can be used in serialization, default is system default timezone."
},
{
"code": null,
"e": 1922,
"s": 1805,
"text": "@Target(value={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER,TYPE})\n@Retention(value=RUNTIME)\npublic @interface JsonFormat\n"
},
{
"code": null,
"e": 3437,
"s": 1922,
"text": "import java.io.*;\nimport java.util.Date;\nimport com.fasterxml.jackson.annotation.JsonFormat;\nimport com.fasterxml.jackson.databind.ObjectMapper;\npublic class JacksonDateformatTest {\n final static ObjectMapper mapper = new ObjectMapper();\n public static void main(String[] args) throws Exception {\n JacksonDateformatTest jacksonDateformat = new JacksonDateformatTest();\n jacksonDateformat.dateformat();\n }\n public void dateformat() throws Exception {\n String json = \"{\\\"createDate\\\":\\\"1980-12-08\\\",\" + \"\\\"createDateGmt\\\":\\\"1980-12-08 3:00 PM GMT+1:00\\\"}\";\n Reader reader = new StringReader(json);\n Employee employee = mapper.readValue(reader, Employee.class);\n System.out.println(employee);\n }\n}\n// Employee class\nclass Employee implements Serializable {\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd\", timezone = \"IST\")\n private Date createDate;\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd HH:mm a z\", timezone = \"IST\")\n private Date createDateGmt;\n public Date getCreateDate() {\n return createDate;\n }\n public void setCreateDate(Date createDate) {\n this.createDate = createDate;\n }\n public Date getCreateDateGmt() {\n return createDateGmt;\n }\n public void setCreateDateGmt(Date createDateGmt) {\n this.createDateGmt = createDateGmt;\n }\n @Override\n public String toString() {\n return \"Employee [\\ncreateDate=\" + createDate + \", \\ncreateDateGmt=\" + createDateGmt + \"\\n]\";\n }\n}"
},
{
"code": null,
"e": 3536,
"s": 3437,
"text": "Employee [\n createDate=Mon Dec 08 00:00:00 IST 1980,\n createDateGmt=Mon Dec 08 07:30:00 IST 1980\n]"
}
] |
Java Guava | Booleans.countTrue() method with Examples - GeeksforGeeks | 30 Jan, 2019
The countTrue() method of Booleans Class in Guava Library is used to count the number of values that are true in the specified boolean values passed as the parameter.
Syntax:
public static int countTrue(boolean... values)
Parameters: This method accepts the boolean values among which the true values are to be count.
Return values: This method returns an integer value which is the count of values that are true.
Example-1 :
// Java code to show implementation of// Guava's Booleans.countTrue() method import com.google.common.primitives.Booleans;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating a Boolean array boolean[] arr = { false, true, false, true, true }; // Using Booleans.countTrue() method to // get the number of values that are true System.out.println(Booleans.countTrue(arr)); }}
3
Example 2 :
// Java code to show implementation of// Guava's Booleans.countTrue() method import com.google.common.primitives.Booleans;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating a Boolean array boolean[] arr = { false, false, false, false }; // Using Booleans.countTrue() method to // get the number of values that are true System.out.println(Booleans.countTrue(arr)); }}
0
Reference: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/primitives/Booleans.html#countTrue-boolean...-
Guava-Booleans
Java-Functions
java-guava
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
Overriding in Java
Multidimensional Arrays in Java
LinkedList in Java
ArrayList in Java
PriorityQueue in Java
How to iterate any Map in Java
Queue Interface In Java
Stack Class in Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 23811,
"s": 23783,
"text": "\n30 Jan, 2019"
},
{
"code": null,
"e": 23978,
"s": 23811,
"text": "The countTrue() method of Booleans Class in Guava Library is used to count the number of values that are true in the specified boolean values passed as the parameter."
},
{
"code": null,
"e": 23986,
"s": 23978,
"text": "Syntax:"
},
{
"code": null,
"e": 24034,
"s": 23986,
"text": "public static int countTrue(boolean... values)\n"
},
{
"code": null,
"e": 24130,
"s": 24034,
"text": "Parameters: This method accepts the boolean values among which the true values are to be count."
},
{
"code": null,
"e": 24226,
"s": 24130,
"text": "Return values: This method returns an integer value which is the count of values that are true."
},
{
"code": null,
"e": 24238,
"s": 24226,
"text": "Example-1 :"
},
{
"code": "// Java code to show implementation of// Guava's Booleans.countTrue() method import com.google.common.primitives.Booleans;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating a Boolean array boolean[] arr = { false, true, false, true, true }; // Using Booleans.countTrue() method to // get the number of values that are true System.out.println(Booleans.countTrue(arr)); }}",
"e": 24745,
"s": 24238,
"text": null
},
{
"code": null,
"e": 24748,
"s": 24745,
"text": "3\n"
},
{
"code": null,
"e": 24760,
"s": 24748,
"text": "Example 2 :"
},
{
"code": "// Java code to show implementation of// Guava's Booleans.countTrue() method import com.google.common.primitives.Booleans;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating a Boolean array boolean[] arr = { false, false, false, false }; // Using Booleans.countTrue() method to // get the number of values that are true System.out.println(Booleans.countTrue(arr)); }}",
"e": 25261,
"s": 24760,
"text": null
},
{
"code": null,
"e": 25264,
"s": 25261,
"text": "0\n"
},
{
"code": null,
"e": 25394,
"s": 25264,
"text": "Reference: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/primitives/Booleans.html#countTrue-boolean...-"
},
{
"code": null,
"e": 25409,
"s": 25394,
"text": "Guava-Booleans"
},
{
"code": null,
"e": 25424,
"s": 25409,
"text": "Java-Functions"
},
{
"code": null,
"e": 25435,
"s": 25424,
"text": "java-guava"
},
{
"code": null,
"e": 25440,
"s": 25435,
"text": "Java"
},
{
"code": null,
"e": 25445,
"s": 25440,
"text": "Java"
},
{
"code": null,
"e": 25543,
"s": 25445,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25552,
"s": 25543,
"text": "Comments"
},
{
"code": null,
"e": 25565,
"s": 25552,
"text": "Old Comments"
},
{
"code": null,
"e": 25597,
"s": 25565,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 25616,
"s": 25597,
"text": "Overriding in Java"
},
{
"code": null,
"e": 25648,
"s": 25616,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 25667,
"s": 25648,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 25685,
"s": 25667,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 25707,
"s": 25685,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 25738,
"s": 25707,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 25762,
"s": 25738,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 25782,
"s": 25762,
"text": "Stack Class in Java"
}
] |
Python Program For Inserting Node In The Middle Of The Linked List | 10 Jul, 2022
Given a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node.
Examples:
Input : list: 1->2->4->5
x = 3
Output : 1->2->3->4->5
Input : list: 5->10->4->32->16
x = 41
Output : 5->10->4->41->32->16
Method 1(Using length of the linked list): Find the number of nodes or length of the linked using one traversal. Let it be len. Calculate c = (len/2), if len is even, else c = (len+1)/2, if len is odd. Traverse again the first c nodes and insert the new node after the cth node.
Python3
# Python3 implementation to insert node# at the middle of a linked list # Node classclass Node: # constructor to create a new node def __init__(self, data): self.data = data self.next = None # function to insert node at the# middle of linked list given the headdef insertAtMid(head, x): if(head == None): #if the list is empty head = Node(x) else: # create a new node for the value # to be inserted newNode = Node(x) ptr = head length = 0 # calculate the length of the linked # list while(ptr != None): ptr = ptr.next length += 1 # 'count' the number of node after which # the new node has to be inserted if(length % 2 == 0): count = length / 2 else: (length + 1) / 2 ptr = head # move ptr to the node after which # the new node has to inserted while(count > 1): count -= 1 ptr = ptr.next # insert the 'newNode' and adjust # links accordingly newNode.next = ptr.next ptr.next = newNode # function to display the linked listdef display(head): temp = head while(temp != None): print(str(temp.data), end = " ") temp = temp.next # Driver Code # Creating the linked list 1.2.4.5head = Node(1)head.next = Node(2)head.next.next = Node(4)head.next.next.next = Node(5) print("Linked list before insertion: ", end = "")display(head) # inserting 3 in the middle of the linked list.x = 3insertAtMid(head, x) print("Linked list after insertion: " , end = "")display(head) # This code is contributed by Pranav Devarakonda
Output:
Linked list before insertion: 1 2 4 5
Linked list after insertion: 1 2 3 4 5
Time Complexity: O(n)
Method 2(Using two pointers): Based on the tortoise and hare algorithm which uses two pointers, one known as slow and the other known as fast. This algorithm helps in finding the middle node of the linked list. It is explained in the front and black split procedure of this post. Now, you can insert the new node after the middle node obtained from the above process. This approach requires only a single traversal of the list.
Python3
# Python implementation to insert node# at the middle of the linked list # Node Classclass Node : def __init__(self, d): self.data = d self.next = None class LinkedList: # function to insert node at the # middle of the linked list def __init__(self): self.head = None # Function to insert a new node # at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def insertAtMid(self, x): # if list is empty if (self.head == None): self.head = Node(x) else: # get a new node newNode = Node(x) # assign values to the slow # and fast pointers slow = self.head fast = self.head.next while (fast != None and fast.next != None): # move slow pointer to next node slow = slow.next # move fast pointer two nodes # at a time fast = fast.next.next # insert the 'newNode' and # adjust the required links newNode.next = slow.next slow.next = newNode # function to display the linked list def display(self): temp = self.head while (temp != None): print(temp.data, end = " "), temp = temp.next # Driver Code # Creating the list 1.2.4.5ll = LinkedList()ll.push(5)ll.push(4)ll.push(2)ll.push(1)print("Linked list before insertion: "),ll.display() x = 3ll.insertAtMid(x) print("Linked list after insertion: "),ll.display() # This code is contributed by prerna saini
Output:
Linked list before insertion: 1 2 4 5
Linked list after insertion: 1 2 3 4 5
Time Complexity: O(n)
Space complexity: O(n) where n is size of linked list
Please refer complete article on Insert node into the middle of the linked list for more details!
technophpfij
kumargaurav97520
Tortoise-Hare-Approach
Linked List
Python Programs
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jul, 2022"
},
{
"code": null,
"e": 257,
"s": 28,
"text": "Given a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node."
},
{
"code": null,
"e": 268,
"s": 257,
"text": "Examples: "
},
{
"code": null,
"e": 407,
"s": 268,
"text": "Input : list: 1->2->4->5\n x = 3\nOutput : 1->2->3->4->5\n\nInput : list: 5->10->4->32->16\n x = 41\nOutput : 5->10->4->41->32->16"
},
{
"code": null,
"e": 688,
"s": 407,
"text": "Method 1(Using length of the linked list): Find the number of nodes or length of the linked using one traversal. Let it be len. Calculate c = (len/2), if len is even, else c = (len+1)/2, if len is odd. Traverse again the first c nodes and insert the new node after the cth node. "
},
{
"code": null,
"e": 696,
"s": 688,
"text": "Python3"
},
{
"code": "# Python3 implementation to insert node# at the middle of a linked list # Node classclass Node: # constructor to create a new node def __init__(self, data): self.data = data self.next = None # function to insert node at the# middle of linked list given the headdef insertAtMid(head, x): if(head == None): #if the list is empty head = Node(x) else: # create a new node for the value # to be inserted newNode = Node(x) ptr = head length = 0 # calculate the length of the linked # list while(ptr != None): ptr = ptr.next length += 1 # 'count' the number of node after which # the new node has to be inserted if(length % 2 == 0): count = length / 2 else: (length + 1) / 2 ptr = head # move ptr to the node after which # the new node has to inserted while(count > 1): count -= 1 ptr = ptr.next # insert the 'newNode' and adjust # links accordingly newNode.next = ptr.next ptr.next = newNode # function to display the linked listdef display(head): temp = head while(temp != None): print(str(temp.data), end = \" \") temp = temp.next # Driver Code # Creating the linked list 1.2.4.5head = Node(1)head.next = Node(2)head.next.next = Node(4)head.next.next.next = Node(5) print(\"Linked list before insertion: \", end = \"\")display(head) # inserting 3 in the middle of the linked list.x = 3insertAtMid(head, x) print(\"Linked list after insertion: \" , end = \"\")display(head) # This code is contributed by Pranav Devarakonda",
"e": 2388,
"s": 696,
"text": null
},
{
"code": null,
"e": 2397,
"s": 2388,
"text": "Output: "
},
{
"code": null,
"e": 2474,
"s": 2397,
"text": "Linked list before insertion: 1 2 4 5\nLinked list after insertion: 1 2 3 4 5"
},
{
"code": null,
"e": 2496,
"s": 2474,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 2925,
"s": 2496,
"text": "Method 2(Using two pointers): Based on the tortoise and hare algorithm which uses two pointers, one known as slow and the other known as fast. This algorithm helps in finding the middle node of the linked list. It is explained in the front and black split procedure of this post. Now, you can insert the new node after the middle node obtained from the above process. This approach requires only a single traversal of the list. "
},
{
"code": null,
"e": 2933,
"s": 2925,
"text": "Python3"
},
{
"code": "# Python implementation to insert node# at the middle of the linked list # Node Classclass Node : def __init__(self, d): self.data = d self.next = None class LinkedList: # function to insert node at the # middle of the linked list def __init__(self): self.head = None # Function to insert a new node # at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def insertAtMid(self, x): # if list is empty if (self.head == None): self.head = Node(x) else: # get a new node newNode = Node(x) # assign values to the slow # and fast pointers slow = self.head fast = self.head.next while (fast != None and fast.next != None): # move slow pointer to next node slow = slow.next # move fast pointer two nodes # at a time fast = fast.next.next # insert the 'newNode' and # adjust the required links newNode.next = slow.next slow.next = newNode # function to display the linked list def display(self): temp = self.head while (temp != None): print(temp.data, end = \" \"), temp = temp.next # Driver Code # Creating the list 1.2.4.5ll = LinkedList()ll.push(5)ll.push(4)ll.push(2)ll.push(1)print(\"Linked list before insertion: \"),ll.display() x = 3ll.insertAtMid(x) print(\"Linked list after insertion: \"),ll.display() # This code is contributed by prerna saini",
"e": 4659,
"s": 2933,
"text": null
},
{
"code": null,
"e": 4668,
"s": 4659,
"text": "Output: "
},
{
"code": null,
"e": 4745,
"s": 4668,
"text": "Linked list before insertion: 1 2 4 5\nLinked list after insertion: 1 2 3 4 5"
},
{
"code": null,
"e": 4767,
"s": 4745,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 4821,
"s": 4767,
"text": "Space complexity: O(n) where n is size of linked list"
},
{
"code": null,
"e": 4919,
"s": 4821,
"text": "Please refer complete article on Insert node into the middle of the linked list for more details!"
},
{
"code": null,
"e": 4932,
"s": 4919,
"text": "technophpfij"
},
{
"code": null,
"e": 4949,
"s": 4932,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 4972,
"s": 4949,
"text": "Tortoise-Hare-Approach"
},
{
"code": null,
"e": 4984,
"s": 4972,
"text": "Linked List"
},
{
"code": null,
"e": 5000,
"s": 4984,
"text": "Python Programs"
},
{
"code": null,
"e": 5012,
"s": 5000,
"text": "Linked List"
}
] |
Corona Virus Live Updates for India – Using Python | 06 Oct, 2020
As we know the whole world is being affected by the COVID-19 pandemic and almost everyone is working from home. We all should utilize this duration at best, to improve our technical skills or writing some good Pythonic scripts. Let’s see a simple Python script to demonstrate the state-wise coronavirus cases in India. This Python script fetches the live data from the Ministry of Health Affairs Official Website. Then data is represented in the horizontal bar graph.To run this script follow the below installation –
$ pip install bs4
$ pip install tabulate
$ pip install matplotlib
$ pip install numpy
$ pip install requests
Let’s try to execute the script step-by-step. Step #1:
Python3
# importing libraries import requestsfrom bs4 import BeautifulSoupfrom tabulate import tabulateimport osimport numpy as npimport matplotlib.pyplot as plt
Step #2:
Python3
extract_contents = lambda row: [x.text.replace('\n', '') for x in row]URL = 'https://www.mohfw.gov.in/' SHORT_HEADERS = ['SNo', 'State','Indian-Confirmed(Including Foreign Confirmed)','Cured','Death'] response = requests.get(URL).contentsoup = BeautifulSoup(response, 'html.parser')header = extract_contents(soup.tr.find_all('th')) stats = []all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) if stat: if len(stat) == 4: # last row stat = ['', *stat] stats.append(stat) elif len(stat) == 5: stats.append(stat) stats[-1][0] = len(stats)stats[-1][1] = "Total Cases"
Step #3:
Python3
objects = []for row in stats : objects.append(row[1]) y_pos = np.arange(len(objects)) performance = []for row in stats[:len(stats)-1] : performance.append(int(row[2])) performance.append(int(stats[-1][2][:len(stats[-1][2])-1])) table = tabulate(stats, headers=SHORT_HEADERS)print(table)
Output:
Step #4:
Python3
plt.barh(y_pos, performance, align='center', alpha=0.5, color=(234/256.0, 128/256.0, 252/256.0), edgecolor=(106/256.0, 27/256.0, 154/256.0)) plt.yticks(y_pos, objects)plt.xlim(1,performance[-1]+1000)plt.xlabel('Number of Cases')plt.title('Corona Virus Cases')plt.show()
Output:
chiragarora3
kjangid897
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Oct, 2020"
},
{
"code": null,
"e": 574,
"s": 54,
"text": "As we know the whole world is being affected by the COVID-19 pandemic and almost everyone is working from home. We all should utilize this duration at best, to improve our technical skills or writing some good Pythonic scripts. Let’s see a simple Python script to demonstrate the state-wise coronavirus cases in India. This Python script fetches the live data from the Ministry of Health Affairs Official Website. Then data is represented in the horizontal bar graph.To run this script follow the below installation – "
},
{
"code": null,
"e": 685,
"s": 574,
"text": "$ pip install bs4\n$ pip install tabulate\n$ pip install matplotlib\n$ pip install numpy \n$ pip install requests\n"
},
{
"code": null,
"e": 744,
"s": 685,
"text": " Let’s try to execute the script step-by-step. Step #1: "
},
{
"code": null,
"e": 752,
"s": 744,
"text": "Python3"
},
{
"code": "# importing libraries import requestsfrom bs4 import BeautifulSoupfrom tabulate import tabulateimport osimport numpy as npimport matplotlib.pyplot as plt",
"e": 906,
"s": 752,
"text": null
},
{
"code": null,
"e": 918,
"s": 906,
"text": " Step #2: "
},
{
"code": null,
"e": 926,
"s": 918,
"text": "Python3"
},
{
"code": "extract_contents = lambda row: [x.text.replace('\\n', '') for x in row]URL = 'https://www.mohfw.gov.in/' SHORT_HEADERS = ['SNo', 'State','Indian-Confirmed(Including Foreign Confirmed)','Cured','Death'] response = requests.get(URL).contentsoup = BeautifulSoup(response, 'html.parser')header = extract_contents(soup.tr.find_all('th')) stats = []all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) if stat: if len(stat) == 4: # last row stat = ['', *stat] stats.append(stat) elif len(stat) == 5: stats.append(stat) stats[-1][0] = len(stats)stats[-1][1] = \"Total Cases\" ",
"e": 1608,
"s": 926,
"text": null
},
{
"code": null,
"e": 1620,
"s": 1608,
"text": " Step #3: "
},
{
"code": null,
"e": 1628,
"s": 1620,
"text": "Python3"
},
{
"code": "objects = []for row in stats : objects.append(row[1]) y_pos = np.arange(len(objects)) performance = []for row in stats[:len(stats)-1] : performance.append(int(row[2])) performance.append(int(stats[-1][2][:len(stats[-1][2])-1])) table = tabulate(stats, headers=SHORT_HEADERS)print(table)",
"e": 1924,
"s": 1628,
"text": null
},
{
"code": null,
"e": 1934,
"s": 1924,
"text": "Output: "
},
{
"code": null,
"e": 1945,
"s": 1934,
"text": "Step #4: "
},
{
"code": null,
"e": 1953,
"s": 1945,
"text": "Python3"
},
{
"code": "plt.barh(y_pos, performance, align='center', alpha=0.5, color=(234/256.0, 128/256.0, 252/256.0), edgecolor=(106/256.0, 27/256.0, 154/256.0)) plt.yticks(y_pos, objects)plt.xlim(1,performance[-1]+1000)plt.xlabel('Number of Cases')plt.title('Corona Virus Cases')plt.show()",
"e": 2257,
"s": 1953,
"text": null
},
{
"code": null,
"e": 2267,
"s": 2257,
"text": "Output: "
},
{
"code": null,
"e": 2282,
"s": 2269,
"text": "chiragarora3"
},
{
"code": null,
"e": 2293,
"s": 2282,
"text": "kjangid897"
},
{
"code": null,
"e": 2309,
"s": 2293,
"text": "Python-projects"
},
{
"code": null,
"e": 2324,
"s": 2309,
"text": "python-utility"
},
{
"code": null,
"e": 2331,
"s": 2324,
"text": "Python"
}
] |
Find the altitude and area of an isosceles triangle | 22 Jun, 2022
Given the side (a) of the isosceles triangle. The task is to find the area (A) and the altitude (h). An isosceles triangle is a triangle with 2 sides of equal length and 2 equal internal angles adjacent to each equal sides.
In this figure, a- Measure of the equal sides of an isosceles triangle. b- Base of the isosceles triangle. h- Altitude of the isosceles triangle.
Examples:
Input: a = 2, b = 3
Output: altitude = 1.32, area = 1.98
Input: a = 5, b = 6
Output: altitude = 4, area = 12
Formulas: Following are the formulas of the altitude and the area of an isosceles triangle.
[Tex]Area (A)= \frac{1}{2} \times b \times h [/Tex]
Below is the implementation using the above formulas:
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to find the Altitude// Area of an isosceles triangle#include <bits/stdc++.h>using namespace std; // function to find the altitudefloat altitude(float a, float b){ // return altitude return sqrt(pow(a, 2) - (pow(b, 2) / 4));} // function to find the areafloat area(float b, float h){ // return area return (1 * b * h) / 2;} // Driver codeint main(){ float a = 2, b = 3; float h = altitude(a, b); cout << setprecision(3); cout << "Altitude= " << h << ", "; cout << "Area= " << area(b, h); return 0;}
// Java program to find the Altitude// Area of an isosceles triangle import java.io.*; class GFG { // function to find the altitude static float altitude(float a, float b) { // return altitude return (float)(Math.sqrt(Math.pow(a, 2) - (Math.pow(b, 2) / 4))); } // function to find the area static float area(float b, float h) { // return area return (1 * b * h) / 2; } // Driver Code public static void main(String[] args) { float a = 2, b = 3; float h = altitude(a, b); System.out.print("Altitude= " + h + ", "); System.out.print("Area= " + area(b, h)); }}// This code is contributed by inder_verma.
# Python 3 program to find# the Altitude Area of an# isosceles triangleimport math # function to find the altitude def altitude(a, b): # return altitude return math.sqrt(pow(a, 2) - (pow(b, 2) / 4)) # function to find the area def area(b, h): # return area return (1 * b * h) / 2 # Driver Codeif __name__ == "__main__": a = 2 b = 3 h = altitude(a, b) print("Altitude = " + str(round(h, 3)), end=", ") print("Area = " + str(round(area(b, h), 3))) # This code is contributed# by ChitraNayal
// C# program to find the Altitude// Area of an isosceles triangleusing System; class GFG { // function to find the altitude static float altitude(float a, float b) { // return altitude return (float)(Math.Sqrt(Math.Pow(a, 2) - (Math.Pow(b, 2) / 4))); } // function to find the area static float area(float b, float h) { // return area return (1 * b * h) / 2; } // Driver Code public static void Main() { float a = 2, b = 3; float h = altitude(a, b); Console.WriteLine("Altitude = " + h + ", "); Console.WriteLine("Area = " + area(b, h)); }} // This code is contributed// by inder_verma
<?php// PHP program to find the Altitude// Area of an isosceles triangle // function to find the altitudefunction altitude($a, $b){ // return altitude return sqrt(pow($a, 2) - (pow($b, 2) / 4));} // function to find the areafunction area($b, $h){ // return area return (1 * $b * $h) / 2;} // Driver Code$a = 2; $b = 3;$h = altitude($a, $b); echo "Altitude = " , $h , ", "; echo "Area = " , area($b, $h); // This code is contributed// by anuj_67?>
<script> // Javascript program to find the Altitude// Area of an isosceles triangle // function to find the altitudefunction altitude(a,b){ // return altitude return Math.sqrt(Math.pow(a, 2) - (Math.pow(b, 2) / 4));} // function to find the areafunction area( b, h){ // return area return (1 * b * h) / 2;} // Driver codelet a = 2, b = 3; let h = altitude(a, b); document.write("Altitude= " + h.toFixed(2) + ", "); document.write( "Area= " + area(b, h).toFixed(2)); // This code contributed by aashish1995 </script>
Altitude= 1.32, Area= 1.98
Time Complexity: O(logn)Auxiliary Space: O(1)
inderDuMCA
vt_m
ukasp
ujjwalgoel1103
aashish1995
surinderdawra388
hasani
area-volume-programs
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 253,
"s": 28,
"text": "Given the side (a) of the isosceles triangle. The task is to find the area (A) and the altitude (h). An isosceles triangle is a triangle with 2 sides of equal length and 2 equal internal angles adjacent to each equal sides. "
},
{
"code": null,
"e": 399,
"s": 253,
"text": "In this figure, a- Measure of the equal sides of an isosceles triangle. b- Base of the isosceles triangle. h- Altitude of the isosceles triangle."
},
{
"code": null,
"e": 410,
"s": 399,
"text": "Examples: "
},
{
"code": null,
"e": 520,
"s": 410,
"text": "Input: a = 2, b = 3\nOutput: altitude = 1.32, area = 1.98\n\nInput: a = 5, b = 6\nOutput: altitude = 4, area = 12"
},
{
"code": null,
"e": 614,
"s": 520,
"text": "Formulas: Following are the formulas of the altitude and the area of an isosceles triangle. "
},
{
"code": null,
"e": 673,
"s": 614,
"text": "[Tex]Area (A)= \\frac{1}{2} \\times b \\times h [/Tex] "
},
{
"code": null,
"e": 728,
"s": 673,
"text": "Below is the implementation using the above formulas: "
},
{
"code": null,
"e": 732,
"s": 728,
"text": "C++"
},
{
"code": null,
"e": 737,
"s": 732,
"text": "Java"
},
{
"code": null,
"e": 746,
"s": 737,
"text": "Python 3"
},
{
"code": null,
"e": 749,
"s": 746,
"text": "C#"
},
{
"code": null,
"e": 753,
"s": 749,
"text": "PHP"
},
{
"code": null,
"e": 764,
"s": 753,
"text": "Javascript"
},
{
"code": "// CPP program to find the Altitude// Area of an isosceles triangle#include <bits/stdc++.h>using namespace std; // function to find the altitudefloat altitude(float a, float b){ // return altitude return sqrt(pow(a, 2) - (pow(b, 2) / 4));} // function to find the areafloat area(float b, float h){ // return area return (1 * b * h) / 2;} // Driver codeint main(){ float a = 2, b = 3; float h = altitude(a, b); cout << setprecision(3); cout << \"Altitude= \" << h << \", \"; cout << \"Area= \" << area(b, h); return 0;}",
"e": 1310,
"s": 764,
"text": null
},
{
"code": "// Java program to find the Altitude// Area of an isosceles triangle import java.io.*; class GFG { // function to find the altitude static float altitude(float a, float b) { // return altitude return (float)(Math.sqrt(Math.pow(a, 2) - (Math.pow(b, 2) / 4))); } // function to find the area static float area(float b, float h) { // return area return (1 * b * h) / 2; } // Driver Code public static void main(String[] args) { float a = 2, b = 3; float h = altitude(a, b); System.out.print(\"Altitude= \" + h + \", \"); System.out.print(\"Area= \" + area(b, h)); }}// This code is contributed by inder_verma.",
"e": 2042,
"s": 1310,
"text": null
},
{
"code": "# Python 3 program to find# the Altitude Area of an# isosceles triangleimport math # function to find the altitude def altitude(a, b): # return altitude return math.sqrt(pow(a, 2) - (pow(b, 2) / 4)) # function to find the area def area(b, h): # return area return (1 * b * h) / 2 # Driver Codeif __name__ == \"__main__\": a = 2 b = 3 h = altitude(a, b) print(\"Altitude = \" + str(round(h, 3)), end=\", \") print(\"Area = \" + str(round(area(b, h), 3))) # This code is contributed# by ChitraNayal",
"e": 2603,
"s": 2042,
"text": null
},
{
"code": "// C# program to find the Altitude// Area of an isosceles triangleusing System; class GFG { // function to find the altitude static float altitude(float a, float b) { // return altitude return (float)(Math.Sqrt(Math.Pow(a, 2) - (Math.Pow(b, 2) / 4))); } // function to find the area static float area(float b, float h) { // return area return (1 * b * h) / 2; } // Driver Code public static void Main() { float a = 2, b = 3; float h = altitude(a, b); Console.WriteLine(\"Altitude = \" + h + \", \"); Console.WriteLine(\"Area = \" + area(b, h)); }} // This code is contributed// by inder_verma",
"e": 3319,
"s": 2603,
"text": null
},
{
"code": "<?php// PHP program to find the Altitude// Area of an isosceles triangle // function to find the altitudefunction altitude($a, $b){ // return altitude return sqrt(pow($a, 2) - (pow($b, 2) / 4));} // function to find the areafunction area($b, $h){ // return area return (1 * $b * $h) / 2;} // Driver Code$a = 2; $b = 3;$h = altitude($a, $b); echo \"Altitude = \" , $h , \", \"; echo \"Area = \" , area($b, $h); // This code is contributed// by anuj_67?>",
"e": 3793,
"s": 3319,
"text": null
},
{
"code": "<script> // Javascript program to find the Altitude// Area of an isosceles triangle // function to find the altitudefunction altitude(a,b){ // return altitude return Math.sqrt(Math.pow(a, 2) - (Math.pow(b, 2) / 4));} // function to find the areafunction area( b, h){ // return area return (1 * b * h) / 2;} // Driver codelet a = 2, b = 3; let h = altitude(a, b); document.write(\"Altitude= \" + h.toFixed(2) + \", \"); document.write( \"Area= \" + area(b, h).toFixed(2)); // This code contributed by aashish1995 </script>",
"e": 4332,
"s": 3793,
"text": null
},
{
"code": null,
"e": 4359,
"s": 4332,
"text": "Altitude= 1.32, Area= 1.98"
},
{
"code": null,
"e": 4407,
"s": 4359,
"text": " Time Complexity: O(logn)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 4418,
"s": 4407,
"text": "inderDuMCA"
},
{
"code": null,
"e": 4423,
"s": 4418,
"text": "vt_m"
},
{
"code": null,
"e": 4429,
"s": 4423,
"text": "ukasp"
},
{
"code": null,
"e": 4444,
"s": 4429,
"text": "ujjwalgoel1103"
},
{
"code": null,
"e": 4456,
"s": 4444,
"text": "aashish1995"
},
{
"code": null,
"e": 4473,
"s": 4456,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4480,
"s": 4473,
"text": "hasani"
},
{
"code": null,
"e": 4501,
"s": 4480,
"text": "area-volume-programs"
},
{
"code": null,
"e": 4511,
"s": 4501,
"text": "Geometric"
},
{
"code": null,
"e": 4524,
"s": 4511,
"text": "Mathematical"
},
{
"code": null,
"e": 4537,
"s": 4524,
"text": "Mathematical"
},
{
"code": null,
"e": 4547,
"s": 4537,
"text": "Geometric"
}
] |
Subsets and Splits