title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
C | Dynamic Memory Allocation | Question 8 - GeeksforGeeks | 08 Aug, 2018
Consider the following program, where are i, j and k are stored in memory?
int i;int main(){ int j; int *k = (int *) malloc (sizeof(int));}
(A) i, j and *k are stored in stack segment(B) i and j are stored in stack segment. *k is stored on heap.(C) i is stored in BSS part of data segment, j is stored in stack segment. *k is stored on heap.(D) j is stored in BSS part of data segment, i is stored in stack segment. *k is stored on heap.Answer: (C)Explanation: i is global variable and it is uninitialized so it is stored on BSS part of Data Segment (http://en.wikipedia.org/wiki/.bss)
j is local in main() so it is stored in stack frame (http://en.wikipedia.org/wiki/Call_stack)
*k is dynamically allocated so it is stored on Heap Segment.
See following article for more details.
Memory Layout of C ProgramsQuiz of this Question
C-Dynamic Memory Allocation
Dynamic Memory Allocation
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
Output of C programs | Set 64 (Pointers)
C | Structure & Union | Question 10
C | File Handling | Question 1 | [
{
"code": null,
"e": 24564,
"s": 24536,
"text": "\n08 Aug, 2018"
},
{
"code": null,
"e": 24639,
"s": 24564,
"text": "Consider the following program, where are i, j and k are stored in memory?"
},
{
"code": "int i;int main(){ int j; int *k = (int *) malloc (sizeof(int));}",
"e": 24710,
"s": 24639,
"text": null
},
{
"code": null,
"e": 25156,
"s": 24710,
"text": "(A) i, j and *k are stored in stack segment(B) i and j are stored in stack segment. *k is stored on heap.(C) i is stored in BSS part of data segment, j is stored in stack segment. *k is stored on heap.(D) j is stored in BSS part of data segment, i is stored in stack segment. *k is stored on heap.Answer: (C)Explanation: i is global variable and it is uninitialized so it is stored on BSS part of Data Segment (http://en.wikipedia.org/wiki/.bss)"
},
{
"code": null,
"e": 25250,
"s": 25156,
"text": "j is local in main() so it is stored in stack frame (http://en.wikipedia.org/wiki/Call_stack)"
},
{
"code": null,
"e": 25311,
"s": 25250,
"text": "*k is dynamically allocated so it is stored on Heap Segment."
},
{
"code": null,
"e": 25351,
"s": 25311,
"text": "See following article for more details."
},
{
"code": null,
"e": 25400,
"s": 25351,
"text": "Memory Layout of C ProgramsQuiz of this Question"
},
{
"code": null,
"e": 25428,
"s": 25400,
"text": "C-Dynamic Memory Allocation"
},
{
"code": null,
"e": 25454,
"s": 25428,
"text": "Dynamic Memory Allocation"
},
{
"code": null,
"e": 25465,
"s": 25454,
"text": "C Language"
},
{
"code": null,
"e": 25472,
"s": 25465,
"text": "C Quiz"
},
{
"code": null,
"e": 25570,
"s": 25472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25598,
"s": 25570,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 25638,
"s": 25598,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 25684,
"s": 25638,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 25696,
"s": 25684,
"text": "fork() in C"
},
{
"code": null,
"e": 25728,
"s": 25696,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 25770,
"s": 25728,
"text": "Compiling a C program:- Behind the Scenes"
},
{
"code": null,
"e": 25813,
"s": 25770,
"text": "Operator Precedence and Associativity in C"
},
{
"code": null,
"e": 25854,
"s": 25813,
"text": "Output of C programs | Set 64 (Pointers)"
},
{
"code": null,
"e": 25890,
"s": 25854,
"text": "C | Structure & Union | Question 10"
}
] |
Can we use “LIKE concat()” in a MySQL query? | Yes, we can do that. Let us first create a table −
mysql> create table DemoTable
(
Name varchar(50)
);
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('Mike');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+
| Name |
+------+
| John |
| Adam |
| Bob |
| Mike |
+------+
4 rows in set (0.00 sec)
Following is the query to use “LIKE concat()” in MySQL −
mysql> select Name from DemoTable where Name LIKE concat('%','o','%');
This will produce the following output −
+------+
| Name |
+------+
| John |
| Bob |
+------+
2 rows in set (0.03 sec) | [
{
"code": null,
"e": 1113,
"s": 1062,
"text": "Yes, we can do that. Let us first create a table −"
},
{
"code": null,
"e": 1205,
"s": 1113,
"text": "mysql> create table DemoTable\n(\n Name varchar(50)\n);\nQuery OK, 0 rows affected (0.63 sec)"
},
{
"code": null,
"e": 1261,
"s": 1205,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1584,
"s": 1261,
"text": "mysql> insert into DemoTable values('John');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('Adam');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable values('Bob');\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable values('Mike');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1644,
"s": 1584,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1675,
"s": 1644,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1716,
"s": 1675,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1813,
"s": 1716,
"text": "+------+\n| Name |\n+------+\n| John |\n| Adam |\n| Bob |\n| Mike |\n+------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1870,
"s": 1813,
"text": "Following is the query to use “LIKE concat()” in MySQL −"
},
{
"code": null,
"e": 1941,
"s": 1870,
"text": "mysql> select Name from DemoTable where Name LIKE concat('%','o','%');"
},
{
"code": null,
"e": 1982,
"s": 1941,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2061,
"s": 1982,
"text": "+------+\n| Name |\n+------+\n| John |\n| Bob |\n+------+\n2 rows in set (0.03 sec)"
}
] |
How to move an element of an array to a specific position (swap)? | To move an element from one position to other (swap) you need to –
Create a temp variable and assign the value of the original position to it.
Now, assign the value in the new position to original position.
Finally, assign the value in the temp to the new position.
Live Demo
import java.util.Arrays;
public class ChangingPositions {
public static void main(String args[]) {
int originalPosition = 1;
int newPosition = 1;
int [] myArray = {23, 93, 56, 92, 39};
int temp = myArray[originalPosition];
myArray[originalPosition] = myArray[newPosition];
myArray[newPosition] = temp;
System.out.println(Arrays.toString(myArray));
}
}
[23, 39, 56, 92, 93] | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "To move an element from one position to other (swap) you need to –"
},
{
"code": null,
"e": 1205,
"s": 1129,
"text": "Create a temp variable and assign the value of the original position to it."
},
{
"code": null,
"e": 1269,
"s": 1205,
"text": "Now, assign the value in the new position to original position."
},
{
"code": null,
"e": 1328,
"s": 1269,
"text": "Finally, assign the value in the temp to the new position."
},
{
"code": null,
"e": 1338,
"s": 1328,
"text": "Live Demo"
},
{
"code": null,
"e": 1744,
"s": 1338,
"text": "import java.util.Arrays;\npublic class ChangingPositions {\n public static void main(String args[]) {\n int originalPosition = 1;\n int newPosition = 1;\n int [] myArray = {23, 93, 56, 92, 39};\n int temp = myArray[originalPosition];\n \n myArray[originalPosition] = myArray[newPosition];\n myArray[newPosition] = temp;\n System.out.println(Arrays.toString(myArray));\n }\n}"
},
{
"code": null,
"e": 1765,
"s": 1744,
"text": "[23, 39, 56, 92, 93]"
}
] |
Plot Multiple Graphics in the Same Figure Using Python | by Gustavo Santos | Towards Data Science | If you work with Jupyter Notebooks, you know that the right side of it becomes really low populated when it comes to graphics. That happens because you usually create one graphic by cell and it does not take more than half of your screen.
However, sometimes it is necessary to plot two graphics side-by-side, not only for the sake of better space utilization, but mainly because we, as Data Scientists, frequently need to compare plots.
Let’s say you’re analyzing the distribution of trips of a Taxi company and you want to know what’s the difference in terms of distance between trips with the pickup happening in Manhattan versus Brooklyn.
Let’s load the dataset. I will use one of the sample datasets from seaborn package called Taxis. You can load it after importing seaborn.
import seaborn as sns# Load datasetdf = sns.load_dataset('taxis')
Then let’s isolate the travels initiating in Manhattan and Brooklyn.
# Brooklyn travelsdf_bklyn = df.query(' pickup_borough == "Brooklyn" ')# Manhattan Travelsdf_mhtn = df.query(' pickup_borough == "Manhattan" ')
Now it’s the time to see how the magic happens. First of all, we’re creating a figure and indicating what’s the quantity of lines and columns we want (in the example below it’s 2 plots on the same row).
Then we should just create our plots and indicate where those will go in the grid using slice notation. If you have only one row, then just one pair of square brackets is needed ( my_grid[0]). When you have multiple rows and columns, use two pairs of square brackets ( my_grid[0][0] means plot on first row , first column).
# Creating a grid figure with matplotlibfig, my_grid = plt.subplots(nrows=1, ncols=2, figsize=(18,8))# Histograms# Plot 1g1 = sns.histplot(data=df_bklyn, x='distance', ax=my_grid[0])# Title of the Plot 1g1.set_title('Histogram of the travels beginning in Brooklyn')# Plot 2g2 = sns.histplot(data=df_mhtn, x='distance', ax=my_grid[1])# Title of the Plot 2g2.set_title('Histogram of the travels beginning in Manhattan');
The multiple plots with matplotlib is pretty similar, but let’s see the little difference when coding it.
You will notice that when we create the grid, we must use tuples and lists. If we have just a single row, you can use just one tuple.
# Creating a grid figure with matplotlib SINGLE ROW EXAMPLEfig, (g1, g2, g3) = plt.subplots(nrows=1, ncols=3, figsize=(18,8))
But in case you have multiple rows, use a list of tuples, being one for each row.
# Creating a grid figure with matplotlib MULTIPLE ROWS EXAMPLEfig, [(g1, g2, g3), (g4, g5, g6)] = plt.subplots(nrows=2, ncols=3, figsize=(18,8))
Let’s see a practical example of the histograms of the distances for 4 different neighborhoods from NYC. Notice that here we do not use the ax parameter anymore.
# Creating a grid figure with matplotlibfig, [(g1, g2), (g3, g4)] = plt.subplots(nrows=2, ncols=2, figsize=(18,8))# Histograms# Plot 1g1.hist(data=df_bklyn, x='distance')# Title of the Plot 1g1.set_title('Histogram of the travels beginning in Brooklyn')# Plot 2g2.hist(data=df_mhtn, x='distance')# Title of the Plot 2g2.set_title('Histogram of the travels beginning in Manhattan')# Plot 3g3.hist(data=df_queens, x='distance')# Title of the Plot 3g3.set_title('Histogram of the travels beginning in Queens')# Plot 4g4.hist(data=df_bronx, x='distance')# Title of the Plot 4g4.set_title('Histogram of the travels beginning in Bronx');
Quick post and yet very useful. I remember having this noted in a notebook and frequently had to come back to refresh my mind how to do that.
That said, I hope this post plays the same role, helping beginners to plot multiple graphics in the same figure with ease.
Remember to follow me for more.
gustavorsantos.medium.com
If you’d like to subscribe to Medium, here’s my referral link. | [
{
"code": null,
"e": 405,
"s": 166,
"text": "If you work with Jupyter Notebooks, you know that the right side of it becomes really low populated when it comes to graphics. That happens because you usually create one graphic by cell and it does not take more than half of your screen."
},
{
"code": null,
"e": 603,
"s": 405,
"text": "However, sometimes it is necessary to plot two graphics side-by-side, not only for the sake of better space utilization, but mainly because we, as Data Scientists, frequently need to compare plots."
},
{
"code": null,
"e": 808,
"s": 603,
"text": "Let’s say you’re analyzing the distribution of trips of a Taxi company and you want to know what’s the difference in terms of distance between trips with the pickup happening in Manhattan versus Brooklyn."
},
{
"code": null,
"e": 946,
"s": 808,
"text": "Let’s load the dataset. I will use one of the sample datasets from seaborn package called Taxis. You can load it after importing seaborn."
},
{
"code": null,
"e": 1012,
"s": 946,
"text": "import seaborn as sns# Load datasetdf = sns.load_dataset('taxis')"
},
{
"code": null,
"e": 1081,
"s": 1012,
"text": "Then let’s isolate the travels initiating in Manhattan and Brooklyn."
},
{
"code": null,
"e": 1225,
"s": 1081,
"text": "# Brooklyn travelsdf_bklyn = df.query(' pickup_borough == \"Brooklyn\" ')# Manhattan Travelsdf_mhtn = df.query(' pickup_borough == \"Manhattan\" ')"
},
{
"code": null,
"e": 1428,
"s": 1225,
"text": "Now it’s the time to see how the magic happens. First of all, we’re creating a figure and indicating what’s the quantity of lines and columns we want (in the example below it’s 2 plots on the same row)."
},
{
"code": null,
"e": 1752,
"s": 1428,
"text": "Then we should just create our plots and indicate where those will go in the grid using slice notation. If you have only one row, then just one pair of square brackets is needed ( my_grid[0]). When you have multiple rows and columns, use two pairs of square brackets ( my_grid[0][0] means plot on first row , first column)."
},
{
"code": null,
"e": 2171,
"s": 1752,
"text": "# Creating a grid figure with matplotlibfig, my_grid = plt.subplots(nrows=1, ncols=2, figsize=(18,8))# Histograms# Plot 1g1 = sns.histplot(data=df_bklyn, x='distance', ax=my_grid[0])# Title of the Plot 1g1.set_title('Histogram of the travels beginning in Brooklyn')# Plot 2g2 = sns.histplot(data=df_mhtn, x='distance', ax=my_grid[1])# Title of the Plot 2g2.set_title('Histogram of the travels beginning in Manhattan');"
},
{
"code": null,
"e": 2277,
"s": 2171,
"text": "The multiple plots with matplotlib is pretty similar, but let’s see the little difference when coding it."
},
{
"code": null,
"e": 2411,
"s": 2277,
"text": "You will notice that when we create the grid, we must use tuples and lists. If we have just a single row, you can use just one tuple."
},
{
"code": null,
"e": 2537,
"s": 2411,
"text": "# Creating a grid figure with matplotlib SINGLE ROW EXAMPLEfig, (g1, g2, g3) = plt.subplots(nrows=1, ncols=3, figsize=(18,8))"
},
{
"code": null,
"e": 2619,
"s": 2537,
"text": "But in case you have multiple rows, use a list of tuples, being one for each row."
},
{
"code": null,
"e": 2764,
"s": 2619,
"text": "# Creating a grid figure with matplotlib MULTIPLE ROWS EXAMPLEfig, [(g1, g2, g3), (g4, g5, g6)] = plt.subplots(nrows=2, ncols=3, figsize=(18,8))"
},
{
"code": null,
"e": 2926,
"s": 2764,
"text": "Let’s see a practical example of the histograms of the distances for 4 different neighborhoods from NYC. Notice that here we do not use the ax parameter anymore."
},
{
"code": null,
"e": 3558,
"s": 2926,
"text": "# Creating a grid figure with matplotlibfig, [(g1, g2), (g3, g4)] = plt.subplots(nrows=2, ncols=2, figsize=(18,8))# Histograms# Plot 1g1.hist(data=df_bklyn, x='distance')# Title of the Plot 1g1.set_title('Histogram of the travels beginning in Brooklyn')# Plot 2g2.hist(data=df_mhtn, x='distance')# Title of the Plot 2g2.set_title('Histogram of the travels beginning in Manhattan')# Plot 3g3.hist(data=df_queens, x='distance')# Title of the Plot 3g3.set_title('Histogram of the travels beginning in Queens')# Plot 4g4.hist(data=df_bronx, x='distance')# Title of the Plot 4g4.set_title('Histogram of the travels beginning in Bronx');"
},
{
"code": null,
"e": 3700,
"s": 3558,
"text": "Quick post and yet very useful. I remember having this noted in a notebook and frequently had to come back to refresh my mind how to do that."
},
{
"code": null,
"e": 3823,
"s": 3700,
"text": "That said, I hope this post plays the same role, helping beginners to plot multiple graphics in the same figure with ease."
},
{
"code": null,
"e": 3855,
"s": 3823,
"text": "Remember to follow me for more."
},
{
"code": null,
"e": 3881,
"s": 3855,
"text": "gustavorsantos.medium.com"
}
] |
Apache Cassandra (NOSQL database) - GeeksforGeeks | 21 Apr, 2022
In this article, we will learn the basics of Apache Cassandra and the basics of CQL (Cassandra Query Language) operations like Create, insert, delete, select, etc.
Apache Cassandra: Apache Cassandra is an open-source no SQL database that is used for handling big data. Apache Cassandra has the capability to handle structure, semi-structured, and unstructured data. Apache Cassandra was originally developed at Facebook after that it was open-sourced in 2008 and after that, it become one of the top-level Apache projects in 2010.
Figure-1: Masterless ring architecture of Cassandra
Apache Cassandra is a highly scalable, distributed database that strictly follows the principle of the CAP (Consistency Availability and Partition tolerance) theorem.
Figure-2: CAP Theorem
In Apache Cassandra, there is no master-client architecture. It has a peer-to-peer architecture. In Apache Cassandra, we can create multiple copies of data at the time of keyspace creation. We can simply define replication strategy and RF (Replication Factor) to create multiple copies of data. Example:
CREATE KEYSPACE Example
WITH replication = {'class': 'NetworkTopologyStrategy',
'replication_factor': '3'};
In this example, we define RF (Replication Factor) as 3 which simply means that we are creating here 3 copies of data across multiple nodes in a clockwise direction.
Figure-3: RF = 3
cqlsh: CQL shell cqlsh is a command-line shell for interacting with Cassandra through CQL (Cassandra Query Language). CQL query for Basic Operation:
Step1: To create keyspace use the following CQL query.
CREATE KEYSPACE Emp
WITH replication = {'class': 'SimpleStrategy',
'replication_factor': '1'};
Step2: CQL query for using keyspace
Syntax:
USE keyspace-name
USE Emp;
Step-3: To create a table use the following CQL query.
Example:
CREATE TABLE Emp_table (
name text PRIMARY KEY,
Emp_id int,
Emp_city text,
Emp_email text,
);
Step-4: To insert into Emp_table use the following CQL query.
Insert into Emp_table(name, Emp_id, Emp_city, Emp_email)
VALUES ('ashish', 1001, 'Delhi', '[email protected]');
Insert into Emp_table(name, Emp_id, Emp_city, Emp_email)
VALUES ('Ashish Gupta', 1001, 'Bangalore', '[email protected]');
Insert into Emp_table(name, Emp_id, Emp_city, Emp_email)
VALUES ('amit ', 1002, 'noida', '[email protected]');
Insert into Emp_table(name, Emp_id, Emp_city, Emp_email)
VALUES ('dhruv', 1003, 'pune', '[email protected]');
Insert into Emp_table(name, Emp_id, Emp_city, Emp_email)
VALUES ('shivang', 1004, 'mumbai', '[email protected]');
Insert into Emp_table(name, Emp_id, Emp_city, Emp_email)
VALUES ('aayush', 1005, 'gurugram', '[email protected]');
Insert into Emp_table(name, Emp_id, Emp_city, Emp_email)
VALUES ('bhagyesh', 1006, 'chandigar', '[email protected]');
Step-5: To read data use the following CQl query.
SELECT * FROM Emp_table;
Ashish_rana
saurabh kundu
Apache
DBMS
GBlog
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of B-Tree
Difference between Clustered and Non-clustered index
Introduction of ER Model
CTE in SQL
SQL | Views
Roadmap to Become a Web Developer in 2022
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
DSA Sheet by Love Babbar
Socket Programming in C/C++
Must Do Coding Questions for Product Based Companies | [
{
"code": null,
"e": 24024,
"s": 23996,
"text": "\n21 Apr, 2022"
},
{
"code": null,
"e": 24189,
"s": 24024,
"text": "In this article, we will learn the basics of Apache Cassandra and the basics of CQL (Cassandra Query Language) operations like Create, insert, delete, select, etc. "
},
{
"code": null,
"e": 24556,
"s": 24189,
"text": "Apache Cassandra: Apache Cassandra is an open-source no SQL database that is used for handling big data. Apache Cassandra has the capability to handle structure, semi-structured, and unstructured data. Apache Cassandra was originally developed at Facebook after that it was open-sourced in 2008 and after that, it become one of the top-level Apache projects in 2010."
},
{
"code": null,
"e": 24612,
"s": 24558,
"text": " Figure-1: Masterless ring architecture of Cassandra "
},
{
"code": null,
"e": 24781,
"s": 24612,
"text": "Apache Cassandra is a highly scalable, distributed database that strictly follows the principle of the CAP (Consistency Availability and Partition tolerance) theorem. "
},
{
"code": null,
"e": 24804,
"s": 24781,
"text": "Figure-2: CAP Theorem "
},
{
"code": null,
"e": 25108,
"s": 24804,
"text": "In Apache Cassandra, there is no master-client architecture. It has a peer-to-peer architecture. In Apache Cassandra, we can create multiple copies of data at the time of keyspace creation. We can simply define replication strategy and RF (Replication Factor) to create multiple copies of data. Example:"
},
{
"code": null,
"e": 25247,
"s": 25108,
"text": "CREATE KEYSPACE Example\nWITH replication = {'class': 'NetworkTopologyStrategy', \n 'replication_factor': '3'}; "
},
{
"code": null,
"e": 25413,
"s": 25247,
"text": "In this example, we define RF (Replication Factor) as 3 which simply means that we are creating here 3 copies of data across multiple nodes in a clockwise direction."
},
{
"code": null,
"e": 25434,
"s": 25416,
"text": "Figure-3: RF = 3 "
},
{
"code": null,
"e": 25584,
"s": 25434,
"text": "cqlsh: CQL shell cqlsh is a command-line shell for interacting with Cassandra through CQL (Cassandra Query Language). CQL query for Basic Operation: "
},
{
"code": null,
"e": 25639,
"s": 25584,
"text": "Step1: To create keyspace use the following CQL query."
},
{
"code": null,
"e": 25765,
"s": 25639,
"text": "CREATE KEYSPACE Emp\nWITH replication = {'class': 'SimpleStrategy', \n 'replication_factor': '1'}; "
},
{
"code": null,
"e": 25801,
"s": 25765,
"text": "Step2: CQL query for using keyspace"
},
{
"code": null,
"e": 25838,
"s": 25801,
"text": "Syntax: \nUSE keyspace-name \nUSE Emp;"
},
{
"code": null,
"e": 25893,
"s": 25838,
"text": "Step-3: To create a table use the following CQL query."
},
{
"code": null,
"e": 26016,
"s": 25893,
"text": "Example:\nCREATE TABLE Emp_table (\n name text PRIMARY KEY,\n Emp_id int,\n Emp_city text,\n Emp_email text,\n );"
},
{
"code": null,
"e": 26078,
"s": 26016,
"text": "Step-4: To insert into Emp_table use the following CQL query."
},
{
"code": null,
"e": 26901,
"s": 26078,
"text": "Insert into Emp_table(name, Emp_id, Emp_city, Emp_email) \n VALUES ('ashish', 1001, 'Delhi', '[email protected]');\nInsert into Emp_table(name, Emp_id, Emp_city, Emp_email) \n VALUES ('Ashish Gupta', 1001, 'Bangalore', '[email protected]');\nInsert into Emp_table(name, Emp_id, Emp_city, Emp_email) \n VALUES ('amit ', 1002, 'noida', '[email protected]');\nInsert into Emp_table(name, Emp_id, Emp_city, Emp_email) \n VALUES ('dhruv', 1003, 'pune', '[email protected]');\nInsert into Emp_table(name, Emp_id, Emp_city, Emp_email) \n VALUES ('shivang', 1004, 'mumbai', '[email protected]');\nInsert into Emp_table(name, Emp_id, Emp_city, Emp_email) \n VALUES ('aayush', 1005, 'gurugram', '[email protected]');\nInsert into Emp_table(name, Emp_id, Emp_city, Emp_email) \n VALUES ('bhagyesh', 1006, 'chandigar', '[email protected]'); "
},
{
"code": null,
"e": 26951,
"s": 26901,
"text": "Step-5: To read data use the following CQl query."
},
{
"code": null,
"e": 26976,
"s": 26951,
"text": "SELECT * FROM Emp_table;"
},
{
"code": null,
"e": 26988,
"s": 26976,
"text": "Ashish_rana"
},
{
"code": null,
"e": 27002,
"s": 26988,
"text": "saurabh kundu"
},
{
"code": null,
"e": 27009,
"s": 27002,
"text": "Apache"
},
{
"code": null,
"e": 27014,
"s": 27009,
"text": "DBMS"
},
{
"code": null,
"e": 27020,
"s": 27014,
"text": "GBlog"
},
{
"code": null,
"e": 27025,
"s": 27020,
"text": "DBMS"
},
{
"code": null,
"e": 27123,
"s": 27025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27146,
"s": 27123,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 27199,
"s": 27146,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 27224,
"s": 27199,
"text": "Introduction of ER Model"
},
{
"code": null,
"e": 27235,
"s": 27224,
"text": "CTE in SQL"
},
{
"code": null,
"e": 27247,
"s": 27235,
"text": "SQL | Views"
},
{
"code": null,
"e": 27289,
"s": 27247,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27363,
"s": 27289,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 27388,
"s": 27363,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 27416,
"s": 27388,
"text": "Socket Programming in C/C++"
}
] |
Remove Vowels from a String in Python | Suppose we have a string, we have to remove all vowels from that string. So if the string is like “iloveprogramming”, then after removing vowels, the result will be − "lvprgrmmng"
To solve this, we will follow these steps −
create one array vowel, that is holding [a,e,i,o,u]
for v in a vowelreplace v using blank string
replace v using blank string
Let us see the following implementation to get a better understanding −
Live Demo
class Solution(object):
def removeVowels(self, s):
s = s.replace("a","")
s = s.replace("e","")
s = s.replace("i","")
s = s.replace("o","")
s = s.replace("u","")
return s
ob1 = Solution()
print(ob1.removeVowels("iloveprogramming"))
"iloveprogramming"
lvprgrmmng | [
{
"code": null,
"e": 1242,
"s": 1062,
"text": "Suppose we have a string, we have to remove all vowels from that string. So if the string is like “iloveprogramming”, then after removing vowels, the result will be − \"lvprgrmmng\""
},
{
"code": null,
"e": 1286,
"s": 1242,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1338,
"s": 1286,
"text": "create one array vowel, that is holding [a,e,i,o,u]"
},
{
"code": null,
"e": 1383,
"s": 1338,
"text": "for v in a vowelreplace v using blank string"
},
{
"code": null,
"e": 1412,
"s": 1383,
"text": "replace v using blank string"
},
{
"code": null,
"e": 1484,
"s": 1412,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 1495,
"s": 1484,
"text": " Live Demo"
},
{
"code": null,
"e": 1765,
"s": 1495,
"text": "class Solution(object):\n def removeVowels(self, s):\n s = s.replace(\"a\",\"\")\n s = s.replace(\"e\",\"\")\n s = s.replace(\"i\",\"\")\n s = s.replace(\"o\",\"\")\n s = s.replace(\"u\",\"\")\n return s\nob1 = Solution()\nprint(ob1.removeVowels(\"iloveprogramming\"))"
},
{
"code": null,
"e": 1784,
"s": 1765,
"text": "\"iloveprogramming\""
},
{
"code": null,
"e": 1795,
"s": 1784,
"text": "lvprgrmmng"
}
] |
Solidity - First Application | We're using Remix IDE to Compile and Run our Solidity Code base.
Step 1 − Copy the given code in Remix IDE Code Section.
pragma solidity ^0.5.0;
contract SolidityTest {
constructor() public{
}
function getResult() public view returns(uint){
uint a = 1;
uint b = 2;
uint result = a + b;
return result;
}
}
Step 2 − Under Compile Tab, click Start to Compile button.
Step 3 − Under Run Tab, click Deploy button.
Step 4 − Under Run Tab, Select SolidityTest at 0x... in drop-down.
Step 5 − Click getResult Button to display the result.
0: uint256: 3
38 Lectures
4.5 hours
Abhilash Nelson
62 Lectures
8.5 hours
Frahaan Hussain
31 Lectures
3.5 hours
Swapnil Kole
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2620,
"s": 2555,
"text": "We're using Remix IDE to Compile and Run our Solidity Code base."
},
{
"code": null,
"e": 2676,
"s": 2620,
"text": "Step 1 − Copy the given code in Remix IDE Code Section."
},
{
"code": null,
"e": 2896,
"s": 2676,
"text": "pragma solidity ^0.5.0;\ncontract SolidityTest {\n constructor() public{\n }\n function getResult() public view returns(uint){\n uint a = 1;\n uint b = 2;\n uint result = a + b;\n return result;\n }\n}"
},
{
"code": null,
"e": 2955,
"s": 2896,
"text": "Step 2 − Under Compile Tab, click Start to Compile button."
},
{
"code": null,
"e": 3000,
"s": 2955,
"text": "Step 3 − Under Run Tab, click Deploy button."
},
{
"code": null,
"e": 3067,
"s": 3000,
"text": "Step 4 − Under Run Tab, Select SolidityTest at 0x... in drop-down."
},
{
"code": null,
"e": 3122,
"s": 3067,
"text": "Step 5 − Click getResult Button to display the result."
},
{
"code": null,
"e": 3137,
"s": 3122,
"text": "0: uint256: 3\n"
},
{
"code": null,
"e": 3172,
"s": 3137,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3189,
"s": 3172,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3224,
"s": 3189,
"text": "\n 62 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3241,
"s": 3224,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3276,
"s": 3241,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3290,
"s": 3276,
"text": " Swapnil Kole"
},
{
"code": null,
"e": 3297,
"s": 3290,
"text": " Print"
},
{
"code": null,
"e": 3308,
"s": 3297,
"text": " Add Notes"
}
] |
How do I format a string using a dictionary in Python 3? | You can use dictionaries to interpolate strings. They have a syntax in which you need to provide the key in the parentheses between the % and the conversion character. For example, if you have a float stored in a key 'cost' and want to format it as '$xxxx.xx', then you'll place '$%(cost).2f' at the place you want to display it.
Here is an example of using string formatting in dictionaries to interpolate a string and format a number:
>>>print('%(language)s has %(number)03d quote types.' % {'language': "Python", "number": 2})
Python has 002 quote types.
You can read up more about string formatting and their operators here: https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting | [
{
"code": null,
"e": 1392,
"s": 1062,
"text": "You can use dictionaries to interpolate strings. They have a syntax in which you need to provide the key in the parentheses between the % and the conversion character. For example, if you have a float stored in a key 'cost' and want to format it as '$xxxx.xx', then you'll place '$%(cost).2f' at the place you want to display it."
},
{
"code": null,
"e": 1499,
"s": 1392,
"text": "Here is an example of using string formatting in dictionaries to interpolate a string and format a number:"
},
{
"code": null,
"e": 1620,
"s": 1499,
"text": ">>>print('%(language)s has %(number)03d quote types.' % {'language': \"Python\", \"number\": 2})\nPython has 002 quote types."
},
{
"code": null,
"e": 1770,
"s": 1620,
"text": "You can read up more about string formatting and their operators here: https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting"
}
] |
How to check the PowerShell version installed in local and remote systems? | To check the PowerShell version installed in your system, you can use either $PSVersionTable or $host command.
Check if $host command available in remote servers.
Check if $host command available in remote servers.
Open the PowerShell console in the system and run the command $PSVersionTable.
$PSVersionTable
PS C:\WINDOWS\system32> $PSVersionTable
Name Value
---- -----
PSVersion 5.1.18362.628
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.18362.628
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
So here, we have an output of the $PSVersionTable. You can see the output property $PSVersion, which indicates the version information of the PowerShell.
$PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
5 1 18362 628
In the Major property, it indicates the PowerShell version is 5 and Build is 18362.
Similarly, you can get the above output with the $Host command in PowerShell.
PS C:\WINDOWS\system32> $Host
Name : ConsoleHost
Version : 5.1.18362.628
InstanceId : f6d2bf19-db26-403b-9749-afede37ea56f
UI : System.Management.Automation.Internal.Host.InternalHostUserInterface CurrentCulture :en-IN
CurrentUICulture : en-US
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled : True
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace
You can get the PowerShell version from version property.
$Host.Version
PS C:\WINDOWS\system32> $Host.Version
Major Minor Build Revision
----- ----- ----- --------
5 1 18362 628
To get the output on the remote computer, you need to use Invoke-Command or PSRemote session command as the $PSverionTable and $Host doesn’t support the − ComputerName Parameter.
Invoke-Command -ComputerName Test-PC -ScriptBlock{$PSVersionTable.PSVersion}
If you have multiple computers and if you need the Hostname and the PS version against the hostname then you can use the Pipeline or the PSCustomObject command.
Invoke-Command -ComputerName Test-PC,DC1 -ScriptBlock{$PSVersionTable.PSVersion} | Select PSComputerName, @{N="PS Version";E={$_.Major}}
If you have a list of servers then you can add all the servers into the text file and run the above command.
For example, We have servers list stored in D:\Temp\Servers.txt and we need to get the PS version on them.
Invoke-Command -ComputerName (Get-Content D:\Temp\Servers.txt) -
ScriptBlock{$PSVersionTable.PSVersion} | Select PSComputerName, @{N="PS Version";E={$_.Major}} | [
{
"code": null,
"e": 1173,
"s": 1062,
"text": "To check the PowerShell version installed in your system, you can use either $PSVersionTable or $host command."
},
{
"code": null,
"e": 1225,
"s": 1173,
"text": "Check if $host command available in remote servers."
},
{
"code": null,
"e": 1277,
"s": 1225,
"text": "Check if $host command available in remote servers."
},
{
"code": null,
"e": 1356,
"s": 1277,
"text": "Open the PowerShell console in the system and run the command $PSVersionTable."
},
{
"code": null,
"e": 1372,
"s": 1356,
"text": "$PSVersionTable"
},
{
"code": null,
"e": 1847,
"s": 1372,
"text": "PS C:\\WINDOWS\\system32> $PSVersionTable\nName Value\n---- -----\nPSVersion 5.1.18362.628\nPSEdition Desktop\nPSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}\nBuildVersion 10.0.18362.628\nCLRVersion 4.0.30319.42000\nWSManStackVersion 3.0\nPSRemotingProtocolVersion 2.3\nSerializationVersion 1.1.0.1"
},
{
"code": null,
"e": 2001,
"s": 1847,
"text": "So here, we have an output of the $PSVersionTable. You can see the output property $PSVersion, which indicates the version information of the PowerShell."
},
{
"code": null,
"e": 2027,
"s": 2001,
"text": "$PSVersionTable.PSVersion"
},
{
"code": null,
"e": 2130,
"s": 2027,
"text": "Major Minor Build Revision\n----- ----- ----- --------\n5 1 18362 628"
},
{
"code": null,
"e": 2214,
"s": 2130,
"text": "In the Major property, it indicates the PowerShell version is 5 and Build is 18362."
},
{
"code": null,
"e": 2292,
"s": 2214,
"text": "Similarly, you can get the above output with the $Host command in PowerShell."
},
{
"code": null,
"e": 2888,
"s": 2292,
"text": "PS C:\\WINDOWS\\system32> $Host\nName : ConsoleHost\nVersion : 5.1.18362.628\nInstanceId : f6d2bf19-db26-403b-9749-afede37ea56f\nUI : System.Management.Automation.Internal.Host.InternalHostUserInterface CurrentCulture :en-IN\nCurrentUICulture : en-US\nPrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy\nDebuggerEnabled : True\nIsRunspacePushed : False\nRunspace : System.Management.Automation.Runspaces.LocalRunspace"
},
{
"code": null,
"e": 2946,
"s": 2888,
"text": "You can get the PowerShell version from version property."
},
{
"code": null,
"e": 2960,
"s": 2946,
"text": "$Host.Version"
},
{
"code": null,
"e": 3101,
"s": 2960,
"text": "PS C:\\WINDOWS\\system32> $Host.Version\nMajor Minor Build Revision\n ----- ----- ----- --------\n 5 1 18362 628"
},
{
"code": null,
"e": 3280,
"s": 3101,
"text": "To get the output on the remote computer, you need to use Invoke-Command or PSRemote session command as the $PSverionTable and $Host doesn’t support the − ComputerName Parameter."
},
{
"code": null,
"e": 3357,
"s": 3280,
"text": "Invoke-Command -ComputerName Test-PC -ScriptBlock{$PSVersionTable.PSVersion}"
},
{
"code": null,
"e": 3518,
"s": 3357,
"text": "If you have multiple computers and if you need the Hostname and the PS version against the hostname then you can use the Pipeline or the PSCustomObject command."
},
{
"code": null,
"e": 3655,
"s": 3518,
"text": "Invoke-Command -ComputerName Test-PC,DC1 -ScriptBlock{$PSVersionTable.PSVersion} | Select PSComputerName, @{N=\"PS Version\";E={$_.Major}}"
},
{
"code": null,
"e": 3764,
"s": 3655,
"text": "If you have a list of servers then you can add all the servers into the text file and run the above command."
},
{
"code": null,
"e": 3871,
"s": 3764,
"text": "For example, We have servers list stored in D:\\Temp\\Servers.txt and we need to get the PS version on them."
},
{
"code": null,
"e": 4031,
"s": 3871,
"text": "Invoke-Command -ComputerName (Get-Content D:\\Temp\\Servers.txt) -\nScriptBlock{$PSVersionTable.PSVersion} | Select PSComputerName, @{N=\"PS Version\";E={$_.Major}}"
}
] |
Emulating a 2-d array using 1-d array - GeeksforGeeks | 25 Jun, 2021
How to convert a 2-d array of size (m x n) into 1-d array and how to store the element at position [i, j] of 2-d array in 1-d array? Clearly, the size of 1-d array is the number of elements in 2-d array i.e. (m x n). If the elements in the 2-d array are stored in row-major order. Then, the element at index [i, j] in 2-d array will be stored in 1-d array at index k as:
k = j + (i * total_no_of_columns_in_matrix)
If the elements in the 2-d array are stored in column-major order, the value of index k will be
k = i + (j * total_no_of_rows_in_matrix)
For more details about Row-major and Column-major order, refer to: https://en.wikipedia.org/wiki/Row-major_order
Examples :
Given 2-d array:
// array is formed in row-major order
__________________________
| |
|1(0,0) 2(0,1) 3(0,2)|
| |
|4(1,0) 5(1,1) 6(1,2)|
|__________________________|
// The elements in parenthesis represents the
// index of the particular element in 2-d array.
Index of element at (0,1) in 1-d array will be:
k(0,1) = 1 + 0 * 3 = 1
Index of element at (1,1) in 1-d array will be:
k(1,1) = 1 + 1 * 3 = 4
C++
Java
Python3
C#
Javascript
// C++ program to emulate 2-d array using// 1-d array#include<stdio.h>#define n 3#define m 3#define max_size 100int main(){ // Initialising a 2-d array int grid[n][m] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // storing elements in 1-d array int i, j, k = 0; int array[max_size]; for (i=0; i<n; i++) { for (j=0; j<m; j++) { k = i*m + j; array[k] = grid[i][j]; k++; } } // displaying elements in 1-d array for (i=0; i<n; i++) { for (j=0; j<m; j++) printf("%d ", *(array + i*m + j)); printf("\n"); } return 0;}
// Java program to emulate 2-d array using// 1-d array class GFG{ // Driver program public static void main(String arg[]) { // Declaring number of rows and columns int n = 3, m = 3; int array[]=new int[100]; // Initialising a 2-d array int grid[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // storing elements in 1-d array int i, j, k = 0; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { k = i * m + j; array[k] = grid[i][j]; k++; } } // displaying elements in 1-d array for (i = 0; i < n; i++) { for (j = 0; j < m; j++) System.out.print((array[i * m + j])+" "); System.out.print("\n"); } }} // This code is contributed by Anant Agarwal.
# Python program to emulate 2-d# array using 1-d array # Declaring number of rows and columnsn = 3; m = 3 array = [0 for i in range(100)] # Initialising a 2-d arraygrid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; # storing elements in 1-d arrayk = 0 for i in range(n): for j in range(m): k = i*m + j array[k] = grid[i][j] k += 1 # displaying elements in 1-d arrayfor i in range(n): for j in range(m): print((array[i*m + j]), " ", end = "") print() # This code is contributed by Anant Agarwal.
// C# program to emulate 2-d array using// 1-d arrayusing System; class GFG{ // Driver program public static void Main() { // Declaring number of rows and columns int n = 3, m = 3; int []array=new int[100]; // Initialising a 2-d array int [,]grid = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // storing elements in 1-d array int i, j, k = 0; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { k = i * m + j; array[k] = grid[i, j]; k++; } } // displaying elements in 1-d array for (i = 0; i < n; i++) { for (j = 0; j < m; j++) Console.Write((array[i * m + j])+" "); Console.Write("\n"); } }} // This code is contributed by nitin mittal
<script> // Javascript program to emulate 2-d array using// 1-d array // Declaring number of rows and columnslet n = 3, m = 3;let array = new Array(100); // Initialising a 2-d arraylet grid = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; // Storing elements in 1-d arraylet i, j, k = 0;for(i = 0; i < n; i++){ for(j = 0; j < m; j++) { k = i * m + j; array[k] = grid[i][j]; k++; }} // Displaying elements in 1-d arrayfor(i = 0; i < n; i++){ for(j = 0; j < m; j++) document.write((array[i * m + j]) + " "); document.write("<br>");} // This code is contributed by _saurabh_jaiswal </script>
Output:
1 2 3
4 5 6
7 8 9
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
anikaseth98
_saurabh_jaiswal
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Building Heap from Array
Remove duplicates from sorted array
Sliding Window Maximum (Maximum of all subarrays of size k)
Move all negative numbers to beginning and positive to end with constant extra space | [
{
"code": null,
"e": 24429,
"s": 24401,
"text": "\n25 Jun, 2021"
},
{
"code": null,
"e": 24801,
"s": 24429,
"text": "How to convert a 2-d array of size (m x n) into 1-d array and how to store the element at position [i, j] of 2-d array in 1-d array? Clearly, the size of 1-d array is the number of elements in 2-d array i.e. (m x n). If the elements in the 2-d array are stored in row-major order. Then, the element at index [i, j] in 2-d array will be stored in 1-d array at index k as: "
},
{
"code": null,
"e": 24845,
"s": 24801,
"text": "k = j + (i * total_no_of_columns_in_matrix)"
},
{
"code": null,
"e": 24942,
"s": 24845,
"text": "If the elements in the 2-d array are stored in column-major order, the value of index k will be "
},
{
"code": null,
"e": 24983,
"s": 24942,
"text": "k = i + (j * total_no_of_rows_in_matrix)"
},
{
"code": null,
"e": 25097,
"s": 24983,
"text": "For more details about Row-major and Column-major order, refer to: https://en.wikipedia.org/wiki/Row-major_order "
},
{
"code": null,
"e": 25110,
"s": 25097,
"text": "Examples : "
},
{
"code": null,
"e": 25598,
"s": 25110,
"text": "Given 2-d array:\n\n// array is formed in row-major order\n __________________________\n | |\n |1(0,0) 2(0,1) 3(0,2)|\n | |\n |4(1,0) 5(1,1) 6(1,2)|\n |__________________________|\n\n// The elements in parenthesis represents the\n// index of the particular element in 2-d array.\n\nIndex of element at (0,1) in 1-d array will be:\nk(0,1) = 1 + 0 * 3 = 1\n\nIndex of element at (1,1) in 1-d array will be:\nk(1,1) = 1 + 1 * 3 = 4 "
},
{
"code": null,
"e": 25602,
"s": 25598,
"text": "C++"
},
{
"code": null,
"e": 25607,
"s": 25602,
"text": "Java"
},
{
"code": null,
"e": 25615,
"s": 25607,
"text": "Python3"
},
{
"code": null,
"e": 25618,
"s": 25615,
"text": "C#"
},
{
"code": null,
"e": 25629,
"s": 25618,
"text": "Javascript"
},
{
"code": "// C++ program to emulate 2-d array using// 1-d array#include<stdio.h>#define n 3#define m 3#define max_size 100int main(){ // Initialising a 2-d array int grid[n][m] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // storing elements in 1-d array int i, j, k = 0; int array[max_size]; for (i=0; i<n; i++) { for (j=0; j<m; j++) { k = i*m + j; array[k] = grid[i][j]; k++; } } // displaying elements in 1-d array for (i=0; i<n; i++) { for (j=0; j<m; j++) printf(\"%d \", *(array + i*m + j)); printf(\"\\n\"); } return 0;}",
"e": 26297,
"s": 25629,
"text": null
},
{
"code": "// Java program to emulate 2-d array using// 1-d array class GFG{ // Driver program public static void main(String arg[]) { // Declaring number of rows and columns int n = 3, m = 3; int array[]=new int[100]; // Initialising a 2-d array int grid[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // storing elements in 1-d array int i, j, k = 0; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { k = i * m + j; array[k] = grid[i][j]; k++; } } // displaying elements in 1-d array for (i = 0; i < n; i++) { for (j = 0; j < m; j++) System.out.print((array[i * m + j])+\" \"); System.out.print(\"\\n\"); } }} // This code is contributed by Anant Agarwal.",
"e": 27222,
"s": 26297,
"text": null
},
{
"code": "# Python program to emulate 2-d# array using 1-d array # Declaring number of rows and columnsn = 3; m = 3 array = [0 for i in range(100)] # Initialising a 2-d arraygrid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; # storing elements in 1-d arrayk = 0 for i in range(n): for j in range(m): k = i*m + j array[k] = grid[i][j] k += 1 # displaying elements in 1-d arrayfor i in range(n): for j in range(m): print((array[i*m + j]), \" \", end = \"\") print() # This code is contributed by Anant Agarwal.",
"e": 27776,
"s": 27222,
"text": null
},
{
"code": "// C# program to emulate 2-d array using// 1-d arrayusing System; class GFG{ // Driver program public static void Main() { // Declaring number of rows and columns int n = 3, m = 3; int []array=new int[100]; // Initialising a 2-d array int [,]grid = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // storing elements in 1-d array int i, j, k = 0; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { k = i * m + j; array[k] = grid[i, j]; k++; } } // displaying elements in 1-d array for (i = 0; i < n; i++) { for (j = 0; j < m; j++) Console.Write((array[i * m + j])+\" \"); Console.Write(\"\\n\"); } }} // This code is contributed by nitin mittal",
"e": 28691,
"s": 27776,
"text": null
},
{
"code": "<script> // Javascript program to emulate 2-d array using// 1-d array // Declaring number of rows and columnslet n = 3, m = 3;let array = new Array(100); // Initialising a 2-d arraylet grid = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; // Storing elements in 1-d arraylet i, j, k = 0;for(i = 0; i < n; i++){ for(j = 0; j < m; j++) { k = i * m + j; array[k] = grid[i][j]; k++; }} // Displaying elements in 1-d arrayfor(i = 0; i < n; i++){ for(j = 0; j < m; j++) document.write((array[i * m + j]) + \" \"); document.write(\"<br>\");} // This code is contributed by _saurabh_jaiswal </script>",
"e": 29352,
"s": 28691,
"text": null
},
{
"code": null,
"e": 29361,
"s": 29352,
"text": "Output: "
},
{
"code": null,
"e": 29390,
"s": 29361,
"text": "1 2 3 \n4 5 6 \n7 8 9 "
},
{
"code": null,
"e": 29812,
"s": 29390,
"text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 29825,
"s": 29812,
"text": "nitin mittal"
},
{
"code": null,
"e": 29837,
"s": 29825,
"text": "anikaseth98"
},
{
"code": null,
"e": 29854,
"s": 29837,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 29861,
"s": 29854,
"text": "Arrays"
},
{
"code": null,
"e": 29868,
"s": 29861,
"text": "Arrays"
},
{
"code": null,
"e": 29966,
"s": 29868,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29975,
"s": 29966,
"text": "Comments"
},
{
"code": null,
"e": 29988,
"s": 29975,
"text": "Old Comments"
},
{
"code": null,
"e": 30009,
"s": 29988,
"text": "Next Greater Element"
},
{
"code": null,
"e": 30034,
"s": 30009,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 30061,
"s": 30034,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 30110,
"s": 30061,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30148,
"s": 30110,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 30207,
"s": 30148,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 30232,
"s": 30207,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 30268,
"s": 30232,
"text": "Remove duplicates from sorted array"
},
{
"code": null,
"e": 30328,
"s": 30268,
"text": "Sliding Window Maximum (Maximum of all subarrays of size k)"
}
] |
Algorithms From Scratch: Support Vector Machines | by Kurtis Pykes | Towards Data Science | A popular algorithm that is capable of performing linear or non-linear classification and regression, Support Vector Machines were the talk of the town before the rise of deep learning due to the exciting kernel trick — If the terminology makes no sense to you right now don’t worry about it. By the end of this post you’ll have an good understanding about the intuition of SVMs, what is happening under the hood of linear SVMs, and how to implement one in Python.
To see the full Algorithms from Scratch Series click on the link below.
towardsdatascience.com
In classification problems the objective of the SVM is to fit the largest possible margin between the 2 classes. On the contrary, regression task flips the objective of classification task and attempts to fit as many instances as possible within the margin — We will first focus on classification.
If we focus solely on the extremes of the data (the observations that are on the edges of the cluster) and we define a threshold to be the mid-point between the two extremes, we are left with a margin that we use to sepereate the two classes — this is often referred to as a hyperplane. When we apply a threshold that gives us the largest margin (meaning that we are strict to ensure that no instances land within the margin) to make classifications this is called Hard Margin Classification (some text refer to this as Maximal Margin Classification).
When detailing hard margin classification it always helps to see what is happening visually, hence Figure 2 is an example of a hard margin classification. To do this we will use the iris dataset from scikit-learn and utility function plot_svm() which you can find when you access the full code on github — link below.
github.com
Note: This story was written straight from jupyter notebooks using python package jupyter_to_medium — for more information on this package click here — and the committed version on github is a first draft hence you may notice some alterations to this post.
import pandas as pd import numpy as np from sklearn.svm import LinearSVCfrom sklearn.preprocessing import StandardScalerfrom sklearn.datasets import load_irisimport matplotlib.pyplot as plt %matplotlib inline# store the data iris = load_iris()# convert to DataFramedf = pd.DataFrame(data=iris.data, columns= iris.feature_names)# store mapping of targets and target namestarget_dict = dict(zip(set(iris.target), iris.target_names))# add the target labels and the feature namesdf["target"] = iris.targetdf["target_names"] = df.target.map(target_dict)# view the datadf.tail()
# setting X and y X = df.query("target_names == 'setosa' or target_names == 'versicolor'").loc[:, "petal length (cm)":"petal width (cm)"] y = df.query("target_names == 'setosa' or target_names == 'versicolor'").loc[:, "target"] # fit the model with hard margin (Large C parameter)svc = LinearSVC(loss="hinge", C=1000)svc.fit(X, y)plot_svm()
Figure 2 displays how the Linear SVM uses hard margin classification to ensure that no instances falls within the margin. Although this looks good for our current scenario, we must be careful to take into account the pitfalls that come with performing hard margin classification:
Very sensitive to outliersIt only works when the classes are linearly separable
Very sensitive to outliers
It only works when the classes are linearly separable
A more flexible alternative to hard margin classification is soft margin classification which is a good solution to overcome the pitfalls listed above when doing hard margin classification — mainly with solving the issue of sensitivity to outliers. When we allow for there to be some misclassifications (meaning that some negative observations may be classified as positive and vice versa), the distance from the threshold to the observations is called soft margin. In soft margin classification we aim to achieve a good balance between maximizing the size of the margin and limiting the amount of violations in the margin (the number of observations that land in the margin).
Yes, Linear SVM classifiers (hard-margin and soft-margin) are quite efficient and work really well in many cases, but when the dataset is not linearly separable, as if often the case with many datasets, a better solution is to make use of the SVMs kernel trick (once you understand the kernel trick you may notice that it is not exclusive to SVMs). The kernel trick maps non-linearly separable data into a higher dimension then uses a hyperplane to separate the classes. What makes this trick so exciting is that the mapping of the data into higher dimensions does not actually add the new features, but we still get the same results as if we did. Since we do not have to add the new features to our data, our model is much more computationally effieicent and works ust as good.
You’ll see an example of this phenomena below.
Decision Boundary: The hyperplane that seperates the dataset into two classes
Support Vectors: The observations are at the edge of the cluster (located nearest to the seperating hyperplane).
Hard Margin: When we strictly impose that all observations do not fall within the margin
Soft Margin: When we allow for some misclassification. We seek to find a balacne of keeping the margin as large as possible and limiting the number of violations (bias/variance tradeoff)
from sklearn.datasets import make_moonsfrom mlxtend.plotting import plot_decision_regionsfrom sklearn.preprocessing import StandardScalerfrom sklearn.svm import SVC# loading the dataX, y = make_moons(noise=0.3, random_state=0)# scale featuresscaler = StandardScaler()X_scaled = scaler.fit_transform(X)# fit the model with polynomial kernelsvc_clf = SVC(kernel="poly", degree=3, C=5, coef0=1)svc_clf.fit(X_scaled, y)# plotting the decision regionsplt.figure(figsize=(10, 5))plot_decision_regions(X_scaled, y, clf=svc_clf)plt.show()
Note: We applied a polynomial kernel to this dataset, however RBF is also a very popular kernel that is applied in many Machine Learning problems and is often used as a default when data is not linearly separable.
Now that we have built up our conceptual understanding of what SVM is doing, lets understand what is happening under the hood of the model. The linear SVM classifier computes the decision function w.T * x + b and predicts the positive class for results that are positive or else it is the negative class. Training a Linear SVM classifier means finding the values w and b that make the margin as wide as possible whilst avoiding margin violations (hard margin classification) or limiting them (soft margin classification)
The slope of the decision function is equal to the norm of the weight vector hence for us to achieve the largest possible margin we want to minimize the norm of the weight vector. However, there are ways to go about this for us to achieve hard margin classification and soft margin classification.
The hard margin optimization problem is as follows:
And soft margin:
Note: For this Implementation I will be doing hard margin classification, however further work will consist of Python implementations of soft-margin and the kernel trick performed to different datasets including regression based task — to be notified of these post you can follow me on Github.
from sklearn.datasets.samples_generator import make_blobs # generating a datasetX, y = make_blobs(n_samples=50, n_features=2, centers=2, cluster_std=1.05, random_state=23)def initialize_param(X): """ Initializing the weight vector and bias """ _, n_features = X.shape w = np.zeros(n_features) b = 0 return w, bdef optimization(X, y, learning_rate=0.001, lambd=0.01, n_iters=1000): """ finding value of w and b that make the margin as large as possible while avoiding violations (Hard margin classification) """ t = np.where(y <= 0, -1, 1) w, b = initialize_param(X) for _ in range(n_iters): for idx, x_i in enumerate(X): condition = t[idx] * (np.dot(x_i, w) + b) >= 1 if condition: w -= learning_rate * (2 * lambd * w) else: w -= learning_rate * (2 * lambd * w - np.dot(x_i, t[idx])) b -= learning_rate * t[idx] return w, bw, b = gradient_descent(X, y)def predict(X, w, b): """ classify examples """ decision = np.dot(X, w) + b return np.sign(decision)# my implementation visualizationvisualize_svm()# convert X to DataFrame to easily copy codeX = pd.DataFrame(data=X, columns= ["x1", "x2"])# fit the model with hard margin (Large C parameter)svc = LinearSVC(loss="hinge", C=1000)svc.fit(X, y)# sklearn implementation visualizationplot_svm()
Very good Linear classifier because it finds the best decision boundary (In a Hard Margin Classification sense)
Easy to transform into a non-linear model
Not suited for large datasets
The SVM is quite a tricky algorithm to code and is a good reminder as to why we should be grateful for Machine Learning libraries that allow us to implement them with few lines of code. In this post I did not go into the full detail of SVMs and there are still quite a few gaps that you may want to read up on such as computing the support vector machine and empirical risk minimization.
Additionally, it may be worth watch Andrew Ng’s lectures on SVMs — Click Here
Thank you for taking the time to read through this story (as it’s called on Medium). You now have a good conceptual understanding of Support Vector Machines, what happens under the hood of a SVM and how to code a hard margin classifier in Python. If you’d like to get in contact with me, I am most accessible on LinkedIn. | [
{
"code": null,
"e": 636,
"s": 171,
"text": "A popular algorithm that is capable of performing linear or non-linear classification and regression, Support Vector Machines were the talk of the town before the rise of deep learning due to the exciting kernel trick — If the terminology makes no sense to you right now don’t worry about it. By the end of this post you’ll have an good understanding about the intuition of SVMs, what is happening under the hood of linear SVMs, and how to implement one in Python."
},
{
"code": null,
"e": 708,
"s": 636,
"text": "To see the full Algorithms from Scratch Series click on the link below."
},
{
"code": null,
"e": 731,
"s": 708,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1029,
"s": 731,
"text": "In classification problems the objective of the SVM is to fit the largest possible margin between the 2 classes. On the contrary, regression task flips the objective of classification task and attempts to fit as many instances as possible within the margin — We will first focus on classification."
},
{
"code": null,
"e": 1581,
"s": 1029,
"text": "If we focus solely on the extremes of the data (the observations that are on the edges of the cluster) and we define a threshold to be the mid-point between the two extremes, we are left with a margin that we use to sepereate the two classes — this is often referred to as a hyperplane. When we apply a threshold that gives us the largest margin (meaning that we are strict to ensure that no instances land within the margin) to make classifications this is called Hard Margin Classification (some text refer to this as Maximal Margin Classification)."
},
{
"code": null,
"e": 1899,
"s": 1581,
"text": "When detailing hard margin classification it always helps to see what is happening visually, hence Figure 2 is an example of a hard margin classification. To do this we will use the iris dataset from scikit-learn and utility function plot_svm() which you can find when you access the full code on github — link below."
},
{
"code": null,
"e": 1910,
"s": 1899,
"text": "github.com"
},
{
"code": null,
"e": 2167,
"s": 1910,
"text": "Note: This story was written straight from jupyter notebooks using python package jupyter_to_medium — for more information on this package click here — and the committed version on github is a first draft hence you may notice some alterations to this post."
},
{
"code": null,
"e": 2757,
"s": 2167,
"text": "import pandas as pd import numpy as np from sklearn.svm import LinearSVCfrom sklearn.preprocessing import StandardScalerfrom sklearn.datasets import load_irisimport matplotlib.pyplot as plt %matplotlib inline# store the data iris = load_iris()# convert to DataFramedf = pd.DataFrame(data=iris.data, columns= iris.feature_names)# store mapping of targets and target namestarget_dict = dict(zip(set(iris.target), iris.target_names))# add the target labels and the feature namesdf[\"target\"] = iris.targetdf[\"target_names\"] = df.target.map(target_dict)# view the datadf.tail()"
},
{
"code": null,
"e": 3099,
"s": 2757,
"text": "# setting X and y X = df.query(\"target_names == 'setosa' or target_names == 'versicolor'\").loc[:, \"petal length (cm)\":\"petal width (cm)\"] y = df.query(\"target_names == 'setosa' or target_names == 'versicolor'\").loc[:, \"target\"] # fit the model with hard margin (Large C parameter)svc = LinearSVC(loss=\"hinge\", C=1000)svc.fit(X, y)plot_svm()"
},
{
"code": null,
"e": 3379,
"s": 3099,
"text": "Figure 2 displays how the Linear SVM uses hard margin classification to ensure that no instances falls within the margin. Although this looks good for our current scenario, we must be careful to take into account the pitfalls that come with performing hard margin classification:"
},
{
"code": null,
"e": 3459,
"s": 3379,
"text": "Very sensitive to outliersIt only works when the classes are linearly separable"
},
{
"code": null,
"e": 3486,
"s": 3459,
"text": "Very sensitive to outliers"
},
{
"code": null,
"e": 3540,
"s": 3486,
"text": "It only works when the classes are linearly separable"
},
{
"code": null,
"e": 4217,
"s": 3540,
"text": "A more flexible alternative to hard margin classification is soft margin classification which is a good solution to overcome the pitfalls listed above when doing hard margin classification — mainly with solving the issue of sensitivity to outliers. When we allow for there to be some misclassifications (meaning that some negative observations may be classified as positive and vice versa), the distance from the threshold to the observations is called soft margin. In soft margin classification we aim to achieve a good balance between maximizing the size of the margin and limiting the amount of violations in the margin (the number of observations that land in the margin)."
},
{
"code": null,
"e": 4996,
"s": 4217,
"text": "Yes, Linear SVM classifiers (hard-margin and soft-margin) are quite efficient and work really well in many cases, but when the dataset is not linearly separable, as if often the case with many datasets, a better solution is to make use of the SVMs kernel trick (once you understand the kernel trick you may notice that it is not exclusive to SVMs). The kernel trick maps non-linearly separable data into a higher dimension then uses a hyperplane to separate the classes. What makes this trick so exciting is that the mapping of the data into higher dimensions does not actually add the new features, but we still get the same results as if we did. Since we do not have to add the new features to our data, our model is much more computationally effieicent and works ust as good."
},
{
"code": null,
"e": 5043,
"s": 4996,
"text": "You’ll see an example of this phenomena below."
},
{
"code": null,
"e": 5121,
"s": 5043,
"text": "Decision Boundary: The hyperplane that seperates the dataset into two classes"
},
{
"code": null,
"e": 5234,
"s": 5121,
"text": "Support Vectors: The observations are at the edge of the cluster (located nearest to the seperating hyperplane)."
},
{
"code": null,
"e": 5323,
"s": 5234,
"text": "Hard Margin: When we strictly impose that all observations do not fall within the margin"
},
{
"code": null,
"e": 5510,
"s": 5323,
"text": "Soft Margin: When we allow for some misclassification. We seek to find a balacne of keeping the margin as large as possible and limiting the number of violations (bias/variance tradeoff)"
},
{
"code": null,
"e": 6041,
"s": 5510,
"text": "from sklearn.datasets import make_moonsfrom mlxtend.plotting import plot_decision_regionsfrom sklearn.preprocessing import StandardScalerfrom sklearn.svm import SVC# loading the dataX, y = make_moons(noise=0.3, random_state=0)# scale featuresscaler = StandardScaler()X_scaled = scaler.fit_transform(X)# fit the model with polynomial kernelsvc_clf = SVC(kernel=\"poly\", degree=3, C=5, coef0=1)svc_clf.fit(X_scaled, y)# plotting the decision regionsplt.figure(figsize=(10, 5))plot_decision_regions(X_scaled, y, clf=svc_clf)plt.show()"
},
{
"code": null,
"e": 6255,
"s": 6041,
"text": "Note: We applied a polynomial kernel to this dataset, however RBF is also a very popular kernel that is applied in many Machine Learning problems and is often used as a default when data is not linearly separable."
},
{
"code": null,
"e": 6776,
"s": 6255,
"text": "Now that we have built up our conceptual understanding of what SVM is doing, lets understand what is happening under the hood of the model. The linear SVM classifier computes the decision function w.T * x + b and predicts the positive class for results that are positive or else it is the negative class. Training a Linear SVM classifier means finding the values w and b that make the margin as wide as possible whilst avoiding margin violations (hard margin classification) or limiting them (soft margin classification)"
},
{
"code": null,
"e": 7074,
"s": 6776,
"text": "The slope of the decision function is equal to the norm of the weight vector hence for us to achieve the largest possible margin we want to minimize the norm of the weight vector. However, there are ways to go about this for us to achieve hard margin classification and soft margin classification."
},
{
"code": null,
"e": 7126,
"s": 7074,
"text": "The hard margin optimization problem is as follows:"
},
{
"code": null,
"e": 7143,
"s": 7126,
"text": "And soft margin:"
},
{
"code": null,
"e": 7437,
"s": 7143,
"text": "Note: For this Implementation I will be doing hard margin classification, however further work will consist of Python implementations of soft-margin and the kernel trick performed to different datasets including regression based task — to be notified of these post you can follow me on Github."
},
{
"code": null,
"e": 8852,
"s": 7437,
"text": "from sklearn.datasets.samples_generator import make_blobs # generating a datasetX, y = make_blobs(n_samples=50, n_features=2, centers=2, cluster_std=1.05, random_state=23)def initialize_param(X): \"\"\" Initializing the weight vector and bias \"\"\" _, n_features = X.shape w = np.zeros(n_features) b = 0 return w, bdef optimization(X, y, learning_rate=0.001, lambd=0.01, n_iters=1000): \"\"\" finding value of w and b that make the margin as large as possible while avoiding violations (Hard margin classification) \"\"\" t = np.where(y <= 0, -1, 1) w, b = initialize_param(X) for _ in range(n_iters): for idx, x_i in enumerate(X): condition = t[idx] * (np.dot(x_i, w) + b) >= 1 if condition: w -= learning_rate * (2 * lambd * w) else: w -= learning_rate * (2 * lambd * w - np.dot(x_i, t[idx])) b -= learning_rate * t[idx] return w, bw, b = gradient_descent(X, y)def predict(X, w, b): \"\"\" classify examples \"\"\" decision = np.dot(X, w) + b return np.sign(decision)# my implementation visualizationvisualize_svm()# convert X to DataFrame to easily copy codeX = pd.DataFrame(data=X, columns= [\"x1\", \"x2\"])# fit the model with hard margin (Large C parameter)svc = LinearSVC(loss=\"hinge\", C=1000)svc.fit(X, y)# sklearn implementation visualizationplot_svm()"
},
{
"code": null,
"e": 8964,
"s": 8852,
"text": "Very good Linear classifier because it finds the best decision boundary (In a Hard Margin Classification sense)"
},
{
"code": null,
"e": 9006,
"s": 8964,
"text": "Easy to transform into a non-linear model"
},
{
"code": null,
"e": 9036,
"s": 9006,
"text": "Not suited for large datasets"
},
{
"code": null,
"e": 9424,
"s": 9036,
"text": "The SVM is quite a tricky algorithm to code and is a good reminder as to why we should be grateful for Machine Learning libraries that allow us to implement them with few lines of code. In this post I did not go into the full detail of SVMs and there are still quite a few gaps that you may want to read up on such as computing the support vector machine and empirical risk minimization."
},
{
"code": null,
"e": 9502,
"s": 9424,
"text": "Additionally, it may be worth watch Andrew Ng’s lectures on SVMs — Click Here"
}
] |
Program to copy the contents of one array into another in the reverse order - GeeksforGeeks | 21 May, 2021
Given an array, the task is to copy these array elements into another array in reverse array.Examples:
Input: array: 1 2 3 4 5
Output: 5 4 3 2 1
Input: array: 10 20 30 40 50
Output: 50 40 30 20 10
Let len be the length of original array. We copy every element original_arr[i] to copy_arr[n-i-1] to get reverse in copy_arr[].
C++
Java
Python3
C#
PHP
Javascript
// C program to copy the contents// of one array into another// in the reverse order #include <stdio.h> // Function to print the arrayvoid printArray(int arr[], int len){ int i; for (i = 0; i < len; i++) { printf("%d ", arr[i]); }} // Driver codeint main(){ int original_arr[] = {1, 2, 3, 4, 5}; int len = sizeof(original_arr)/sizeof(original_arr[0]); int copied_arr[len], i, j; // Copy the elements of the array // in the copied_arr in Reverse Order for (i = 0; i < len; i++) { copied_arr[i] = original_arr[len - i - 1]; } // Print the original_arr printf("\nOriginal array: "); printArray(original_arr, len); // Print the copied array printf("\nResultant array: "); printArray(copied_arr, len); return 0;}
// Java program to copy the contents// of one array into another// in the reverse orderclass GFG { // Function to print the arraystatic void printArray(int arr[], int len){ int i; for (i = 0; i < len; i++) { System.out.printf("%d ", arr[i]); }} // Driver codepublic static void main(String[] args){ int original_arr[] = {1, 2, 3, 4, 5}; int len = original_arr.length; int copied_arr[] = new int[len], i, j; // Copy the elements of the array // in the copied_arr in Reverse Order for (i = 0; i < len; i++) { copied_arr[i] = original_arr[len - i - 1]; } // Print the original_arr System.out.printf("\nOriginal array: "); printArray(original_arr, len); // Print the copied array System.out.printf("\nResultant array: "); printArray(copied_arr, len); }} // This code is contributed by// PrinciRaj1992
# Python3 program to copy the contents of one# array into another in the reverse orderimport math as mt # Function to print the arraydef printArray(arr, Len): for i in range(Len): print(arr[i], end = " ") # Driver codeoriginal_arr = [1, 2, 3, 4, 5]Len = len(original_arr) copied_arr = [0 for i in range(Len)] # Copy the elements of the array# in the copied_arr in Reverse Orderfor i in range(Len): copied_arr[i] = original_arr[Len - i - 1] # Print the original_arrprint("Original array: ", end = "")printArray(original_arr, Len) # Print the copied arrayprint("\nResultant array: ", end = "")printArray(copied_arr, Len) # This code is contributed by# Mohit kumar 29
// C# program to copy the contents// of one array into another// in the reverse orderusing System;class GFG{ // Function to print the arraystatic void printArray(int []arr, int len){ int i; for (i = 0; i < len; i++) { Console.Write(arr[i]); }} // Driver codepublic static void Main(){ int []original_arr = {1, 2, 3, 4, 5}; int len = original_arr.Length; int []copied_arr = new int[len]; int i; // Copy the elements of the array // in the copied_arr in Reverse Order for (i = 0; i < len; i++) { copied_arr[i] = original_arr[len - i - 1]; } // Print the original_arr Console.Write("\nOriginal array: "); printArray(original_arr, len); // Print the copied array Console.Write("\nResultant array: "); printArray(copied_arr, len); }} // This code is contributed by Rajput-Ji
<?php// PHP program to copy the contents// of one array into another// in the reverse order // Function to print the arrayfunction printArray($arr, $len){ for ($i = 0; $i < $len; $i++) { echo $arr[$i], " "; }} // Driver code$original_arr = array(1, 2, 3, 4, 5);$len = sizeof($original_arr); $copied_arr = array(); // Copy the elements of the array// in the copied_arr in Reverse Orderfor ($i = 0; $i < $len; $i++){ $copied_arr[$i] = $original_arr[$len - $i - 1];} // Print the original_arrecho "Original array: ";printArray($original_arr, $len); // Print the copied arrayecho "\nResultant array: ";printArray($copied_arr, $len); // This code is contributed by Ryuga?>
<script> // JavaScript program to copy the contents// of one array into another// in the reverse order // Function to print the arrayfunction printArray(arr, len){ var i; for (i = 0; i < len; i++) { document.write( arr[i] + " "); }} // Driver codevar original_arr = [1, 2, 3, 4, 5];var len = original_arr.length;var copied_arr = Array(len), i, j; // Copy the elements of the array// in the copied_arr in Reverse Orderfor (i = 0; i < len; i++) { copied_arr[i] = original_arr[len - i - 1];}// Print the original_arrdocument.write("Original array: ");printArray(original_arr, len); // Print the copied arraydocument.write("<br>Resultant array: ");printArray(copied_arr, len); </script>
Original array: 1 2 3 4 5
Resultant array: 5 4 3 2 1
Time Complexity: O(len)
Auxiliary Space: O(len)
princiraj1992
mohit kumar 29
Rajput-Ji
ankthon
nidhi_biet
subhammahato348
famously
Arrays
Reverse
C Language
C Programs
Arrays
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Exception Handling in C++
TCP Server-Client implementation in C
'this' pointer in C++
Input-output system calls in C | Create, Open, Close, Read, Write
Multithreading in C
Strings in C
UDP Server-Client implementation in C
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++? | [
{
"code": null,
"e": 24153,
"s": 24125,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 24257,
"s": 24153,
"text": "Given an array, the task is to copy these array elements into another array in reverse array.Examples: "
},
{
"code": null,
"e": 24357,
"s": 24257,
"text": "Input: array: 1 2 3 4 5 \nOutput: 5 4 3 2 1 \n\nInput: array: 10 20 30 40 50 \nOutput: 50 40 30 20 10 "
},
{
"code": null,
"e": 24486,
"s": 24357,
"text": "Let len be the length of original array. We copy every element original_arr[i] to copy_arr[n-i-1] to get reverse in copy_arr[]. "
},
{
"code": null,
"e": 24490,
"s": 24486,
"text": "C++"
},
{
"code": null,
"e": 24495,
"s": 24490,
"text": "Java"
},
{
"code": null,
"e": 24503,
"s": 24495,
"text": "Python3"
},
{
"code": null,
"e": 24506,
"s": 24503,
"text": "C#"
},
{
"code": null,
"e": 24510,
"s": 24506,
"text": "PHP"
},
{
"code": null,
"e": 24521,
"s": 24510,
"text": "Javascript"
},
{
"code": "// C program to copy the contents// of one array into another// in the reverse order #include <stdio.h> // Function to print the arrayvoid printArray(int arr[], int len){ int i; for (i = 0; i < len; i++) { printf(\"%d \", arr[i]); }} // Driver codeint main(){ int original_arr[] = {1, 2, 3, 4, 5}; int len = sizeof(original_arr)/sizeof(original_arr[0]); int copied_arr[len], i, j; // Copy the elements of the array // in the copied_arr in Reverse Order for (i = 0; i < len; i++) { copied_arr[i] = original_arr[len - i - 1]; } // Print the original_arr printf(\"\\nOriginal array: \"); printArray(original_arr, len); // Print the copied array printf(\"\\nResultant array: \"); printArray(copied_arr, len); return 0;}",
"e": 25302,
"s": 24521,
"text": null
},
{
"code": "// Java program to copy the contents// of one array into another// in the reverse orderclass GFG { // Function to print the arraystatic void printArray(int arr[], int len){ int i; for (i = 0; i < len; i++) { System.out.printf(\"%d \", arr[i]); }} // Driver codepublic static void main(String[] args){ int original_arr[] = {1, 2, 3, 4, 5}; int len = original_arr.length; int copied_arr[] = new int[len], i, j; // Copy the elements of the array // in the copied_arr in Reverse Order for (i = 0; i < len; i++) { copied_arr[i] = original_arr[len - i - 1]; } // Print the original_arr System.out.printf(\"\\nOriginal array: \"); printArray(original_arr, len); // Print the copied array System.out.printf(\"\\nResultant array: \"); printArray(copied_arr, len); }} // This code is contributed by// PrinciRaj1992",
"e": 26177,
"s": 25302,
"text": null
},
{
"code": "# Python3 program to copy the contents of one# array into another in the reverse orderimport math as mt # Function to print the arraydef printArray(arr, Len): for i in range(Len): print(arr[i], end = \" \") # Driver codeoriginal_arr = [1, 2, 3, 4, 5]Len = len(original_arr) copied_arr = [0 for i in range(Len)] # Copy the elements of the array# in the copied_arr in Reverse Orderfor i in range(Len): copied_arr[i] = original_arr[Len - i - 1] # Print the original_arrprint(\"Original array: \", end = \"\")printArray(original_arr, Len) # Print the copied arrayprint(\"\\nResultant array: \", end = \"\")printArray(copied_arr, Len) # This code is contributed by# Mohit kumar 29",
"e": 26860,
"s": 26177,
"text": null
},
{
"code": "// C# program to copy the contents// of one array into another// in the reverse orderusing System;class GFG{ // Function to print the arraystatic void printArray(int []arr, int len){ int i; for (i = 0; i < len; i++) { Console.Write(arr[i]); }} // Driver codepublic static void Main(){ int []original_arr = {1, 2, 3, 4, 5}; int len = original_arr.Length; int []copied_arr = new int[len]; int i; // Copy the elements of the array // in the copied_arr in Reverse Order for (i = 0; i < len; i++) { copied_arr[i] = original_arr[len - i - 1]; } // Print the original_arr Console.Write(\"\\nOriginal array: \"); printArray(original_arr, len); // Print the copied array Console.Write(\"\\nResultant array: \"); printArray(copied_arr, len); }} // This code is contributed by Rajput-Ji",
"e": 27711,
"s": 26860,
"text": null
},
{
"code": "<?php// PHP program to copy the contents// of one array into another// in the reverse order // Function to print the arrayfunction printArray($arr, $len){ for ($i = 0; $i < $len; $i++) { echo $arr[$i], \" \"; }} // Driver code$original_arr = array(1, 2, 3, 4, 5);$len = sizeof($original_arr); $copied_arr = array(); // Copy the elements of the array// in the copied_arr in Reverse Orderfor ($i = 0; $i < $len; $i++){ $copied_arr[$i] = $original_arr[$len - $i - 1];} // Print the original_arrecho \"Original array: \";printArray($original_arr, $len); // Print the copied arrayecho \"\\nResultant array: \";printArray($copied_arr, $len); // This code is contributed by Ryuga?>",
"e": 28398,
"s": 27711,
"text": null
},
{
"code": "<script> // JavaScript program to copy the contents// of one array into another// in the reverse order // Function to print the arrayfunction printArray(arr, len){ var i; for (i = 0; i < len; i++) { document.write( arr[i] + \" \"); }} // Driver codevar original_arr = [1, 2, 3, 4, 5];var len = original_arr.length;var copied_arr = Array(len), i, j; // Copy the elements of the array// in the copied_arr in Reverse Orderfor (i = 0; i < len; i++) { copied_arr[i] = original_arr[len - i - 1];}// Print the original_arrdocument.write(\"Original array: \");printArray(original_arr, len); // Print the copied arraydocument.write(\"<br>Resultant array: \");printArray(copied_arr, len); </script>",
"e": 29101,
"s": 28398,
"text": null
},
{
"code": null,
"e": 29155,
"s": 29101,
"text": "Original array: 1 2 3 4 5 \nResultant array: 5 4 3 2 1"
},
{
"code": null,
"e": 29181,
"s": 29157,
"text": "Time Complexity: O(len)"
},
{
"code": null,
"e": 29205,
"s": 29181,
"text": "Auxiliary Space: O(len)"
},
{
"code": null,
"e": 29219,
"s": 29205,
"text": "princiraj1992"
},
{
"code": null,
"e": 29234,
"s": 29219,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 29244,
"s": 29234,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 29252,
"s": 29244,
"text": "ankthon"
},
{
"code": null,
"e": 29263,
"s": 29252,
"text": "nidhi_biet"
},
{
"code": null,
"e": 29279,
"s": 29263,
"text": "subhammahato348"
},
{
"code": null,
"e": 29288,
"s": 29279,
"text": "famously"
},
{
"code": null,
"e": 29295,
"s": 29288,
"text": "Arrays"
},
{
"code": null,
"e": 29303,
"s": 29295,
"text": "Reverse"
},
{
"code": null,
"e": 29314,
"s": 29303,
"text": "C Language"
},
{
"code": null,
"e": 29325,
"s": 29314,
"text": "C Programs"
},
{
"code": null,
"e": 29332,
"s": 29325,
"text": "Arrays"
},
{
"code": null,
"e": 29340,
"s": 29332,
"text": "Reverse"
},
{
"code": null,
"e": 29438,
"s": 29340,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29447,
"s": 29438,
"text": "Comments"
},
{
"code": null,
"e": 29460,
"s": 29447,
"text": "Old Comments"
},
{
"code": null,
"e": 29486,
"s": 29460,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 29524,
"s": 29486,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 29546,
"s": 29524,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 29612,
"s": 29546,
"text": "Input-output system calls in C | Create, Open, Close, Read, Write"
},
{
"code": null,
"e": 29632,
"s": 29612,
"text": "Multithreading in C"
},
{
"code": null,
"e": 29645,
"s": 29632,
"text": "Strings in C"
},
{
"code": null,
"e": 29683,
"s": 29645,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 29724,
"s": 29683,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29759,
"s": 29724,
"text": "Header files in C/C++ and its uses"
}
] |
Python | Check order of character in string using OrderedDict( ) - GeeksforGeeks | 23 Nov, 2020
Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern.
Examples:
Input:
string = "engineers rock"
pattern = "er";
Output: true
Explanation:
All 'e' in the input string are before all 'r'.
Input:
string = "engineers rock"
pattern = "egr";
Output: false
Explanation:
There are two 'e' after 'g' in the input string.
Input:
string = "engineers rock"
pattern = "gsr";
Output: false
Explanation:
There are one 'r' before 's' in the input string.
We have existing solution for this problem, please refer Check if string follows order of characters defined by a pattern or not | Set 1. Here we solve this problem quickly in python using OrderedDict(). Approach is very simple,
Create an OrderedDict of input string which contains characters of input strings as Key only.
Now set a pointer at the start of pattern string.
Now traverse generated OrderedDict and match keys with individual character of pattern string, if key and character matches with each other then increment pointer by 1.
If pointer of pattern reaches it’s end that means string follows order of characters defined by a pattern otherwise not.
# Function to check if string follows order of # characters defined by a pattern from collections import OrderedDict def checkOrder(input, pattern): # create empty OrderedDict # output will be like {'a': None,'b': None, 'c': None} dict = OrderedDict.fromkeys(input) # traverse generated OrderedDict parallel with # pattern string to check if order of characters # are same or not ptrlen = 0 for key,value in dict.items(): if (key == pattern[ptrlen]): ptrlen = ptrlen + 1 # check if we have traverse complete # pattern string if (ptrlen == (len(pattern))): return 'true' # if we come out from for loop that means # order was mismatched return 'false' # Driver program if __name__ == "__main__": input = 'engineers rock' pattern = 'egr' print (checkOrder(input,pattern))
Output:
true
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
python-dict
Python
Strings
python-dict
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Reverse a string in Java
Write a program to reverse an array or string
C++ Data Types
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string | [
{
"code": null,
"e": 25076,
"s": 25048,
"text": "\n23 Nov, 2020"
},
{
"code": null,
"e": 25291,
"s": 25076,
"text": "Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern."
},
{
"code": null,
"e": 25301,
"s": 25291,
"text": "Examples:"
},
{
"code": null,
"e": 25685,
"s": 25301,
"text": "Input: \nstring = \"engineers rock\"\npattern = \"er\";\nOutput: true\nExplanation: \nAll 'e' in the input string are before all 'r'.\n\nInput: \nstring = \"engineers rock\"\npattern = \"egr\";\nOutput: false\nExplanation: \nThere are two 'e' after 'g' in the input string.\n\nInput: \nstring = \"engineers rock\"\npattern = \"gsr\";\nOutput: false\nExplanation:\nThere are one 'r' before 's' in the input string.\n"
},
{
"code": null,
"e": 25914,
"s": 25685,
"text": "We have existing solution for this problem, please refer Check if string follows order of characters defined by a pattern or not | Set 1. Here we solve this problem quickly in python using OrderedDict(). Approach is very simple,"
},
{
"code": null,
"e": 26008,
"s": 25914,
"text": "Create an OrderedDict of input string which contains characters of input strings as Key only."
},
{
"code": null,
"e": 26058,
"s": 26008,
"text": "Now set a pointer at the start of pattern string."
},
{
"code": null,
"e": 26227,
"s": 26058,
"text": "Now traverse generated OrderedDict and match keys with individual character of pattern string, if key and character matches with each other then increment pointer by 1."
},
{
"code": null,
"e": 26348,
"s": 26227,
"text": "If pointer of pattern reaches it’s end that means string follows order of characters defined by a pattern otherwise not."
},
{
"code": "# Function to check if string follows order of # characters defined by a pattern from collections import OrderedDict def checkOrder(input, pattern): # create empty OrderedDict # output will be like {'a': None,'b': None, 'c': None} dict = OrderedDict.fromkeys(input) # traverse generated OrderedDict parallel with # pattern string to check if order of characters # are same or not ptrlen = 0 for key,value in dict.items(): if (key == pattern[ptrlen]): ptrlen = ptrlen + 1 # check if we have traverse complete # pattern string if (ptrlen == (len(pattern))): return 'true' # if we come out from for loop that means # order was mismatched return 'false' # Driver program if __name__ == \"__main__\": input = 'engineers rock' pattern = 'egr' print (checkOrder(input,pattern)) ",
"e": 27248,
"s": 26348,
"text": null
},
{
"code": null,
"e": 27256,
"s": 27248,
"text": "Output:"
},
{
"code": null,
"e": 27262,
"s": 27256,
"text": "true\n"
},
{
"code": null,
"e": 27573,
"s": 27262,
"text": "This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27698,
"s": 27573,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27710,
"s": 27698,
"text": "python-dict"
},
{
"code": null,
"e": 27717,
"s": 27710,
"text": "Python"
},
{
"code": null,
"e": 27725,
"s": 27717,
"text": "Strings"
},
{
"code": null,
"e": 27737,
"s": 27725,
"text": "python-dict"
},
{
"code": null,
"e": 27745,
"s": 27737,
"text": "Strings"
},
{
"code": null,
"e": 27843,
"s": 27745,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27852,
"s": 27843,
"text": "Comments"
},
{
"code": null,
"e": 27865,
"s": 27852,
"text": "Old Comments"
},
{
"code": null,
"e": 27883,
"s": 27865,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27915,
"s": 27883,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27950,
"s": 27915,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27972,
"s": 27950,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28002,
"s": 27972,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28027,
"s": 28002,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 28073,
"s": 28027,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 28088,
"s": 28073,
"text": "C++ Data Types"
},
{
"code": null,
"e": 28122,
"s": 28088,
"text": "Longest Common Subsequence | DP-4"
}
] |
Implementing Shamir's Secret Sharing Scheme in Python - GeeksforGeeks | 12 Mar, 2021
Secret Sharing schemes are used in the distribution of a secret value among multiple participants (shareholders) by dividing the secret into fragments (shares). This is done in a manner that prevents a single shareholder from having any useful knowledge of the original secret at all. The only way to retrieve the original secret is to combine the shares, distributed among the participants. Hence, the control of the secret is distributed. These schemes are examples of Threshold Cryptosystems, which involve the division of secrets among multiple parties such that several parties (more than some threshold number) must cooperate to reconstruct the secret.
Fig 1: Depiction of Secret Sharing between n participants
In general, a secret may be split into n shares (for n shareholders), out of which, a minimum of t, (t < n) shares are required for successful reconstruction. Such a scheme is referred to as a (t, n) sharing-scheme. From the n participants, any subset of shareholders, of size greater or equal to t, can regenerate the secret. Importantly, even with any k (k < t) shares, no new information about the original secret is learned.
Shamir Secret Sharing (SSS) is one of the most popular implementations of a secret sharing scheme created by Adi Shamir, a famous Israeli cryptographer, who also contributed to the invention of RSA algorithm. SSS allows the secret to be divided into an arbitrary number of shares and allows an arbitrary threshold (as long as it is less than the total participants). SSS is based on the mathematical concept of polynomial interpolation which states that a polynomial of degree t-1 can be reconstructed from the knowledge of t or more points, known to be lying on the curve.For instance, to reconstruct a curve of degree 1 (a straight line), we require at least 2 points that lie on the line. Conversely, it is mathematically infeasible to reconstruct a curve if the number of unique points available is less than (degree-of-curve + 1). One can imagine having infinite possible straight lines that could be formed as a result of just one point in 2D space.
The concept of polynomial interpolation can be applied to produce a secret sharing scheme by embedding the secret into the polynomial. A general polynomial of degree p can be expressed as follows:
In the expression of P(x), the values a_{1}, a_{2}, a_{3}, ..., a_{n} represent the coefficients of the polynomial. Thus, construction of a polynomial requires the selection of these coefficients. Note that no values are actually substituted in for x; every term in the polynomial acts as a “placeholder” to store the coefficient values. Once the polynomial is generated, we can essentially represent the curve by just p+1 points that lie on the curve. This follows from the polynomial interpolation principle. For example, a curve of degree 4 can be reconstructed if we have access to at least 5 unique points lying on it. To do this, we can run Lagrange’s interpolation or any other similar interpolation mechanism.
Fig 2: Example of using Polynomial Interpolation to reconstruct a curve
Consequently, if we conceal the secret value into such a polynomial and use various points on the curve as shares, we arrive at a secret sharing scheme. More precisely, to establish a (t, n) secret sharing scheme, we can construct a polynomial of degree t-1 and pick n points on the curve as shares such that the polynomial will only be regenerated if t or more shares are pooled. The secret value (s) is concealed in the constant term of the polynomial (coefficient of 0-degree term or the curve’s y-intercept) which can only be obtained after the successful reconstruction of the curve.
Shamir’s Secret Sharing uses the polynomial interpolation principle to perform threshold sharing in the following two phases: Phase I: Generation of Shares This phase involves the setup of the system as well as the generation of the shares.
Decide the values for the number of participants (n) and the threshold (t) to secure some secret value (s)Construct a random polynomial, P(x), with degree t-1 by choosing random coefficients of the polynomial. Set the constant term in the polynomial (coefficient of zero degree term) to be equal to the secret value sTo generate the n shares, randomly pick n points lying on the polynomial P(x)Distribute the picked coordinates in the previous step among the participants. These act as the shares in the system
Decide the values for the number of participants (n) and the threshold (t) to secure some secret value (s)
Construct a random polynomial, P(x), with degree t-1 by choosing random coefficients of the polynomial. Set the constant term in the polynomial (coefficient of zero degree term) to be equal to the secret value s
To generate the n shares, randomly pick n points lying on the polynomial P(x)
Distribute the picked coordinates in the previous step among the participants. These act as the shares in the system
Phase II: Reconstruction of Secret For reconstruction of the secret, a minimum of t participants are required to pool their shares.
Collect t or more sharesUse an interpolation algorithm to reconstruct the polynomial, P'(x), from the shares. Lagrange’s Interpolation is an example of such an algorithmDetermine the value of the reconstructed polynomial for x = 0, i.e. calculate P'(0). This value reveals the constant term of the polynomial which happens to be the original secret. Thus, the secret is reconstructed
Collect t or more shares
Use an interpolation algorithm to reconstruct the polynomial, P'(x), from the shares. Lagrange’s Interpolation is an example of such an algorithm
Determine the value of the reconstructed polynomial for x = 0, i.e. calculate P'(0). This value reveals the constant term of the polynomial which happens to be the original secret. Thus, the secret is reconstructed
Below is the implementation.
Python3
import randomfrom math import ceilfrom decimal import Decimal FIELD_SIZE = 10**5 def reconstruct_secret(shares): """ Combines individual shares (points on graph) using Lagranges interpolation. `shares` is a list of points (x, y) belonging to a polynomial with a constant of our key. """ sums = 0 prod_arr = [] for j, share_j in enumerate(shares): xj, yj = share_j prod = Decimal(1) for i, share_i in enumerate(shares): xi, _ = share_i if i != j: prod *= Decimal(Decimal(xi)/(xi-xj)) prod *= yj sums += Decimal(prod) return int(round(Decimal(sums), 0)) def polynom(x, coefficients): """ This generates a single point on the graph of given polynomial in `x`. The polynomial is given by the list of `coefficients`. """ point = 0 # Loop through reversed list, so that indices from enumerate match the # actual coefficient indices for coefficient_index, coefficient_value in enumerate(coefficients[::-1]): point += x ** coefficient_index * coefficient_value return point def coeff(t, secret): """ Randomly generate a list of coefficients for a polynomial with degree of `t` - 1, whose constant is `secret`. For example with a 3rd degree coefficient like this: 3x^3 + 4x^2 + 18x + 554 554 is the secret, and the polynomial degree + 1 is how many points are needed to recover this secret. (in this case it's 4 points). """ coeff = [random.randrange(0, FIELD_SIZE) for _ in range(t - 1)] coeff.append(secret) return coeff def generate_shares(n, m, secret): """ Split given `secret` into `n` shares with minimum threshold of `m` shares to recover this `secret`, using SSS algorithm. """ coefficients = coeff(m, secret) shares = [] for i in range(1, n+1): x = random.randrange(1, FIELD_SIZE) shares.append((x, polynom(x, coefficients))) return shares # Driver codeif __name__ == '__main__': # (3,5) sharing scheme t, n = 3, 5 secret = 1234 print(f'Original Secret: {secret}') # Phase I: Generation of shares shares = generate_shares(n, t, secret) print(f'Shares: {", ".join(str(share) for share in shares)}') # Phase II: Secret Reconstruction # Picking t shares randomly for # reconstruction pool = random.sample(shares, t) print(f'Combining shares: {", ".join(str(share) for share in pool)}') print(f'Reconstructed secret: {reconstruct_secret(pool)}')
Output:
Original Secret: 1234
Shares: (79761, 4753361900938), (67842, 3439017561016), (42323, 1338629004828), (68237, 3479175081966), (32818, 804981007208)
Combining shares: (32818, 804981007208), (79761, 4753361900938), (68237, 3479175081966)
Reconstructed secret: 1234
Secret sharing schemes are widely used in cryptosystems where trust is required to be distributed instead of centralized. Prominent examples of real world scenarios where secret sharing is used include:
Threshold Based Signatures for Bitcoin
Secure Multi-Party Computation
Private Machine Learning with Multi Party Computation
Management of Passwords
billywu31415926
itsdrikeofficial
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25815,
"s": 25787,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 26476,
"s": 25815,
"text": "Secret Sharing schemes are used in the distribution of a secret value among multiple participants (shareholders) by dividing the secret into fragments (shares). This is done in a manner that prevents a single shareholder from having any useful knowledge of the original secret at all. The only way to retrieve the original secret is to combine the shares, distributed among the participants. Hence, the control of the secret is distributed. These schemes are examples of Threshold Cryptosystems, which involve the division of secrets among multiple parties such that several parties (more than some threshold number) must cooperate to reconstruct the secret. "
},
{
"code": null,
"e": 26534,
"s": 26476,
"text": "Fig 1: Depiction of Secret Sharing between n participants"
},
{
"code": null,
"e": 26965,
"s": 26534,
"text": "In general, a secret may be split into n shares (for n shareholders), out of which, a minimum of t, (t < n) shares are required for successful reconstruction. Such a scheme is referred to as a (t, n) sharing-scheme. From the n participants, any subset of shareholders, of size greater or equal to t, can regenerate the secret. Importantly, even with any k (k < t) shares, no new information about the original secret is learned. "
},
{
"code": null,
"e": 27923,
"s": 26965,
"text": "Shamir Secret Sharing (SSS) is one of the most popular implementations of a secret sharing scheme created by Adi Shamir, a famous Israeli cryptographer, who also contributed to the invention of RSA algorithm. SSS allows the secret to be divided into an arbitrary number of shares and allows an arbitrary threshold (as long as it is less than the total participants). SSS is based on the mathematical concept of polynomial interpolation which states that a polynomial of degree t-1 can be reconstructed from the knowledge of t or more points, known to be lying on the curve.For instance, to reconstruct a curve of degree 1 (a straight line), we require at least 2 points that lie on the line. Conversely, it is mathematically infeasible to reconstruct a curve if the number of unique points available is less than (degree-of-curve + 1). One can imagine having infinite possible straight lines that could be formed as a result of just one point in 2D space. "
},
{
"code": null,
"e": 28121,
"s": 27923,
"text": "The concept of polynomial interpolation can be applied to produce a secret sharing scheme by embedding the secret into the polynomial. A general polynomial of degree p can be expressed as follows: "
},
{
"code": null,
"e": 28841,
"s": 28121,
"text": "In the expression of P(x), the values a_{1}, a_{2}, a_{3}, ..., a_{n} represent the coefficients of the polynomial. Thus, construction of a polynomial requires the selection of these coefficients. Note that no values are actually substituted in for x; every term in the polynomial acts as a “placeholder” to store the coefficient values. Once the polynomial is generated, we can essentially represent the curve by just p+1 points that lie on the curve. This follows from the polynomial interpolation principle. For example, a curve of degree 4 can be reconstructed if we have access to at least 5 unique points lying on it. To do this, we can run Lagrange’s interpolation or any other similar interpolation mechanism. "
},
{
"code": null,
"e": 28913,
"s": 28841,
"text": "Fig 2: Example of using Polynomial Interpolation to reconstruct a curve"
},
{
"code": null,
"e": 29503,
"s": 28913,
"text": "Consequently, if we conceal the secret value into such a polynomial and use various points on the curve as shares, we arrive at a secret sharing scheme. More precisely, to establish a (t, n) secret sharing scheme, we can construct a polynomial of degree t-1 and pick n points on the curve as shares such that the polynomial will only be regenerated if t or more shares are pooled. The secret value (s) is concealed in the constant term of the polynomial (coefficient of 0-degree term or the curve’s y-intercept) which can only be obtained after the successful reconstruction of the curve. "
},
{
"code": null,
"e": 29745,
"s": 29503,
"text": "Shamir’s Secret Sharing uses the polynomial interpolation principle to perform threshold sharing in the following two phases: Phase I: Generation of Shares This phase involves the setup of the system as well as the generation of the shares. "
},
{
"code": null,
"e": 30256,
"s": 29745,
"text": "Decide the values for the number of participants (n) and the threshold (t) to secure some secret value (s)Construct a random polynomial, P(x), with degree t-1 by choosing random coefficients of the polynomial. Set the constant term in the polynomial (coefficient of zero degree term) to be equal to the secret value sTo generate the n shares, randomly pick n points lying on the polynomial P(x)Distribute the picked coordinates in the previous step among the participants. These act as the shares in the system"
},
{
"code": null,
"e": 30363,
"s": 30256,
"text": "Decide the values for the number of participants (n) and the threshold (t) to secure some secret value (s)"
},
{
"code": null,
"e": 30575,
"s": 30363,
"text": "Construct a random polynomial, P(x), with degree t-1 by choosing random coefficients of the polynomial. Set the constant term in the polynomial (coefficient of zero degree term) to be equal to the secret value s"
},
{
"code": null,
"e": 30653,
"s": 30575,
"text": "To generate the n shares, randomly pick n points lying on the polynomial P(x)"
},
{
"code": null,
"e": 30770,
"s": 30653,
"text": "Distribute the picked coordinates in the previous step among the participants. These act as the shares in the system"
},
{
"code": null,
"e": 30904,
"s": 30770,
"text": "Phase II: Reconstruction of Secret For reconstruction of the secret, a minimum of t participants are required to pool their shares. "
},
{
"code": null,
"e": 31288,
"s": 30904,
"text": "Collect t or more sharesUse an interpolation algorithm to reconstruct the polynomial, P'(x), from the shares. Lagrange’s Interpolation is an example of such an algorithmDetermine the value of the reconstructed polynomial for x = 0, i.e. calculate P'(0). This value reveals the constant term of the polynomial which happens to be the original secret. Thus, the secret is reconstructed"
},
{
"code": null,
"e": 31313,
"s": 31288,
"text": "Collect t or more shares"
},
{
"code": null,
"e": 31459,
"s": 31313,
"text": "Use an interpolation algorithm to reconstruct the polynomial, P'(x), from the shares. Lagrange’s Interpolation is an example of such an algorithm"
},
{
"code": null,
"e": 31674,
"s": 31459,
"text": "Determine the value of the reconstructed polynomial for x = 0, i.e. calculate P'(0). This value reveals the constant term of the polynomial which happens to be the original secret. Thus, the secret is reconstructed"
},
{
"code": null,
"e": 31704,
"s": 31674,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 31712,
"s": 31704,
"text": "Python3"
},
{
"code": "import randomfrom math import ceilfrom decimal import Decimal FIELD_SIZE = 10**5 def reconstruct_secret(shares): \"\"\" Combines individual shares (points on graph) using Lagranges interpolation. `shares` is a list of points (x, y) belonging to a polynomial with a constant of our key. \"\"\" sums = 0 prod_arr = [] for j, share_j in enumerate(shares): xj, yj = share_j prod = Decimal(1) for i, share_i in enumerate(shares): xi, _ = share_i if i != j: prod *= Decimal(Decimal(xi)/(xi-xj)) prod *= yj sums += Decimal(prod) return int(round(Decimal(sums), 0)) def polynom(x, coefficients): \"\"\" This generates a single point on the graph of given polynomial in `x`. The polynomial is given by the list of `coefficients`. \"\"\" point = 0 # Loop through reversed list, so that indices from enumerate match the # actual coefficient indices for coefficient_index, coefficient_value in enumerate(coefficients[::-1]): point += x ** coefficient_index * coefficient_value return point def coeff(t, secret): \"\"\" Randomly generate a list of coefficients for a polynomial with degree of `t` - 1, whose constant is `secret`. For example with a 3rd degree coefficient like this: 3x^3 + 4x^2 + 18x + 554 554 is the secret, and the polynomial degree + 1 is how many points are needed to recover this secret. (in this case it's 4 points). \"\"\" coeff = [random.randrange(0, FIELD_SIZE) for _ in range(t - 1)] coeff.append(secret) return coeff def generate_shares(n, m, secret): \"\"\" Split given `secret` into `n` shares with minimum threshold of `m` shares to recover this `secret`, using SSS algorithm. \"\"\" coefficients = coeff(m, secret) shares = [] for i in range(1, n+1): x = random.randrange(1, FIELD_SIZE) shares.append((x, polynom(x, coefficients))) return shares # Driver codeif __name__ == '__main__': # (3,5) sharing scheme t, n = 3, 5 secret = 1234 print(f'Original Secret: {secret}') # Phase I: Generation of shares shares = generate_shares(n, t, secret) print(f'Shares: {\", \".join(str(share) for share in shares)}') # Phase II: Secret Reconstruction # Picking t shares randomly for # reconstruction pool = random.sample(shares, t) print(f'Combining shares: {\", \".join(str(share) for share in pool)}') print(f'Reconstructed secret: {reconstruct_secret(pool)}')",
"e": 34237,
"s": 31712,
"text": null
},
{
"code": null,
"e": 34246,
"s": 34237,
"text": "Output: "
},
{
"code": null,
"e": 34509,
"s": 34246,
"text": "Original Secret: 1234\nShares: (79761, 4753361900938), (67842, 3439017561016), (42323, 1338629004828), (68237, 3479175081966), (32818, 804981007208)\nCombining shares: (32818, 804981007208), (79761, 4753361900938), (68237, 3479175081966)\nReconstructed secret: 1234"
},
{
"code": null,
"e": 34713,
"s": 34509,
"text": "Secret sharing schemes are widely used in cryptosystems where trust is required to be distributed instead of centralized. Prominent examples of real world scenarios where secret sharing is used include: "
},
{
"code": null,
"e": 34752,
"s": 34713,
"text": "Threshold Based Signatures for Bitcoin"
},
{
"code": null,
"e": 34783,
"s": 34752,
"text": "Secure Multi-Party Computation"
},
{
"code": null,
"e": 34837,
"s": 34783,
"text": "Private Machine Learning with Multi Party Computation"
},
{
"code": null,
"e": 34861,
"s": 34837,
"text": "Management of Passwords"
},
{
"code": null,
"e": 34877,
"s": 34861,
"text": "billywu31415926"
},
{
"code": null,
"e": 34894,
"s": 34877,
"text": "itsdrikeofficial"
},
{
"code": null,
"e": 34909,
"s": 34894,
"text": "python-utility"
},
{
"code": null,
"e": 34916,
"s": 34909,
"text": "Python"
},
{
"code": null,
"e": 35014,
"s": 34916,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35032,
"s": 35014,
"text": "Python Dictionary"
},
{
"code": null,
"e": 35067,
"s": 35032,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 35099,
"s": 35067,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 35121,
"s": 35099,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 35163,
"s": 35121,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 35193,
"s": 35163,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 35219,
"s": 35193,
"text": "Python String | replace()"
},
{
"code": null,
"e": 35248,
"s": 35219,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 35292,
"s": 35248,
"text": "Reading and Writing to text files in Python"
}
] |
Merge K sorted arrays of different sizes | ( Divide and Conquer Approach ) - GeeksforGeeks | 10 Nov, 2021
Given k sorted arrays of different length, merge them into a single array such that the merged array is also sorted.Examples:
Input : {{3, 13},
{8, 10, 11}
{9, 15}}
Output : {3, 8, 9, 10, 11, 13, 15}
Input : {{1, 5},
{2, 3, 4}}
Output : {1, 2, 3, 4, 5}
Let S be the total number of elements in all the arrays.Simple Approach: A simple approach is to append the arrays one after another and sort them. Time complexity in this case will be O( S * log(S)).Efficient Approach: An efficient solution will be to take pairs of arrays at each step. Then merge the pairs using the two pointer technique of merging two sorted arrays. Thus, after merging all the pairs, the number of arrays will reduce by half. We, will continue this till the number of remaining arrays doesn’t become 1. Thus, the number of steps required will be of the order log(k) and since at each step, we are taking O(S) time to perform the merge operations, the total time complexity of this approach becomes O(S * log(k)).We already have discussed this approach for merging K sorted arrays of same sizes.Since in this problem the arrays are of different sizes, we will use dynamic arrays ( eg: vector in case of C++ or arraylist in case of Java ) because they reduce the number of lines and work load significantly.Below is the implementation of the above approach:
C++
Python3
Javascript
// C++ program to merge K sorted arrays of// different arrays #include <iostream>#include <vector>using namespace std; // Function to merge two arraysvector<int> mergeTwoArrays(vector<int> l, vector<int> r){ // array to store the result // after merging l and r vector<int> ret; // variables to store the current // pointers for l and r int l_in = 0, r_in = 0; // loop to merge l and r using two pointer while (l_in + r_in < l.size() + r.size()) { if (l_in != l.size() && (r_in == r.size() || l[l_in] < r[r_in])) { ret.push_back(l[l_in]); l_in++; } else { ret.push_back(r[r_in]); r_in++; } } return ret;} // Function to merge all the arraysvector<int> mergeArrays(vector<vector<int> > arr){ // 2D-array to store the results of // a step temporarily vector<vector<int> > arr_s; // Loop to make pairs of arrays and merge them while (arr.size() != 1) { // To clear the data of previous steps arr_s.clear(); for (int i = 0; i < arr.size(); i += 2) { if (i == arr.size() - 1) arr_s.push_back(arr[i]); else arr_s.push_back(mergeTwoArrays(arr[i], arr[i + 1])); } arr = arr_s; } // Returning the required output array return arr[0];} // Driver Codeint main(){ // Input arrays vector<vector<int> > arr{ { 3, 13 }, { 8, 10, 11 }, { 9, 15 } }; // Merged sorted array vector<int> output = mergeArrays(arr); for (int i = 0; i < output.size(); i++) cout << output[i] << " "; return 0;}
# Python3 program to merge K sorted# arrays of different arrays # Function to merge two arraysdef mergeTwoArrays(l, r): # array to store the result # after merging l and r ret = [] # variables to store the current # pointers for l and r l_in, r_in = 0, 0 # loop to merge l and r using two pointer while l_in + r_in < len(l) + len(r): if (l_in != len(l) and (r_in == len(r) or l[l_in] < r[r_in])): ret.append(l[l_in]) l_in += 1 else: ret.append(r[r_in]) r_in += 1 return ret # Function to merge all the arraysdef mergeArrays(arr): # 2D-array to store the results # of a step temporarily arr_s = [] # Loop to make pairs of arrays # and merge them while len(arr) != 1: # To clear the data of previous steps arr_s[:] = [] for i in range(0, len(arr), 2): if i == len(arr) - 1: arr_s.append(arr[i]) else: arr_s.append(mergeTwoArrays(arr[i], arr[i + 1])) arr = arr_s[:] # Returning the required output array return arr[0] # Driver Codeif __name__ == "__main__": # Input arrays arr = [[3, 13], [8, 10, 11], [9, 15]] # Merged sorted array output = mergeArrays(arr) for i in range(0, len(output)): print(output[i], end = " ") # This code is contributed by Rituraj Jain
<script> // Javascript program to merge K sorted arrays of// different arrays // Function to merge two arraysfunction mergeTwoArrays(l, r){ // array to store the result // after merging l and r var ret = []; // variables to store the current // pointers for l and r var l_in = 0, r_in = 0; // loop to merge l and r using two pointer while (l_in + r_in < l.length + r.length) { if (l_in != l.length && (r_in == r.length || l[l_in] < r[r_in])) { ret.push(l[l_in]); l_in++; } else { ret.push(r[r_in]); r_in++; } } return ret;} // Function to merge all the arraysfunction mergeArrays(arr){ // 2D-array to store the results of // a step temporarily var arr_s = []; // Loop to make pairs of arrays and merge them while (arr.length != 1) { // To clear the data of previous steps arr_s = []; for (var i = 0; i < arr.length; i += 2) { if (i == arr.length - 1) arr_s.push(arr[i]); else arr_s.push(mergeTwoArrays(arr[i], arr[i + 1])); } arr = arr_s; } // Returning the required output array return arr[0];} // Driver Code// Input arraysvar arr = [ [ 3, 13 ], [ 8, 10, 11 ], [ 9, 15 ] ];// Merged sorted arrayvar output = mergeArrays(arr);for (var i = 0; i < output.length; i++) document.write(output[i] + " "); // This code is contributed by rrrtnx.</script>
3 8 9 10 11 13 15
Time Complexity: O(S*logK)Auxiliary Space: O(logK)Note that there exist a better solution using heap (or priority queue). The time complexity of the heap based solution is O(N Log k) where N is the total number of elements in all K arrays.
rituraj_jain
pankajsharmagfg
rrrtnx
Algorithms
Arrays
Competitive Programming
Divide and Conquer
Sorting
Arrays
Divide and Conquer
Sorting
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Difference between Algorithm, Pseudocode and Program
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation | [
{
"code": null,
"e": 25941,
"s": 25913,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 26069,
"s": 25941,
"text": "Given k sorted arrays of different length, merge them into a single array such that the merged array is also sorted.Examples: "
},
{
"code": null,
"e": 26224,
"s": 26069,
"text": "Input : {{3, 13}, \n {8, 10, 11}\n {9, 15}}\nOutput : {3, 8, 9, 10, 11, 13, 15}\n\nInput : {{1, 5}, \n {2, 3, 4}}\nOutput : {1, 2, 3, 4, 5}"
},
{
"code": null,
"e": 27305,
"s": 26226,
"text": "Let S be the total number of elements in all the arrays.Simple Approach: A simple approach is to append the arrays one after another and sort them. Time complexity in this case will be O( S * log(S)).Efficient Approach: An efficient solution will be to take pairs of arrays at each step. Then merge the pairs using the two pointer technique of merging two sorted arrays. Thus, after merging all the pairs, the number of arrays will reduce by half. We, will continue this till the number of remaining arrays doesn’t become 1. Thus, the number of steps required will be of the order log(k) and since at each step, we are taking O(S) time to perform the merge operations, the total time complexity of this approach becomes O(S * log(k)).We already have discussed this approach for merging K sorted arrays of same sizes.Since in this problem the arrays are of different sizes, we will use dynamic arrays ( eg: vector in case of C++ or arraylist in case of Java ) because they reduce the number of lines and work load significantly.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27309,
"s": 27305,
"text": "C++"
},
{
"code": null,
"e": 27317,
"s": 27309,
"text": "Python3"
},
{
"code": null,
"e": 27328,
"s": 27317,
"text": "Javascript"
},
{
"code": "// C++ program to merge K sorted arrays of// different arrays #include <iostream>#include <vector>using namespace std; // Function to merge two arraysvector<int> mergeTwoArrays(vector<int> l, vector<int> r){ // array to store the result // after merging l and r vector<int> ret; // variables to store the current // pointers for l and r int l_in = 0, r_in = 0; // loop to merge l and r using two pointer while (l_in + r_in < l.size() + r.size()) { if (l_in != l.size() && (r_in == r.size() || l[l_in] < r[r_in])) { ret.push_back(l[l_in]); l_in++; } else { ret.push_back(r[r_in]); r_in++; } } return ret;} // Function to merge all the arraysvector<int> mergeArrays(vector<vector<int> > arr){ // 2D-array to store the results of // a step temporarily vector<vector<int> > arr_s; // Loop to make pairs of arrays and merge them while (arr.size() != 1) { // To clear the data of previous steps arr_s.clear(); for (int i = 0; i < arr.size(); i += 2) { if (i == arr.size() - 1) arr_s.push_back(arr[i]); else arr_s.push_back(mergeTwoArrays(arr[i], arr[i + 1])); } arr = arr_s; } // Returning the required output array return arr[0];} // Driver Codeint main(){ // Input arrays vector<vector<int> > arr{ { 3, 13 }, { 8, 10, 11 }, { 9, 15 } }; // Merged sorted array vector<int> output = mergeArrays(arr); for (int i = 0; i < output.size(); i++) cout << output[i] << \" \"; return 0;}",
"e": 29053,
"s": 27328,
"text": null
},
{
"code": "# Python3 program to merge K sorted# arrays of different arrays # Function to merge two arraysdef mergeTwoArrays(l, r): # array to store the result # after merging l and r ret = [] # variables to store the current # pointers for l and r l_in, r_in = 0, 0 # loop to merge l and r using two pointer while l_in + r_in < len(l) + len(r): if (l_in != len(l) and (r_in == len(r) or l[l_in] < r[r_in])): ret.append(l[l_in]) l_in += 1 else: ret.append(r[r_in]) r_in += 1 return ret # Function to merge all the arraysdef mergeArrays(arr): # 2D-array to store the results # of a step temporarily arr_s = [] # Loop to make pairs of arrays # and merge them while len(arr) != 1: # To clear the data of previous steps arr_s[:] = [] for i in range(0, len(arr), 2): if i == len(arr) - 1: arr_s.append(arr[i]) else: arr_s.append(mergeTwoArrays(arr[i], arr[i + 1])) arr = arr_s[:] # Returning the required output array return arr[0] # Driver Codeif __name__ == \"__main__\": # Input arrays arr = [[3, 13], [8, 10, 11], [9, 15]] # Merged sorted array output = mergeArrays(arr) for i in range(0, len(output)): print(output[i], end = \" \") # This code is contributed by Rituraj Jain",
"e": 30553,
"s": 29053,
"text": null
},
{
"code": "<script> // Javascript program to merge K sorted arrays of// different arrays // Function to merge two arraysfunction mergeTwoArrays(l, r){ // array to store the result // after merging l and r var ret = []; // variables to store the current // pointers for l and r var l_in = 0, r_in = 0; // loop to merge l and r using two pointer while (l_in + r_in < l.length + r.length) { if (l_in != l.length && (r_in == r.length || l[l_in] < r[r_in])) { ret.push(l[l_in]); l_in++; } else { ret.push(r[r_in]); r_in++; } } return ret;} // Function to merge all the arraysfunction mergeArrays(arr){ // 2D-array to store the results of // a step temporarily var arr_s = []; // Loop to make pairs of arrays and merge them while (arr.length != 1) { // To clear the data of previous steps arr_s = []; for (var i = 0; i < arr.length; i += 2) { if (i == arr.length - 1) arr_s.push(arr[i]); else arr_s.push(mergeTwoArrays(arr[i], arr[i + 1])); } arr = arr_s; } // Returning the required output array return arr[0];} // Driver Code// Input arraysvar arr = [ [ 3, 13 ], [ 8, 10, 11 ], [ 9, 15 ] ];// Merged sorted arrayvar output = mergeArrays(arr);for (var i = 0; i < output.length; i++) document.write(output[i] + \" \"); // This code is contributed by rrrtnx.</script>",
"e": 32123,
"s": 30553,
"text": null
},
{
"code": null,
"e": 32141,
"s": 32123,
"text": "3 8 9 10 11 13 15"
},
{
"code": null,
"e": 32385,
"s": 32143,
"text": "Time Complexity: O(S*logK)Auxiliary Space: O(logK)Note that there exist a better solution using heap (or priority queue). The time complexity of the heap based solution is O(N Log k) where N is the total number of elements in all K arrays. "
},
{
"code": null,
"e": 32398,
"s": 32385,
"text": "rituraj_jain"
},
{
"code": null,
"e": 32414,
"s": 32398,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 32421,
"s": 32414,
"text": "rrrtnx"
},
{
"code": null,
"e": 32432,
"s": 32421,
"text": "Algorithms"
},
{
"code": null,
"e": 32439,
"s": 32432,
"text": "Arrays"
},
{
"code": null,
"e": 32463,
"s": 32439,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32482,
"s": 32463,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 32490,
"s": 32482,
"text": "Sorting"
},
{
"code": null,
"e": 32497,
"s": 32490,
"text": "Arrays"
},
{
"code": null,
"e": 32516,
"s": 32497,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 32524,
"s": 32516,
"text": "Sorting"
},
{
"code": null,
"e": 32535,
"s": 32524,
"text": "Algorithms"
},
{
"code": null,
"e": 32633,
"s": 32535,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32658,
"s": 32633,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32685,
"s": 32658,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 32738,
"s": 32685,
"text": "Difference between Algorithm, Pseudocode and Program"
},
{
"code": null,
"e": 32772,
"s": 32738,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 32839,
"s": 32772,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 32854,
"s": 32839,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32870,
"s": 32854,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 32938,
"s": 32870,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32984,
"s": 32938,
"text": "Write a program to reverse an array or string"
}
] |
BigInteger isProbablePrime() Method in Java with Examples - GeeksforGeeks | 03 Apr, 2019
The java.math.BigInteger.isProbablePrime(int certainty) method is used to tell if this BigInteger is probably prime or if it’s definitely composite. This method checks for prime or composite upon the current BigInteger by which this method is called and returns a boolean value. It returns true if this BigInteger is probably prime, false if it’s definitely composite. If certainty is <= 0, true is returned.
Syntax:
public boolean isProbablePrime(int certainty)
Parameters: This method accepts a mandatory parameter certainty which is a measure of the uncertainty that is acceptable to the user. This is due to the fact the BigInteger is a very very large number and finding exactly if it is prime is very difficult and expensive. Hence it can be said that this method checks for the prime of this BigInteger based on a threshold value (1 – 1/2certainty).
Return Value: This method returns a boolean value stating whether this BigInteger is prime or not. It returns true if this BigInteger is probably prime, false if it’s definitely composite.
Below program is used to illustrate the isProbablePrime() method of BigInteger.
Example 1:
// Java program to demonstrate// isProbablePrime() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Boolean variable to store the result boolean result; // Creates one BigInteger object BigInteger a = new BigInteger( "95848961698036841689418631330196"); // When certainty is one, // it will check number for prime or composite result = a.isProbablePrime(1); System.out.println(a.toString() + " with certainty 1 " + result); // When certainty is zero, // it is always true result = a.isProbablePrime(0); System.out.println(a.toString() + " with certainty 0 " + result); // When certainty is negative, // it is always true result = a.isProbablePrime(-1); System.out.println(a.toString() + " with certainty -1 " + result); }}
95848961698036841689418631330196 with certainty 1 false
95848961698036841689418631330196 with certainty 0 true
95848961698036841689418631330196 with certainty -1 true
Example 2:
// Java program to demonstrate// isProbablePrime() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Boolean variable to store the result boolean result; // Creates one BigInteger object BigInteger a = new BigInteger( "654561561356879113561"); // When certainty is one, // it will check number for prime or composite result = a.isProbablePrime(1); System.out.println(a.toString() + " with certainty 1 " + result); // When certainty is zero, // it is always true result = a.isProbablePrime(0); System.out.println(a.toString() + " with certainty 0 " + result); // When certainty is negative, // it is always true result = a.isProbablePrime(-1); System.out.println(a.toString() + " with certainty -1 " + result); }}
654561561356879113561 with certainty 1 false
654561561356879113561 with certainty 0 true
654561561356879113561 with certainty -1 true
Reference: https://docs.oracle.com/javase/9/docs/api/java/math/BigInteger.html#isProbablePrime(int)
Java-BigInteger
Java-Functions
Java-math-package
Java
Java-BigInteger
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java | [
{
"code": null,
"e": 25690,
"s": 25662,
"text": "\n03 Apr, 2019"
},
{
"code": null,
"e": 26099,
"s": 25690,
"text": "The java.math.BigInteger.isProbablePrime(int certainty) method is used to tell if this BigInteger is probably prime or if it’s definitely composite. This method checks for prime or composite upon the current BigInteger by which this method is called and returns a boolean value. It returns true if this BigInteger is probably prime, false if it’s definitely composite. If certainty is <= 0, true is returned."
},
{
"code": null,
"e": 26107,
"s": 26099,
"text": "Syntax:"
},
{
"code": null,
"e": 26153,
"s": 26107,
"text": "public boolean isProbablePrime(int certainty)"
},
{
"code": null,
"e": 26547,
"s": 26153,
"text": "Parameters: This method accepts a mandatory parameter certainty which is a measure of the uncertainty that is acceptable to the user. This is due to the fact the BigInteger is a very very large number and finding exactly if it is prime is very difficult and expensive. Hence it can be said that this method checks for the prime of this BigInteger based on a threshold value (1 – 1/2certainty)."
},
{
"code": null,
"e": 26736,
"s": 26547,
"text": "Return Value: This method returns a boolean value stating whether this BigInteger is prime or not. It returns true if this BigInteger is probably prime, false if it’s definitely composite."
},
{
"code": null,
"e": 26816,
"s": 26736,
"text": "Below program is used to illustrate the isProbablePrime() method of BigInteger."
},
{
"code": null,
"e": 26827,
"s": 26816,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// isProbablePrime() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Boolean variable to store the result boolean result; // Creates one BigInteger object BigInteger a = new BigInteger( \"95848961698036841689418631330196\"); // When certainty is one, // it will check number for prime or composite result = a.isProbablePrime(1); System.out.println(a.toString() + \" with certainty 1 \" + result); // When certainty is zero, // it is always true result = a.isProbablePrime(0); System.out.println(a.toString() + \" with certainty 0 \" + result); // When certainty is negative, // it is always true result = a.isProbablePrime(-1); System.out.println(a.toString() + \" with certainty -1 \" + result); }}",
"e": 27929,
"s": 26827,
"text": null
},
{
"code": null,
"e": 28097,
"s": 27929,
"text": "95848961698036841689418631330196 with certainty 1 false\n95848961698036841689418631330196 with certainty 0 true\n95848961698036841689418631330196 with certainty -1 true\n"
},
{
"code": null,
"e": 28108,
"s": 28097,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// isProbablePrime() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Boolean variable to store the result boolean result; // Creates one BigInteger object BigInteger a = new BigInteger( \"654561561356879113561\"); // When certainty is one, // it will check number for prime or composite result = a.isProbablePrime(1); System.out.println(a.toString() + \" with certainty 1 \" + result); // When certainty is zero, // it is always true result = a.isProbablePrime(0); System.out.println(a.toString() + \" with certainty 0 \" + result); // When certainty is negative, // it is always true result = a.isProbablePrime(-1); System.out.println(a.toString() + \" with certainty -1 \" + result); }}",
"e": 29199,
"s": 28108,
"text": null
},
{
"code": null,
"e": 29334,
"s": 29199,
"text": "654561561356879113561 with certainty 1 false\n654561561356879113561 with certainty 0 true\n654561561356879113561 with certainty -1 true\n"
},
{
"code": null,
"e": 29434,
"s": 29334,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/math/BigInteger.html#isProbablePrime(int)"
},
{
"code": null,
"e": 29450,
"s": 29434,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 29465,
"s": 29450,
"text": "Java-Functions"
},
{
"code": null,
"e": 29483,
"s": 29465,
"text": "Java-math-package"
},
{
"code": null,
"e": 29488,
"s": 29483,
"text": "Java"
},
{
"code": null,
"e": 29504,
"s": 29488,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 29509,
"s": 29504,
"text": "Java"
},
{
"code": null,
"e": 29607,
"s": 29509,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29658,
"s": 29607,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29688,
"s": 29658,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29707,
"s": 29688,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29722,
"s": 29707,
"text": "Stream In Java"
},
{
"code": null,
"e": 29753,
"s": 29722,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29771,
"s": 29753,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29803,
"s": 29771,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29823,
"s": 29803,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29855,
"s": 29823,
"text": "Multidimensional Arrays in Java"
}
] |
Response Methods - Python requests - GeeksforGeeks | 23 Jul, 2021
When one makes a request to a URI, it returns a response. This Response object in terms of python is returned by requests.method(), method being – get, post, put, etc. Response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code. For example, response.status_code returns the status code from the headers itself, and one can check if the request was processed successfully or not. Response object can be used to imply lots of features, methods, and functionalities. Example :
Python3
# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com/') # print request objectprint(response.url) # print status codeprint(response.status_code)
Save this file as request.py, and run using below command
Python request.py
Status code 200 indicates that request was made successfully.
Some methods are most commonly used with response, such as response.json(), response.status_code, response.ok, etc. Requests is mostly used for making http request to APIs(Application Programming Interface). Some of commonly used response methods are discussed here –
response.json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error).
To illustrate use of response.json(), let’s ping geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC.
Example code –
Python3
# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com') # print responseprint(response) # print json contentprint(response.json())
Example Implementation –
Save above file as request.py and run using
Python request.py
Output –
Check the json content at the terminal output. This basically returns a Python dictionary.
response.ok returns True if status_code is less than 200, otherwise False.
To illustrate use of response.ok, let’s ping geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC.
Example code –
Python3
# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com/') # print responseprint(response) # print if status code is less than 200print(response.ok)
Example Implementation –
Save above file as request.py and run using
Python request.py
Output –
Check that True which matches the condition of request being less than or equal to 200.
response.status_code returns a number that indicates the status (200 is OK, 404 is Not Found).
To illustrate use of response.status_code, let’s ping api.github.com. To run this script, you need to have Python and requests installed on your PC.
Example code –
Python3
# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com/') # print responseprint(response) # print request status_codeprint(response.status_code)
Example Implementation –
Save above file as request.py and run using
Python request.py
Output –
Check that and 200 in the output which refer to HttpResponse and Status code respectively.
response.headers returns a dictionary of response headers. To check more about headers, visit – Different HTTP Headers
To illustrate use of response.headers, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC.
Example code –
Python3
# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com') # print responseprint(response) # print headers of responseprint(response.headers)
Example Implementation –
Save above file as request.py and run using
Python request.py
Output –
response.content returns the content of the response, in bytes. Basically, it refers to Binary Response content.
To illustrate use of response.content, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC.
Example code –
Python3
import requests # Making a get requestresponse = requests.get('https://api.github.com') # printing request contentprint(response.content)
Example Implementation –
Save above file as request.py and run using
Python request.py
Output –
Check that b’ at the start of output, it means the reference to a bytes object.
kapoorsagar226
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 25689,
"s": 25661,
"text": "\n23 Jul, 2021"
},
{
"code": null,
"e": 26241,
"s": 25689,
"text": "When one makes a request to a URI, it returns a response. This Response object in terms of python is returned by requests.method(), method being – get, post, put, etc. Response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code. For example, response.status_code returns the status code from the headers itself, and one can check if the request was processed successfully or not. Response object can be used to imply lots of features, methods, and functionalities. Example : "
},
{
"code": null,
"e": 26249,
"s": 26241,
"text": "Python3"
},
{
"code": "# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com/') # print request objectprint(response.url) # print status codeprint(response.status_code)",
"e": 26451,
"s": 26249,
"text": null
},
{
"code": null,
"e": 26511,
"s": 26451,
"text": "Save this file as request.py, and run using below command "
},
{
"code": null,
"e": 26529,
"s": 26511,
"text": "Python request.py"
},
{
"code": null,
"e": 26595,
"s": 26531,
"text": "Status code 200 indicates that request was made successfully. "
},
{
"code": null,
"e": 26871,
"s": 26601,
"text": "Some methods are most commonly used with response, such as response.json(), response.status_code, response.ok, etc. Requests is mostly used for making http request to APIs(Application Programming Interface). Some of commonly used response methods are discussed here – "
},
{
"code": null,
"e": 26996,
"s": 26871,
"text": "response.json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error). "
},
{
"code": null,
"e": 27144,
"s": 26996,
"text": "To illustrate use of response.json(), let’s ping geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC. "
},
{
"code": null,
"e": 27159,
"s": 27144,
"text": "Example code –"
},
{
"code": null,
"e": 27169,
"s": 27161,
"text": "Python3"
},
{
"code": "# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com') # print responseprint(response) # print json contentprint(response.json())",
"e": 27356,
"s": 27169,
"text": null
},
{
"code": null,
"e": 27381,
"s": 27356,
"text": "Example Implementation –"
},
{
"code": null,
"e": 27427,
"s": 27381,
"text": "Save above file as request.py and run using "
},
{
"code": null,
"e": 27445,
"s": 27427,
"text": "Python request.py"
},
{
"code": null,
"e": 27456,
"s": 27447,
"text": "Output –"
},
{
"code": null,
"e": 27550,
"s": 27458,
"text": "Check the json content at the terminal output. This basically returns a Python dictionary. "
},
{
"code": null,
"e": 27626,
"s": 27550,
"text": "response.ok returns True if status_code is less than 200, otherwise False. "
},
{
"code": null,
"e": 27770,
"s": 27626,
"text": "To illustrate use of response.ok, let’s ping geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC. "
},
{
"code": null,
"e": 27785,
"s": 27770,
"text": "Example code –"
},
{
"code": null,
"e": 27795,
"s": 27787,
"text": "Python3"
},
{
"code": "# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com/') # print responseprint(response) # print if status code is less than 200print(response.ok)",
"e": 27998,
"s": 27795,
"text": null
},
{
"code": null,
"e": 28023,
"s": 27998,
"text": "Example Implementation –"
},
{
"code": null,
"e": 28069,
"s": 28023,
"text": "Save above file as request.py and run using "
},
{
"code": null,
"e": 28087,
"s": 28069,
"text": "Python request.py"
},
{
"code": null,
"e": 28097,
"s": 28087,
"text": " Output –"
},
{
"code": null,
"e": 28187,
"s": 28097,
"text": "Check that True which matches the condition of request being less than or equal to 200. "
},
{
"code": null,
"e": 28284,
"s": 28187,
"text": "response.status_code returns a number that indicates the status (200 is OK, 404 is Not Found). "
},
{
"code": null,
"e": 28434,
"s": 28284,
"text": "To illustrate use of response.status_code, let’s ping api.github.com. To run this script, you need to have Python and requests installed on your PC. "
},
{
"code": null,
"e": 28449,
"s": 28434,
"text": "Example code –"
},
{
"code": null,
"e": 28457,
"s": 28449,
"text": "Python3"
},
{
"code": "# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com/') # print responseprint(response) # print request status_codeprint(response.status_code)",
"e": 28657,
"s": 28457,
"text": null
},
{
"code": null,
"e": 28682,
"s": 28657,
"text": "Example Implementation –"
},
{
"code": null,
"e": 28728,
"s": 28682,
"text": "Save above file as request.py and run using "
},
{
"code": null,
"e": 28746,
"s": 28728,
"text": "Python request.py"
},
{
"code": null,
"e": 28755,
"s": 28746,
"text": "Output –"
},
{
"code": null,
"e": 28848,
"s": 28755,
"text": "Check that and 200 in the output which refer to HttpResponse and Status code respectively. "
},
{
"code": null,
"e": 28968,
"s": 28848,
"text": "response.headers returns a dictionary of response headers. To check more about headers, visit – Different HTTP Headers "
},
{
"code": null,
"e": 29113,
"s": 28968,
"text": "To illustrate use of response.headers, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC. "
},
{
"code": null,
"e": 29128,
"s": 29113,
"text": "Example code –"
},
{
"code": null,
"e": 29138,
"s": 29130,
"text": "Python3"
},
{
"code": "# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com') # print responseprint(response) # print headers of responseprint(response.headers)",
"e": 29333,
"s": 29138,
"text": null
},
{
"code": null,
"e": 29358,
"s": 29333,
"text": "Example Implementation –"
},
{
"code": null,
"e": 29404,
"s": 29358,
"text": "Save above file as request.py and run using "
},
{
"code": null,
"e": 29422,
"s": 29404,
"text": "Python request.py"
},
{
"code": null,
"e": 29433,
"s": 29422,
"text": " Output – "
},
{
"code": null,
"e": 29547,
"s": 29433,
"text": "response.content returns the content of the response, in bytes. Basically, it refers to Binary Response content. "
},
{
"code": null,
"e": 29692,
"s": 29547,
"text": "To illustrate use of response.content, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC. "
},
{
"code": null,
"e": 29707,
"s": 29692,
"text": "Example code –"
},
{
"code": null,
"e": 29715,
"s": 29707,
"text": "Python3"
},
{
"code": "import requests # Making a get requestresponse = requests.get('https://api.github.com') # printing request contentprint(response.content)",
"e": 29853,
"s": 29715,
"text": null
},
{
"code": null,
"e": 29878,
"s": 29853,
"text": "Example Implementation –"
},
{
"code": null,
"e": 29924,
"s": 29878,
"text": "Save above file as request.py and run using "
},
{
"code": null,
"e": 29942,
"s": 29924,
"text": "Python request.py"
},
{
"code": null,
"e": 29952,
"s": 29942,
"text": "Output – "
},
{
"code": null,
"e": 30033,
"s": 29952,
"text": "Check that b’ at the start of output, it means the reference to a bytes object. "
},
{
"code": null,
"e": 30048,
"s": 30033,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 30064,
"s": 30048,
"text": "Python-requests"
},
{
"code": null,
"e": 30071,
"s": 30064,
"text": "Python"
},
{
"code": null,
"e": 30169,
"s": 30071,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30201,
"s": 30169,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30223,
"s": 30201,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30265,
"s": 30223,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30291,
"s": 30265,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30320,
"s": 30291,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30357,
"s": 30320,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 30393,
"s": 30357,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 30435,
"s": 30393,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30460,
"s": 30435,
"text": "sum() function in Python"
}
] |
Node.js Buffer.toJSON() Method - GeeksforGeeks | 13 Oct, 2021
Buffer is a temporary memory storage which stores the data when it is being moved from one place to another. It is like the array of integers.
The Buffer.toJSON() method returns the buffer in JSON format.
Note: The JSON.Stringify() is the method which can also be used to return the data in JSON format. When we call the JSON.Stringify() method, it directly in the background calls the buffer.toJSON() Method.
Syntax:
buffer.toJSON()
Return Value: It returns the buffer in JSON format.
Below examples illustrate the use of Buffer.toJSON() method in Node.js:
Example 1:
// Node.js program to demonstrate the // Buffer.toJSON() Method var buffer = Buffer.from('GeeksforGeeks'); // Prints: the ascii values of each// character of 'GeeksforGeeks'console.log(buffer.toJSON());
Output:
{
type: 'Buffer',
data: [
71, 101, 101, 107,
115, 102, 111, 114,
71, 101, 101, 107,
115
]
}
Example 2: This example implements the use of JSON.Stringify() method.
// Node.js program to demonstrate the // Buffer.toJSON() Method const buffer = Buffer.from([1, 2, 3, 4]); const output = JSON.stringify(buffer); // Prints: {"type":"Buffer", "data":[1, 2, 3, 4]}console.log(output);
Output:
{"type":"Buffer", "data":[1, 2, 3, 4]}
Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/buffer.html#buffer_buf_tojson
Node.js-Buffer-module
Picked
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
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26253,
"s": 26225,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 26396,
"s": 26253,
"text": "Buffer is a temporary memory storage which stores the data when it is being moved from one place to another. It is like the array of integers."
},
{
"code": null,
"e": 26458,
"s": 26396,
"text": "The Buffer.toJSON() method returns the buffer in JSON format."
},
{
"code": null,
"e": 26663,
"s": 26458,
"text": "Note: The JSON.Stringify() is the method which can also be used to return the data in JSON format. When we call the JSON.Stringify() method, it directly in the background calls the buffer.toJSON() Method."
},
{
"code": null,
"e": 26671,
"s": 26663,
"text": "Syntax:"
},
{
"code": null,
"e": 26687,
"s": 26671,
"text": "buffer.toJSON()"
},
{
"code": null,
"e": 26739,
"s": 26687,
"text": "Return Value: It returns the buffer in JSON format."
},
{
"code": null,
"e": 26811,
"s": 26739,
"text": "Below examples illustrate the use of Buffer.toJSON() method in Node.js:"
},
{
"code": null,
"e": 26822,
"s": 26811,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the // Buffer.toJSON() Method var buffer = Buffer.from('GeeksforGeeks'); // Prints: the ascii values of each// character of 'GeeksforGeeks'console.log(buffer.toJSON());",
"e": 27029,
"s": 26822,
"text": null
},
{
"code": null,
"e": 27037,
"s": 27029,
"text": "Output:"
},
{
"code": null,
"e": 27154,
"s": 27037,
"text": "{\n type: 'Buffer',\n data: [\n 71, 101, 101, 107,\n 115, 102, 111, 114,\n 71, 101, 101, 107,\n 115\n ]\n}\n"
},
{
"code": null,
"e": 27225,
"s": 27154,
"text": "Example 2: This example implements the use of JSON.Stringify() method."
},
{
"code": "// Node.js program to demonstrate the // Buffer.toJSON() Method const buffer = Buffer.from([1, 2, 3, 4]); const output = JSON.stringify(buffer); // Prints: {\"type\":\"Buffer\", \"data\":[1, 2, 3, 4]}console.log(output);",
"e": 27444,
"s": 27225,
"text": null
},
{
"code": null,
"e": 27452,
"s": 27444,
"text": "Output:"
},
{
"code": null,
"e": 27491,
"s": 27452,
"text": "{\"type\":\"Buffer\", \"data\":[1, 2, 3, 4]}"
},
{
"code": null,
"e": 27572,
"s": 27491,
"text": "Note: The above program will compile and run by using the node index.js command."
},
{
"code": null,
"e": 27636,
"s": 27572,
"text": "Reference: https://nodejs.org/api/buffer.html#buffer_buf_tojson"
},
{
"code": null,
"e": 27658,
"s": 27636,
"text": "Node.js-Buffer-module"
},
{
"code": null,
"e": 27665,
"s": 27658,
"text": "Picked"
},
{
"code": null,
"e": 27673,
"s": 27665,
"text": "Node.js"
},
{
"code": null,
"e": 27690,
"s": 27673,
"text": "Web Technologies"
},
{
"code": null,
"e": 27788,
"s": 27690,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27818,
"s": 27788,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 27847,
"s": 27818,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 27904,
"s": 27847,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 27958,
"s": 27904,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 27995,
"s": 27958,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 28035,
"s": 27995,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28080,
"s": 28035,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28123,
"s": 28080,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28173,
"s": 28123,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to create a dynamic 2D array inside a class in C++ ? - GeeksforGeeks | 29 May, 2017
Suppose we want to create a class for Graph. The class stores adjacency matrix representation of the graph. Therefore, our class structure would be something like below.
class Graph { int V; int adj[V][V]; // This line doesn't work /* Rest of the members */}; int main(){}
Output :
error: invalid use of non-static data
member 'Graph::V'.
Even if we make V static, we get error “array bound is not an integer constant”
C++ doesn’t allow to create an stack allocated array in a class whose size is not constant. So we need to dynamically allocate memory. Below is a simple program to show how to dynamically allocate 2D array in a C++ class using a class for Graph with adjacency matrix representation.
// C++ program to show how to allocate dynamic 2D// array in a class using a Graph example.#include<bits/stdc++.h>using namespace std; // A Class to represent directed graphclass Graph{ int V; // No. of vertices // adj[u][v] would be true if there is an edge // from u to v, else false bool **adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v) { adj[u][v] = true; } void print();}; Graph::Graph(int V){ this->V = V; // Create a dynamic array of pointers adj = new bool* [V]; // Create a row for every pointer for (int i=0; i<V; i++) { // Note : Rows may not be contiguous adj[i] = new bool[V]; // Initialize all entries as false to indicate // that there are no edges initially memset(adj[i], false, V*sizeof(bool)); }} // Utility method to print adjacency matrixvoid Graph::print(){ for (int u=0; u<V; u++) { for (int v=0; v<V; v++) cout << adj[u][v] << " "; cout << endl; }} // Driver methodint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); g.print(); return 0;}
Output :
0 1 1 0
0 0 1 0
1 0 0 1
0 0 0 1
A note on call of memset():memset() is used separately for individual rows. We can’t replace these calls with one call because rows are allocated at different addresses and making a memset call like below would be disastrous.
// Wrong!! (Rows of matrix at different addresses)
memset(adj, false, V*V*sizeof(bool));
This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
cpp-array
cpp-class
cpp-pointer
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
Substring in C++
rand() and srand() in C/C++
fork() in C
std::string class in C++
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Virtual Function in C++ | [
{
"code": null,
"e": 25739,
"s": 25711,
"text": "\n29 May, 2017"
},
{
"code": null,
"e": 25909,
"s": 25739,
"text": "Suppose we want to create a class for Graph. The class stores adjacency matrix representation of the graph. Therefore, our class structure would be something like below."
},
{
"code": "class Graph { int V; int adj[V][V]; // This line doesn't work /* Rest of the members */}; int main(){}",
"e": 26022,
"s": 25909,
"text": null
},
{
"code": null,
"e": 26031,
"s": 26022,
"text": "Output :"
},
{
"code": null,
"e": 26096,
"s": 26031,
"text": "error: invalid use of non-static data\n member 'Graph::V'.\n"
},
{
"code": null,
"e": 26176,
"s": 26096,
"text": "Even if we make V static, we get error “array bound is not an integer constant”"
},
{
"code": null,
"e": 26459,
"s": 26176,
"text": "C++ doesn’t allow to create an stack allocated array in a class whose size is not constant. So we need to dynamically allocate memory. Below is a simple program to show how to dynamically allocate 2D array in a C++ class using a class for Graph with adjacency matrix representation."
},
{
"code": "// C++ program to show how to allocate dynamic 2D// array in a class using a Graph example.#include<bits/stdc++.h>using namespace std; // A Class to represent directed graphclass Graph{ int V; // No. of vertices // adj[u][v] would be true if there is an edge // from u to v, else false bool **adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v) { adj[u][v] = true; } void print();}; Graph::Graph(int V){ this->V = V; // Create a dynamic array of pointers adj = new bool* [V]; // Create a row for every pointer for (int i=0; i<V; i++) { // Note : Rows may not be contiguous adj[i] = new bool[V]; // Initialize all entries as false to indicate // that there are no edges initially memset(adj[i], false, V*sizeof(bool)); }} // Utility method to print adjacency matrixvoid Graph::print(){ for (int u=0; u<V; u++) { for (int v=0; v<V; v++) cout << adj[u][v] << \" \"; cout << endl; }} // Driver methodint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); g.print(); return 0;}",
"e": 27753,
"s": 26459,
"text": null
},
{
"code": null,
"e": 27762,
"s": 27753,
"text": "Output :"
},
{
"code": null,
"e": 27799,
"s": 27762,
"text": "0 1 1 0 \n0 0 1 0 \n1 0 0 1 \n0 0 0 1 \n"
},
{
"code": null,
"e": 28025,
"s": 27799,
"text": "A note on call of memset():memset() is used separately for individual rows. We can’t replace these calls with one call because rows are allocated at different addresses and making a memset call like below would be disastrous."
},
{
"code": null,
"e": 28128,
"s": 28025,
"text": " // Wrong!! (Rows of matrix at different addresses)\n memset(adj, false, V*V*sizeof(bool));"
},
{
"code": null,
"e": 28298,
"s": 28128,
"text": "This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 28308,
"s": 28298,
"text": "cpp-array"
},
{
"code": null,
"e": 28318,
"s": 28308,
"text": "cpp-class"
},
{
"code": null,
"e": 28330,
"s": 28318,
"text": "cpp-pointer"
},
{
"code": null,
"e": 28341,
"s": 28330,
"text": "C Language"
},
{
"code": null,
"e": 28345,
"s": 28341,
"text": "C++"
},
{
"code": null,
"e": 28349,
"s": 28345,
"text": "CPP"
},
{
"code": null,
"e": 28447,
"s": 28349,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28469,
"s": 28447,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 28486,
"s": 28469,
"text": "Substring in C++"
},
{
"code": null,
"e": 28514,
"s": 28486,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 28526,
"s": 28514,
"text": "fork() in C"
},
{
"code": null,
"e": 28551,
"s": 28526,
"text": "std::string class in C++"
},
{
"code": null,
"e": 28570,
"s": 28551,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28616,
"s": 28570,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 28659,
"s": 28616,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28683,
"s": 28659,
"text": "C++ Classes and Objects"
}
] |
Build a Simple Beginner App with Node.js Bootstrap and MongoDB - GeeksforGeeks | 27 Sep, 2021
Node.js is one of the famous open-source environments that allows to you run javascript scripts outside the browser. MERN and MEAN stacks are the two most popular combination that helps you to create an amazing application. In this article, we will be creating a simple beginner-friendly Contact Form App with Node, Bootstrap, and MongoDB. Before starting the project we have to make sure that Node.js and MongoDB are installed in your system.
Project Structure:
Step 1: Create a project folder and open that folder in your IDE.
First to create a package.json file with values that you supply, use the npm init command in the terminal of IDE.
npm init
You can customize the questions asked and fields created during the init process or leave it as default. After the process, you will find the package.json file in your project folder.
Step 2: Next create an index.js file in the project folder, which will be the entry point of the app.
Step 3: Now install the dependencies express, mongoose, and nodemon using the npm command.
npm install express mongoose nodemon
Installing express, mongoose, and nodemon
It will take some time to install the dependencies and after it’s done, a folder named node_modules will be created and in the package.json file under dependencies, you will find the name of all the installed dependencies along with their version.
Dependencies
Step 4: We will next open the index.js file and create a simple express app with the following code.
Javascript
// Importing express modulevar express = require("express"); // Importing mongoose modulevar mongoose = require("mongoose");const port = 80;const app = express(); // Handling the get requestapp.get("/", (req, res) => { res.send("Hello World");}); // Starting the server on the 80 portapp.listen(port, () => { console.log(`The application started successfully on port ${port}`);});
This code creates a simple express app that starts a server and listens on port 80 for connections. The app responds with “Hello World” for requests to “/”.
Step 5: To run the code, go to terminal and type
nodemon index.js
Application started successfully
Step 6: Then open your browser, use http://localhost, or simply localhost to access the server from itself.
Localhost
The page shows “Hello World”, which means our express app is working properly.
Step 7: We now need to add 2 lines of code, as we will need express.json() and express.urlencoded() for POST and PUT requests. Express provides us with middleware to deal with incoming data objects in the body of the request. In both POST and PUT requests we are sending data objects to the server and are asking the server to accept or store that data object, which is enclosed in the req.body of that request.
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
Step 8: Create a folder named public inside the project folder. We will create all the static HTML files in the public directory of our project.
// For serving static html files
app.use(express.static('public'));
Step 9: Now we are going to connect to the mongoose database by using the following code. The name of the database for this project is given as projectDG
mongoose.connect("mongodb://localhost/projectDG", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var db = mongoose.connection;
Step 10: Next, we are going to define a post method to save the data of the contact form to our database. We define our data object and create collection named users here. On successful data insertion, we will redirect to formSubmitted.html
This is the main part of the index.js file where the post request will be handled and proper transfer of the data will be taken place from the client request to the main database server.
app.post("/formFillUp", (req, res) => {
var name = req.body.name;
var reason = req.body.reason;
var email = req.body.email;
var phone = req.body.phone;
var city = req.body.city;
var state = req.body.state;
var addressline = req.body.addressline;
var data = {
name: name,
reason: reason,
email: email,
phone: phone,
city: city,
state: state,
addressline: addressline,
};
db.collection("users").insertOne(data,
(err, collection) => {
if (err) {
throw err;
}
console.log("Data inserted successfully!");
});
return res.redirect("formSubmitted.html");
});
Final index.js will look like as below:
Filename: index.js
Javascript
var express = require("express");var mongoose = require("mongoose");const port = 80;const app = express(); mongoose.connect("mongodb://localhost/projectDG", { useNewUrlParser: true, useUnifiedTopology: true,});var db = mongoose.connection; app.use(express.json()); // For serving static HTML filesapp.use(express.static("public"));app.use(express.urlencoded({ extended: true })); app.get("/", (req, res) => { res.set({ "Allow-access-Allow-Origin": "*", }); // res.send("Hello World"); return res.redirect("index.html");}); app.post("/formFillUp", (req, res) => { var name = req.body.name; var reason = req.body.reason; var email = req.body.email; var phone = req.body.phone; var city = req.body.city; var state = req.body.state; var addressline = req.body.addressline; var data = { name: name, reason: reason, email: email, phone: phone, city: city, state: state, addressline: addressline, }; db.collection("users").insertOne( data, (err, collection) => { if (err) { throw err; } console.log("Data inserted successfully!"); }); return res.redirect("formSubmitted.html");}); app.listen(port, () => { console.log(`The application started successfully on port ${port}`);});
Step 11: Now we will create index.html, formSubmittedhtml, and style.css files inside the public folder.
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" /> <link rel="stylesheet" href="./style.css" /> <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet" /></head> <body> <div class="container mt-3"> <br /> <h1>Contact Us</h1> <br /> <form action="/formFillUp" method="POST"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputName" style="font-size: 23px"> Name </label> <input type="text" class="form-control" id="name" name="name" /> </div> <div class="form-group col-md-6"> <label for="inputReason" style="font-size: 23px"> Reason for contacting </label> <input type="text" class="form-control" id="reason" name="reason" /> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail" style="font-size: 23px"> Email </label> <input type="email" class="form-control" id="inputEmail" name="email" /> </div> <div class="form-group col-md-6"> <label for="inputPhone" style="font-size: 23px">Phone </label> <input type="text" class="form-control" id="inputPhone" name="phone" /> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputCity" style="font-size: 23px">City </label> <input type="text" class="form-control" id="inputCity" name="city" /> </div> <div class="form-group col-md-6"> <label for="inputState" style="font-size: 23px">State </label> <input type="text" class="form-control" id="inputState" name="state" /> </div> </div> <div class="form-group"> <label for="inputAddress" style="font-size: 23px">Address</label> <input type="text" class="form-control" id="inputAddress" name="addressline" /> </div> <button type="submit" class="btn btn-primary"> Submit </button> </form> </div></body> </html>
Output:
index.html
formSubmitted.html
HTML
<!DOCTYPE html><html> <head> <title>Form Submitted Successfully</title> <link rel="stylesheet" href="./style.css" /> <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet" /></head> <body> <div class="containerFormSubmittedMessage"> <h1>Form Submitted Successfully!</h1> <p> Thank you for contacting us! Our team will mail you shortly. </p> </div></body> </html>
Output:
formSubmitted.html
style.css
CSS
body { background-image: linear-gradient(120deg, #9de7fa 0%, #f89fba 100%); color: white; font-family: "Poppins", sans-serif; min-height: 100vh;} .btn-primary { color: #fff; background-color: #f89fba; border-color: #f89fba;}.containerFormSubmittedMessage { display: flex; flex-direction: column; margin: auto; justify-content: center; align-items: center; height: 200px; border: 3px solid whitesmoke;}
Step 12: After creating these three files, we are almost done with our project. We will now start MongoDB. Open the Windows Powershell window and then type the command mongod.
mongod
Type mongod command in powershell window
Open another Windows Powershell window and type the command mongo
mongo
Type mongo command in another powershell window
Step 13: Open your IDE, and in the terminal type nodemon index.js to start the app. Go to localhost.
Note: Data inserted successfully will be print after handling the post request properly.
Fill up the details of the contact form. On successful submission of the form, you will be redirected to formSubmitted.html from index.html.
Contact Form
Now to check if our data entered in the contact form has been saved to the projectDG database, we will use the following commands in the second Windows Powershell window.
This command lists all the databases in mongoDB:
show dbs
This command will let us switch to our database:
use projectDG
This command we will check of a particular data in the collection:
db.users.find()
Data present in users collection in projectDG database
We can see clearly out data has been inserted in the MongoDB database.
saurabh1990aror
Blogathon-2021
Bootstrap-Questions
CSS-Properties
NodeJS-Questions
Picked
Blogathon
Bootstrap
CSS
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to Show Images on Click using HTML ? | [
{
"code": null,
"e": 26385,
"s": 26357,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 26829,
"s": 26385,
"text": "Node.js is one of the famous open-source environments that allows to you run javascript scripts outside the browser. MERN and MEAN stacks are the two most popular combination that helps you to create an amazing application. In this article, we will be creating a simple beginner-friendly Contact Form App with Node, Bootstrap, and MongoDB. Before starting the project we have to make sure that Node.js and MongoDB are installed in your system."
},
{
"code": null,
"e": 26848,
"s": 26829,
"text": "Project Structure:"
},
{
"code": null,
"e": 26914,
"s": 26848,
"text": "Step 1: Create a project folder and open that folder in your IDE."
},
{
"code": null,
"e": 27029,
"s": 26914,
"text": "First to create a package.json file with values that you supply, use the npm init command in the terminal of IDE. "
},
{
"code": null,
"e": 27038,
"s": 27029,
"text": "npm init"
},
{
"code": null,
"e": 27222,
"s": 27038,
"text": "You can customize the questions asked and fields created during the init process or leave it as default. After the process, you will find the package.json file in your project folder."
},
{
"code": null,
"e": 27325,
"s": 27222,
"text": "Step 2: Next create an index.js file in the project folder, which will be the entry point of the app."
},
{
"code": null,
"e": 27418,
"s": 27325,
"text": "Step 3: Now install the dependencies express, mongoose, and nodemon using the npm command. "
},
{
"code": null,
"e": 27455,
"s": 27418,
"text": "npm install express mongoose nodemon"
},
{
"code": null,
"e": 27497,
"s": 27455,
"text": "Installing express, mongoose, and nodemon"
},
{
"code": null,
"e": 27746,
"s": 27497,
"text": "It will take some time to install the dependencies and after it’s done, a folder named node_modules will be created and in the package.json file under dependencies, you will find the name of all the installed dependencies along with their version. "
},
{
"code": null,
"e": 27759,
"s": 27746,
"text": "Dependencies"
},
{
"code": null,
"e": 27863,
"s": 27759,
"text": "Step 4: We will next open the index.js file and create a simple express app with the following code. "
},
{
"code": null,
"e": 27874,
"s": 27863,
"text": "Javascript"
},
{
"code": "// Importing express modulevar express = require(\"express\"); // Importing mongoose modulevar mongoose = require(\"mongoose\");const port = 80;const app = express(); // Handling the get requestapp.get(\"/\", (req, res) => { res.send(\"Hello World\");}); // Starting the server on the 80 portapp.listen(port, () => { console.log(`The application started successfully on port ${port}`);});",
"e": 28258,
"s": 27874,
"text": null
},
{
"code": null,
"e": 28415,
"s": 28258,
"text": "This code creates a simple express app that starts a server and listens on port 80 for connections. The app responds with “Hello World” for requests to “/”."
},
{
"code": null,
"e": 28466,
"s": 28415,
"text": "Step 5: To run the code, go to terminal and type "
},
{
"code": null,
"e": 28483,
"s": 28466,
"text": "nodemon index.js"
},
{
"code": null,
"e": 28516,
"s": 28483,
"text": "Application started successfully"
},
{
"code": null,
"e": 28624,
"s": 28516,
"text": "Step 6: Then open your browser, use http://localhost, or simply localhost to access the server from itself."
},
{
"code": null,
"e": 28634,
"s": 28624,
"text": "Localhost"
},
{
"code": null,
"e": 28713,
"s": 28634,
"text": "The page shows “Hello World”, which means our express app is working properly."
},
{
"code": null,
"e": 29126,
"s": 28713,
"text": "Step 7: We now need to add 2 lines of code, as we will need express.json() and express.urlencoded() for POST and PUT requests. Express provides us with middleware to deal with incoming data objects in the body of the request. In both POST and PUT requests we are sending data objects to the server and are asking the server to accept or store that data object, which is enclosed in the req.body of that request. "
},
{
"code": null,
"e": 29200,
"s": 29126,
"text": "app.use(express.json());\napp.use(express.urlencoded({ extended: true }));"
},
{
"code": null,
"e": 29347,
"s": 29200,
"text": "Step 8: Create a folder named public inside the project folder. We will create all the static HTML files in the public directory of our project. "
},
{
"code": null,
"e": 29415,
"s": 29347,
"text": "// For serving static html files\napp.use(express.static('public'));"
},
{
"code": null,
"e": 29571,
"s": 29415,
"text": "Step 9: Now we are going to connect to the mongoose database by using the following code. The name of the database for this project is given as projectDG "
},
{
"code": null,
"e": 29710,
"s": 29571,
"text": "mongoose.connect(\"mongodb://localhost/projectDG\", {\n useNewUrlParser: true,\n useUnifiedTopology: true,\n});\nvar db = mongoose.connection;"
},
{
"code": null,
"e": 29952,
"s": 29710,
"text": "Step 10: Next, we are going to define a post method to save the data of the contact form to our database. We define our data object and create collection named users here. On successful data insertion, we will redirect to formSubmitted.html "
},
{
"code": null,
"e": 30139,
"s": 29952,
"text": "This is the main part of the index.js file where the post request will be handled and proper transfer of the data will be taken place from the client request to the main database server."
},
{
"code": null,
"e": 30766,
"s": 30139,
"text": "app.post(\"/formFillUp\", (req, res) => {\n var name = req.body.name;\n var reason = req.body.reason;\n var email = req.body.email;\n var phone = req.body.phone;\n var city = req.body.city;\n var state = req.body.state;\n var addressline = req.body.addressline;\n\n var data = {\n name: name,\n reason: reason,\n email: email,\n phone: phone,\n city: city,\n state: state,\n addressline: addressline,\n };\n\n db.collection(\"users\").insertOne(data, \n (err, collection) => {\n if (err) {\n throw err;\n }\n console.log(\"Data inserted successfully!\");\n });\n\n return res.redirect(\"formSubmitted.html\");\n});"
},
{
"code": null,
"e": 30806,
"s": 30766,
"text": "Final index.js will look like as below:"
},
{
"code": null,
"e": 30825,
"s": 30806,
"text": "Filename: index.js"
},
{
"code": null,
"e": 30836,
"s": 30825,
"text": "Javascript"
},
{
"code": "var express = require(\"express\");var mongoose = require(\"mongoose\");const port = 80;const app = express(); mongoose.connect(\"mongodb://localhost/projectDG\", { useNewUrlParser: true, useUnifiedTopology: true,});var db = mongoose.connection; app.use(express.json()); // For serving static HTML filesapp.use(express.static(\"public\"));app.use(express.urlencoded({ extended: true })); app.get(\"/\", (req, res) => { res.set({ \"Allow-access-Allow-Origin\": \"*\", }); // res.send(\"Hello World\"); return res.redirect(\"index.html\");}); app.post(\"/formFillUp\", (req, res) => { var name = req.body.name; var reason = req.body.reason; var email = req.body.email; var phone = req.body.phone; var city = req.body.city; var state = req.body.state; var addressline = req.body.addressline; var data = { name: name, reason: reason, email: email, phone: phone, city: city, state: state, addressline: addressline, }; db.collection(\"users\").insertOne( data, (err, collection) => { if (err) { throw err; } console.log(\"Data inserted successfully!\"); }); return res.redirect(\"formSubmitted.html\");}); app.listen(port, () => { console.log(`The application started successfully on port ${port}`);});",
"e": 32093,
"s": 30836,
"text": null
},
{
"code": null,
"e": 32198,
"s": 32093,
"text": "Step 11: Now we will create index.html, formSubmittedhtml, and style.css files inside the public folder."
},
{
"code": null,
"e": 32203,
"s": 32198,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" /> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\" /> <link rel=\"stylesheet\" href=\"./style.css\" /> <link href=\"https://fonts.googleapis.com/css2?family=Poppins&display=swap\" rel=\"stylesheet\" /></head> <body> <div class=\"container mt-3\"> <br /> <h1>Contact Us</h1> <br /> <form action=\"/formFillUp\" method=\"POST\"> <div class=\"form-row\"> <div class=\"form-group col-md-6\"> <label for=\"inputName\" style=\"font-size: 23px\"> Name </label> <input type=\"text\" class=\"form-control\" id=\"name\" name=\"name\" /> </div> <div class=\"form-group col-md-6\"> <label for=\"inputReason\" style=\"font-size: 23px\"> Reason for contacting </label> <input type=\"text\" class=\"form-control\" id=\"reason\" name=\"reason\" /> </div> </div> <div class=\"form-row\"> <div class=\"form-group col-md-6\"> <label for=\"inputEmail\" style=\"font-size: 23px\"> Email </label> <input type=\"email\" class=\"form-control\" id=\"inputEmail\" name=\"email\" /> </div> <div class=\"form-group col-md-6\"> <label for=\"inputPhone\" style=\"font-size: 23px\">Phone </label> <input type=\"text\" class=\"form-control\" id=\"inputPhone\" name=\"phone\" /> </div> </div> <div class=\"form-row\"> <div class=\"form-group col-md-6\"> <label for=\"inputCity\" style=\"font-size: 23px\">City </label> <input type=\"text\" class=\"form-control\" id=\"inputCity\" name=\"city\" /> </div> <div class=\"form-group col-md-6\"> <label for=\"inputState\" style=\"font-size: 23px\">State </label> <input type=\"text\" class=\"form-control\" id=\"inputState\" name=\"state\" /> </div> </div> <div class=\"form-group\"> <label for=\"inputAddress\" style=\"font-size: 23px\">Address</label> <input type=\"text\" class=\"form-control\" id=\"inputAddress\" name=\"addressline\" /> </div> <button type=\"submit\" class=\"btn btn-primary\"> Submit </button> </form> </div></body> </html>",
"e": 35478,
"s": 32203,
"text": null
},
{
"code": null,
"e": 35487,
"s": 35478,
"text": "Output: "
},
{
"code": null,
"e": 35498,
"s": 35487,
"text": "index.html"
},
{
"code": null,
"e": 35517,
"s": 35498,
"text": "formSubmitted.html"
},
{
"code": null,
"e": 35522,
"s": 35517,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Form Submitted Successfully</title> <link rel=\"stylesheet\" href=\"./style.css\" /> <link href=\"https://fonts.googleapis.com/css2?family=Poppins&display=swap\" rel=\"stylesheet\" /></head> <body> <div class=\"containerFormSubmittedMessage\"> <h1>Form Submitted Successfully!</h1> <p> Thank you for contacting us! Our team will mail you shortly. </p> </div></body> </html>",
"e": 35989,
"s": 35522,
"text": null
},
{
"code": null,
"e": 35998,
"s": 35989,
"text": "Output: "
},
{
"code": null,
"e": 36017,
"s": 35998,
"text": "formSubmitted.html"
},
{
"code": null,
"e": 36028,
"s": 36017,
"text": "style.css "
},
{
"code": null,
"e": 36032,
"s": 36028,
"text": "CSS"
},
{
"code": "body { background-image: linear-gradient(120deg, #9de7fa 0%, #f89fba 100%); color: white; font-family: \"Poppins\", sans-serif; min-height: 100vh;} .btn-primary { color: #fff; background-color: #f89fba; border-color: #f89fba;}.containerFormSubmittedMessage { display: flex; flex-direction: column; margin: auto; justify-content: center; align-items: center; height: 200px; border: 3px solid whitesmoke;}",
"e": 36464,
"s": 36032,
"text": null
},
{
"code": null,
"e": 36641,
"s": 36464,
"text": " Step 12: After creating these three files, we are almost done with our project. We will now start MongoDB. Open the Windows Powershell window and then type the command mongod."
},
{
"code": null,
"e": 36648,
"s": 36641,
"text": "mongod"
},
{
"code": null,
"e": 36689,
"s": 36648,
"text": "Type mongod command in powershell window"
},
{
"code": null,
"e": 36756,
"s": 36689,
"text": "Open another Windows Powershell window and type the command mongo "
},
{
"code": null,
"e": 36762,
"s": 36756,
"text": "mongo"
},
{
"code": null,
"e": 36810,
"s": 36762,
"text": "Type mongo command in another powershell window"
},
{
"code": null,
"e": 36914,
"s": 36810,
"text": "Step 13: Open your IDE, and in the terminal type nodemon index.js to start the app. Go to localhost. "
},
{
"code": null,
"e": 37003,
"s": 36914,
"text": "Note: Data inserted successfully will be print after handling the post request properly."
},
{
"code": null,
"e": 37144,
"s": 37003,
"text": "Fill up the details of the contact form. On successful submission of the form, you will be redirected to formSubmitted.html from index.html."
},
{
"code": null,
"e": 37157,
"s": 37144,
"text": "Contact Form"
},
{
"code": null,
"e": 37328,
"s": 37157,
"text": "Now to check if our data entered in the contact form has been saved to the projectDG database, we will use the following commands in the second Windows Powershell window."
},
{
"code": null,
"e": 37378,
"s": 37328,
"text": "This command lists all the databases in mongoDB: "
},
{
"code": null,
"e": 37387,
"s": 37378,
"text": "show dbs"
},
{
"code": null,
"e": 37437,
"s": 37387,
"text": "This command will let us switch to our database: "
},
{
"code": null,
"e": 37452,
"s": 37437,
"text": "use projectDG "
},
{
"code": null,
"e": 37523,
"s": 37452,
"text": "This command we will check of a particular data in the collection: "
},
{
"code": null,
"e": 37539,
"s": 37523,
"text": "db.users.find()"
},
{
"code": null,
"e": 37594,
"s": 37539,
"text": "Data present in users collection in projectDG database"
},
{
"code": null,
"e": 37665,
"s": 37594,
"text": "We can see clearly out data has been inserted in the MongoDB database."
},
{
"code": null,
"e": 37683,
"s": 37667,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 37698,
"s": 37683,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 37718,
"s": 37698,
"text": "Bootstrap-Questions"
},
{
"code": null,
"e": 37733,
"s": 37718,
"text": "CSS-Properties"
},
{
"code": null,
"e": 37750,
"s": 37733,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 37757,
"s": 37750,
"text": "Picked"
},
{
"code": null,
"e": 37767,
"s": 37757,
"text": "Blogathon"
},
{
"code": null,
"e": 37777,
"s": 37767,
"text": "Bootstrap"
},
{
"code": null,
"e": 37781,
"s": 37777,
"text": "CSS"
},
{
"code": null,
"e": 37789,
"s": 37781,
"text": "MongoDB"
},
{
"code": null,
"e": 37797,
"s": 37789,
"text": "Node.js"
},
{
"code": null,
"e": 37814,
"s": 37797,
"text": "Web Technologies"
},
{
"code": null,
"e": 37912,
"s": 37814,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37969,
"s": 37912,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 38010,
"s": 37969,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 38040,
"s": 38010,
"text": "Stratified Sampling in Pandas"
},
{
"code": null,
"e": 38075,
"s": 38040,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 38119,
"s": 38075,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 38169,
"s": 38119,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 38198,
"s": 38169,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 38239,
"s": 38198,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 38295,
"s": 38239,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
}
] |
bits Package in Golang - GeeksforGeeks | 08 Jun, 2020
Go language provides inbuilt support for bit counting and manipulation functions for the predeclared unsigned integer types with the help of the bits package.
Example 1:
// Golang program to illustrate bits.Sub() Functionpackage main import ( "fmt" "math/bits") // Main functionfunc main() { // Finding diff and borrowOu // of the specified numbers // Using Sub() function nvalue_1, borrowOut := bits.Sub(4, 3, 0) fmt.Println("Diff:", nvalue_1) fmt.Println("BorrowOut :", borrowOut)}
Output:
Diff: 1
BorrowOut : 0
Example 2:
// Golang program to illustrate bits.TrailingZeros64() Functionpackage main import ( "fmt" "math/bits") // Main functionfunc main() { // Using TrailingZeros64() function a := bits.TrailingZeros64(15) fmt.Printf("Total number of trailing"+ " zero bits in %d: %d", 15, a)}
Output:
Total number of trailing zero bits in 15: 0
Golang-bits
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
How to Parse JSON in Golang?
Time Durations in Golang
Strings in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Loops in Go Language
Defer Keyword in Golang
Class and Object in Golang | [
{
"code": null,
"e": 25703,
"s": 25675,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 25862,
"s": 25703,
"text": "Go language provides inbuilt support for bit counting and manipulation functions for the predeclared unsigned integer types with the help of the bits package."
},
{
"code": null,
"e": 25873,
"s": 25862,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate bits.Sub() Functionpackage main import ( \"fmt\" \"math/bits\") // Main functionfunc main() { // Finding diff and borrowOu // of the specified numbers // Using Sub() function nvalue_1, borrowOut := bits.Sub(4, 3, 0) fmt.Println(\"Diff:\", nvalue_1) fmt.Println(\"BorrowOut :\", borrowOut)}",
"e": 26215,
"s": 25873,
"text": null
},
{
"code": null,
"e": 26223,
"s": 26215,
"text": "Output:"
},
{
"code": null,
"e": 26245,
"s": 26223,
"text": "Diff: 1\nBorrowOut : 0"
},
{
"code": null,
"e": 26256,
"s": 26245,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate bits.TrailingZeros64() Functionpackage main import ( \"fmt\" \"math/bits\") // Main functionfunc main() { // Using TrailingZeros64() function a := bits.TrailingZeros64(15) fmt.Printf(\"Total number of trailing\"+ \" zero bits in %d: %d\", 15, a)}",
"e": 26557,
"s": 26256,
"text": null
},
{
"code": null,
"e": 26565,
"s": 26557,
"text": "Output:"
},
{
"code": null,
"e": 26609,
"s": 26565,
"text": "Total number of trailing zero bits in 15: 0"
},
{
"code": null,
"e": 26621,
"s": 26609,
"text": "Golang-bits"
},
{
"code": null,
"e": 26633,
"s": 26621,
"text": "Go Language"
},
{
"code": null,
"e": 26731,
"s": 26633,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26777,
"s": 26731,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 26806,
"s": 26777,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 26831,
"s": 26806,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 26849,
"s": 26831,
"text": "Strings in Golang"
},
{
"code": null,
"e": 26870,
"s": 26849,
"text": "Structures in Golang"
},
{
"code": null,
"e": 26925,
"s": 26870,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 26940,
"s": 26925,
"text": "Rune in Golang"
},
{
"code": null,
"e": 26961,
"s": 26940,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 26985,
"s": 26961,
"text": "Defer Keyword in Golang"
}
] |
How to position legends inside a plot in Plotly-Python? - GeeksforGeeks | 28 Nov, 2021
In this article, we will learn How to hide legend with Plotly Express and Plotly. A legend is an area describing the elements of the graph. In the plotly legend is used to Place a legend on the axes.
Example 1:
In this example, we are positioning legends inside a plot with the help of method fig.update_layout(), by passing the position as x=0.3 and y=0.1.
Python3
# importing packagesimport plotly.graph_objects as go # using medals_wide datasetfig = go.Figure() # plotting the scatter chartfig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5],)) # plotting the scatter chartfig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[5, 4, 3, 2, 1],)) # position legends inside a plotfig.update_layout( legend=dict( x=0.3, # value must be between 0 to 1. y=.1, # value must be between 0 to 1. traceorder="normal", font=dict( family="sans-serif", size=12, color="black" ), )) fig.show()
Output:
Example 2:
In this example, we are positioning legends inside a plot with the help of method fig.update_layout(), by passing the position as x=0.6 and y=1.
Python3
# importing packagesimport plotly.graph_objects as go # using medals_wide datasetfig = go.Figure() # plotting the scatter chartfig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5],)) # plotting the scatter chartfig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[5, 4, 3, 2, 1], visible='legendonly')) # position legends inside a plotfig.update_layout( legend=dict( x=0.6, # value must be between 0 to 1. y=1, # value must be between 0 to 1. traceorder="normal", font=dict( family="sans-serif", size=12, color="black" ), )) fig.show()
Output:
Example 3:
In this example, we are positioning legends inside a plot with the help of method fig.update_layout(), by passing the position as x=0.9 and y=1.
Python3
import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5], mode='markers', marker={'size': 10})) # plotting the scatter chartfig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[5, 4, 3, 2, 1], mode='markers', marker={'size': 100})) # position legends inside a plotfig.update_layout( legend=dict( x=.9, # value must be between 0 to 1. y=1, # value must be between 0 to 1. traceorder="normal", font=dict( family="sans-serif", size=12, color="black" ), )) fig.update_layout(legend={'itemsizing': 'constant'}) fig.show()
Output:
Picked
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 25737,
"s": 25537,
"text": "In this article, we will learn How to hide legend with Plotly Express and Plotly. A legend is an area describing the elements of the graph. In the plotly legend is used to Place a legend on the axes."
},
{
"code": null,
"e": 25748,
"s": 25737,
"text": "Example 1:"
},
{
"code": null,
"e": 25895,
"s": 25748,
"text": "In this example, we are positioning legends inside a plot with the help of method fig.update_layout(), by passing the position as x=0.3 and y=0.1."
},
{
"code": null,
"e": 25903,
"s": 25895,
"text": "Python3"
},
{
"code": "# importing packagesimport plotly.graph_objects as go # using medals_wide datasetfig = go.Figure() # plotting the scatter chartfig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5],)) # plotting the scatter chartfig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[5, 4, 3, 2, 1],)) # position legends inside a plotfig.update_layout( legend=dict( x=0.3, # value must be between 0 to 1. y=.1, # value must be between 0 to 1. traceorder=\"normal\", font=dict( family=\"sans-serif\", size=12, color=\"black\" ), )) fig.show()",
"e": 26519,
"s": 25903,
"text": null
},
{
"code": null,
"e": 26527,
"s": 26519,
"text": "Output:"
},
{
"code": null,
"e": 26538,
"s": 26527,
"text": "Example 2:"
},
{
"code": null,
"e": 26683,
"s": 26538,
"text": "In this example, we are positioning legends inside a plot with the help of method fig.update_layout(), by passing the position as x=0.6 and y=1."
},
{
"code": null,
"e": 26691,
"s": 26683,
"text": "Python3"
},
{
"code": "# importing packagesimport plotly.graph_objects as go # using medals_wide datasetfig = go.Figure() # plotting the scatter chartfig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5],)) # plotting the scatter chartfig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[5, 4, 3, 2, 1], visible='legendonly')) # position legends inside a plotfig.update_layout( legend=dict( x=0.6, # value must be between 0 to 1. y=1, # value must be between 0 to 1. traceorder=\"normal\", font=dict( family=\"sans-serif\", size=12, color=\"black\" ), )) fig.show()",
"e": 27328,
"s": 26691,
"text": null
},
{
"code": null,
"e": 27336,
"s": 27328,
"text": "Output:"
},
{
"code": null,
"e": 27347,
"s": 27336,
"text": "Example 3:"
},
{
"code": null,
"e": 27492,
"s": 27347,
"text": "In this example, we are positioning legends inside a plot with the help of method fig.update_layout(), by passing the position as x=0.9 and y=1."
},
{
"code": null,
"e": 27500,
"s": 27492,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5], mode='markers', marker={'size': 10})) # plotting the scatter chartfig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[5, 4, 3, 2, 1], mode='markers', marker={'size': 100})) # position legends inside a plotfig.update_layout( legend=dict( x=.9, # value must be between 0 to 1. y=1, # value must be between 0 to 1. traceorder=\"normal\", font=dict( family=\"sans-serif\", size=12, color=\"black\" ), )) fig.update_layout(legend={'itemsizing': 'constant'}) fig.show()",
"e": 28177,
"s": 27500,
"text": null
},
{
"code": null,
"e": 28185,
"s": 28177,
"text": "Output:"
},
{
"code": null,
"e": 28192,
"s": 28185,
"text": "Picked"
},
{
"code": null,
"e": 28206,
"s": 28192,
"text": "Python-Plotly"
},
{
"code": null,
"e": 28213,
"s": 28206,
"text": "Python"
},
{
"code": null,
"e": 28311,
"s": 28213,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28343,
"s": 28311,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28385,
"s": 28343,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28427,
"s": 28385,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28483,
"s": 28427,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28510,
"s": 28483,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28549,
"s": 28510,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28580,
"s": 28549,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28602,
"s": 28580,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28631,
"s": 28602,
"text": "Create a directory in Python"
}
] |
How to Browse From the Linux Terminal Using W3M? - GeeksforGeeks | 17 Sep, 2019
W3M is an open-source text-based terminal web browser for Linux used to browse through the terminal. It is simple to use and do not require any additional interacting interface application though it interacts through the terminal. It renders the web pages in a form as their original layout.
How to Install W3M?
As W3M is not included by default on most Linux distributions, we have to install the main w3m package and the w3m-img package for inline image support using the following command:
sudo apt-get install w3m w3m-img
While installing, it asks your permission, type Y to proceed
Browsing: To access a webpage, we just have to specify the web address. If you want to bring up Google, then you just to run following command:
w3m google.com
Instructions to Use:
Use arrow keys to move the cursor around or click at the desired location.
Where you want to type anything, select the text box with your cursor and press enter before typing the text.
Load a hyperlink by selecting it and pressing enter.
Searching
Result
Note: Tab key can be used to position the cursor over different links or tabs.
Linux-Unix
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
Top Programming Languages for Android App Development
How to Run a Python Script using Docker?
Setting up the environment in Java | [
{
"code": null,
"e": 25475,
"s": 25447,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 25767,
"s": 25475,
"text": "W3M is an open-source text-based terminal web browser for Linux used to browse through the terminal. It is simple to use and do not require any additional interacting interface application though it interacts through the terminal. It renders the web pages in a form as their original layout."
},
{
"code": null,
"e": 25787,
"s": 25767,
"text": "How to Install W3M?"
},
{
"code": null,
"e": 25968,
"s": 25787,
"text": "As W3M is not included by default on most Linux distributions, we have to install the main w3m package and the w3m-img package for inline image support using the following command:"
},
{
"code": null,
"e": 26001,
"s": 25968,
"text": "sudo apt-get install w3m w3m-img"
},
{
"code": null,
"e": 26062,
"s": 26001,
"text": "While installing, it asks your permission, type Y to proceed"
},
{
"code": null,
"e": 26206,
"s": 26062,
"text": "Browsing: To access a webpage, we just have to specify the web address. If you want to bring up Google, then you just to run following command:"
},
{
"code": null,
"e": 26221,
"s": 26206,
"text": "w3m google.com"
},
{
"code": null,
"e": 26242,
"s": 26221,
"text": "Instructions to Use:"
},
{
"code": null,
"e": 26317,
"s": 26242,
"text": "Use arrow keys to move the cursor around or click at the desired location."
},
{
"code": null,
"e": 26427,
"s": 26317,
"text": "Where you want to type anything, select the text box with your cursor and press enter before typing the text."
},
{
"code": null,
"e": 26480,
"s": 26427,
"text": "Load a hyperlink by selecting it and pressing enter."
},
{
"code": null,
"e": 26490,
"s": 26480,
"text": "Searching"
},
{
"code": null,
"e": 26497,
"s": 26490,
"text": "Result"
},
{
"code": null,
"e": 26576,
"s": 26497,
"text": "Note: Tab key can be used to position the cursor over different links or tabs."
},
{
"code": null,
"e": 26587,
"s": 26576,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26596,
"s": 26587,
"text": "TechTips"
},
{
"code": null,
"e": 26694,
"s": 26596,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26729,
"s": 26694,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 26767,
"s": 26729,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 26802,
"s": 26767,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 26838,
"s": 26802,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 26876,
"s": 26838,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 26929,
"s": 26876,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 26955,
"s": 26929,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27009,
"s": 26955,
"text": "Top Programming Languages for Android App Development"
},
{
"code": null,
"e": 27050,
"s": 27009,
"text": "How to Run a Python Script using Docker?"
}
] |
classmethod() in Python - GeeksforGeeks | 13 Sep, 2021
The classmethod() is an inbuilt function in Python, which returns a class method for a given function.;
Syntax: classmethod(function)
Parameter :This function accepts the function name as a parameter.
Return Type:This function returns the converted class method.
You can also use @classmethod decorator for classmethod definition.
Syntax:
@classmethod
def fun(cls, arg1, arg2, ...):
Where,
fun: the function that needs to be converted into a class method
returns: a class method for function.
classmethod() methods are bound to a class rather than an object. Class methods can be called by both class and object. These methods can be called with a class or with an object.
A class method takes cls as the first parameter while a static method needs no specific parameters.
A class method can access or modify the class state while a static method can’t access or modify it.
In general, static methods know nothing about the class state. They are utility-type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as a parameter.
We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python.
In this example, we are going to see a how to create classmethod, for this we created a class with geeks name with member variable course and created a function purchase which prints the object.
Now we passed the method geeks.purchase into classmethod which converts the methods to a class method and then we call the class function purchase without creating a function object.
Python3
class geeks: course = 'DSA' def purchase(obj): print("Puchase course : ", obj.course) geeks.purchase = classmethod(geeks.purchase)geeks.purchase()
Output:
Puchase course : DSA
Python3
# Python program to understand the classmethod class Student: # create a variable name = "Geeksforgeeks" # create a function def print_name(obj): print("The name is : ", obj.name) # create print_name classmethod# before creating this line print_name()# It can be called only with object not with classStudent.print_name = classmethod(Student.print_name) # now this method can be called as classmethod# print_name() method is called a class methodStudent.print_name()
Output:
The name is : Geeksforgeeks
Uses of classmethod() function are used in factory design patterns where we want to call many functions with the class name rather than an object.
Python3
# Python program to demonstrate# use of a class method and static method.from datetime import date class Person: def __init__(self, name, age): self.name = name self.age = age # a class method to create a # Person object by birth year. @classmethod def fromBirthYear(cls, name, year): return cls(name, date.today().year - year) def display(self): print("Name : ", self.name, "Age : ", self.age) person = Person('mayank', 21)person.display()
Output:
Name : mayank Age : 21
The @classmethod decorator is a built-in function decorator which is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition.
A class method receives the class as the implicit first argument, just like an instance method receives the instance.
Syntax:
class C(object):
@classmethod
def fun(cls, arg1, arg2, ...):
....
Where,
fun: the function that needs to be converted into a class method
returns: a class method for function.
Note:
A class method is a method which is bound to the class and not the object of the class.
They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.
It can modify a class state that would apply across all the instances of the class. For example, it can modify a class variable that would be applicable to all the instances.
In the below example we use a staticmethod() and classmethod() to check if a person is an adult or not.
Python
# Python program to demonstrate# use of a class method and static method.from datetime import date class Person: def __init__(self, name, age): self.name = name self.age = age # a class method to create a # Person object by birth year. @classmethod def fromBirthYear(cls, name, year): return cls(name, date.today().year - year) # a static method to check if a # Person is adult or not. @staticmethod def isAdult(age): return age > 18 person1 = Person('mayank', 21)person2 = Person.fromBirthYear('mayank', 1996) print(person1.age)print(person2.age) # print the resultprint(Person.isAdult(22))
Output:
21
25
True
yegoun98
kumar_satyam
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25361,
"s": 25333,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 25465,
"s": 25361,
"text": "The classmethod() is an inbuilt function in Python, which returns a class method for a given function.;"
},
{
"code": null,
"e": 25495,
"s": 25465,
"text": "Syntax: classmethod(function)"
},
{
"code": null,
"e": 25562,
"s": 25495,
"text": "Parameter :This function accepts the function name as a parameter."
},
{
"code": null,
"e": 25624,
"s": 25562,
"text": "Return Type:This function returns the converted class method."
},
{
"code": null,
"e": 25692,
"s": 25624,
"text": "You can also use @classmethod decorator for classmethod definition."
},
{
"code": null,
"e": 25701,
"s": 25692,
"text": "Syntax: "
},
{
"code": null,
"e": 25748,
"s": 25701,
"text": "@classmethod\n def fun(cls, arg1, arg2, ...):"
},
{
"code": null,
"e": 25756,
"s": 25748,
"text": "Where, "
},
{
"code": null,
"e": 25821,
"s": 25756,
"text": "fun: the function that needs to be converted into a class method"
},
{
"code": null,
"e": 25859,
"s": 25821,
"text": "returns: a class method for function."
},
{
"code": null,
"e": 26040,
"s": 25859,
"text": "classmethod() methods are bound to a class rather than an object. Class methods can be called by both class and object. These methods can be called with a class or with an object. "
},
{
"code": null,
"e": 26140,
"s": 26040,
"text": "A class method takes cls as the first parameter while a static method needs no specific parameters."
},
{
"code": null,
"e": 26241,
"s": 26140,
"text": "A class method can access or modify the class state while a static method can’t access or modify it."
},
{
"code": null,
"e": 26456,
"s": 26241,
"text": "In general, static methods know nothing about the class state. They are utility-type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as a parameter."
},
{
"code": null,
"e": 26593,
"s": 26456,
"text": "We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python."
},
{
"code": null,
"e": 26788,
"s": 26593,
"text": "In this example, we are going to see a how to create classmethod, for this we created a class with geeks name with member variable course and created a function purchase which prints the object."
},
{
"code": null,
"e": 26971,
"s": 26788,
"text": "Now we passed the method geeks.purchase into classmethod which converts the methods to a class method and then we call the class function purchase without creating a function object."
},
{
"code": null,
"e": 26979,
"s": 26971,
"text": "Python3"
},
{
"code": "class geeks: course = 'DSA' def purchase(obj): print(\"Puchase course : \", obj.course) geeks.purchase = classmethod(geeks.purchase)geeks.purchase()",
"e": 27144,
"s": 26979,
"text": null
},
{
"code": null,
"e": 27152,
"s": 27144,
"text": "Output:"
},
{
"code": null,
"e": 27174,
"s": 27152,
"text": "Puchase course : DSA"
},
{
"code": null,
"e": 27182,
"s": 27174,
"text": "Python3"
},
{
"code": "# Python program to understand the classmethod class Student: # create a variable name = \"Geeksforgeeks\" # create a function def print_name(obj): print(\"The name is : \", obj.name) # create print_name classmethod# before creating this line print_name()# It can be called only with object not with classStudent.print_name = classmethod(Student.print_name) # now this method can be called as classmethod# print_name() method is called a class methodStudent.print_name()",
"e": 27677,
"s": 27182,
"text": null
},
{
"code": null,
"e": 27685,
"s": 27677,
"text": "Output:"
},
{
"code": null,
"e": 27714,
"s": 27685,
"text": "The name is : Geeksforgeeks"
},
{
"code": null,
"e": 27861,
"s": 27714,
"text": "Uses of classmethod() function are used in factory design patterns where we want to call many functions with the class name rather than an object."
},
{
"code": null,
"e": 27869,
"s": 27861,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# use of a class method and static method.from datetime import date class Person: def __init__(self, name, age): self.name = name self.age = age # a class method to create a # Person object by birth year. @classmethod def fromBirthYear(cls, name, year): return cls(name, date.today().year - year) def display(self): print(\"Name : \", self.name, \"Age : \", self.age) person = Person('mayank', 21)person.display()",
"e": 28362,
"s": 27869,
"text": null
},
{
"code": null,
"e": 28370,
"s": 28362,
"text": "Output:"
},
{
"code": null,
"e": 28395,
"s": 28370,
"text": "Name : mayank Age : 21"
},
{
"code": null,
"e": 28595,
"s": 28395,
"text": "The @classmethod decorator is a built-in function decorator which is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition. "
},
{
"code": null,
"e": 28713,
"s": 28595,
"text": "A class method receives the class as the implicit first argument, just like an instance method receives the instance."
},
{
"code": null,
"e": 28721,
"s": 28713,
"text": "Syntax:"
},
{
"code": null,
"e": 28802,
"s": 28721,
"text": "class C(object):\n @classmethod\n def fun(cls, arg1, arg2, ...):\n ...."
},
{
"code": null,
"e": 28809,
"s": 28802,
"text": "Where,"
},
{
"code": null,
"e": 28874,
"s": 28809,
"text": "fun: the function that needs to be converted into a class method"
},
{
"code": null,
"e": 28912,
"s": 28874,
"text": "returns: a class method for function."
},
{
"code": null,
"e": 28918,
"s": 28912,
"text": "Note:"
},
{
"code": null,
"e": 29006,
"s": 28918,
"text": "A class method is a method which is bound to the class and not the object of the class."
},
{
"code": null,
"e": 29137,
"s": 29006,
"text": "They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance."
},
{
"code": null,
"e": 29312,
"s": 29137,
"text": "It can modify a class state that would apply across all the instances of the class. For example, it can modify a class variable that would be applicable to all the instances."
},
{
"code": null,
"e": 29416,
"s": 29312,
"text": "In the below example we use a staticmethod() and classmethod() to check if a person is an adult or not."
},
{
"code": null,
"e": 29423,
"s": 29416,
"text": "Python"
},
{
"code": "# Python program to demonstrate# use of a class method and static method.from datetime import date class Person: def __init__(self, name, age): self.name = name self.age = age # a class method to create a # Person object by birth year. @classmethod def fromBirthYear(cls, name, year): return cls(name, date.today().year - year) # a static method to check if a # Person is adult or not. @staticmethod def isAdult(age): return age > 18 person1 = Person('mayank', 21)person2 = Person.fromBirthYear('mayank', 1996) print(person1.age)print(person2.age) # print the resultprint(Person.isAdult(22))",
"e": 30078,
"s": 29423,
"text": null
},
{
"code": null,
"e": 30086,
"s": 30078,
"text": "Output:"
},
{
"code": null,
"e": 30097,
"s": 30086,
"text": "21\n25\nTrue"
},
{
"code": null,
"e": 30106,
"s": 30097,
"text": "yegoun98"
},
{
"code": null,
"e": 30119,
"s": 30106,
"text": "kumar_satyam"
},
{
"code": null,
"e": 30136,
"s": 30119,
"text": "Python-Functions"
},
{
"code": null,
"e": 30143,
"s": 30136,
"text": "Python"
},
{
"code": null,
"e": 30241,
"s": 30143,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30259,
"s": 30241,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30294,
"s": 30259,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30326,
"s": 30294,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30348,
"s": 30326,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30390,
"s": 30348,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30420,
"s": 30390,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 30446,
"s": 30420,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30475,
"s": 30446,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30519,
"s": 30475,
"text": "Reading and Writing to text files in Python"
}
] |
Swiggy Interview Experience | Set 2 (On-Campus) - GeeksforGeeks | 30 May, 2018
First Round (Online Coding on HackerRank)4 problemsTime -90 min
1. Stock Buy Sell to Maximize Profit
Input: 1 3 100
Output: 196
link- https://www.hackerrank.com/challenges/stockmax
2. Given A string you need to print all subset of that string
Input: "abc"
Output:
"a"
"b"
"c"
"ab"
"ac"
"bc"
"abc"
3. Check if a given sequence of moves for a robot is circular or not
Input: path[] = “GLGLGLG”Output: Given sequence of moves is circular
Input: path[] = “GLLG”Output: Given sequence of moves is circular
link- https://www.geeksforgeeks.org/check-if-a-given-sequence-of-moves-for-a-robot-is-circular-or-not/
Second Round (F2F Interview) 45 min.
1. First he asked me to design the database for food shop, then he asked me to minimize the complexity of database and then he asked me some DBMS Query related to Join Operation.
2. Given a Sorted array in which all elements are repeated except one element. Find non repeated element in O (log n).
3. Some Questions On DNS server and IP address.
4. What is cache Memory? What is TLB? And uses?
5. Which policy you will use to swap pages? Implement LRU?
Third Round (F2F Interview) (70-80) min.
1. Discussion on project
2. What is Encryption? How you can use it in your project?
3. What is Block cipher and Advanced Encryption Standard (AES)? If someone knows that you are using
Polybius Cipher then what is the complexity in decrypting your original data (information)?
4. He modified “Stock Buy Sell to Maximize Profit “problem i.e. you can’t buy or sell stock continuously and you can skip any day to sell or purchase.
Input: 2 100 2 3 500 2 1
Output: max profit 596
3. Diff between Mutex and Semaphore?
4. There is stream of infinite number you need to find the median of number?
Input: 1 5 10 15 20 22 35 ....inf
Output:
Median of first number 1
Median of first 2 numbers 3
Median of first 3 numbers 5
Median of first 4 numbers 7.5
Median of first 5 numbers 15
....
....
5. There are 4 resources and 4 process .Is there any condition in which Deadlock occurs?
6. Find an Element in A Sorted Array which is rotated any number of times.
7. Again he asked me about Robot problem (1st round 3rd question).
8. What is synchronization? If a process has opened a word file in write mode and preempted beforeclosing it, at the same time another process is trying to open that file in write mode .Will it Open or Not?
Fourth Round (Online Interview on Skype) 60 min
1. Any challenging task you did in last two Years?
2. Write a code For Expression Evaluation?
3. If i type www.facebook.com and clicked on search button, what will happen in background?
4. Tell me about data structure that DNS server uses? How DNS search for IP address?
5. O (2^n), O (n!) Which one complexity is better and why? Prove mathematically.
6. How Hashing works? Why its complexity is always O (1).
7. Again he asked about my Project.
Fifth Round (HR round) 20 min
1. Tell me about yourself?
2. How was your online interview round?
2. Why you want to join Start-up like Swiggy even you have other companies also?
3. Do you have any question?
Then i asked 3-4 questions.
Thank you GeeksforGeeks
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Swiggy
Interview Experiences
Swiggy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Zoho Interview | Set 3 (Off-Campus)
Amazon Interview Experience for SDE-1 (Off-Campus) 2022
Amazon Interview Experience
Amazon Interview Experience for SDE-1
EPAM Interview Experience (Off-Campus)
Amazon Interview Experience (Off-Campus) 2022
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 | [
{
"code": null,
"e": 26325,
"s": 26297,
"text": "\n30 May, 2018"
},
{
"code": null,
"e": 26389,
"s": 26325,
"text": "First Round (Online Coding on HackerRank)4 problemsTime -90 min"
},
{
"code": null,
"e": 26426,
"s": 26389,
"text": "1. Stock Buy Sell to Maximize Profit"
},
{
"code": null,
"e": 26453,
"s": 26426,
"text": "Input: 1 3 100\nOutput: 196"
},
{
"code": null,
"e": 26506,
"s": 26453,
"text": "link- https://www.hackerrank.com/challenges/stockmax"
},
{
"code": null,
"e": 26568,
"s": 26506,
"text": "2. Given A string you need to print all subset of that string"
},
{
"code": null,
"e": 26665,
"s": 26568,
"text": "Input: \"abc\"\n\nOutput:\n \"a\"\n \"b\"\n \"c\"\n \"ab\"\n \"ac\"\n \"bc\"\n \"abc\""
},
{
"code": null,
"e": 26734,
"s": 26665,
"text": "3. Check if a given sequence of moves for a robot is circular or not"
},
{
"code": null,
"e": 26803,
"s": 26734,
"text": "Input: path[] = “GLGLGLG”Output: Given sequence of moves is circular"
},
{
"code": null,
"e": 26869,
"s": 26803,
"text": "Input: path[] = “GLLG”Output: Given sequence of moves is circular"
},
{
"code": null,
"e": 26972,
"s": 26869,
"text": "link- https://www.geeksforgeeks.org/check-if-a-given-sequence-of-moves-for-a-robot-is-circular-or-not/"
},
{
"code": null,
"e": 27009,
"s": 26972,
"text": "Second Round (F2F Interview) 45 min."
},
{
"code": null,
"e": 27188,
"s": 27009,
"text": "1. First he asked me to design the database for food shop, then he asked me to minimize the complexity of database and then he asked me some DBMS Query related to Join Operation."
},
{
"code": null,
"e": 27307,
"s": 27188,
"text": "2. Given a Sorted array in which all elements are repeated except one element. Find non repeated element in O (log n)."
},
{
"code": null,
"e": 27355,
"s": 27307,
"text": "3. Some Questions On DNS server and IP address."
},
{
"code": null,
"e": 27403,
"s": 27355,
"text": "4. What is cache Memory? What is TLB? And uses?"
},
{
"code": null,
"e": 27462,
"s": 27403,
"text": "5. Which policy you will use to swap pages? Implement LRU?"
},
{
"code": null,
"e": 27503,
"s": 27462,
"text": "Third Round (F2F Interview) (70-80) min."
},
{
"code": null,
"e": 27528,
"s": 27503,
"text": "1. Discussion on project"
},
{
"code": null,
"e": 27587,
"s": 27528,
"text": "2. What is Encryption? How you can use it in your project?"
},
{
"code": null,
"e": 27687,
"s": 27587,
"text": "3. What is Block cipher and Advanced Encryption Standard (AES)? If someone knows that you are using"
},
{
"code": null,
"e": 27779,
"s": 27687,
"text": "Polybius Cipher then what is the complexity in decrypting your original data (information)?"
},
{
"code": null,
"e": 27930,
"s": 27779,
"text": "4. He modified “Stock Buy Sell to Maximize Profit “problem i.e. you can’t buy or sell stock continuously and you can skip any day to sell or purchase."
},
{
"code": null,
"e": 27982,
"s": 27930,
"text": " Input: 2 100 2 3 500 2 1\n Output: max profit 596"
},
{
"code": null,
"e": 28019,
"s": 27982,
"text": "3. Diff between Mutex and Semaphore?"
},
{
"code": null,
"e": 28096,
"s": 28019,
"text": "4. There is stream of infinite number you need to find the median of number?"
},
{
"code": null,
"e": 28340,
"s": 28096,
"text": "Input: 1 5 10 15 20 22 35 ....inf\n\nOutput:\n Median of first number 1\n Median of first 2 numbers 3\n Median of first 3 numbers 5\n Median of first 4 numbers 7.5\n Median of first 5 numbers 15\n\n ....\n\n ...."
},
{
"code": null,
"e": 28429,
"s": 28340,
"text": "5. There are 4 resources and 4 process .Is there any condition in which Deadlock occurs?"
},
{
"code": null,
"e": 28504,
"s": 28429,
"text": "6. Find an Element in A Sorted Array which is rotated any number of times."
},
{
"code": null,
"e": 28571,
"s": 28504,
"text": "7. Again he asked me about Robot problem (1st round 3rd question)."
},
{
"code": null,
"e": 28778,
"s": 28571,
"text": "8. What is synchronization? If a process has opened a word file in write mode and preempted beforeclosing it, at the same time another process is trying to open that file in write mode .Will it Open or Not?"
},
{
"code": null,
"e": 28826,
"s": 28778,
"text": "Fourth Round (Online Interview on Skype) 60 min"
},
{
"code": null,
"e": 28877,
"s": 28826,
"text": "1. Any challenging task you did in last two Years?"
},
{
"code": null,
"e": 28920,
"s": 28877,
"text": "2. Write a code For Expression Evaluation?"
},
{
"code": null,
"e": 29012,
"s": 28920,
"text": "3. If i type www.facebook.com and clicked on search button, what will happen in background?"
},
{
"code": null,
"e": 29097,
"s": 29012,
"text": "4. Tell me about data structure that DNS server uses? How DNS search for IP address?"
},
{
"code": null,
"e": 29178,
"s": 29097,
"text": "5. O (2^n), O (n!) Which one complexity is better and why? Prove mathematically."
},
{
"code": null,
"e": 29236,
"s": 29178,
"text": "6. How Hashing works? Why its complexity is always O (1)."
},
{
"code": null,
"e": 29272,
"s": 29236,
"text": "7. Again he asked about my Project."
},
{
"code": null,
"e": 29302,
"s": 29272,
"text": "Fifth Round (HR round) 20 min"
},
{
"code": null,
"e": 29329,
"s": 29302,
"text": "1. Tell me about yourself?"
},
{
"code": null,
"e": 29369,
"s": 29329,
"text": "2. How was your online interview round?"
},
{
"code": null,
"e": 29450,
"s": 29369,
"text": "2. Why you want to join Start-up like Swiggy even you have other companies also?"
},
{
"code": null,
"e": 29479,
"s": 29450,
"text": "3. Do you have any question?"
},
{
"code": null,
"e": 29507,
"s": 29479,
"text": "Then i asked 3-4 questions."
},
{
"code": null,
"e": 29532,
"s": 29507,
"text": "Thank you GeeksforGeeks "
},
{
"code": null,
"e": 29753,
"s": 29532,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29760,
"s": 29753,
"text": "Swiggy"
},
{
"code": null,
"e": 29782,
"s": 29760,
"text": "Interview Experiences"
},
{
"code": null,
"e": 29789,
"s": 29782,
"text": "Swiggy"
},
{
"code": null,
"e": 29887,
"s": 29789,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29938,
"s": 29887,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 29980,
"s": 29938,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 30016,
"s": 29980,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 30052,
"s": 30016,
"text": "Zoho Interview | Set 3 (Off-Campus)"
},
{
"code": null,
"e": 30108,
"s": 30052,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022"
},
{
"code": null,
"e": 30136,
"s": 30108,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 30174,
"s": 30136,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 30213,
"s": 30174,
"text": "EPAM Interview Experience (Off-Campus)"
},
{
"code": null,
"e": 30259,
"s": 30213,
"text": "Amazon Interview Experience (Off-Campus) 2022"
}
] |
NumberFormat setMaximumFractionDigits() method in Java with Examples - GeeksforGeeks | 01 Apr, 2019
The setMaximumFractionDigits() method is a built-in method of the java.text.NumberFormat which sets the maximum number of digits allowed in the fraction portion of a number.If the new value for maximumFractionDigits is less than the current value of minimumFractionDigits, then minimumFractionDigits will also be set to the new value.
Syntax:
public void setMaximumFractionDigits(int val)
Parameters: The function accepts a mandatory parameter val which specifies the maximum value to be set.
Return Value: The function returns nothing, hence has a return type void.
Below is the implementation of the above function:
Program 1:
// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { NumberFormat nF = NumberFormat.getNumberInstance(); System.out.println("Maximum set initially as: " + nF.getMaximumFractionDigits()); // Set grouping nF.setMaximumFractionDigits(100); // Print the final System.out.println("Maximum set finally as: " + nF.getMaximumFractionDigits()); }}
Maximum set initially as: 3
Maximum set finally as: 100
Program 2:
// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { NumberFormat nF = NumberFormat.getNumberInstance(); System.out.println("Maximum set initially as: " + nF.getMaximumFractionDigits()); // Set grouping nF.setMaximumFractionDigits(6785); // Print the final System.out.println("Maximum set finally as: " + nF.getMaximumFractionDigits()); }}
Maximum set initially as: 3
Maximum set finally as: 6785
Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#setMaximumFractionDigits(int)
Java-Functions
Java-NumberFormat
Java-text package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java | [
{
"code": null,
"e": 25653,
"s": 25625,
"text": "\n01 Apr, 2019"
},
{
"code": null,
"e": 25988,
"s": 25653,
"text": "The setMaximumFractionDigits() method is a built-in method of the java.text.NumberFormat which sets the maximum number of digits allowed in the fraction portion of a number.If the new value for maximumFractionDigits is less than the current value of minimumFractionDigits, then minimumFractionDigits will also be set to the new value."
},
{
"code": null,
"e": 25996,
"s": 25988,
"text": "Syntax:"
},
{
"code": null,
"e": 26042,
"s": 25996,
"text": "public void setMaximumFractionDigits(int val)"
},
{
"code": null,
"e": 26146,
"s": 26042,
"text": "Parameters: The function accepts a mandatory parameter val which specifies the maximum value to be set."
},
{
"code": null,
"e": 26220,
"s": 26146,
"text": "Return Value: The function returns nothing, hence has a return type void."
},
{
"code": null,
"e": 26271,
"s": 26220,
"text": "Below is the implementation of the above function:"
},
{
"code": null,
"e": 26282,
"s": 26271,
"text": "Program 1:"
},
{
"code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { NumberFormat nF = NumberFormat.getNumberInstance(); System.out.println(\"Maximum set initially as: \" + nF.getMaximumFractionDigits()); // Set grouping nF.setMaximumFractionDigits(100); // Print the final System.out.println(\"Maximum set finally as: \" + nF.getMaximumFractionDigits()); }}",
"e": 26908,
"s": 26282,
"text": null
},
{
"code": null,
"e": 26965,
"s": 26908,
"text": "Maximum set initially as: 3\nMaximum set finally as: 100\n"
},
{
"code": null,
"e": 26976,
"s": 26965,
"text": "Program 2:"
},
{
"code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { NumberFormat nF = NumberFormat.getNumberInstance(); System.out.println(\"Maximum set initially as: \" + nF.getMaximumFractionDigits()); // Set grouping nF.setMaximumFractionDigits(6785); // Print the final System.out.println(\"Maximum set finally as: \" + nF.getMaximumFractionDigits()); }}",
"e": 27603,
"s": 26976,
"text": null
},
{
"code": null,
"e": 27661,
"s": 27603,
"text": "Maximum set initially as: 3\nMaximum set finally as: 6785\n"
},
{
"code": null,
"e": 27773,
"s": 27661,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#setMaximumFractionDigits(int)"
},
{
"code": null,
"e": 27788,
"s": 27773,
"text": "Java-Functions"
},
{
"code": null,
"e": 27806,
"s": 27788,
"text": "Java-NumberFormat"
},
{
"code": null,
"e": 27824,
"s": 27806,
"text": "Java-text package"
},
{
"code": null,
"e": 27829,
"s": 27824,
"text": "Java"
},
{
"code": null,
"e": 27834,
"s": 27829,
"text": "Java"
},
{
"code": null,
"e": 27932,
"s": 27834,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27983,
"s": 27932,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28013,
"s": 27983,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28028,
"s": 28013,
"text": "Stream In Java"
},
{
"code": null,
"e": 28047,
"s": 28028,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28078,
"s": 28047,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28096,
"s": 28078,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28128,
"s": 28096,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28148,
"s": 28128,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28180,
"s": 28148,
"text": "Multidimensional Arrays in Java"
}
] |
Python - Double Split String to Matrix - GeeksforGeeks | 01 Oct, 2020
Given a String, perform the double split, 1st for rows, and next for individual elements so that the given string can be converted to a matrix.
Examples:
Input : test_str = ‘Gfg,best*for,all*geeks,and,CS’, row_splt = “*”, ele_splt = “,” Output : [[‘Gfg’, ‘best’], [‘for’, ‘all’], [‘geeks’, ‘and’, ‘CS’]] Explanation : String split by rows, and elements by respective delims.
Input : test_str = ‘Gfg!best*for!all*geeks!and!CS’, row_splt = “*”, ele_splt = “!” Output : [[‘Gfg’, ‘best’], [‘for’, ‘all’], [‘geeks’, ‘and’, ‘CS’]] Explanation : String split by rows, and elements by respective delims.
Method #1 : Using split() + loop
In this, 1st split() is used to construct rows of Matrix, and then nested split() to get separation between individual elements.
Python3
# Python3 code to demonstrate working of # Double Split String to Matrix# Using split() + loop # initializing stringtest_str = 'Gfg,best#for,all#geeks,and,CS' # printing original stringprint("The original string is : " + str(test_str)) # initializing row split char row_splt = "#" # initializing element split char ele_splt = "," # split for rowstemp = test_str.split(row_splt)res = [] for ele in temp: # split for elements res.append(ele.split(ele_splt)) # printing result print("String after Matrix conversion : " + str(res))
Output:
The original string is : Gfg,best#for,all#geeks,and,CSString after Matrix conversion : [[‘Gfg’, ‘best’], [‘for’, ‘all’], [‘geeks’, ‘and’, ‘CS’]]
Method #2 : Using list comprehension + split()
This is yet another way in which this task can be performed. In this, we use a similar process, but one-liner to solve the problem.
Python3
# Python3 code to demonstrate working of # Double Split String to Matrix# Using list comprehension + split() # initializing stringtest_str = 'Gfg,best#for,all#geeks,and,CS' # printing original stringprint("The original string is : " + str(test_str)) # initializing row split char row_splt = "#" # initializing element split char ele_splt = "," # split for rowstemp = test_str.split(row_splt) # using list comprehension as shorthandres = [ele.split(ele_splt) for ele in temp] # printing result print("String after Matrix conversion : " + str(res))
Output:
The original string is : Gfg,best#for,all#geeks,and,CSString after Matrix conversion : [[‘Gfg’, ‘best’], [‘for’, ‘all’], [‘geeks’, ‘and’, ‘CS’]]
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 25681,
"s": 25537,
"text": "Given a String, perform the double split, 1st for rows, and next for individual elements so that the given string can be converted to a matrix."
},
{
"code": null,
"e": 25691,
"s": 25681,
"text": "Examples:"
},
{
"code": null,
"e": 25912,
"s": 25691,
"text": "Input : test_str = ‘Gfg,best*for,all*geeks,and,CS’, row_splt = “*”, ele_splt = “,” Output : [[‘Gfg’, ‘best’], [‘for’, ‘all’], [‘geeks’, ‘and’, ‘CS’]] Explanation : String split by rows, and elements by respective delims."
},
{
"code": null,
"e": 26134,
"s": 25912,
"text": "Input : test_str = ‘Gfg!best*for!all*geeks!and!CS’, row_splt = “*”, ele_splt = “!” Output : [[‘Gfg’, ‘best’], [‘for’, ‘all’], [‘geeks’, ‘and’, ‘CS’]] Explanation : String split by rows, and elements by respective delims. "
},
{
"code": null,
"e": 26167,
"s": 26134,
"text": "Method #1 : Using split() + loop"
},
{
"code": null,
"e": 26296,
"s": 26167,
"text": "In this, 1st split() is used to construct rows of Matrix, and then nested split() to get separation between individual elements."
},
{
"code": null,
"e": 26304,
"s": 26296,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Double Split String to Matrix# Using split() + loop # initializing stringtest_str = 'Gfg,best#for,all#geeks,and,CS' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing row split char row_splt = \"#\" # initializing element split char ele_splt = \",\" # split for rowstemp = test_str.split(row_splt)res = [] for ele in temp: # split for elements res.append(ele.split(ele_splt)) # printing result print(\"String after Matrix conversion : \" + str(res)) ",
"e": 26860,
"s": 26304,
"text": null
},
{
"code": null,
"e": 26868,
"s": 26860,
"text": "Output:"
},
{
"code": null,
"e": 27013,
"s": 26868,
"text": "The original string is : Gfg,best#for,all#geeks,and,CSString after Matrix conversion : [[‘Gfg’, ‘best’], [‘for’, ‘all’], [‘geeks’, ‘and’, ‘CS’]]"
},
{
"code": null,
"e": 27060,
"s": 27013,
"text": "Method #2 : Using list comprehension + split()"
},
{
"code": null,
"e": 27192,
"s": 27060,
"text": "This is yet another way in which this task can be performed. In this, we use a similar process, but one-liner to solve the problem."
},
{
"code": null,
"e": 27200,
"s": 27192,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Double Split String to Matrix# Using list comprehension + split() # initializing stringtest_str = 'Gfg,best#for,all#geeks,and,CS' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing row split char row_splt = \"#\" # initializing element split char ele_splt = \",\" # split for rowstemp = test_str.split(row_splt) # using list comprehension as shorthandres = [ele.split(ele_splt) for ele in temp] # printing result print(\"String after Matrix conversion : \" + str(res))",
"e": 27762,
"s": 27200,
"text": null
},
{
"code": null,
"e": 27770,
"s": 27762,
"text": "Output:"
},
{
"code": null,
"e": 27915,
"s": 27770,
"text": "The original string is : Gfg,best#for,all#geeks,and,CSString after Matrix conversion : [[‘Gfg’, ‘best’], [‘for’, ‘all’], [‘geeks’, ‘and’, ‘CS’]]"
},
{
"code": null,
"e": 27938,
"s": 27915,
"text": "Python string-programs"
},
{
"code": null,
"e": 27945,
"s": 27938,
"text": "Python"
},
{
"code": null,
"e": 27961,
"s": 27945,
"text": "Python Programs"
},
{
"code": null,
"e": 28059,
"s": 27961,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28091,
"s": 28059,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28133,
"s": 28091,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28175,
"s": 28133,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28231,
"s": 28175,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28258,
"s": 28231,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28280,
"s": 28258,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28319,
"s": 28280,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28365,
"s": 28319,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28403,
"s": 28365,
"text": "Python | Convert a list to dictionary"
}
] |
Collections swap() method in Java with Examples - GeeksforGeeks | 11 May, 2021
The swap() method of java.util.Collections class is used to swap the elements at the specified positions in the specified list. If the specified positions are equal, invoking this method leaves the list unchanged.
Syntax:
public static void swap(List list, int i, int j)
Parameters: This method takes the following argument as a Parameter
list – The list in which to swap elements.
i – the index of one element to be swapped.
j – the index of the other element to be swapped.
Exception This method throws IndexOutOfBoundsException, if either i or j is out of range (i = list.size() || j = list.size()).
Below are the examples to illustrate the swap() method
Example 1:
Java
// Java program to demonstrate// swap() method for String value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of List<String> List<String> vector = new ArrayList<String>(); // populate the vector vector.add("A"); vector.add("B"); vector.add("C"); vector.add("D"); vector.add("E"); // printing the vector before swap System.out.println("Before swap: " + vector); // swap the elements System.out.println("\nSwapping 0th and 4th element."); Collections.swap(vector, 0, 4); // printing the vector after swap System.out.println("\nAfter swap: " + vector); } catch (IndexOutOfBoundsException e) { System.out.println("\nException thrown : " + e); } }}
Before swap: [A, B, C, D, E]
Swapping 0th and 4th element.
After swap: [E, B, C, D, A]
Example 2: For IndexOutOfBoundsException
Java
// Java program to demonstrate// swap() method for IndexOutOfBoundsException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of List<String> List<String> vector = new ArrayList<String>(); // populate the vector vector.add("A"); vector.add("B"); vector.add("C"); vector.add("D"); vector.add("E"); // printing the vector before swap System.out.println("Before swap: " + vector); // swap the elements System.out.println("\nTrying to swap elements" + " more than upper bound index "); Collections.swap(vector, 0, 5); // printing the vector after swap System.out.println("After swap: " + vector); } catch (IndexOutOfBoundsException e) { System.out.println("Exception thrown : " + e); } }}
Before swap: [A, B, C, D, E]
Trying to swap elements more than upper bound index
Exception thrown : java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
sweetyty
Java - util package
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Multithreading in Java
Collections in Java
Queue Interface In Java | [
{
"code": null,
"e": 25549,
"s": 25521,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 25763,
"s": 25549,
"text": "The swap() method of java.util.Collections class is used to swap the elements at the specified positions in the specified list. If the specified positions are equal, invoking this method leaves the list unchanged."
},
{
"code": null,
"e": 25772,
"s": 25763,
"text": "Syntax: "
},
{
"code": null,
"e": 25821,
"s": 25772,
"text": "public static void swap(List list, int i, int j)"
},
{
"code": null,
"e": 25891,
"s": 25821,
"text": "Parameters: This method takes the following argument as a Parameter "
},
{
"code": null,
"e": 25934,
"s": 25891,
"text": "list – The list in which to swap elements."
},
{
"code": null,
"e": 25978,
"s": 25934,
"text": "i – the index of one element to be swapped."
},
{
"code": null,
"e": 26028,
"s": 25978,
"text": "j – the index of the other element to be swapped."
},
{
"code": null,
"e": 26155,
"s": 26028,
"text": "Exception This method throws IndexOutOfBoundsException, if either i or j is out of range (i = list.size() || j = list.size())."
},
{
"code": null,
"e": 26210,
"s": 26155,
"text": "Below are the examples to illustrate the swap() method"
},
{
"code": null,
"e": 26223,
"s": 26210,
"text": "Example 1: "
},
{
"code": null,
"e": 26228,
"s": 26223,
"text": "Java"
},
{
"code": "// Java program to demonstrate// swap() method for String value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of List<String> List<String> vector = new ArrayList<String>(); // populate the vector vector.add(\"A\"); vector.add(\"B\"); vector.add(\"C\"); vector.add(\"D\"); vector.add(\"E\"); // printing the vector before swap System.out.println(\"Before swap: \" + vector); // swap the elements System.out.println(\"\\nSwapping 0th and 4th element.\"); Collections.swap(vector, 0, 4); // printing the vector after swap System.out.println(\"\\nAfter swap: \" + vector); } catch (IndexOutOfBoundsException e) { System.out.println(\"\\nException thrown : \" + e); } }}",
"e": 27177,
"s": 26228,
"text": null
},
{
"code": null,
"e": 27266,
"s": 27177,
"text": "Before swap: [A, B, C, D, E]\n\nSwapping 0th and 4th element.\n\nAfter swap: [E, B, C, D, A]"
},
{
"code": null,
"e": 27310,
"s": 27268,
"text": "Example 2: For IndexOutOfBoundsException "
},
{
"code": null,
"e": 27315,
"s": 27310,
"text": "Java"
},
{
"code": "// Java program to demonstrate// swap() method for IndexOutOfBoundsException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of List<String> List<String> vector = new ArrayList<String>(); // populate the vector vector.add(\"A\"); vector.add(\"B\"); vector.add(\"C\"); vector.add(\"D\"); vector.add(\"E\"); // printing the vector before swap System.out.println(\"Before swap: \" + vector); // swap the elements System.out.println(\"\\nTrying to swap elements\" + \" more than upper bound index \"); Collections.swap(vector, 0, 5); // printing the vector after swap System.out.println(\"After swap: \" + vector); } catch (IndexOutOfBoundsException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 28323,
"s": 27315,
"text": null
},
{
"code": null,
"e": 28480,
"s": 28323,
"text": "Before swap: [A, B, C, D, E]\n\nTrying to swap elements more than upper bound index \nException thrown : java.lang.IndexOutOfBoundsException: Index: 5, Size: 5"
},
{
"code": null,
"e": 28491,
"s": 28482,
"text": "sweetyty"
},
{
"code": null,
"e": 28511,
"s": 28491,
"text": "Java - util package"
},
{
"code": null,
"e": 28528,
"s": 28511,
"text": "Java-Collections"
},
{
"code": null,
"e": 28543,
"s": 28528,
"text": "Java-Functions"
},
{
"code": null,
"e": 28548,
"s": 28543,
"text": "Java"
},
{
"code": null,
"e": 28553,
"s": 28548,
"text": "Java"
},
{
"code": null,
"e": 28570,
"s": 28553,
"text": "Java-Collections"
},
{
"code": null,
"e": 28668,
"s": 28570,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28683,
"s": 28668,
"text": "Stream In Java"
},
{
"code": null,
"e": 28702,
"s": 28683,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28720,
"s": 28702,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28740,
"s": 28720,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28772,
"s": 28740,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28796,
"s": 28772,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 28808,
"s": 28796,
"text": "Set in Java"
},
{
"code": null,
"e": 28831,
"s": 28808,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 28851,
"s": 28831,
"text": "Collections in Java"
}
] |
How to display title in Bootstrap-Select without empty element ? - GeeksforGeeks | 09 Apr, 2021
In this article, we will cover how to display the title in the Bootstrap-Select without any empty element in the select dropdown menu. Bootstrap Select is a form control that displays a collapsable list of different values that can be selected. This can be used for displaying forms or menus to the user.
Example 1: Using data-hidden attribute in the first option tag to hide the item in the list view. This sets the first data to be hidden and at the same time, we get to see it in the title.
HTML
<!DOCTYPE html><html> <head> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js"> </script></head> <body> <select class="selectpicker" title="Pick One"> <option data-hidden="true"> Choose Option </option> <option>First</option> <option>Second</option> <option>Third</option> </select></body> </html>
Output:
Setting title as per requirement without the empty element
Example 2: Using the multiple option, select attribute in the select tag and limiting the data-max-attribute to 1. After this, we set the title property as per our requirements.
HTML
<!DOCTYPE html><html> <head> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js"> </script></head> <body> <select class="selectpicker" multiple data-max-options="1" title="Choose Option"> <option>First</option> <option>Second</option> <option>Third</option> </select></body> </html>
Output:
Setting title as per requirement without the empty element
Example 3: Using CSS to hide the first option and setting the title as per our requirement.
HTML
<!DOCTYPE html><html> <head> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js"> </script> <style> .bootstrap-select ul.dropdown-menu li:first-child { display: none; } </style></head> <body> <br> <select class="selectpicker" title="Choose Option"> <option></option> <option>First</option> <option>Second</option> <option>Third</option> </select></body> </html>
Output:
Setting title as per requirement without the empty element
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Bootstrap-Questions
HTML-Attributes
HTML-Questions
HTML-Tags
Picked
Bootstrap
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
How to change the background color of the active nav-item?
How to keep gap between columns using Bootstrap?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 26745,
"s": 26717,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 27050,
"s": 26745,
"text": "In this article, we will cover how to display the title in the Bootstrap-Select without any empty element in the select dropdown menu. Bootstrap Select is a form control that displays a collapsable list of different values that can be selected. This can be used for displaying forms or menus to the user."
},
{
"code": null,
"e": 27239,
"s": 27050,
"text": "Example 1: Using data-hidden attribute in the first option tag to hide the item in the list view. This sets the first data to be hidden and at the same time, we get to see it in the title."
},
{
"code": null,
"e": 27244,
"s": 27239,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css\" rel=\"stylesheet\" /> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css\" rel=\"stylesheet\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js\"> </script></head> <body> <select class=\"selectpicker\" title=\"Pick One\"> <option data-hidden=\"true\"> Choose Option </option> <option>First</option> <option>Second</option> <option>Third</option> </select></body> </html>",
"e": 28097,
"s": 27244,
"text": null
},
{
"code": null,
"e": 28105,
"s": 28097,
"text": "Output:"
},
{
"code": null,
"e": 28164,
"s": 28105,
"text": "Setting title as per requirement without the empty element"
},
{
"code": null,
"e": 28342,
"s": 28164,
"text": "Example 2: Using the multiple option, select attribute in the select tag and limiting the data-max-attribute to 1. After this, we set the title property as per our requirements."
},
{
"code": null,
"e": 28347,
"s": 28342,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css\" rel=\"stylesheet\" /> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css\" rel=\"stylesheet\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js\"> </script></head> <body> <select class=\"selectpicker\" multiple data-max-options=\"1\" title=\"Choose Option\"> <option>First</option> <option>Second</option> <option>Third</option> </select></body> </html>",
"e": 29172,
"s": 28347,
"text": null
},
{
"code": null,
"e": 29180,
"s": 29172,
"text": "Output:"
},
{
"code": null,
"e": 29239,
"s": 29180,
"text": "Setting title as per requirement without the empty element"
},
{
"code": null,
"e": 29331,
"s": 29239,
"text": "Example 3: Using CSS to hide the first option and setting the title as per our requirement."
},
{
"code": null,
"e": 29336,
"s": 29331,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css\" rel=\"stylesheet\" /> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css\" rel=\"stylesheet\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js\"> </script> <style> .bootstrap-select ul.dropdown-menu li:first-child { display: none; } </style></head> <body> <br> <select class=\"selectpicker\" title=\"Choose Option\"> <option></option> <option>First</option> <option>Second</option> <option>Third</option> </select></body> </html>",
"e": 30271,
"s": 29336,
"text": null
},
{
"code": null,
"e": 30279,
"s": 30271,
"text": "Output:"
},
{
"code": null,
"e": 30338,
"s": 30279,
"text": "Setting title as per requirement without the empty element"
},
{
"code": null,
"e": 30475,
"s": 30338,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 30495,
"s": 30475,
"text": "Bootstrap-Questions"
},
{
"code": null,
"e": 30511,
"s": 30495,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 30526,
"s": 30511,
"text": "HTML-Questions"
},
{
"code": null,
"e": 30536,
"s": 30526,
"text": "HTML-Tags"
},
{
"code": null,
"e": 30543,
"s": 30536,
"text": "Picked"
},
{
"code": null,
"e": 30553,
"s": 30543,
"text": "Bootstrap"
},
{
"code": null,
"e": 30558,
"s": 30553,
"text": "HTML"
},
{
"code": null,
"e": 30575,
"s": 30558,
"text": "Web Technologies"
},
{
"code": null,
"e": 30580,
"s": 30575,
"text": "HTML"
},
{
"code": null,
"e": 30678,
"s": 30580,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30719,
"s": 30678,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 30782,
"s": 30719,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 30815,
"s": 30782,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 30874,
"s": 30815,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 30923,
"s": 30874,
"text": "How to keep gap between columns using Bootstrap?"
},
{
"code": null,
"e": 30985,
"s": 30923,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31035,
"s": 30985,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 31083,
"s": 31035,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31143,
"s": 31083,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
GATE | GATE-CS-2014-(Set-1) | Question 65 - GeeksforGeeks | 28 Jun, 2021
Which of the regular expressions given below represent the following DFA?
I) 0*1(1+00*1)*
II) 0*1*1+11*0*1
III) (0+1)*1
(A) I and II only(B) I and III only(C) II and III only(D) I, II, and IIIAnswer: (B)Explanation:
I) 0*1(1+00*1)*
II) 0*1*1+11*0*1
III) (0+1)*1
(I) and (III) represent DFA.
(II) doesn't represent as the DFA accepts strings like 11011,
but the regular expression doesn't accept.
Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25675,
"s": 25647,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25749,
"s": 25675,
"text": "Which of the regular expressions given below represent the following DFA?"
},
{
"code": null,
"e": 25796,
"s": 25749,
"text": "I) 0*1(1+00*1)*\nII) 0*1*1+11*0*1\nIII) (0+1)*1 "
},
{
"code": null,
"e": 25892,
"s": 25796,
"text": "(A) I and II only(B) I and III only(C) II and III only(D) I, II, and IIIAnswer: (B)Explanation:"
},
{
"code": null,
"e": 26081,
"s": 25892,
"text": "I) 0*1(1+00*1)*\nII) 0*1*1+11*0*1\nIII) (0+1)*1 \n\n(I) and (III) represent DFA.\n\n(II) doesn't represent as the DFA accepts strings like 11011,\n but the regular expression doesn't accept. "
},
{
"code": null,
"e": 26103,
"s": 26081,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 26124,
"s": 26103,
"text": "GATE-CS-2014-(Set-1)"
},
{
"code": null,
"e": 26150,
"s": 26124,
"text": "GATE-GATE-CS-2014-(Set-1)"
},
{
"code": null,
"e": 26155,
"s": 26150,
"text": "GATE"
},
{
"code": null,
"e": 26253,
"s": 26155,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26287,
"s": 26253,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26321,
"s": 26287,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26355,
"s": 26321,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26388,
"s": 26355,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26424,
"s": 26388,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26460,
"s": 26424,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26494,
"s": 26460,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26528,
"s": 26494,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26562,
"s": 26528,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
File length() method in Java with Examples | 28 Jan, 2019
The length() function is a part of File class in Java . This function returns the length of the file denoted by the this abstract pathname was length.The function returns long value which represents the number of bits else returns 0L if the file does not exists or if an exception occurs.
Function signature:
public long length()
Syntax:
long var = file.length();
Parameters: This method does not accept any parameter.
Return Type The function returns long data type represents the length of the file in bits.
Exception: This method throws Security Exception if the write access to the file is denied
Below programs illustrates the use of length() function:
Example 1: The file “F:\\program.txt” is a existing file in F: Directory.
// Java program to demonstrate// length() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File("F:\\program.txt"); // Get the length of the file System.out.println("length: " + f.length()); }}
Output:
length: 100000
Example 2: The file “F:\\program1.txt” is empty
// Java program to demonstrate// length() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File("F:\\program.txt"); // Get the length of the file System.out.println("length: " + f.length()); }}
Output:
length: 0
Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file.
Java-File Class
java-file-handling
Java-Functions
Java-IO package
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 317,
"s": 28,
"text": "The length() function is a part of File class in Java . This function returns the length of the file denoted by the this abstract pathname was length.The function returns long value which represents the number of bits else returns 0L if the file does not exists or if an exception occurs."
},
{
"code": null,
"e": 337,
"s": 317,
"text": "Function signature:"
},
{
"code": null,
"e": 358,
"s": 337,
"text": "public long length()"
},
{
"code": null,
"e": 366,
"s": 358,
"text": "Syntax:"
},
{
"code": null,
"e": 392,
"s": 366,
"text": "long var = file.length();"
},
{
"code": null,
"e": 447,
"s": 392,
"text": "Parameters: This method does not accept any parameter."
},
{
"code": null,
"e": 538,
"s": 447,
"text": "Return Type The function returns long data type represents the length of the file in bits."
},
{
"code": null,
"e": 629,
"s": 538,
"text": "Exception: This method throws Security Exception if the write access to the file is denied"
},
{
"code": null,
"e": 686,
"s": 629,
"text": "Below programs illustrates the use of length() function:"
},
{
"code": null,
"e": 760,
"s": 686,
"text": "Example 1: The file “F:\\\\program.txt” is a existing file in F: Directory."
},
{
"code": "// Java program to demonstrate// length() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File(\"F:\\\\program.txt\"); // Get the length of the file System.out.println(\"length: \" + f.length()); }}",
"e": 1107,
"s": 760,
"text": null
},
{
"code": null,
"e": 1115,
"s": 1107,
"text": "Output:"
},
{
"code": null,
"e": 1130,
"s": 1115,
"text": "length: 100000"
},
{
"code": null,
"e": 1178,
"s": 1130,
"text": "Example 2: The file “F:\\\\program1.txt” is empty"
},
{
"code": "// Java program to demonstrate// length() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File(\"F:\\\\program.txt\"); // Get the length of the file System.out.println(\"length: \" + f.length()); }}",
"e": 1525,
"s": 1178,
"text": null
},
{
"code": null,
"e": 1533,
"s": 1525,
"text": "Output:"
},
{
"code": null,
"e": 1543,
"s": 1533,
"text": "length: 0"
},
{
"code": null,
"e": 1650,
"s": 1543,
"text": "Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file."
},
{
"code": null,
"e": 1666,
"s": 1650,
"text": "Java-File Class"
},
{
"code": null,
"e": 1685,
"s": 1666,
"text": "java-file-handling"
},
{
"code": null,
"e": 1700,
"s": 1685,
"text": "Java-Functions"
},
{
"code": null,
"e": 1716,
"s": 1700,
"text": "Java-IO package"
},
{
"code": null,
"e": 1730,
"s": 1716,
"text": "Java Programs"
}
] |
Collections unmodifiableMap() method in Java with Examples | 08 Oct, 2018
The unmodifiableMap() method of java.util.Collections class is used to return an unmodifiable view of the specified map. This method allows modules to provide users with “read-only” access to internal maps. Query operations on the returned map “read through” to the specified map, and attempts to modify the returned map, whether direct or via its collection views, result in an UnsupportedOperationException.
The returned map will be serializable if the specified map is serializable
Syntax:
public static <K, V> Map<K, V>
unmodifiableMap(Map<? extends K, ? extends V> m)
Parameters: This method takes the map as a parameter for which an unmodifiable view is to be returned.
Return Value: This method returns an unmodifiable view of the specified map.
Below are the examples to illustrate the unmodifiableMap() method
Example 1:
// Java program to demonstrate// unmodifiableMap() method// for <String, String> value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of Hashtable<String, String> Hashtable<String, String> table = new Hashtable<String, String>(); // populate the table table.put("key1", "1"); table.put("key2", "2"); table.put("key3", "3"); // getting unmodifiable map // using unmodifiableMap() method Map<String, String> m = Collections .unmodifiableMap(table); // printing the unmodifiableMap System.out.println("Initial collection: " + table); } catch (UnsupportedOperationException e) { System.out.println("Exception thrown : " + e); } }}
Initial collection: {key3=3, key2=2, key1=1}
Example 2: For UnsupportedOperationException
// Java program to demonstrate// unmodifiableMap() method// for <String, String> value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of Hashtable<String, String> Hashtable<String, String> table = new Hashtable<String, String>(); // populate the table table.put("key1", "1"); table.put("key2", "2"); table.put("key3", "3"); // getting unmodifiable map // using unmodifiableMap() method Map<String, String> m = Collections .unmodifiableMap(table); // printing the unmodifiableMap System.out.println("Initial collection: " + table); // Adding element to new Collection System.out.println("\nTrying to modify" + " the unmodifiablemap"); m.put("key4", "4"); } catch (UnsupportedOperationException e) { System.out.println("Exception thrown : " + e); } }}
Initial collection: {key3=3, key2=2, key1=1}
Trying to modify the unmodifiablemap
Exception thrown : java.lang.UnsupportedOperationException
Java - util package
Java-Collections
Java-Functions
Java Programs
Java-Collections
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, 2018"
},
{
"code": null,
"e": 462,
"s": 52,
"text": "The unmodifiableMap() method of java.util.Collections class is used to return an unmodifiable view of the specified map. This method allows modules to provide users with “read-only” access to internal maps. Query operations on the returned map “read through” to the specified map, and attempts to modify the returned map, whether direct or via its collection views, result in an UnsupportedOperationException."
},
{
"code": null,
"e": 537,
"s": 462,
"text": "The returned map will be serializable if the specified map is serializable"
},
{
"code": null,
"e": 545,
"s": 537,
"text": "Syntax:"
},
{
"code": null,
"e": 630,
"s": 545,
"text": "public static <K, V> Map<K, V> \n unmodifiableMap(Map<? extends K, ? extends V> m)"
},
{
"code": null,
"e": 733,
"s": 630,
"text": "Parameters: This method takes the map as a parameter for which an unmodifiable view is to be returned."
},
{
"code": null,
"e": 810,
"s": 733,
"text": "Return Value: This method returns an unmodifiable view of the specified map."
},
{
"code": null,
"e": 876,
"s": 810,
"text": "Below are the examples to illustrate the unmodifiableMap() method"
},
{
"code": null,
"e": 887,
"s": 876,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// unmodifiableMap() method// for <String, String> value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of Hashtable<String, String> Hashtable<String, String> table = new Hashtable<String, String>(); // populate the table table.put(\"key1\", \"1\"); table.put(\"key2\", \"2\"); table.put(\"key3\", \"3\"); // getting unmodifiable map // using unmodifiableMap() method Map<String, String> m = Collections .unmodifiableMap(table); // printing the unmodifiableMap System.out.println(\"Initial collection: \" + table); } catch (UnsupportedOperationException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 1827,
"s": 887,
"text": null
},
{
"code": null,
"e": 1873,
"s": 1827,
"text": "Initial collection: {key3=3, key2=2, key1=1}\n"
},
{
"code": null,
"e": 1918,
"s": 1873,
"text": "Example 2: For UnsupportedOperationException"
},
{
"code": "// Java program to demonstrate// unmodifiableMap() method// for <String, String> value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of Hashtable<String, String> Hashtable<String, String> table = new Hashtable<String, String>(); // populate the table table.put(\"key1\", \"1\"); table.put(\"key2\", \"2\"); table.put(\"key3\", \"3\"); // getting unmodifiable map // using unmodifiableMap() method Map<String, String> m = Collections .unmodifiableMap(table); // printing the unmodifiableMap System.out.println(\"Initial collection: \" + table); // Adding element to new Collection System.out.println(\"\\nTrying to modify\" + \" the unmodifiablemap\"); m.put(\"key4\", \"4\"); } catch (UnsupportedOperationException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 3083,
"s": 1918,
"text": null
},
{
"code": null,
"e": 3226,
"s": 3083,
"text": "Initial collection: {key3=3, key2=2, key1=1}\n\nTrying to modify the unmodifiablemap\nException thrown : java.lang.UnsupportedOperationException\n"
},
{
"code": null,
"e": 3246,
"s": 3226,
"text": "Java - util package"
},
{
"code": null,
"e": 3263,
"s": 3246,
"text": "Java-Collections"
},
{
"code": null,
"e": 3278,
"s": 3263,
"text": "Java-Functions"
},
{
"code": null,
"e": 3292,
"s": 3278,
"text": "Java Programs"
},
{
"code": null,
"e": 3309,
"s": 3292,
"text": "Java-Collections"
}
] |
Inheritance in Python | 07 Jul, 2022
Inheritance is the capability of one class to derive or inherit the properties from another class.
It represents real-world relationships well.
It provides the reusability of a code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it.
It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
Creating a Person class with Display methods.
Python3
# A Python program to demonstrate inheritance class Person(object): # Constructor def __init__(self, name, id): self.name = name self.id = id # To check if this person is an employee def Display(self): print(self.name, self.id) # Driver codeemp = Person("Satyam", 102) # An Object of Personemp.Display()
Output:
Satyam 102
Here Emp is another class which is going to inherit the properties of the Person class(base class).
Python3
class Emp(Person): def Print(self): print("Emp class called") Emp_details = Emp("Mayank", 103) # calling parent class functionEmp_details.Display() # Calling child class functionEmp_details.Print()
Output:
Mayank 103
Emp class called
Python3
# A Python program to demonstrate inheritance # Base or Super class. Note object in bracket.# (Generally, object is made ancestor of all classes)# In Python 3.x "class Person" is# equivalent to "class Person(object)" class Person(object): # Constructor def __init__(self, name): self.name = name # To get name def getName(self): return self.name # To check if this person is an employee def isEmployee(self): return False # Inherited or Subclass (Note Person in bracket)class Employee(Person): # Here we return true def isEmployee(self): return True # Driver codeemp = Person("Geek1") # An Object of Personprint(emp.getName(), emp.isEmployee()) emp = Employee("Geek2") # An Object of Employeeprint(emp.getName(), emp.isEmployee())
Output:
Geek1 False
Geek2 True
Like the Java Object class, in Python (from version 3. x), the object is the root of all classes.
In Python 3.x, “class Test(object)” and “class Test” are same.
In Python 2. x, “class Test(object)” creates a class with the object as a parent (called a new-style class), and “class Test” creates an old-style class (without an objecting parent).
A child class needs to identify which class is its parent class. This can be done by mentioning the parent class name in the definition of the child class.
Eg: class subclass_name (superclass_name):
Python3
# Python code to demonstrate how parent constructors# are called. # parent classclass Person(object): # __init__ is known as the constructor def __init__(self, name, idnumber): self.name = name self.idnumber = idnumber def display(self): print(self.name) print(self.idnumber) # child class class Employee(Person): def __init__(self, name, idnumber, salary, post): self.salary = salary self.post = post # invoking the __init__ of the parent class Person.__init__(self, name, idnumber) # creation of an object variable or an instancea = Employee('Rahul', 886012, 200000, "Intern") # calling a function of the class Person using its instancea.display()
Output:
Rahul
886012
‘a’ is the instance created for the class Person. It invokes the __init__() of the referred class. You can see ‘object’ written in the declaration of the class Person. In Python, every class inherits from a built-in basic class called ‘object’. The constructor i.e. the ‘__init__’ function of a class is invoked when we create an object variable or an instance of the class.The variables defined within __init__() are called the instance variables or objects. Hence, ‘name’ and ‘idnumber’ are the objects of the class Person. Similarly, ‘salary’ and ‘post’ are the objects of the class Employee. Since the class Employee inherits from class Person, ‘name’ and ‘idnumber’ are also the objects of class Employee.
If you forget to invoke the __init__() of the parent class then its instance variables would not be available to the child class.
The following code produces an error for the same reason.
Python3
class A: def __init__(self, n='Rahul'): self.name = n class B(A): def __init__(self, roll): self.roll = roll object = B(23)print(object.name)
Output :
Traceback (most recent call last):
File "/home/de4570cca20263ac2c4149f435dba22c.py", line 12, in
print (object.name)
AttributeError: 'B' object has no attribute 'name'
Single inheritance: When a child class inherits from only one parent class, it is called single inheritance. We saw an example above.
Multiple inheritances: When a child class inherits from multiple parent classes, it is called multiple inheritances.
Unlike java, python shows multiple inheritances.
Python3
# Python example to show the working of multiple# inheritance class Base1(object): def __init__(self): self.str1 = "Geek1" print("Base1") class Base2(object): def __init__(self): self.str2 = "Geek2" print("Base2") class Derived(Base1, Base2): def __init__(self): # Calling constructors of Base1 # and Base2 classes Base1.__init__(self) Base2.__init__(self) print("Derived") def printStrs(self): print(self.str1, self.str2) ob = Derived()ob.printStrs()
Output:
Base1
Base2
Derived
Geek1 Geek2
Multilevel inheritance: When we have a child and grandchild relationship.
Python3
# A Python program to demonstrate inheritance # Base or Super class. Note object in bracket.# (Generally, object is made ancestor of all classes)# In Python 3.x "class Person" is# equivalent to "class Person(object)" class Base(object): # Constructor def __init__(self, name): self.name = name # To get name def getName(self): return self.name # Inherited or Sub class (Note Person in bracket)class Child(Base): # Constructor def __init__(self, name, age): Base.__init__(self, name) self.age = age # To get name def getAge(self): return self.age # Inherited or Sub class (Note Person in bracket) class GrandChild(Child): # Constructor def __init__(self, name, age, address): Child.__init__(self, name, age) self.address = address # To get address def getAddress(self): return self.address # Driver codeg = GrandChild("Geek1", 23, "Noida")print(g.getName(), g.getAge(), g.getAddress())
Output:
Geek1 23 Noida
Hierarchical inheritance More than one derived class are created from a single base.
Hybrid inheritance: This form combines more than one form of inheritance. Basically, it is a blend of more than one type of inheritance.
For more details please read this article: Types of inheritance in Python
We don’t always want the instance variables of the parent class to be inherited by the child class i.e. we can make some of the instance variables of the parent class private, which won’t be available to the child class. We can make an instance variable private by adding double underscores before its name. For example,
Python3
# Python program to demonstrate private members# of the parent class class C(object): def __init__(self): self.c = 21 # d is private instance variable self.__d = 42 class D(C): def __init__(self): self.e = 84 C.__init__(self) object1 = D() # produces an error as d is private instance variableprint(object1.d)
Output :
File "/home/993bb61c3e76cda5bb67bd9ea05956a1.py", line 16, in
print (object1.d)
AttributeError: type object 'D' has no attribute 'd'
Since ‘d’ is made private by those underscores, it is not available to the child class ‘D’ and hence the error.
AyushShekhar
harshit_gokharu
shawnlouis2000
rohanasnani
droidbot
meghanathj1
surajkumarguptaintern
kumar_satyam
python-inheritance
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 152,
"s": 52,
"text": "Inheritance is the capability of one class to derive or inherit the properties from another class. "
},
{
"code": null,
"e": 197,
"s": 152,
"text": "It represents real-world relationships well."
},
{
"code": null,
"e": 363,
"s": 197,
"text": "It provides the reusability of a code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it."
},
{
"code": null,
"e": 521,
"s": 363,
"text": "It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A."
},
{
"code": null,
"e": 591,
"s": 521,
"text": "Class BaseClass:\n {Body}\nClass DerivedClass(BaseClass):\n {Body}"
},
{
"code": null,
"e": 637,
"s": 591,
"text": "Creating a Person class with Display methods."
},
{
"code": null,
"e": 645,
"s": 637,
"text": "Python3"
},
{
"code": "# A Python program to demonstrate inheritance class Person(object): # Constructor def __init__(self, name, id): self.name = name self.id = id # To check if this person is an employee def Display(self): print(self.name, self.id) # Driver codeemp = Person(\"Satyam\", 102) # An Object of Personemp.Display()",
"e": 967,
"s": 645,
"text": null
},
{
"code": null,
"e": 975,
"s": 967,
"text": "Output:"
},
{
"code": null,
"e": 986,
"s": 975,
"text": "Satyam 102"
},
{
"code": null,
"e": 1086,
"s": 986,
"text": "Here Emp is another class which is going to inherit the properties of the Person class(base class)."
},
{
"code": null,
"e": 1094,
"s": 1086,
"text": "Python3"
},
{
"code": "class Emp(Person): def Print(self): print(\"Emp class called\") Emp_details = Emp(\"Mayank\", 103) # calling parent class functionEmp_details.Display() # Calling child class functionEmp_details.Print()",
"e": 1303,
"s": 1094,
"text": null
},
{
"code": null,
"e": 1311,
"s": 1303,
"text": "Output:"
},
{
"code": null,
"e": 1339,
"s": 1311,
"text": "Mayank 103\nEmp class called"
},
{
"code": null,
"e": 1347,
"s": 1339,
"text": "Python3"
},
{
"code": "# A Python program to demonstrate inheritance # Base or Super class. Note object in bracket.# (Generally, object is made ancestor of all classes)# In Python 3.x \"class Person\" is# equivalent to \"class Person(object)\" class Person(object): # Constructor def __init__(self, name): self.name = name # To get name def getName(self): return self.name # To check if this person is an employee def isEmployee(self): return False # Inherited or Subclass (Note Person in bracket)class Employee(Person): # Here we return true def isEmployee(self): return True # Driver codeemp = Person(\"Geek1\") # An Object of Personprint(emp.getName(), emp.isEmployee()) emp = Employee(\"Geek2\") # An Object of Employeeprint(emp.getName(), emp.isEmployee())",
"e": 2139,
"s": 1347,
"text": null
},
{
"code": null,
"e": 2148,
"s": 2139,
"text": "Output: "
},
{
"code": null,
"e": 2171,
"s": 2148,
"text": "Geek1 False\nGeek2 True"
},
{
"code": null,
"e": 2270,
"s": 2171,
"text": "Like the Java Object class, in Python (from version 3. x), the object is the root of all classes. "
},
{
"code": null,
"e": 2334,
"s": 2270,
"text": "In Python 3.x, “class Test(object)” and “class Test” are same. "
},
{
"code": null,
"e": 2519,
"s": 2334,
"text": "In Python 2. x, “class Test(object)” creates a class with the object as a parent (called a new-style class), and “class Test” creates an old-style class (without an objecting parent). "
},
{
"code": null,
"e": 2676,
"s": 2519,
"text": "A child class needs to identify which class is its parent class. This can be done by mentioning the parent class name in the definition of the child class. "
},
{
"code": null,
"e": 2720,
"s": 2676,
"text": "Eg: class subclass_name (superclass_name): "
},
{
"code": null,
"e": 2728,
"s": 2720,
"text": "Python3"
},
{
"code": "# Python code to demonstrate how parent constructors# are called. # parent classclass Person(object): # __init__ is known as the constructor def __init__(self, name, idnumber): self.name = name self.idnumber = idnumber def display(self): print(self.name) print(self.idnumber) # child class class Employee(Person): def __init__(self, name, idnumber, salary, post): self.salary = salary self.post = post # invoking the __init__ of the parent class Person.__init__(self, name, idnumber) # creation of an object variable or an instancea = Employee('Rahul', 886012, 200000, \"Intern\") # calling a function of the class Person using its instancea.display()",
"e": 3451,
"s": 2728,
"text": null
},
{
"code": null,
"e": 3460,
"s": 3451,
"text": "Output: "
},
{
"code": null,
"e": 3473,
"s": 3460,
"text": "Rahul\n886012"
},
{
"code": null,
"e": 4184,
"s": 3473,
"text": "‘a’ is the instance created for the class Person. It invokes the __init__() of the referred class. You can see ‘object’ written in the declaration of the class Person. In Python, every class inherits from a built-in basic class called ‘object’. The constructor i.e. the ‘__init__’ function of a class is invoked when we create an object variable or an instance of the class.The variables defined within __init__() are called the instance variables or objects. Hence, ‘name’ and ‘idnumber’ are the objects of the class Person. Similarly, ‘salary’ and ‘post’ are the objects of the class Employee. Since the class Employee inherits from class Person, ‘name’ and ‘idnumber’ are also the objects of class Employee."
},
{
"code": null,
"e": 4315,
"s": 4184,
"text": "If you forget to invoke the __init__() of the parent class then its instance variables would not be available to the child class. "
},
{
"code": null,
"e": 4374,
"s": 4315,
"text": "The following code produces an error for the same reason. "
},
{
"code": null,
"e": 4382,
"s": 4374,
"text": "Python3"
},
{
"code": "class A: def __init__(self, n='Rahul'): self.name = n class B(A): def __init__(self, roll): self.roll = roll object = B(23)print(object.name)",
"e": 4546,
"s": 4382,
"text": null
},
{
"code": null,
"e": 4556,
"s": 4546,
"text": "Output : "
},
{
"code": null,
"e": 4731,
"s": 4556,
"text": "Traceback (most recent call last):\n File \"/home/de4570cca20263ac2c4149f435dba22c.py\", line 12, in \n print (object.name)\nAttributeError: 'B' object has no attribute 'name'"
},
{
"code": null,
"e": 4865,
"s": 4731,
"text": "Single inheritance: When a child class inherits from only one parent class, it is called single inheritance. We saw an example above."
},
{
"code": null,
"e": 4983,
"s": 4865,
"text": "Multiple inheritances: When a child class inherits from multiple parent classes, it is called multiple inheritances. "
},
{
"code": null,
"e": 5032,
"s": 4983,
"text": "Unlike java, python shows multiple inheritances."
},
{
"code": null,
"e": 5040,
"s": 5032,
"text": "Python3"
},
{
"code": "# Python example to show the working of multiple# inheritance class Base1(object): def __init__(self): self.str1 = \"Geek1\" print(\"Base1\") class Base2(object): def __init__(self): self.str2 = \"Geek2\" print(\"Base2\") class Derived(Base1, Base2): def __init__(self): # Calling constructors of Base1 # and Base2 classes Base1.__init__(self) Base2.__init__(self) print(\"Derived\") def printStrs(self): print(self.str1, self.str2) ob = Derived()ob.printStrs()",
"e": 5580,
"s": 5040,
"text": null
},
{
"code": null,
"e": 5589,
"s": 5580,
"text": "Output: "
},
{
"code": null,
"e": 5621,
"s": 5589,
"text": "Base1\nBase2\nDerived\nGeek1 Geek2"
},
{
"code": null,
"e": 5696,
"s": 5621,
"text": "Multilevel inheritance: When we have a child and grandchild relationship. "
},
{
"code": null,
"e": 5704,
"s": 5696,
"text": "Python3"
},
{
"code": "# A Python program to demonstrate inheritance # Base or Super class. Note object in bracket.# (Generally, object is made ancestor of all classes)# In Python 3.x \"class Person\" is# equivalent to \"class Person(object)\" class Base(object): # Constructor def __init__(self, name): self.name = name # To get name def getName(self): return self.name # Inherited or Sub class (Note Person in bracket)class Child(Base): # Constructor def __init__(self, name, age): Base.__init__(self, name) self.age = age # To get name def getAge(self): return self.age # Inherited or Sub class (Note Person in bracket) class GrandChild(Child): # Constructor def __init__(self, name, age, address): Child.__init__(self, name, age) self.address = address # To get address def getAddress(self): return self.address # Driver codeg = GrandChild(\"Geek1\", 23, \"Noida\")print(g.getName(), g.getAge(), g.getAddress())",
"e": 6691,
"s": 5704,
"text": null
},
{
"code": null,
"e": 6700,
"s": 6691,
"text": "Output: "
},
{
"code": null,
"e": 6715,
"s": 6700,
"text": "Geek1 23 Noida"
},
{
"code": null,
"e": 6800,
"s": 6715,
"text": "Hierarchical inheritance More than one derived class are created from a single base."
},
{
"code": null,
"e": 6937,
"s": 6800,
"text": "Hybrid inheritance: This form combines more than one form of inheritance. Basically, it is a blend of more than one type of inheritance."
},
{
"code": null,
"e": 7011,
"s": 6937,
"text": "For more details please read this article: Types of inheritance in Python"
},
{
"code": null,
"e": 7332,
"s": 7011,
"text": "We don’t always want the instance variables of the parent class to be inherited by the child class i.e. we can make some of the instance variables of the parent class private, which won’t be available to the child class. We can make an instance variable private by adding double underscores before its name. For example,"
},
{
"code": null,
"e": 7340,
"s": 7332,
"text": "Python3"
},
{
"code": "# Python program to demonstrate private members# of the parent class class C(object): def __init__(self): self.c = 21 # d is private instance variable self.__d = 42 class D(C): def __init__(self): self.e = 84 C.__init__(self) object1 = D() # produces an error as d is private instance variableprint(object1.d)",
"e": 7695,
"s": 7340,
"text": null
},
{
"code": null,
"e": 7705,
"s": 7695,
"text": "Output : "
},
{
"code": null,
"e": 7866,
"s": 7705,
"text": " File \"/home/993bb61c3e76cda5bb67bd9ea05956a1.py\", line 16, in \n print (object1.d) \nAttributeError: type object 'D' has no attribute 'd'"
},
{
"code": null,
"e": 7978,
"s": 7866,
"text": "Since ‘d’ is made private by those underscores, it is not available to the child class ‘D’ and hence the error."
},
{
"code": null,
"e": 7991,
"s": 7978,
"text": "AyushShekhar"
},
{
"code": null,
"e": 8007,
"s": 7991,
"text": "harshit_gokharu"
},
{
"code": null,
"e": 8022,
"s": 8007,
"text": "shawnlouis2000"
},
{
"code": null,
"e": 8034,
"s": 8022,
"text": "rohanasnani"
},
{
"code": null,
"e": 8043,
"s": 8034,
"text": "droidbot"
},
{
"code": null,
"e": 8055,
"s": 8043,
"text": "meghanathj1"
},
{
"code": null,
"e": 8077,
"s": 8055,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 8090,
"s": 8077,
"text": "kumar_satyam"
},
{
"code": null,
"e": 8109,
"s": 8090,
"text": "python-inheritance"
},
{
"code": null,
"e": 8129,
"s": 8109,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 8136,
"s": 8129,
"text": "Python"
}
] |
Puzzle | Guess the total number of coins | 28 Aug, 2018
There are 10 robbers named as’A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’ they stole some coins from a bank and they decided to divide these coins equally among themselves. So they divide the coins into 10 parts but the last robber ‘J’ got 1 coin less than other robbers. So the remaining 9 robbers murder ‘J’. They again decided to divide the coins into 9 parts. But this time again the last robber ‘I’ got 1 less coin than other robbers. So again the remaining 8 robbers murder ‘I’ and try to divide all coins in between remaining 8 robbers. But again this time ‘H’ got one less coin than the other. Now, this process goes on until 1 robber left i.e. is ‘A’. After that ‘A’ take all the coins and run away. Now you have to guess the total number of coins.
Answer: 2519
Explanation:In a first attempt if there was 1 more coin then the coins could be easily divided among 10 robbers. And in the second attempt also the coins could be equally divided in among 9 robbers and so on. So let just add one coin to the total number of the coin. So the total coins become N+1.now this (N+1) should be divisible by 10. It should be divisible by 9, 8, 7, 6, 5, 4, 3, 2, 1.So our answer should be LCM of (10, 9, 8, 7, 6, 5, 4, 3, 2, 1).Total Number of coins = LCM of (10, 9, 8, 7, 6, 5, 4, 3, 2, 1) which is 2520.Now we have to subtract 1 coin which we have added before, so the total number of coins is 2519.
Puzzles
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Aug, 2018"
},
{
"code": null,
"e": 816,
"s": 54,
"text": "There are 10 robbers named as’A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’ they stole some coins from a bank and they decided to divide these coins equally among themselves. So they divide the coins into 10 parts but the last robber ‘J’ got 1 coin less than other robbers. So the remaining 9 robbers murder ‘J’. They again decided to divide the coins into 9 parts. But this time again the last robber ‘I’ got 1 less coin than other robbers. So again the remaining 8 robbers murder ‘I’ and try to divide all coins in between remaining 8 robbers. But again this time ‘H’ got one less coin than the other. Now, this process goes on until 1 robber left i.e. is ‘A’. After that ‘A’ take all the coins and run away. Now you have to guess the total number of coins."
},
{
"code": null,
"e": 829,
"s": 816,
"text": "Answer: 2519"
},
{
"code": null,
"e": 1457,
"s": 829,
"text": "Explanation:In a first attempt if there was 1 more coin then the coins could be easily divided among 10 robbers. And in the second attempt also the coins could be equally divided in among 9 robbers and so on. So let just add one coin to the total number of the coin. So the total coins become N+1.now this (N+1) should be divisible by 10. It should be divisible by 9, 8, 7, 6, 5, 4, 3, 2, 1.So our answer should be LCM of (10, 9, 8, 7, 6, 5, 4, 3, 2, 1).Total Number of coins = LCM of (10, 9, 8, 7, 6, 5, 4, 3, 2, 1) which is 2520.Now we have to subtract 1 coin which we have added before, so the total number of coins is 2519."
},
{
"code": null,
"e": 1465,
"s": 1457,
"text": "Puzzles"
},
{
"code": null,
"e": 1473,
"s": 1465,
"text": "Puzzles"
}
] |
How to Compare Two Queries in SQL | 08 Jun, 2021
Queries in SQL :A query will either be an invitation for data results from your info or for action on the info, or each. a question will provide you with a solution to a straightforward question, perform calculations, mix data from totally different tables, add, change, or delete data from info.
Creating a Database :We use CREATE DATABASE command to create a new SQL database.
Syntax –
CREATE DATABASE db_name;
Creating a Table into a created Database :We use the CREATE TABLE command to create a new SQL database.
Syntax –
CREATE TABLE table_name ( col1 datatype, col2 datatype, col3 datatype, );
Inserting the values into created Table :We use INSERT INTO command to create a new SQL database.
Syntax –
INSERT INTO table_nameVALUES (value1, value2, value3);
Example Code to create a database and a table into it –
PHP
CREATE DATABASE myDatabase; CREATE TABLE myTable(Pid int,FName varchar(255),LName varchar(255),Adrs varchar(255),District varchar(255)); INSERT INTO myTable (Pid, FName, LName, Adrs, District)VALUES ('1','Krishna','Kripa','Jansa','Varanasi');
myDatabase: myTable
Pid
FName
LName
Adrs
District
1
Krishna
Kripa
Jansa
Varanasi
Comparison of Queries :For example, we’ve 2 similar tables in completely different databases and we wish to understand what’s different. Here are the scripts that make sample databases, tables, and information.
PHP
CREATE DATABASE myDatabase1;GOUSE myDatabase1;GO CREATE TABLE myTable(Aid int,Atype varchar(10),Acost varchar(10)); GO INSERT INTO myTable (Aid, Atype, Acost) VALUES ('001', '1', '40'), ('002', '2', '80'), ('003', '3', '120')GO CREATE DATABASE myDatabase2;GOUSE myDatabase2;GO CREATE TABLE myTable(Aid int,Atype varchar(10),Acost varchar(10)); GO INSERT INTO myTable (Aid, Atype, Acost) VALUES ('001', '1', '40'), ('002', '2', '80'), ('003', '3', '120'), ('004', '4', '160') GO
Output –For myDatabse1 –
Aid
Atype
Acost
001
1
40
002
2
80
003
3
120
For myDatabase2 –
Aid
Atype
Acost
001
1
40
002
2
80
003
3
120
004
4
160
Compare SQL Queries in Tables by using the EXCEPT keyword :EXCEPT shows the distinction between 2 tables. it’s wont to compare the variations between 2 tables.
Now run this query where we use the EXCEPT keyword over DB2 from DB1 –
PHP
SELECT * FROM myDatabase2.myTableEXCEPTSELECT * FROM myDatabase1.myTable
Aid
Atype
Acost
004
4
160
DBMS-SQL
Picked
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?
SQL | Sub queries in From Clause
Window functions in SQL
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
How to Import JSON Data into SQL Server?
SQL Query to Compare Two Dates | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 325,
"s": 28,
"text": "Queries in SQL :A query will either be an invitation for data results from your info or for action on the info, or each. a question will provide you with a solution to a straightforward question, perform calculations, mix data from totally different tables, add, change, or delete data from info."
},
{
"code": null,
"e": 407,
"s": 325,
"text": "Creating a Database :We use CREATE DATABASE command to create a new SQL database."
},
{
"code": null,
"e": 416,
"s": 407,
"text": "Syntax –"
},
{
"code": null,
"e": 441,
"s": 416,
"text": "CREATE DATABASE db_name;"
},
{
"code": null,
"e": 545,
"s": 441,
"text": "Creating a Table into a created Database :We use the CREATE TABLE command to create a new SQL database."
},
{
"code": null,
"e": 555,
"s": 545,
"text": "Syntax –"
},
{
"code": null,
"e": 636,
"s": 555,
"text": "CREATE TABLE table_name ( col1 datatype, col2 datatype, col3 datatype, );"
},
{
"code": null,
"e": 734,
"s": 636,
"text": "Inserting the values into created Table :We use INSERT INTO command to create a new SQL database."
},
{
"code": null,
"e": 743,
"s": 734,
"text": "Syntax –"
},
{
"code": null,
"e": 798,
"s": 743,
"text": "INSERT INTO table_nameVALUES (value1, value2, value3);"
},
{
"code": null,
"e": 854,
"s": 798,
"text": "Example Code to create a database and a table into it –"
},
{
"code": null,
"e": 858,
"s": 854,
"text": "PHP"
},
{
"code": "CREATE DATABASE myDatabase; CREATE TABLE myTable(Pid int,FName varchar(255),LName varchar(255),Adrs varchar(255),District varchar(255)); INSERT INTO myTable (Pid, FName, LName, Adrs, District)VALUES ('1','Krishna','Kripa','Jansa','Varanasi');",
"e": 1103,
"s": 858,
"text": null
},
{
"code": null,
"e": 1123,
"s": 1103,
"text": "myDatabase: myTable"
},
{
"code": null,
"e": 1127,
"s": 1123,
"text": "Pid"
},
{
"code": null,
"e": 1133,
"s": 1127,
"text": "FName"
},
{
"code": null,
"e": 1139,
"s": 1133,
"text": "LName"
},
{
"code": null,
"e": 1144,
"s": 1139,
"text": "Adrs"
},
{
"code": null,
"e": 1153,
"s": 1144,
"text": "District"
},
{
"code": null,
"e": 1155,
"s": 1153,
"text": "1"
},
{
"code": null,
"e": 1163,
"s": 1155,
"text": "Krishna"
},
{
"code": null,
"e": 1169,
"s": 1163,
"text": "Kripa"
},
{
"code": null,
"e": 1175,
"s": 1169,
"text": "Jansa"
},
{
"code": null,
"e": 1184,
"s": 1175,
"text": "Varanasi"
},
{
"code": null,
"e": 1395,
"s": 1184,
"text": "Comparison of Queries :For example, we’ve 2 similar tables in completely different databases and we wish to understand what’s different. Here are the scripts that make sample databases, tables, and information."
},
{
"code": null,
"e": 1399,
"s": 1395,
"text": "PHP"
},
{
"code": "CREATE DATABASE myDatabase1;GOUSE myDatabase1;GO CREATE TABLE myTable(Aid int,Atype varchar(10),Acost varchar(10)); GO INSERT INTO myTable (Aid, Atype, Acost) VALUES ('001', '1', '40'), ('002', '2', '80'), ('003', '3', '120')GO CREATE DATABASE myDatabase2;GOUSE myDatabase2;GO CREATE TABLE myTable(Aid int,Atype varchar(10),Acost varchar(10)); GO INSERT INTO myTable (Aid, Atype, Acost) VALUES ('001', '1', '40'), ('002', '2', '80'), ('003', '3', '120'), ('004', '4', '160') GO",
"e": 1892,
"s": 1399,
"text": null
},
{
"code": null,
"e": 1917,
"s": 1892,
"text": "Output –For myDatabse1 –"
},
{
"code": null,
"e": 1921,
"s": 1917,
"text": "Aid"
},
{
"code": null,
"e": 1927,
"s": 1921,
"text": "Atype"
},
{
"code": null,
"e": 1933,
"s": 1927,
"text": "Acost"
},
{
"code": null,
"e": 1937,
"s": 1933,
"text": "001"
},
{
"code": null,
"e": 1939,
"s": 1937,
"text": "1"
},
{
"code": null,
"e": 1942,
"s": 1939,
"text": "40"
},
{
"code": null,
"e": 1946,
"s": 1942,
"text": "002"
},
{
"code": null,
"e": 1948,
"s": 1946,
"text": "2"
},
{
"code": null,
"e": 1951,
"s": 1948,
"text": "80"
},
{
"code": null,
"e": 1955,
"s": 1951,
"text": "003"
},
{
"code": null,
"e": 1957,
"s": 1955,
"text": "3"
},
{
"code": null,
"e": 1961,
"s": 1957,
"text": "120"
},
{
"code": null,
"e": 1979,
"s": 1961,
"text": "For myDatabase2 –"
},
{
"code": null,
"e": 1983,
"s": 1979,
"text": "Aid"
},
{
"code": null,
"e": 1989,
"s": 1983,
"text": "Atype"
},
{
"code": null,
"e": 1995,
"s": 1989,
"text": "Acost"
},
{
"code": null,
"e": 1999,
"s": 1995,
"text": "001"
},
{
"code": null,
"e": 2001,
"s": 1999,
"text": "1"
},
{
"code": null,
"e": 2004,
"s": 2001,
"text": "40"
},
{
"code": null,
"e": 2008,
"s": 2004,
"text": "002"
},
{
"code": null,
"e": 2010,
"s": 2008,
"text": "2"
},
{
"code": null,
"e": 2013,
"s": 2010,
"text": "80"
},
{
"code": null,
"e": 2017,
"s": 2013,
"text": "003"
},
{
"code": null,
"e": 2019,
"s": 2017,
"text": "3"
},
{
"code": null,
"e": 2023,
"s": 2019,
"text": "120"
},
{
"code": null,
"e": 2027,
"s": 2023,
"text": "004"
},
{
"code": null,
"e": 2029,
"s": 2027,
"text": "4"
},
{
"code": null,
"e": 2033,
"s": 2029,
"text": "160"
},
{
"code": null,
"e": 2193,
"s": 2033,
"text": "Compare SQL Queries in Tables by using the EXCEPT keyword :EXCEPT shows the distinction between 2 tables. it’s wont to compare the variations between 2 tables."
},
{
"code": null,
"e": 2264,
"s": 2193,
"text": "Now run this query where we use the EXCEPT keyword over DB2 from DB1 –"
},
{
"code": null,
"e": 2268,
"s": 2264,
"text": "PHP"
},
{
"code": "SELECT * FROM myDatabase2.myTableEXCEPTSELECT * FROM myDatabase1.myTable",
"e": 2341,
"s": 2268,
"text": null
},
{
"code": null,
"e": 2345,
"s": 2341,
"text": "Aid"
},
{
"code": null,
"e": 2351,
"s": 2345,
"text": "Atype"
},
{
"code": null,
"e": 2357,
"s": 2351,
"text": "Acost"
},
{
"code": null,
"e": 2361,
"s": 2357,
"text": "004"
},
{
"code": null,
"e": 2363,
"s": 2361,
"text": "4"
},
{
"code": null,
"e": 2367,
"s": 2363,
"text": "160"
},
{
"code": null,
"e": 2376,
"s": 2367,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2383,
"s": 2376,
"text": "Picked"
},
{
"code": null,
"e": 2387,
"s": 2383,
"text": "SQL"
},
{
"code": null,
"e": 2391,
"s": 2387,
"text": "SQL"
},
{
"code": null,
"e": 2489,
"s": 2391,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2555,
"s": 2489,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2588,
"s": 2555,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2612,
"s": 2588,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2644,
"s": 2612,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2722,
"s": 2644,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2739,
"s": 2722,
"text": "SQL using Python"
},
{
"code": null,
"e": 2775,
"s": 2739,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2805,
"s": 2775,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2846,
"s": 2805,
"text": "How to Import JSON Data into SQL Server?"
}
] |
Vulmap – Web Vulnerability Scanning And Verification Tools | 14 Sep, 2021
Vulnerability Scanning is the process of testing the target domain for various vulnerabilities in Web containers, Web servers, Web middleware, and CMS, and other Web programs, and has vulnerability exploitation functions. Testing each CVE against the target domain manually is not possible as manual testing takes a lot of time. So automated testing is the approach through which we can test the different CVEs against the target domain more quickly. Vulmap is an automated script developed in the Python Language which tests for various CVEs against the target domain. Vulmap is open-source and free to use the tool. Vulmap supports the testing of multiple target domains parallelly. Vulmap supports saving the results in the text and JSON format for further uses.
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process Python Installation Steps on Linux
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/zhzyker/vulmap.git
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 vulmap
Step 3: You are in the directory of the Vulmap. Now you have to install a dependency of the Vulmap using the following command.
sudo pip3 install -r requirements.txt
Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section.
python3 vulmap.py -h
Example 1: Test all vulnerabilities poc mode.
In this example, We are testing some common vulnerabilities against the target domain geeksforgeeks.org.
python3 vulmap.py -u http://geeksforgeeks.org
Example 2: Display the list of supported vulnerabilities
In this example, We are displaying the list of available vulnerabilities.
python3 vulmap.py --list
Example 3: Check target domain for struts2 vuln
In this example, We are testing struts2 vulnerability against the geeksforgeeks.org domain.
python3 vulmap.py -u http://geeksforgeeks.org -a struts2
Example 4: Batch scan URLs in list.txt
In this example, We are testing a list of multiple targets at the same time.
python3 vulmap.py -f targets.txt
Example 5: Export scan results to result.txt
In this example, We are saving the results in text file format.
python3 vulmap.py -u http://facebook.com --output-text result.txt
Kali-Linux
Linux-Tools
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": "\n14 Sep, 2021"
},
{
"code": null,
"e": 795,
"s": 28,
"text": "Vulnerability Scanning is the process of testing the target domain for various vulnerabilities in Web containers, Web servers, Web middleware, and CMS, and other Web programs, and has vulnerability exploitation functions. Testing each CVE against the target domain manually is not possible as manual testing takes a lot of time. So automated testing is the approach through which we can test the different CVEs against the target domain more quickly. Vulmap is an automated script developed in the Python Language which tests for various CVEs against the target domain. Vulmap is open-source and free to use the tool. Vulmap supports the testing of multiple target domains parallelly. Vulmap supports saving the results in the text and JSON format for further uses. "
},
{
"code": null,
"e": 960,
"s": 795,
"text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process Python Installation Steps on Linux"
},
{
"code": null,
"e": 1051,
"s": 960,
"text": "Step 1: Use the following command to install the tool in your Kali Linux operating system."
},
{
"code": null,
"e": 1099,
"s": 1051,
"text": "git clone https://github.com/zhzyker/vulmap.git"
},
{
"code": null,
"e": 1237,
"s": 1099,
"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": 1248,
"s": 1237,
"text": "cd vulmap "
},
{
"code": null,
"e": 1376,
"s": 1248,
"text": "Step 3: You are in the directory of the Vulmap. Now you have to install a dependency of the Vulmap using the following command."
},
{
"code": null,
"e": 1414,
"s": 1376,
"text": "sudo pip3 install -r requirements.txt"
},
{
"code": null,
"e": 1574,
"s": 1414,
"text": "Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section."
},
{
"code": null,
"e": 1595,
"s": 1574,
"text": "python3 vulmap.py -h"
},
{
"code": null,
"e": 1641,
"s": 1595,
"text": "Example 1: Test all vulnerabilities poc mode."
},
{
"code": null,
"e": 1746,
"s": 1641,
"text": "In this example, We are testing some common vulnerabilities against the target domain geeksforgeeks.org."
},
{
"code": null,
"e": 1792,
"s": 1746,
"text": "python3 vulmap.py -u http://geeksforgeeks.org"
},
{
"code": null,
"e": 1849,
"s": 1792,
"text": "Example 2: Display the list of supported vulnerabilities"
},
{
"code": null,
"e": 1923,
"s": 1849,
"text": "In this example, We are displaying the list of available vulnerabilities."
},
{
"code": null,
"e": 1948,
"s": 1923,
"text": "python3 vulmap.py --list"
},
{
"code": null,
"e": 1996,
"s": 1948,
"text": "Example 3: Check target domain for struts2 vuln"
},
{
"code": null,
"e": 2088,
"s": 1996,
"text": "In this example, We are testing struts2 vulnerability against the geeksforgeeks.org domain."
},
{
"code": null,
"e": 2145,
"s": 2088,
"text": "python3 vulmap.py -u http://geeksforgeeks.org -a struts2"
},
{
"code": null,
"e": 2184,
"s": 2145,
"text": "Example 4: Batch scan URLs in list.txt"
},
{
"code": null,
"e": 2261,
"s": 2184,
"text": "In this example, We are testing a list of multiple targets at the same time."
},
{
"code": null,
"e": 2294,
"s": 2261,
"text": "python3 vulmap.py -f targets.txt"
},
{
"code": null,
"e": 2339,
"s": 2294,
"text": "Example 5: Export scan results to result.txt"
},
{
"code": null,
"e": 2403,
"s": 2339,
"text": "In this example, We are saving the results in text file format."
},
{
"code": null,
"e": 2469,
"s": 2403,
"text": "python3 vulmap.py -u http://facebook.com --output-text result.txt"
},
{
"code": null,
"e": 2480,
"s": 2469,
"text": "Kali-Linux"
},
{
"code": null,
"e": 2492,
"s": 2480,
"text": "Linux-Tools"
},
{
"code": null,
"e": 2503,
"s": 2492,
"text": "Linux-Unix"
}
] |
How to reverse an Array using STL in C++? | 23 Jun, 2022
Given an array arr[], reverse this array using STL in C++. Example:
Input: arr[] = {1, 45, 54, 71, 76, 12}
Output: {12, 76, 71, 54, 45, 1}
Input: arr[] = {1, 7, 5, 4, 6, 12}
Output: {12, 6, 4, 5, 7, 1}
Approach: Reversing can be done with the help of reverse() function provided in STL. Syntax:
reverse(start_index, index_next_to_last_index);
For example to reverse an array arr[] of size 'n' we need to write as follows:
reverse(arr, arr+n);
if we observe it is reverse(arr+0, arr+n);
which means, the reverse function reverse the elements in an array from index-0 to index-(n-1)
Ex: Given an array arr of size 7
reverse(arr, arr+5);
The above reverse function reverses the elements in an array from index-0 to index-4
CPP
// C++ program to reverse Array// using reverse() in STL #include <algorithm>#include <iostream>using namespace std; int main(){ // Get the array int arr[] = { 1, 45, 54, 71, 76, 12 }; // Compute the sizes int n = sizeof(arr) / sizeof(arr[0]); // Print the array cout << "Array: "; for (int i = 0; i < n; i++) cout << arr[i] << " "; // Reverse the array reverse(arr, arr + n); // Print the reversed array cout << "\nReversed Array: "; for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;}
Array: 1 45 54 71 76 12
Reversed Array: 12 76 71 54 45 1
gufideg
saitej7
cpp-array
STL
C++
C++ Programs
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 121,
"s": 53,
"text": "Given an array arr[], reverse this array using STL in C++. Example:"
},
{
"code": null,
"e": 256,
"s": 121,
"text": "Input: arr[] = {1, 45, 54, 71, 76, 12}\nOutput: {12, 76, 71, 54, 45, 1}\n\nInput: arr[] = {1, 7, 5, 4, 6, 12}\nOutput: {12, 6, 4, 5, 7, 1}"
},
{
"code": null,
"e": 349,
"s": 256,
"text": "Approach: Reversing can be done with the help of reverse() function provided in STL. Syntax:"
},
{
"code": null,
"e": 779,
"s": 349,
"text": "reverse(start_index, index_next_to_last_index);\n\nFor example to reverse an array arr[] of size 'n' we need to write as follows:\nreverse(arr, arr+n); \nif we observe it is reverse(arr+0, arr+n);\nwhich means, the reverse function reverse the elements in an array from index-0 to index-(n-1)\n\nEx: Given an array arr of size 7 \nreverse(arr, arr+5); \nThe above reverse function reverses the elements in an array from index-0 to index-4"
},
{
"code": null,
"e": 783,
"s": 779,
"text": "CPP"
},
{
"code": "// C++ program to reverse Array// using reverse() in STL #include <algorithm>#include <iostream>using namespace std; int main(){ // Get the array int arr[] = { 1, 45, 54, 71, 76, 12 }; // Compute the sizes int n = sizeof(arr) / sizeof(arr[0]); // Print the array cout << \"Array: \"; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; // Reverse the array reverse(arr, arr + n); // Print the reversed array cout << \"\\nReversed Array: \"; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}",
"e": 1337,
"s": 783,
"text": null
},
{
"code": null,
"e": 1395,
"s": 1337,
"text": "Array: 1 45 54 71 76 12 \nReversed Array: 12 76 71 54 45 1"
},
{
"code": null,
"e": 1403,
"s": 1395,
"text": "gufideg"
},
{
"code": null,
"e": 1411,
"s": 1403,
"text": "saitej7"
},
{
"code": null,
"e": 1421,
"s": 1411,
"text": "cpp-array"
},
{
"code": null,
"e": 1425,
"s": 1421,
"text": "STL"
},
{
"code": null,
"e": 1429,
"s": 1425,
"text": "C++"
},
{
"code": null,
"e": 1442,
"s": 1429,
"text": "C++ Programs"
},
{
"code": null,
"e": 1446,
"s": 1442,
"text": "STL"
},
{
"code": null,
"e": 1450,
"s": 1446,
"text": "CPP"
}
] |
Python | Writing to an excel file using openpyxl module | 03 May, 2018
Prerequisite : Reading an excel file using openpyxl
Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files.
For example, user might have to go through thousands of rows and pick out few handful information to make small changes based on some criteria. Using Openpyxl module, these tasks can be done very efficiently and easily.
Let’s see how to create and write to an excel-sheet using Python.
Code #1 : Program to print a active sheet title name
# import openpyxl moduleimport openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute. sheet = wb.active # Once have the Worksheet object,# one can get its name from the# title attribute.sheet_title = sheet.title print("active sheet title: " + sheet_title)
Output :
active sheet title: Sheet
Code #2 : Program to change the Title name
# import openpyxl moduleimport openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attributesheet = wb.active # One can change the name of the titlesheet.title = "sheet1" print("sheet name is renamed as: " + sheet.title)
Output :
sheet name is renamed as: sheet1
Code #3 :Program to write to an Excel sheet
# import openpyxl moduleimport openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attributesheet = wb.active # Cell objects also have row, column# and coordinate attributes that provide# location information for the cell. # Note: The first row or column integer# is 1, not 0. Cell object is created by# using sheet object's cell() method.c1 = sheet.cell(row = 1, column = 1) # writing values to cellsc1.value = "ANKIT" c2 = sheet.cell(row= 1 , column = 2)c2.value = "RAI" # Once have a Worksheet object, one can# access a cell object by its name also.# A2 means column = 1 & row = 2.c3 = sheet['A2']c3.value = "RAHUL" # B2 means column = 2 & row = 2.c4 = sheet['B2']c4.value = "RAI" # Anytime you modify the Workbook object# or its sheets and cells, the spreadsheet# file will not be saved until you call# the save() workbook method.wb.save("C:\\Users\\user\\Desktop\\demo.xlsx")
Output :
code #4 :Program to add Sheets in the Workbook
# import openpyxl moduleimport openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() sheet = wb.active # Sheets can be added to workbook with the# workbook object's create_sheet() method. wb.create_sheet(index = 1 , title = "demo sheet2") wb.save("C:\\Users\\user\\Desktop\\demo.xlsx")
Output :
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 May, 2018"
},
{
"code": null,
"e": 104,
"s": 52,
"text": "Prerequisite : Reading an excel file using openpyxl"
},
{
"code": null,
"e": 281,
"s": 104,
"text": "Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files."
},
{
"code": null,
"e": 501,
"s": 281,
"text": "For example, user might have to go through thousands of rows and pick out few handful information to make small changes based on some criteria. Using Openpyxl module, these tasks can be done very efficiently and easily."
},
{
"code": null,
"e": 567,
"s": 501,
"text": "Let’s see how to create and write to an excel-sheet using Python."
},
{
"code": null,
"e": 620,
"s": 567,
"text": "Code #1 : Program to print a active sheet title name"
},
{
"code": "# import openpyxl moduleimport openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute. sheet = wb.active # Once have the Worksheet object,# one can get its name from the# title attribute.sheet_title = sheet.title print(\"active sheet title: \" + sheet_title)",
"e": 997,
"s": 620,
"text": null
},
{
"code": null,
"e": 1006,
"s": 997,
"text": "Output :"
},
{
"code": null,
"e": 1032,
"s": 1006,
"text": "active sheet title: Sheet"
},
{
"code": null,
"e": 1076,
"s": 1032,
"text": " Code #2 : Program to change the Title name"
},
{
"code": "# import openpyxl moduleimport openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attributesheet = wb.active # One can change the name of the titlesheet.title = \"sheet1\" print(\"sheet name is renamed as: \" + sheet.title)",
"e": 1410,
"s": 1076,
"text": null
},
{
"code": null,
"e": 1419,
"s": 1410,
"text": "Output :"
},
{
"code": null,
"e": 1452,
"s": 1419,
"text": "sheet name is renamed as: sheet1"
},
{
"code": null,
"e": 1497,
"s": 1452,
"text": " Code #3 :Program to write to an Excel sheet"
},
{
"code": "# import openpyxl moduleimport openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attributesheet = wb.active # Cell objects also have row, column# and coordinate attributes that provide# location information for the cell. # Note: The first row or column integer# is 1, not 0. Cell object is created by# using sheet object's cell() method.c1 = sheet.cell(row = 1, column = 1) # writing values to cellsc1.value = \"ANKIT\" c2 = sheet.cell(row= 1 , column = 2)c2.value = \"RAI\" # Once have a Worksheet object, one can# access a cell object by its name also.# A2 means column = 1 & row = 2.c3 = sheet['A2']c3.value = \"RAHUL\" # B2 means column = 2 & row = 2.c4 = sheet['B2']c4.value = \"RAI\" # Anytime you modify the Workbook object# or its sheets and cells, the spreadsheet# file will not be saved until you call# the save() workbook method.wb.save(\"C:\\\\Users\\\\user\\\\Desktop\\\\demo.xlsx\")",
"e": 2496,
"s": 1497,
"text": null
},
{
"code": null,
"e": 2506,
"s": 2496,
"text": "Output : "
},
{
"code": null,
"e": 2553,
"s": 2506,
"text": "code #4 :Program to add Sheets in the Workbook"
},
{
"code": "# import openpyxl moduleimport openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() sheet = wb.active # Sheets can be added to workbook with the# workbook object's create_sheet() method. wb.create_sheet(index = 1 , title = \"demo sheet2\") wb.save(\"C:\\\\Users\\\\user\\\\Desktop\\\\demo.xlsx\")",
"e": 2903,
"s": 2553,
"text": null
},
{
"code": null,
"e": 2912,
"s": 2903,
"text": "Output :"
},
{
"code": null,
"e": 2927,
"s": 2912,
"text": "python-modules"
},
{
"code": null,
"e": 2934,
"s": 2927,
"text": "Python"
}
] |
Java - String Buffer reverse() Method | This method reverses the value of the StringBuffer object that invoked the method.
Let n be the length of the old character sequence, the one contained in the string buffer just prior to the execution of the reverse method. Then, the character at index k in the new character sequence is equal to the character at index n-k-1 in the old character sequence.
Here is the syntax for this method −
public StringBuffer reverse()
Here is the detail of parameters −
NA
NA
This method returns StringBuffer object with the reversed sequence.
public class Test {
public static void main(String args[]) {
StringBuffer buffer = new StringBuffer("Game Plan");
buffer.reverse();
System.out.println(buffer);
}
}
This will produce the following result −
nalP emaG
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2460,
"s": 2377,
"text": "This method reverses the value of the StringBuffer object that invoked the method."
},
{
"code": null,
"e": 2734,
"s": 2460,
"text": "Let n be the length of the old character sequence, the one contained in the string buffer just prior to the execution of the reverse method. Then, the character at index k in the new character sequence is equal to the character at index n-k-1 in the old character sequence."
},
{
"code": null,
"e": 2771,
"s": 2734,
"text": "Here is the syntax for this method −"
},
{
"code": null,
"e": 2802,
"s": 2771,
"text": "public StringBuffer reverse()\n"
},
{
"code": null,
"e": 2837,
"s": 2802,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2840,
"s": 2837,
"text": "NA"
},
{
"code": null,
"e": 2843,
"s": 2840,
"text": "NA"
},
{
"code": null,
"e": 2911,
"s": 2843,
"text": "This method returns StringBuffer object with the reversed sequence."
},
{
"code": null,
"e": 3102,
"s": 2911,
"text": "public class Test {\n\n public static void main(String args[]) {\n StringBuffer buffer = new StringBuffer(\"Game Plan\");\n buffer.reverse();\n System.out.println(buffer);\n } \n}"
},
{
"code": null,
"e": 3143,
"s": 3102,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3154,
"s": 3143,
"text": "nalP emaG\n"
},
{
"code": null,
"e": 3187,
"s": 3154,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3203,
"s": 3187,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3236,
"s": 3203,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3252,
"s": 3236,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3287,
"s": 3252,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3301,
"s": 3287,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3335,
"s": 3301,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3349,
"s": 3335,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3386,
"s": 3349,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3401,
"s": 3386,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3434,
"s": 3401,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3453,
"s": 3434,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3460,
"s": 3453,
"text": " Print"
},
{
"code": null,
"e": 3471,
"s": 3460,
"text": " Add Notes"
}
] |
Solving Mazes With Python. Using Dijkstra’s Algorithm and OpenCV | by Max Reynolds | Towards Data Science | Mazes are often simple puzzles for humans, but they present a great programming problem that we can solve using shortest-path techniques like Dijkstra’s algorithm.
Dijkstra’s Algorithm is one of the more popular basic graph theory algorithms. It is used to find the shortest path between nodes on a directed graph. We start with a source node and known edge lengths between nodes.
We first assign a distance-from-source value to all the nodes. Node s receives a 0 value because it is the source; the rest receive values of ∞ to start.
Our node of interest is the smallest-value unprocessed node (shown in grey), which is s. First, we “relax” each adjacent vertex to our node of interest, updating their values to the minimum of their current value or the node of interest’s value plus the connecting edge length.
Node s is now finalized (black) and its neighbors a and b have taken on new values. The new node of interest is b, so we repeat the process of “relaxing” b’s adjacent nodes and finalizing the shortest-path value of b.
After going through each node, we eventually end up with a graph showing the shortest path length from the source to every node.
We can think of an image as a matrix of pixels. Each pixel (for simplicity’s sake) has an RGB value of 0,0,0 (black) or 255,255,255 (white). Our goal is to create a shortest path which starts in the white and does not cross into the black boundaries. To represent this goal we can treat each pixel as a node and draw edges between neighboring pixels with edge lengths based on RGB value differences. We will use the Euclidean squared distance formula and add 0.1 to ensure no 0-distance path lengths (a requirement for Dijkstra’s algorithm):
This formula makes the distance of crossing through the maze boundary prohibitively large. As we can see, the shortest path from source to destination will clearly be around the barrier, not through it.
We can use OpenCV, a popular image processing library for Python, to extract pixel values and show our maze images. Let’s also identify the coordinates of our starting and ending locations by adding points to our maze
import cv2import matplotlib.pyplot as pltimport numpy as npimg = cv2.imread('maze.png') # read an image from a file usingcv2.circle(img,(5,220), 3, (255,0,0), -1) # add a circle at (5, 220)cv2.circle(img, (25,5), 3, (0,0,255), -1) # add a circle at (5,5)plt.figure(figsize=(7,7))plt.imshow(img) # show the imageplt.show()
We create a Vertex class which will help us keep track of the coordinates. We also want to keep track of the parent node so that we can reconstruct the entire path once we find our distance values.
class Vertex: def __init__(self,x_coord,y_coord): self.x=x_coord self.y=y_coord self.d=float('inf') #current distance from source node self.parent_x=None self.parent_y=None self.processed=False self.index_in_queue=None
We need to create a matrix of Vertices, representing the 2D layout of pixels in an image. This will be the basis for our Dijkstra’s algorithm graph. We also maintain a min-heap priority queue to keep track of unprocessed nodes.
def find_shortest_path(img,src,dst): pq=[] #min-heap priority queue imagerows,imagecols=img.shape[0],img.shape[1] matrix = np.full((imagerows, imagecols), None) #access matrix elements by matrix[row][col] #fill matrix with vertices for r in range(imagerows): for c in range(imagecols): matrix[r][c]=Vertex(c,r) matrix[r][c].index_in_queue=len(pq) pq.append(matrix[r][c]) #set source distance value to 0 matrix[source_y][source_x].d=0 #maintain min-heap invariant (minimum d Vertex at list index 0) pq = bubble_up(pq, matrix[source_y][source_x].index_in_queue)
We need several helper functions to help find edges and edge lengths between vertices:
#Implement euclidean squared distance formuladef get_distance(img,u,v): return 0.1 + (float(img[v][0])-float(img[u][0]))**2+(float(img[v][1])-float(img[u][1]))**2+(float(img[v][2])-float(img[u][2]))**2#Return neighbor directly above, below, right, and leftdef get_neighbors(mat,r,c): shape=mat.shape neighbors=[] #ensure neighbors are within image boundaries if r > 0 and not mat[r-1][c].processed: neighbors.append(mat[r-1][c]) if r < shape[0] - 1 and not mat[r+1][c].processed: neighbors.append(mat[r+1][c]) if c > 0 and not mat[r][c-1].processed: neighbors.append(mat[r][c-1]) if c < shape[1] - 1 and not mat[r][c+1].processed: neighbors.append(mat[r][c+1]) return neighbors
Now, we can implement Dijkstra’s Algorithm and assign distance (d) values to all of the pixel Vertices in the maze image:
while len(pq) > 0: u=pq[0] #smallest-value unprocessed node #remove node of interest from the queue pq[0]=pq[-1] pq[0].index_in_queue=0 pq.pop() pq=bubble_down(pq,0) #min-heap function, see source code u.processed=True neighbors = get_neighbors(matrix,u.y,u.x) for v in neighbors: dist=get_distance(img,(u.y,u.x),(v.y,v.x)) if u.d + dist < v.d: v.d = u.d+dist v.parent_x=u.x #keep track of the shortest path v.parent_y=u.y idx=v.index_in_queue pq=bubble_down(pq,idx) pq=bubble_up(pq,idx)
We can now call our shortest path function and draw the solution on our maze:
img = cv2.imread('maze.png') # read an image from a file using opencv (cv2) libraryp = find_shortest_path(img, (25,5), (5,220))drawPath(img,p)plt.figure(figsize=(7,7))plt.imshow(img) # show the image on the screen plt.show()
Let’s try other mazes from around the web.
The full source code is available on GitHub here and Part 2, creating a user interface for the maze solver is below:
medium.com
Registering for Medium membership supports my work. | [
{
"code": null,
"e": 336,
"s": 172,
"text": "Mazes are often simple puzzles for humans, but they present a great programming problem that we can solve using shortest-path techniques like Dijkstra’s algorithm."
},
{
"code": null,
"e": 553,
"s": 336,
"text": "Dijkstra’s Algorithm is one of the more popular basic graph theory algorithms. It is used to find the shortest path between nodes on a directed graph. We start with a source node and known edge lengths between nodes."
},
{
"code": null,
"e": 707,
"s": 553,
"text": "We first assign a distance-from-source value to all the nodes. Node s receives a 0 value because it is the source; the rest receive values of ∞ to start."
},
{
"code": null,
"e": 985,
"s": 707,
"text": "Our node of interest is the smallest-value unprocessed node (shown in grey), which is s. First, we “relax” each adjacent vertex to our node of interest, updating their values to the minimum of their current value or the node of interest’s value plus the connecting edge length."
},
{
"code": null,
"e": 1203,
"s": 985,
"text": "Node s is now finalized (black) and its neighbors a and b have taken on new values. The new node of interest is b, so we repeat the process of “relaxing” b’s adjacent nodes and finalizing the shortest-path value of b."
},
{
"code": null,
"e": 1332,
"s": 1203,
"text": "After going through each node, we eventually end up with a graph showing the shortest path length from the source to every node."
},
{
"code": null,
"e": 1874,
"s": 1332,
"text": "We can think of an image as a matrix of pixels. Each pixel (for simplicity’s sake) has an RGB value of 0,0,0 (black) or 255,255,255 (white). Our goal is to create a shortest path which starts in the white and does not cross into the black boundaries. To represent this goal we can treat each pixel as a node and draw edges between neighboring pixels with edge lengths based on RGB value differences. We will use the Euclidean squared distance formula and add 0.1 to ensure no 0-distance path lengths (a requirement for Dijkstra’s algorithm):"
},
{
"code": null,
"e": 2077,
"s": 1874,
"text": "This formula makes the distance of crossing through the maze boundary prohibitively large. As we can see, the shortest path from source to destination will clearly be around the barrier, not through it."
},
{
"code": null,
"e": 2295,
"s": 2077,
"text": "We can use OpenCV, a popular image processing library for Python, to extract pixel values and show our maze images. Let’s also identify the coordinates of our starting and ending locations by adding points to our maze"
},
{
"code": null,
"e": 2617,
"s": 2295,
"text": "import cv2import matplotlib.pyplot as pltimport numpy as npimg = cv2.imread('maze.png') # read an image from a file usingcv2.circle(img,(5,220), 3, (255,0,0), -1) # add a circle at (5, 220)cv2.circle(img, (25,5), 3, (0,0,255), -1) # add a circle at (5,5)plt.figure(figsize=(7,7))plt.imshow(img) # show the imageplt.show()"
},
{
"code": null,
"e": 2815,
"s": 2617,
"text": "We create a Vertex class which will help us keep track of the coordinates. We also want to keep track of the parent node so that we can reconstruct the entire path once we find our distance values."
},
{
"code": null,
"e": 3086,
"s": 2815,
"text": "class Vertex: def __init__(self,x_coord,y_coord): self.x=x_coord self.y=y_coord self.d=float('inf') #current distance from source node self.parent_x=None self.parent_y=None self.processed=False self.index_in_queue=None"
},
{
"code": null,
"e": 3314,
"s": 3086,
"text": "We need to create a matrix of Vertices, representing the 2D layout of pixels in an image. This will be the basis for our Dijkstra’s algorithm graph. We also maintain a min-heap priority queue to keep track of unprocessed nodes."
},
{
"code": null,
"e": 3945,
"s": 3314,
"text": "def find_shortest_path(img,src,dst): pq=[] #min-heap priority queue imagerows,imagecols=img.shape[0],img.shape[1] matrix = np.full((imagerows, imagecols), None) #access matrix elements by matrix[row][col] #fill matrix with vertices for r in range(imagerows): for c in range(imagecols): matrix[r][c]=Vertex(c,r) matrix[r][c].index_in_queue=len(pq) pq.append(matrix[r][c]) #set source distance value to 0 matrix[source_y][source_x].d=0 #maintain min-heap invariant (minimum d Vertex at list index 0) pq = bubble_up(pq, matrix[source_y][source_x].index_in_queue)"
},
{
"code": null,
"e": 4032,
"s": 3945,
"text": "We need several helper functions to help find edges and edge lengths between vertices:"
},
{
"code": null,
"e": 4774,
"s": 4032,
"text": "#Implement euclidean squared distance formuladef get_distance(img,u,v): return 0.1 + (float(img[v][0])-float(img[u][0]))**2+(float(img[v][1])-float(img[u][1]))**2+(float(img[v][2])-float(img[u][2]))**2#Return neighbor directly above, below, right, and leftdef get_neighbors(mat,r,c): shape=mat.shape neighbors=[] #ensure neighbors are within image boundaries if r > 0 and not mat[r-1][c].processed: neighbors.append(mat[r-1][c]) if r < shape[0] - 1 and not mat[r+1][c].processed: neighbors.append(mat[r+1][c]) if c > 0 and not mat[r][c-1].processed: neighbors.append(mat[r][c-1]) if c < shape[1] - 1 and not mat[r][c+1].processed: neighbors.append(mat[r][c+1]) return neighbors"
},
{
"code": null,
"e": 4896,
"s": 4774,
"text": "Now, we can implement Dijkstra’s Algorithm and assign distance (d) values to all of the pixel Vertices in the maze image:"
},
{
"code": null,
"e": 5498,
"s": 4896,
"text": "while len(pq) > 0: u=pq[0] #smallest-value unprocessed node #remove node of interest from the queue pq[0]=pq[-1] pq[0].index_in_queue=0 pq.pop() pq=bubble_down(pq,0) #min-heap function, see source code u.processed=True neighbors = get_neighbors(matrix,u.y,u.x) for v in neighbors: dist=get_distance(img,(u.y,u.x),(v.y,v.x)) if u.d + dist < v.d: v.d = u.d+dist v.parent_x=u.x #keep track of the shortest path v.parent_y=u.y idx=v.index_in_queue pq=bubble_down(pq,idx) pq=bubble_up(pq,idx)"
},
{
"code": null,
"e": 5576,
"s": 5498,
"text": "We can now call our shortest path function and draw the solution on our maze:"
},
{
"code": null,
"e": 5801,
"s": 5576,
"text": "img = cv2.imread('maze.png') # read an image from a file using opencv (cv2) libraryp = find_shortest_path(img, (25,5), (5,220))drawPath(img,p)plt.figure(figsize=(7,7))plt.imshow(img) # show the image on the screen plt.show()"
},
{
"code": null,
"e": 5844,
"s": 5801,
"text": "Let’s try other mazes from around the web."
},
{
"code": null,
"e": 5961,
"s": 5844,
"text": "The full source code is available on GitHub here and Part 2, creating a user interface for the maze solver is below:"
},
{
"code": null,
"e": 5972,
"s": 5961,
"text": "medium.com"
}
] |
Tflearn: Solving XOR with a 2x2x1 feed forward neural network in Tensorflow | by Tadej Magajna | Towards Data Science | A simple guide on how to train a 2x2x1 feed forward neural network to solve the XOR problem using only 12 lines of code in python tflearn — a deep learning library built on top of Tensorflow.
The goal of our network is to train a network to receive two boolean inputs and return True only when one input is True and the other is False.
from tflearn import DNNfrom tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression
We define our input data X and expected results Y as a list of lists.Since neural networks in essence only deal with numerical values, we’ll transform our boolean expressions into numbers so that True=1 and False=0
X = [[0,0], [0,1], [1,0], [1,1]]Y = [[0], [1], [1], [0]]
We define the input, hidden and the output layers.Syntax for that couldn’t be simpler — use input_layer() for the input layer and fully_connected() for subsequent layers.
input_layer = input_data(shape=[None, 2])hidden_layer = fully_connected(input_layer , 2, activation='tanh') output_layer = fully_connected(hidden_layer, 1, activation='tanh')
Why is the input of shape [None, 2]? The network is fed in multiple learning examples at once. Since we’re using two features per leaning example and there are four examples, our data is of shape [4, 2]. But sometimes we like to define our network so it can receive any number of training examples. We can use None for any number of training examples and define the input shape as [None, number_of_features, ...]
regression = regression(output_layer , optimizer='sgd', loss='binary_crossentropy', learning_rate=5)model = DNN(regression)
In the code block above we define the regressor that will perform backpropagation and train our network. We’ll use Stochastic Gradient Descent as optimisation method and Binary Crossentropy as the loss function.
Finally we define our (hardly) deep neural network in ftlearn using, simply, DNN().
Next, we need to train the model. During this process, the regressor will try to optimise the loss function. The end result of training are simply weights (and biases) connecting layer nodes.
model.fit(X, Y, n_epoch=5000, show_metric=True)
After running model.fit(), Tensorflow will feed the input data 5000 times and try to fit the model.
If your output looks something like this (aim for small loss and high accuracy),
>>> Training Step: 5048 | total loss: 0.31394 | time: 0.002s| SGD | epoch: 5048 | loss: 0.31394 - binary_acc: 0.9994 -- iter: 4/4
your model is 0.999% accurate meaning that it successfully learned to solve the problem.
Note that your regressor will not always yield same results. It might even fail to learn to solve our problem correctly. This is because network weights are randomly initialised every time. Neural networks also need a lot of training data for backpropagation to work properly. Our code is therefore very dependent on how the weights are initialised.
To check whether out model really works, lets predict all possible combinations and transform the outputs to booleans using simple list comprehension
[i[0] > 0 for i in model.predict(X)]>>> [False, True, True, False]
Great! Our model works.
But what logic did the model use to solve the XOR problem? Let’s check under the hood.
Unlike AND and OR, XOR’s outputs are not linearly separable.Therefore, we need to introduce another hidden layer to solve it. It turns out that each node in the hidden layer represents one of the simpler linearly separable logical operations (AND, OR, NAND, ...) and the output layer will act as another logical operation fed by outputs from the previous layer.
If we were limited to using only simple logical operations, we could define XOR as
XOR(X1, X2) = AND(OR(X1, X2), NAND(X1, X2))
To understand what logic our network uses to come up with results, we need to analyse it’s weights (and biases).We do that with model.get_weights(layer.W) to get the weights vector and model.get_weights(layer.W) to get the biases vector.
print(model.get_weights(hidden_layer.W), model.get_weights(hidden_layer.b))print(model.get_weights(output_layer.W), model.get_weights(output_layer.b))>>> [[ 3.86708593 -3.11288071] [ 3.87053323 -3.1126008 ]] [-1.82562542 4.58438063]>>> [[ 5.19325304] [-4.87336922]
The image below shows which node the individual weights belong to (numbers are rounded for simplicity)
X1 and X2 are our input nodes. a1 and a2 are nodes in our hidden layer and O is the output node. B1 and B2 are biases.
What does this tell us? Well, nothing much yet. But by calculating the activations of nodes for individual inputs we can see how a particular node behaves. We’re using the formula (× stands for matrix multiplication):
activation = tanh(input × weights + biases)
Note that we’re using tanh() meaning that activations will be in range [-1, 1].
a1 is True (1) when there’s at least one 1 supplied in the input. a1 node therefore represents OR logical operation
a2 is True always apart from when both inputs are True. a2 node therefore represents NAND logical operation
output node is only True when both a1 and a2 are True.
The output node can be rewritten as:
O(X1, X2) = AND(a1(X1, X2), a2(X1, X2)) = AND(OR(X1, X2), NAND(X1, X2))
The trained network is therefore an AND operation of OR(X1, X2) and NAND(X1, X2)
Note that results will vary due to random weight initialisation, meaning that your weights will likely be different every time you train the model.
Full source can be found here: | [
{
"code": null,
"e": 364,
"s": 172,
"text": "A simple guide on how to train a 2x2x1 feed forward neural network to solve the XOR problem using only 12 lines of code in python tflearn — a deep learning library built on top of Tensorflow."
},
{
"code": null,
"e": 508,
"s": 364,
"text": "The goal of our network is to train a network to receive two boolean inputs and return True only when one input is True and the other is False."
},
{
"code": null,
"e": 648,
"s": 508,
"text": "from tflearn import DNNfrom tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression"
},
{
"code": null,
"e": 863,
"s": 648,
"text": "We define our input data X and expected results Y as a list of lists.Since neural networks in essence only deal with numerical values, we’ll transform our boolean expressions into numbers so that True=1 and False=0"
},
{
"code": null,
"e": 920,
"s": 863,
"text": "X = [[0,0], [0,1], [1,0], [1,1]]Y = [[0], [1], [1], [0]]"
},
{
"code": null,
"e": 1091,
"s": 920,
"text": "We define the input, hidden and the output layers.Syntax for that couldn’t be simpler — use input_layer() for the input layer and fully_connected() for subsequent layers."
},
{
"code": null,
"e": 1267,
"s": 1091,
"text": "input_layer = input_data(shape=[None, 2])hidden_layer = fully_connected(input_layer , 2, activation='tanh') output_layer = fully_connected(hidden_layer, 1, activation='tanh') "
},
{
"code": null,
"e": 1680,
"s": 1267,
"text": "Why is the input of shape [None, 2]? The network is fed in multiple learning examples at once. Since we’re using two features per leaning example and there are four examples, our data is of shape [4, 2]. But sometimes we like to define our network so it can receive any number of training examples. We can use None for any number of training examples and define the input shape as [None, number_of_features, ...]"
},
{
"code": null,
"e": 1804,
"s": 1680,
"text": "regression = regression(output_layer , optimizer='sgd', loss='binary_crossentropy', learning_rate=5)model = DNN(regression)"
},
{
"code": null,
"e": 2016,
"s": 1804,
"text": "In the code block above we define the regressor that will perform backpropagation and train our network. We’ll use Stochastic Gradient Descent as optimisation method and Binary Crossentropy as the loss function."
},
{
"code": null,
"e": 2100,
"s": 2016,
"text": "Finally we define our (hardly) deep neural network in ftlearn using, simply, DNN()."
},
{
"code": null,
"e": 2292,
"s": 2100,
"text": "Next, we need to train the model. During this process, the regressor will try to optimise the loss function. The end result of training are simply weights (and biases) connecting layer nodes."
},
{
"code": null,
"e": 2340,
"s": 2292,
"text": "model.fit(X, Y, n_epoch=5000, show_metric=True)"
},
{
"code": null,
"e": 2440,
"s": 2340,
"text": "After running model.fit(), Tensorflow will feed the input data 5000 times and try to fit the model."
},
{
"code": null,
"e": 2521,
"s": 2440,
"text": "If your output looks something like this (aim for small loss and high accuracy),"
},
{
"code": null,
"e": 2652,
"s": 2521,
"text": ">>> Training Step: 5048 | total loss: 0.31394 | time: 0.002s| SGD | epoch: 5048 | loss: 0.31394 - binary_acc: 0.9994 -- iter: 4/4"
},
{
"code": null,
"e": 2741,
"s": 2652,
"text": "your model is 0.999% accurate meaning that it successfully learned to solve the problem."
},
{
"code": null,
"e": 3091,
"s": 2741,
"text": "Note that your regressor will not always yield same results. It might even fail to learn to solve our problem correctly. This is because network weights are randomly initialised every time. Neural networks also need a lot of training data for backpropagation to work properly. Our code is therefore very dependent on how the weights are initialised."
},
{
"code": null,
"e": 3241,
"s": 3091,
"text": "To check whether out model really works, lets predict all possible combinations and transform the outputs to booleans using simple list comprehension"
},
{
"code": null,
"e": 3308,
"s": 3241,
"text": "[i[0] > 0 for i in model.predict(X)]>>> [False, True, True, False]"
},
{
"code": null,
"e": 3332,
"s": 3308,
"text": "Great! Our model works."
},
{
"code": null,
"e": 3419,
"s": 3332,
"text": "But what logic did the model use to solve the XOR problem? Let’s check under the hood."
},
{
"code": null,
"e": 3781,
"s": 3419,
"text": "Unlike AND and OR, XOR’s outputs are not linearly separable.Therefore, we need to introduce another hidden layer to solve it. It turns out that each node in the hidden layer represents one of the simpler linearly separable logical operations (AND, OR, NAND, ...) and the output layer will act as another logical operation fed by outputs from the previous layer."
},
{
"code": null,
"e": 3864,
"s": 3781,
"text": "If we were limited to using only simple logical operations, we could define XOR as"
},
{
"code": null,
"e": 3908,
"s": 3864,
"text": "XOR(X1, X2) = AND(OR(X1, X2), NAND(X1, X2))"
},
{
"code": null,
"e": 4146,
"s": 3908,
"text": "To understand what logic our network uses to come up with results, we need to analyse it’s weights (and biases).We do that with model.get_weights(layer.W) to get the weights vector and model.get_weights(layer.W) to get the biases vector."
},
{
"code": null,
"e": 4418,
"s": 4146,
"text": "print(model.get_weights(hidden_layer.W), model.get_weights(hidden_layer.b))print(model.get_weights(output_layer.W), model.get_weights(output_layer.b))>>> [[ 3.86708593 -3.11288071] [ 3.87053323 -3.1126008 ]] [-1.82562542 4.58438063]>>> [[ 5.19325304] [-4.87336922]"
},
{
"code": null,
"e": 4521,
"s": 4418,
"text": "The image below shows which node the individual weights belong to (numbers are rounded for simplicity)"
},
{
"code": null,
"e": 4640,
"s": 4521,
"text": "X1 and X2 are our input nodes. a1 and a2 are nodes in our hidden layer and O is the output node. B1 and B2 are biases."
},
{
"code": null,
"e": 4858,
"s": 4640,
"text": "What does this tell us? Well, nothing much yet. But by calculating the activations of nodes for individual inputs we can see how a particular node behaves. We’re using the formula (× stands for matrix multiplication):"
},
{
"code": null,
"e": 4902,
"s": 4858,
"text": "activation = tanh(input × weights + biases)"
},
{
"code": null,
"e": 4982,
"s": 4902,
"text": "Note that we’re using tanh() meaning that activations will be in range [-1, 1]."
},
{
"code": null,
"e": 5098,
"s": 4982,
"text": "a1 is True (1) when there’s at least one 1 supplied in the input. a1 node therefore represents OR logical operation"
},
{
"code": null,
"e": 5206,
"s": 5098,
"text": "a2 is True always apart from when both inputs are True. a2 node therefore represents NAND logical operation"
},
{
"code": null,
"e": 5261,
"s": 5206,
"text": "output node is only True when both a1 and a2 are True."
},
{
"code": null,
"e": 5298,
"s": 5261,
"text": "The output node can be rewritten as:"
},
{
"code": null,
"e": 5370,
"s": 5298,
"text": "O(X1, X2) = AND(a1(X1, X2), a2(X1, X2)) = AND(OR(X1, X2), NAND(X1, X2))"
},
{
"code": null,
"e": 5451,
"s": 5370,
"text": "The trained network is therefore an AND operation of OR(X1, X2) and NAND(X1, X2)"
},
{
"code": null,
"e": 5599,
"s": 5451,
"text": "Note that results will vary due to random weight initialisation, meaning that your weights will likely be different every time you train the model."
}
] |
for_each_n in C++17 - GeeksforGeeks | 13 Jun, 2018
The for_each_n() function was added in the C++17 technical specification. Its idea has been borrowed from the use of map in Python or Haskel. This function can be called with or without an execution policy. The execution policy lets you decide whether to utilize the new parallelization capabilities optimized to run on multiple cores or simply run it sequentially as with the previous standards. Even ignore the execution policy as all the functions have overloaded counterparts that run sequentially.
Simply put, for_each_n() helps apply a common function to all the elements of an array (or any other linear data-type). It essentially batches updates a range of elements starting from a given iterator and for a fixed number of elements from that iterator.
Syntax:
InputIt for_each_n( ExecutionPolicy&& policy,
InputIt first, Size n, UnaryFunction f )
policy: [Optional] The execution policy to use.
The function is overloaded without its use.
first: The iterator to the first element
you want to apply the operation on.
n: the number of elements to apply the function to.
f: the function object that is applied to the elements.
(Note: The given code requires C++17 or later and may not run in all C++17 environments.)
// Requires C++17 or 17+// C++ program to demonstrate the use for_each_n// using function pointers as lambda expressions.#include <bits/stdc++.h>using namespace std; /* Helper function to modify each element */int add1(int x){ return (x + 2);} int main(){ vector<int> arr({ 1, 2, 3, 4, 5, 6 }); // The initial vector for (auto i : arr) cout << i << " "; cout << endl; // Using function pointer as third parameter for_each_n(arr.begin(), 2, add1); // Print the modified vector for (auto i : arr) cout << i << " "; cout << endl; // Using lambda expression as third parameter for_each_n(arr.begin() + 2, 2, [](auto& x) { x += 2; }); // Print the modified vector for (auto i : arr) cout << i << " "; cout << endl; return 0;}
Output:
1 2 3 4 5 6
2 3 3 4 5 6
2 3 5 6 5 6
The true power and flexibility of for_each_n() can only be leveraged by the use of functors as its third argument.
(Note: The given code requires c++17 or later and may not run in all c++17 environments.)
// Requires C++17 or 17+// A C++ program to demonstrate the use for_each_n// using funcctors.#include <bits/stdc++.h>using namespace std; // A Functorclass add_del {private: int n; public: increment(int _n) : n(_n) { } // overloading () to create Functor objects int operator()(int delta) const { return n + delta; }}; int main(){ vector<int> arr({ 1, 2, 3, 4, 5, 6 }); // The initial vector for (auto i : arr) cout << i << " "; cout << endl; // Using functor as third parameter for_each_n(arr.begin(), 2, add_del(1)); for_each_n(arr.begin() + 2, 2, add_del(2)); // Print the modified vector for (auto i : arr) cout << i << " "; cout << endl; return 0;}
Output:
1 2 3 4 5 6
2 3 5 6 5 6
cpp-algorithm-library
Loops & Control Structure
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Friend class and function in C++
Polymorphism in C++
Inline Functions in C++
Exception Handling in C++
new and delete operators in C++ for dynamic memory
Destructors in C++
Sorting a vector in C++
std::string class in C++ | [
{
"code": null,
"e": 24018,
"s": 23990,
"text": "\n13 Jun, 2018"
},
{
"code": null,
"e": 24521,
"s": 24018,
"text": "The for_each_n() function was added in the C++17 technical specification. Its idea has been borrowed from the use of map in Python or Haskel. This function can be called with or without an execution policy. The execution policy lets you decide whether to utilize the new parallelization capabilities optimized to run on multiple cores or simply run it sequentially as with the previous standards. Even ignore the execution policy as all the functions have overloaded counterparts that run sequentially."
},
{
"code": null,
"e": 24778,
"s": 24521,
"text": "Simply put, for_each_n() helps apply a common function to all the elements of an array (or any other linear data-type). It essentially batches updates a range of elements starting from a given iterator and for a fixed number of elements from that iterator."
},
{
"code": null,
"e": 24786,
"s": 24778,
"text": "Syntax:"
},
{
"code": null,
"e": 25166,
"s": 24786,
"text": "InputIt for_each_n( ExecutionPolicy&& policy,\n InputIt first, Size n, UnaryFunction f )\n\npolicy: [Optional] The execution policy to use.\nThe function is overloaded without its use.\nfirst: The iterator to the first element \nyou want to apply the operation on.\nn: the number of elements to apply the function to.\nf: the function object that is applied to the elements. \n"
},
{
"code": null,
"e": 25256,
"s": 25166,
"text": "(Note: The given code requires C++17 or later and may not run in all C++17 environments.)"
},
{
"code": "// Requires C++17 or 17+// C++ program to demonstrate the use for_each_n// using function pointers as lambda expressions.#include <bits/stdc++.h>using namespace std; /* Helper function to modify each element */int add1(int x){ return (x + 2);} int main(){ vector<int> arr({ 1, 2, 3, 4, 5, 6 }); // The initial vector for (auto i : arr) cout << i << \" \"; cout << endl; // Using function pointer as third parameter for_each_n(arr.begin(), 2, add1); // Print the modified vector for (auto i : arr) cout << i << \" \"; cout << endl; // Using lambda expression as third parameter for_each_n(arr.begin() + 2, 2, [](auto& x) { x += 2; }); // Print the modified vector for (auto i : arr) cout << i << \" \"; cout << endl; return 0;}",
"e": 26060,
"s": 25256,
"text": null
},
{
"code": null,
"e": 26068,
"s": 26060,
"text": "Output:"
},
{
"code": null,
"e": 26105,
"s": 26068,
"text": "1 2 3 4 5 6\n2 3 3 4 5 6\n2 3 5 6 5 6\n"
},
{
"code": null,
"e": 26220,
"s": 26105,
"text": "The true power and flexibility of for_each_n() can only be leveraged by the use of functors as its third argument."
},
{
"code": null,
"e": 26310,
"s": 26220,
"text": "(Note: The given code requires c++17 or later and may not run in all c++17 environments.)"
},
{
"code": "// Requires C++17 or 17+// A C++ program to demonstrate the use for_each_n// using funcctors.#include <bits/stdc++.h>using namespace std; // A Functorclass add_del {private: int n; public: increment(int _n) : n(_n) { } // overloading () to create Functor objects int operator()(int delta) const { return n + delta; }}; int main(){ vector<int> arr({ 1, 2, 3, 4, 5, 6 }); // The initial vector for (auto i : arr) cout << i << \" \"; cout << endl; // Using functor as third parameter for_each_n(arr.begin(), 2, add_del(1)); for_each_n(arr.begin() + 2, 2, add_del(2)); // Print the modified vector for (auto i : arr) cout << i << \" \"; cout << endl; return 0;}",
"e": 27062,
"s": 26310,
"text": null
},
{
"code": null,
"e": 27070,
"s": 27062,
"text": "Output:"
},
{
"code": null,
"e": 27095,
"s": 27070,
"text": "1 2 3 4 5 6\n2 3 5 6 5 6\n"
},
{
"code": null,
"e": 27117,
"s": 27095,
"text": "cpp-algorithm-library"
},
{
"code": null,
"e": 27143,
"s": 27117,
"text": "Loops & Control Structure"
},
{
"code": null,
"e": 27147,
"s": 27143,
"text": "STL"
},
{
"code": null,
"e": 27151,
"s": 27147,
"text": "C++"
},
{
"code": null,
"e": 27155,
"s": 27151,
"text": "STL"
},
{
"code": null,
"e": 27159,
"s": 27155,
"text": "CPP"
},
{
"code": null,
"e": 27257,
"s": 27159,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27266,
"s": 27257,
"text": "Comments"
},
{
"code": null,
"e": 27279,
"s": 27266,
"text": "Old Comments"
},
{
"code": null,
"e": 27300,
"s": 27279,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 27328,
"s": 27300,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27361,
"s": 27328,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27381,
"s": 27361,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27405,
"s": 27381,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 27431,
"s": 27405,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 27482,
"s": 27431,
"text": "new and delete operators in C++ for dynamic memory"
},
{
"code": null,
"e": 27501,
"s": 27482,
"text": "Destructors in C++"
},
{
"code": null,
"e": 27525,
"s": 27501,
"text": "Sorting a vector in C++"
}
] |
How do I get the resource id of an image if I know its name in Android using Kotlin? | This example demonstrates how to get the resource id of an image if I know its name in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="400dp"
android:src="@drawable/ic_baseline_account_balance_24" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:textColor="@android:color/holo_blue_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val drawableName: String = "ic_baseline_account_balance_24" val resID = resources.getIdentifier(
drawableName, "drawable",
packageName
)
val tvResourceId: TextView = findViewById(R.id.textView)
tvResourceId.text = "Resource ID:$resID"
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen. | [
{
"code": null,
"e": 1171,
"s": 1062,
"text": "This example demonstrates how to get the resource id of an image if I know its name in Android using Kotlin."
},
{
"code": null,
"e": 1300,
"s": 1171,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1365,
"s": 1300,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2251,
"s": 1365,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"400dp\"\n android:src=\"@drawable/ic_baseline_account_balance_24\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/imageView\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"10dp\"\n android:textColor=\"@android:color/holo_blue_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2306,
"s": 2251,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 2905,
"s": 2306,
"text": "import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.widget.TextView\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val drawableName: String = \"ic_baseline_account_balance_24\" val resID = resources.getIdentifier(\n drawableName, \"drawable\",\n packageName\n )\n val tvResourceId: TextView = findViewById(R.id.textView)\n tvResourceId.text = \"Resource ID:$resID\"\n }\n}"
},
{
"code": null,
"e": 2960,
"s": 2905,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3634,
"s": 2960,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3983,
"s": 3634,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
}
] |
How To Analyse A Single Time Series Variable | by Jiahui Wang | Towards Data Science | Welcome back! This is the 2nd post in the column to explore analysing and modeling time series data with Python code. If you are not familiar with the basic statistical concepts, such as estimator, hypothesis testing, and p value, please check out my previous post: Time Series Modeling With Python Code: Fundamental Statistics.
In this post, we will start to explore analysing a single time series variable. Given a single time series variable, where should we start the analysis? How can we get some insights into the data? To be honest, the first time I was asked to generate insights of a time series data which just came in a .csv file without any further information about the data source and application, I got no idea of where to start. After this post, hopefully, the next time you will have some ideas on how to kick start analysing a single time series variable.
Here I will analyse the historical Apple stock price data. The .csv file can be downloaded from Yahoo finance. I downloaded the last year AAPL data, ranging from 3/13/2019 to 3/13/2020. The raw data includes daily open, high, low, close, adj close price and volume. In this post, I will analyse the daily close price of AAPL.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltAAPL_price = pd.read_csv('AAPL.csv',usecols=['Date', 'Close'])AAPL_price.set_index('Date',inplace=True,drop=True)AAPL_price.plot(legend=False)plt.title('AAPL Daily Close Price')
Sample parameters are not constant, and they are also changing with time. A single point sample mean or sample variance won’t reveal much information to us. Without knowing the variance of the sample parameter, we cannot know how well the sample parameter estimates the population parameter. Thus, we cannot rely on the point sample mean or sample variance to estimate the population parameters.
Instead of calculating a point sample mean and sample variance from the one-year AAPL stock price data, we will apply rolling window method to get multiple sample mean and sample variance values over the one year period. The following code shows how to visualize sample mean with different window size of 10, 30, and 50.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltAAPL_price = pd.read_csv('AAPL.csv',usecols=['Date', 'Close'])AAPL_price.set_index('Date',inplace=True,drop=True)ax = AAPL_price.plot(legend=False)ax.set_title('AAPL Daily Close Price')AAPL_price.rolling(window=10).mean().plot(ax=ax)AAPL_price.rolling(window=30).mean().plot(ax=ax)AAPL_price.rolling(window=50).mean().plot(ax=ax)ax.legend(['Daily price', 'm=10', 'm=20', 'm=30'])
Similarly, we can visualize sample variance with different window size.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltAAPL_price = pd.read_csv('AAPL.csv',usecols=['Date', 'Close'])AAPL_price.set_index('Date',inplace=True,drop=True)ax = AAPL_price.plot(legend=False)ax.set_title('AAPL Daily Close Price')AAPL_price.rolling(window=10).var().plot(ax=ax)AAPL_price.rolling(window=30).var().plot(ax=ax)AAPL_price.rolling(window=50).var().plot(ax=ax)ax.legend(['Daily price', 'm=10', 'm=30', 'm=50'])
When choosing the window size, there is always a tradeoff. Take rolling sample mean as an example, we will find that larger window size generates smoother rolling sample mean plot. I like to think about the choice of window size in terms of overfitting and underfitting. A small window size tends to catch more detailed information of each time point, while a large window size includes more overall information of a longer time period. In this way, a small window size may cause overfitting, as it pays too much attention to the movement of each time point. While a large window size may cause underfitting, as it captures too much overall trend but neglects the local movement of each point. Thus, a proper window size should be carefully chosen to avoid overfitting and underfitting.
In order to use ordinary least squares (OLS) to estimate the generation process, time series data need to stationary and weakly dependent. OLS is a commonly used method in linear regression and will be discussed in detail in the 4th post of this series: Time Series Modeling With Python Code: How To Model Time Series Data With Linear Regression.
Stationarity has three requirements. The mean and variance of the time series data both are constant. In addition, the covariance of two time points with a lag (h) is a function of the lag, while it should not be dependent on time point (t).
Weak dependence requires that the correlation of two time points becomes zero when the lag h becomes infinity.
There are two common time series processes: autoregressive process and moving average process. We will discuss these two processes in detail.
3.1 Autoregressive Process Property
For autoregressive process, the time series data depends on itself with a time lag. When the time series data only depends on itself with a time lag of 1, the process is called AR(1). If the time series data depends on itself with a time lag of N, then the process is called AR(N).
Here, take AR(1) as an example. AR(1) process is stationary and weak dependent if two requirements are met: the expected value of the first time point is zero, and the time series is dependent on the previous time point with a multiplying parameter that lies in between -1 and 1.
In AR(1) process, the value of ρ determines whether the AR(1) process is stationary. The following is a simple visualization of how ρ affects the AR(1) process. From the results, we can tell when ρ is closer to 1, the AR(1) process crosses zero line less frequently.
import numpy as npimport matplotlib.pyplot as pltN = 10000rho = 1sigma = np.random.normal(loc=0, scale=1, size=N)x = [0]for i in range(1,N): x.append(rho*x[-1]+sigma[i])plt.plot(x, label='rho=1')plt.legend()plt.xlim(0,N)
3.2 Moving Average Process Property
MA(1) process is stationary and weak dependent.
3.3 Autocorrelation Function (ACF) and Partial Autocorrelation Function (PACF)
According to the above MA(1) and AR(1) properties, we can write the correlation as follows:
By plotting the correlation of different time lags, we can clearly see the difference between AR(1) process and MA(1) process. This correlation graph is called autocorrelation function (ACF). The ACF plot of AR process shows exponential decrease, and the correlation decreases to almost zero after serval time points. However, the ACF plot of MA(1) process shows the correlation quickly drops towards zero after the first 2 time points.
import numpy as npimport matplotlib.pyplot as pltfrom statsmodels.graphics.tsaplots import plot_acfN = 10000rho = 0.5sigma = np.random.normal(loc=0, scale=1, size=N)x = [0]for i in range(1,N): x.append(rho*x[-1]+sigma[i])plot_acf(np.array(x),lags=10)
import numpy as npimport matplotlib.pyplot as pltfrom statsmodels.graphics.tsaplots import plot_acfN = 10000theta = 0.5sigma = np.random.normal(loc=0, scale=1, size=N+1)x = []for i in range(1,N+1): x.append(sigma[i]+theta*sigma[i-1])plot_acf(np.array(x),lags=10)
Although ACF plot can be used to differentiate MA and AR process, it cannot well differentiate AR(1) process from AR(2) process. Partial autocorrelation function (PACF) can be used to differentiate AR(1) and AR(2) process. As shown in the following example, PACF of AR(1) process shows the correlation quickly drops toward zero after the first 2 time points, while the PACF of AR(2) process shows the correlation drops toward zero after the first 3 time points.
import numpy as npimport matplotlib.pyplot as pltfrom statsmodels.graphics.tsaplots import plot_pacfN = 10000rho = 0.5rho2 = 0.4sigma = np.random.normal(loc=0, scale=1, size=N)x = [0,0]for i in range(2,N): x.append(rho*x[-1]+rho2*x[-2]+sigma[i])plot_pacf(np.array(x),lags=10)
4.1 Unit Root and Dickey-Fuller Test
As shown above, when ρ is 1, AR(1) process is non-stationary. The scenario where the ρ=1 in AR process is called unit root. The following is a simple proof of why unit root is non-stationary.
Unit root can be tested with Augmented Dickey-Fuller (ADF) test.
import pandas as pdfrom statsmodels.tsa.stattools import adfullerAAPL_price = pd.read_csv('AAPL.csv',usecols=['Close'])result = adfuller(AAPL_price.iloc[:,0].values)print(f'p value is {result[1]}')
Output:
p value is 0.5961654850033034
Since the p value is larger than the significance level of 0.05, we cannot reject the null hypothesis that the time series data is non-stationary. Thus, the time series data is non-stationary.
AR process with unit root is serially correlated. However, serially correlated time series data might not necessarily be AR process with unit root.
4.2 Order of Integration Process
For AR process with unit root, if the first order difference of the time series data is stationary, then the time series data follows I(1) process. Similarly, if the second order difference is required to get stationary data, then the process follows I(2) process. To find out the order of the integration process, a series of ADF need to be tested.
In this post, we discussed on how to analyse a single time series variable. Typically, we can start the analysis by plotting the rolling mean and variance of the time series data. Then we can use ACF test to see if the time series data follows the autoregressive process or moving average process. If the data follows the autoregressive process, we can then use the PACF test to find the order of the autoregressive process. In addition, we can use a Dickey-Fuller test to find if the time series data follows the integration process.
In the next post, we will continue to discuss how to analyse multiple time series variables. Please stay tuned! | [
{
"code": null,
"e": 500,
"s": 171,
"text": "Welcome back! This is the 2nd post in the column to explore analysing and modeling time series data with Python code. If you are not familiar with the basic statistical concepts, such as estimator, hypothesis testing, and p value, please check out my previous post: Time Series Modeling With Python Code: Fundamental Statistics."
},
{
"code": null,
"e": 1045,
"s": 500,
"text": "In this post, we will start to explore analysing a single time series variable. Given a single time series variable, where should we start the analysis? How can we get some insights into the data? To be honest, the first time I was asked to generate insights of a time series data which just came in a .csv file without any further information about the data source and application, I got no idea of where to start. After this post, hopefully, the next time you will have some ideas on how to kick start analysing a single time series variable."
},
{
"code": null,
"e": 1371,
"s": 1045,
"text": "Here I will analyse the historical Apple stock price data. The .csv file can be downloaded from Yahoo finance. I downloaded the last year AAPL data, ranging from 3/13/2019 to 3/13/2020. The raw data includes daily open, high, low, close, adj close price and volume. In this post, I will analyse the daily close price of AAPL."
},
{
"code": null,
"e": 1617,
"s": 1371,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltAAPL_price = pd.read_csv('AAPL.csv',usecols=['Date', 'Close'])AAPL_price.set_index('Date',inplace=True,drop=True)AAPL_price.plot(legend=False)plt.title('AAPL Daily Close Price')"
},
{
"code": null,
"e": 2013,
"s": 1617,
"text": "Sample parameters are not constant, and they are also changing with time. A single point sample mean or sample variance won’t reveal much information to us. Without knowing the variance of the sample parameter, we cannot know how well the sample parameter estimates the population parameter. Thus, we cannot rely on the point sample mean or sample variance to estimate the population parameters."
},
{
"code": null,
"e": 2334,
"s": 2013,
"text": "Instead of calculating a point sample mean and sample variance from the one-year AAPL stock price data, we will apply rolling window method to get multiple sample mean and sample variance values over the one year period. The following code shows how to visualize sample mean with different window size of 10, 30, and 50."
},
{
"code": null,
"e": 2782,
"s": 2334,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltAAPL_price = pd.read_csv('AAPL.csv',usecols=['Date', 'Close'])AAPL_price.set_index('Date',inplace=True,drop=True)ax = AAPL_price.plot(legend=False)ax.set_title('AAPL Daily Close Price')AAPL_price.rolling(window=10).mean().plot(ax=ax)AAPL_price.rolling(window=30).mean().plot(ax=ax)AAPL_price.rolling(window=50).mean().plot(ax=ax)ax.legend(['Daily price', 'm=10', 'm=20', 'm=30'])"
},
{
"code": null,
"e": 2854,
"s": 2782,
"text": "Similarly, we can visualize sample variance with different window size."
},
{
"code": null,
"e": 3299,
"s": 2854,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltAAPL_price = pd.read_csv('AAPL.csv',usecols=['Date', 'Close'])AAPL_price.set_index('Date',inplace=True,drop=True)ax = AAPL_price.plot(legend=False)ax.set_title('AAPL Daily Close Price')AAPL_price.rolling(window=10).var().plot(ax=ax)AAPL_price.rolling(window=30).var().plot(ax=ax)AAPL_price.rolling(window=50).var().plot(ax=ax)ax.legend(['Daily price', 'm=10', 'm=30', 'm=50'])"
},
{
"code": null,
"e": 4086,
"s": 3299,
"text": "When choosing the window size, there is always a tradeoff. Take rolling sample mean as an example, we will find that larger window size generates smoother rolling sample mean plot. I like to think about the choice of window size in terms of overfitting and underfitting. A small window size tends to catch more detailed information of each time point, while a large window size includes more overall information of a longer time period. In this way, a small window size may cause overfitting, as it pays too much attention to the movement of each time point. While a large window size may cause underfitting, as it captures too much overall trend but neglects the local movement of each point. Thus, a proper window size should be carefully chosen to avoid overfitting and underfitting."
},
{
"code": null,
"e": 4433,
"s": 4086,
"text": "In order to use ordinary least squares (OLS) to estimate the generation process, time series data need to stationary and weakly dependent. OLS is a commonly used method in linear regression and will be discussed in detail in the 4th post of this series: Time Series Modeling With Python Code: How To Model Time Series Data With Linear Regression."
},
{
"code": null,
"e": 4675,
"s": 4433,
"text": "Stationarity has three requirements. The mean and variance of the time series data both are constant. In addition, the covariance of two time points with a lag (h) is a function of the lag, while it should not be dependent on time point (t)."
},
{
"code": null,
"e": 4786,
"s": 4675,
"text": "Weak dependence requires that the correlation of two time points becomes zero when the lag h becomes infinity."
},
{
"code": null,
"e": 4928,
"s": 4786,
"text": "There are two common time series processes: autoregressive process and moving average process. We will discuss these two processes in detail."
},
{
"code": null,
"e": 4964,
"s": 4928,
"text": "3.1 Autoregressive Process Property"
},
{
"code": null,
"e": 5246,
"s": 4964,
"text": "For autoregressive process, the time series data depends on itself with a time lag. When the time series data only depends on itself with a time lag of 1, the process is called AR(1). If the time series data depends on itself with a time lag of N, then the process is called AR(N)."
},
{
"code": null,
"e": 5526,
"s": 5246,
"text": "Here, take AR(1) as an example. AR(1) process is stationary and weak dependent if two requirements are met: the expected value of the first time point is zero, and the time series is dependent on the previous time point with a multiplying parameter that lies in between -1 and 1."
},
{
"code": null,
"e": 5793,
"s": 5526,
"text": "In AR(1) process, the value of ρ determines whether the AR(1) process is stationary. The following is a simple visualization of how ρ affects the AR(1) process. From the results, we can tell when ρ is closer to 1, the AR(1) process crosses zero line less frequently."
},
{
"code": null,
"e": 6017,
"s": 5793,
"text": "import numpy as npimport matplotlib.pyplot as pltN = 10000rho = 1sigma = np.random.normal(loc=0, scale=1, size=N)x = [0]for i in range(1,N): x.append(rho*x[-1]+sigma[i])plt.plot(x, label='rho=1')plt.legend()plt.xlim(0,N)"
},
{
"code": null,
"e": 6053,
"s": 6017,
"text": "3.2 Moving Average Process Property"
},
{
"code": null,
"e": 6101,
"s": 6053,
"text": "MA(1) process is stationary and weak dependent."
},
{
"code": null,
"e": 6180,
"s": 6101,
"text": "3.3 Autocorrelation Function (ACF) and Partial Autocorrelation Function (PACF)"
},
{
"code": null,
"e": 6272,
"s": 6180,
"text": "According to the above MA(1) and AR(1) properties, we can write the correlation as follows:"
},
{
"code": null,
"e": 6709,
"s": 6272,
"text": "By plotting the correlation of different time lags, we can clearly see the difference between AR(1) process and MA(1) process. This correlation graph is called autocorrelation function (ACF). The ACF plot of AR process shows exponential decrease, and the correlation decreases to almost zero after serval time points. However, the ACF plot of MA(1) process shows the correlation quickly drops towards zero after the first 2 time points."
},
{
"code": null,
"e": 6963,
"s": 6709,
"text": "import numpy as npimport matplotlib.pyplot as pltfrom statsmodels.graphics.tsaplots import plot_acfN = 10000rho = 0.5sigma = np.random.normal(loc=0, scale=1, size=N)x = [0]for i in range(1,N): x.append(rho*x[-1]+sigma[i])plot_acf(np.array(x),lags=10)"
},
{
"code": null,
"e": 7229,
"s": 6963,
"text": "import numpy as npimport matplotlib.pyplot as pltfrom statsmodels.graphics.tsaplots import plot_acfN = 10000theta = 0.5sigma = np.random.normal(loc=0, scale=1, size=N+1)x = []for i in range(1,N+1): x.append(sigma[i]+theta*sigma[i-1])plot_acf(np.array(x),lags=10)"
},
{
"code": null,
"e": 7691,
"s": 7229,
"text": "Although ACF plot can be used to differentiate MA and AR process, it cannot well differentiate AR(1) process from AR(2) process. Partial autocorrelation function (PACF) can be used to differentiate AR(1) and AR(2) process. As shown in the following example, PACF of AR(1) process shows the correlation quickly drops toward zero after the first 2 time points, while the PACF of AR(2) process shows the correlation drops toward zero after the first 3 time points."
},
{
"code": null,
"e": 7970,
"s": 7691,
"text": "import numpy as npimport matplotlib.pyplot as pltfrom statsmodels.graphics.tsaplots import plot_pacfN = 10000rho = 0.5rho2 = 0.4sigma = np.random.normal(loc=0, scale=1, size=N)x = [0,0]for i in range(2,N): x.append(rho*x[-1]+rho2*x[-2]+sigma[i])plot_pacf(np.array(x),lags=10)"
},
{
"code": null,
"e": 8007,
"s": 7970,
"text": "4.1 Unit Root and Dickey-Fuller Test"
},
{
"code": null,
"e": 8199,
"s": 8007,
"text": "As shown above, when ρ is 1, AR(1) process is non-stationary. The scenario where the ρ=1 in AR process is called unit root. The following is a simple proof of why unit root is non-stationary."
},
{
"code": null,
"e": 8264,
"s": 8199,
"text": "Unit root can be tested with Augmented Dickey-Fuller (ADF) test."
},
{
"code": null,
"e": 8462,
"s": 8264,
"text": "import pandas as pdfrom statsmodels.tsa.stattools import adfullerAAPL_price = pd.read_csv('AAPL.csv',usecols=['Close'])result = adfuller(AAPL_price.iloc[:,0].values)print(f'p value is {result[1]}')"
},
{
"code": null,
"e": 8470,
"s": 8462,
"text": "Output:"
},
{
"code": null,
"e": 8500,
"s": 8470,
"text": "p value is 0.5961654850033034"
},
{
"code": null,
"e": 8693,
"s": 8500,
"text": "Since the p value is larger than the significance level of 0.05, we cannot reject the null hypothesis that the time series data is non-stationary. Thus, the time series data is non-stationary."
},
{
"code": null,
"e": 8841,
"s": 8693,
"text": "AR process with unit root is serially correlated. However, serially correlated time series data might not necessarily be AR process with unit root."
},
{
"code": null,
"e": 8874,
"s": 8841,
"text": "4.2 Order of Integration Process"
},
{
"code": null,
"e": 9224,
"s": 8874,
"text": "For AR process with unit root, if the first order difference of the time series data is stationary, then the time series data follows I(1) process. Similarly, if the second order difference is required to get stationary data, then the process follows I(2) process. To find out the order of the integration process, a series of ADF need to be tested."
},
{
"code": null,
"e": 9759,
"s": 9224,
"text": "In this post, we discussed on how to analyse a single time series variable. Typically, we can start the analysis by plotting the rolling mean and variance of the time series data. Then we can use ACF test to see if the time series data follows the autoregressive process or moving average process. If the data follows the autoregressive process, we can then use the PACF test to find the order of the autoregressive process. In addition, we can use a Dickey-Fuller test to find if the time series data follows the integration process."
}
] |
How to hide a widget after some time in Python Tkinter? | Tkinter is a standard Python library for developing GUI-based applications. We can create games, tools, and other applications using the Tkinter library. To develop GUI-based applications, Tkinter provides widgets.
Sometimes, there might be a requirement to hide a widget for some time. This can be achieved by using the pack_forget() method. When we pack the widget in the window using the various methods, we have to use the same method for hiding the widget.
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Create a canvas widget
canvas=Canvas(win, width=400, height=300)
canvas.pack()
# Add an image in the canvas widget
img=ImageTk.PhotoImage(file="baseball.png")
canvas.create_image(100, 150,image=img)
# Hide the image from the canvas after sometime
canvas.after(3000, canvas.pack_forget)
win.mainloop()
Running the given code will display an image in the Canvas widget that will disappear after sometime. | [
{
"code": null,
"e": 1277,
"s": 1062,
"text": "Tkinter is a standard Python library for developing GUI-based applications. We can create games, tools, and other applications using the Tkinter library. To develop GUI-based applications, Tkinter provides widgets."
},
{
"code": null,
"e": 1524,
"s": 1277,
"text": "Sometimes, there might be a requirement to hide a widget for some time. This can be achieved by using the pack_forget() method. When we pack the widget in the window using the various methods, we have to use the same method for hiding the widget."
},
{
"code": null,
"e": 2036,
"s": 1524,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom PIL import Image, ImageTk\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Create a canvas widget\ncanvas=Canvas(win, width=400, height=300)\ncanvas.pack()\n\n# Add an image in the canvas widget\nimg=ImageTk.PhotoImage(file=\"baseball.png\")\ncanvas.create_image(100, 150,image=img)\n\n# Hide the image from the canvas after sometime\ncanvas.after(3000, canvas.pack_forget)\n\nwin.mainloop()"
},
{
"code": null,
"e": 2138,
"s": 2036,
"text": "Running the given code will display an image in the Canvas widget that will disappear after sometime."
}
] |
Creating child process using fork() in Python | Our task is to create a child process and display process id of both parent and child process using fork() function in Python.
When we use fork(), it creates a copy of itself, it is a very important aspect of LINUX, UNIX. fork() is mainly applicable for multithreading environment that means the execution of the thread is duplicated created a child thread from a parent thread. When there is an error, the method will return a negative value and for the child process, it returns 0, Otherwise, it returns positive value that means we are in the parent process.
The fork() module can be used from the os module or from Pseudo terminal module called pty. So we should import os or pty for it.
The fork() is used to create a process, it has no argument and its return the process ID. The main reason for using fork() to create a new process which becomes the child process of the caller. When a new child process is created, both processes will execute the next instruction.
The return value of fork() we can understand which process we are when return 0 that means we are in the child process and if return positive value that means we are in the parent process and return negative value means that some error occurred.
import os
def parentchild():
n = os.fork()
if n > 0:
print("Parent process : ", os.getpid())
else:
print("Child proces : ", os.getpid())
# Driver code
parentchild()
Parent process : 8023
Child process : 8024
$
The Pseudo-terminal utility module pty is defined to handle pseudo-terminal concepts. Using this we can start another process, and also can read or write from controlling terminal using programs.
This module is highly platform oriented. We should use UNIX systems to perform these operations.
import pty, os
def process_parent_child():
(process_id, fd) = pty.fork()
print("The Process ID for the Current process is: " + str(os.getpid()))
print("The Process ID for the Child process is: " + str(process_id))
process_parent_child()
The Process ID for the Current process is: 12508
The Process ID for the Child process is: 12509 | [
{
"code": null,
"e": 1189,
"s": 1062,
"text": "Our task is to create a child process and display process id of both parent and child process using fork() function in Python."
},
{
"code": null,
"e": 1624,
"s": 1189,
"text": "When we use fork(), it creates a copy of itself, it is a very important aspect of LINUX, UNIX. fork() is mainly applicable for multithreading environment that means the execution of the thread is duplicated created a child thread from a parent thread. When there is an error, the method will return a negative value and for the child process, it returns 0, Otherwise, it returns positive value that means we are in the parent process."
},
{
"code": null,
"e": 1754,
"s": 1624,
"text": "The fork() module can be used from the os module or from Pseudo terminal module called pty. So we should import os or pty for it."
},
{
"code": null,
"e": 2035,
"s": 1754,
"text": "The fork() is used to create a process, it has no argument and its return the process ID. The main reason for using fork() to create a new process which becomes the child process of the caller. When a new child process is created, both processes will execute the next instruction."
},
{
"code": null,
"e": 2281,
"s": 2035,
"text": "The return value of fork() we can understand which process we are when return 0 that means we are in the child process and if return positive value that means we are in the parent process and return negative value means that some error occurred."
},
{
"code": null,
"e": 2473,
"s": 2281,
"text": "import os\n def parentchild():\n n = os.fork()\n if n > 0:\n print(\"Parent process : \", os.getpid())\n else:\n print(\"Child proces : \", os.getpid())\n# Driver code\nparentchild()"
},
{
"code": null,
"e": 2518,
"s": 2473,
"text": "Parent process : 8023\nChild process : 8024\n$"
},
{
"code": null,
"e": 2714,
"s": 2518,
"text": "The Pseudo-terminal utility module pty is defined to handle pseudo-terminal concepts. Using this we can start another process, and also can read or write from controlling terminal using programs."
},
{
"code": null,
"e": 2811,
"s": 2714,
"text": "This module is highly platform oriented. We should use UNIX systems to perform these operations."
},
{
"code": null,
"e": 3063,
"s": 2811,
"text": "import pty, os\n def process_parent_child():\n (process_id, fd) = pty.fork()\n print(\"The Process ID for the Current process is: \" + str(os.getpid()))\n print(\"The Process ID for the Child process is: \" + str(process_id))\nprocess_parent_child()"
},
{
"code": null,
"e": 3159,
"s": 3063,
"text": "The Process ID for the Current process is: 12508\nThe Process ID for the Child process is: 12509"
}
] |
Node.js process.traceDeprecation Property - GeeksforGeeks | 10 Jun, 2021
The process.traceDeprecation property is an inbuilt application programming interface of the process module which is used to indicate whether the –trace-deprecation flag is set on the current Node.js process.
Syntax:
process.traceDeprecation
Return Value: This property indicates whether the –trace-deprecation flag is set on the current Node.js process.
Below examples illustrate the use of the process.traceDeprecation property in Node.js:
Example 1:
index.js
// Node.js program to demonstrate the
// process.traceDeprecation Property
// Include process module
const process = require('process');
// Printing process.traceDeprecation property value
console.log(process.traceDeprecation);
Run the index.js file using the following command:
node --trace-deprecation index.js
Output:
true
Again run the same file, but using the different command as shown below:
node index.js
Output:
undefined
Example 2:
Filename: index.js
Javascript
// Node.js program to demonstrate the
// process.traceDeprecation Property
// Include process module
const process = require('process');
// Instance Properties
process.traceDeprecation = false;
// Printing process.traceDeprecation
// property value
console.log(process.traceDeprecation);
// Instance Properties
process.traceDeprecation = true;
// Printing process.traceDeprecation
// property value
console.log(process.traceDeprecation);
Run the index.js file using the following command:
node --trace-deprecation index.js
Output:
true
true
Again run the same file, but using the different command as shown below:
node index.js
Output:
false
true
Node.js-process-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
Mongoose Populate() Method
JWT Authentication with Node.js
Node.js Event Loop
How to build a basic CRUD app with Node.js and ReactJS ?
Express.js express.Router() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 24603,
"s": 24572,
"text": " \n10 Jun, 2021\n"
},
{
"code": null,
"e": 24812,
"s": 24603,
"text": "The process.traceDeprecation property is an inbuilt application programming interface of the process module which is used to indicate whether the –trace-deprecation flag is set on the current Node.js process."
},
{
"code": null,
"e": 24820,
"s": 24812,
"text": "Syntax:"
},
{
"code": null,
"e": 24845,
"s": 24820,
"text": "process.traceDeprecation"
},
{
"code": null,
"e": 24958,
"s": 24845,
"text": "Return Value: This property indicates whether the –trace-deprecation flag is set on the current Node.js process."
},
{
"code": null,
"e": 25045,
"s": 24958,
"text": "Below examples illustrate the use of the process.traceDeprecation property in Node.js:"
},
{
"code": null,
"e": 25058,
"s": 25047,
"text": "Example 1:"
},
{
"code": null,
"e": 25067,
"s": 25058,
"text": "index.js"
},
{
"code": "\n\n\n\n\n\n\n// Node.js program to demonstrate the \n// process.traceDeprecation Property \n \n// Include process module \nconst process = require('process'); \n \n// Printing process.traceDeprecation property value \nconsole.log(process.traceDeprecation); \n\n\n\n\n\n",
"e": 25330,
"s": 25077,
"text": null
},
{
"code": null,
"e": 25381,
"s": 25330,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 25415,
"s": 25381,
"text": "node --trace-deprecation index.js"
},
{
"code": null,
"e": 25423,
"s": 25415,
"text": "Output:"
},
{
"code": null,
"e": 25428,
"s": 25423,
"text": "true"
},
{
"code": null,
"e": 25501,
"s": 25428,
"text": "Again run the same file, but using the different command as shown below:"
},
{
"code": null,
"e": 25515,
"s": 25501,
"text": "node index.js"
},
{
"code": null,
"e": 25523,
"s": 25515,
"text": "Output:"
},
{
"code": null,
"e": 25533,
"s": 25523,
"text": "undefined"
},
{
"code": null,
"e": 25544,
"s": 25533,
"text": "Example 2:"
},
{
"code": null,
"e": 25563,
"s": 25544,
"text": "Filename: index.js"
},
{
"code": null,
"e": 25574,
"s": 25563,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// Node.js program to demonstrate the \n// process.traceDeprecation Property \n \n// Include process module \nconst process = require('process'); \n \n// Instance Properties \nprocess.traceDeprecation = false; \n \n// Printing process.traceDeprecation \n// property value \nconsole.log(process.traceDeprecation); \n \n// Instance Properties \nprocess.traceDeprecation = true; \n \n// Printing process.traceDeprecation \n// property value \nconsole.log(process.traceDeprecation); \n\n\n\n\n\n",
"e": 26066,
"s": 25584,
"text": null
},
{
"code": null,
"e": 26117,
"s": 26066,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 26151,
"s": 26117,
"text": "node --trace-deprecation index.js"
},
{
"code": null,
"e": 26159,
"s": 26151,
"text": "Output:"
},
{
"code": null,
"e": 26169,
"s": 26159,
"text": "true\ntrue"
},
{
"code": null,
"e": 26242,
"s": 26169,
"text": "Again run the same file, but using the different command as shown below:"
},
{
"code": null,
"e": 26256,
"s": 26242,
"text": "node index.js"
},
{
"code": null,
"e": 26264,
"s": 26256,
"text": "Output:"
},
{
"code": null,
"e": 26275,
"s": 26264,
"text": "false\ntrue"
},
{
"code": null,
"e": 26300,
"s": 26275,
"text": "\nNode.js-process-module\n"
},
{
"code": null,
"e": 26309,
"s": 26300,
"text": "\nPicked\n"
},
{
"code": null,
"e": 26319,
"s": 26309,
"text": "\nNode.js\n"
},
{
"code": null,
"e": 26338,
"s": 26319,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 26543,
"s": 26338,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26580,
"s": 26543,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 26607,
"s": 26580,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 26639,
"s": 26607,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 26658,
"s": 26639,
"text": "Node.js Event Loop"
},
{
"code": null,
"e": 26715,
"s": 26658,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 26752,
"s": 26715,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 26814,
"s": 26752,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26857,
"s": 26814,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26918,
"s": 26857,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Creating a JavaScript array with new keyword. | Following is the code for creating a JavaScript array with new keyword −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Creating array with new keyword</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to create a new array and display it
</h3>
<script>
let resEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
let arr = new Array(1, 2, 3, 4, "A", "B", "C", "D");
resEle.innerHTML = "arr = " + arr;
});
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button− | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "Following is the code for creating a JavaScript array with new keyword −"
},
{
"code": null,
"e": 1146,
"s": 1135,
"text": " Live Demo"
},
{
"code": null,
"e": 1950,
"s": 1146,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>Creating array with new keyword</h1>\n<div style=\"color: green;\" class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>\nClick on the above button to create a new array and display it\n</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n let arr = new Array(1, 2, 3, 4, \"A\", \"B\", \"C\", \"D\");\n resEle.innerHTML = \"arr = \" + arr;\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2001,
"s": 1950,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2038,
"s": 2001,
"text": "On clicking the ‘CLICK HERE’ button−"
}
] |
Absolute difference between the first X and last X Digits of N? | Here we will see how to get the differences between first and last X digits of a number N. The number and X are given. To solve this problem, we have to find the length of the number, then cut the last x digits using modulus operator. After that cut all digits from the number except first x digits. Then get the difference, and return the result. Let the number is N = 568424. The X is 2 so first two digits are 56, and last two digits are 24. The difference is (56 - 24) = 32.
begin
p := 10^X
last := N mod p
len := length of the number N
while len is not same as X, do
N := N / 10
len := len -1
done
first := len
return |first - last|
end
Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int lengthCount(int n){
return floor(log10(n) + 1);
}
int diffFirstLastDigits(int n, int x) {
int first, last, p, len;
p = pow(10, x);
last = n % p;
len = lengthCount(n);
while(len != x){
n /= 10;
len--;
}
first = n;
return abs(first - last);
}
main() {
int n, x;
cout << "Enter number and number of digits from first and last: ";
cin >> n >> x;
cout << "Difference: " << diffFirstLastDigits(n,x);
}
Enter number and number of digits from first and last: 568424 2
Difference: 32 | [
{
"code": null,
"e": 1541,
"s": 1062,
"text": "Here we will see how to get the differences between first and last X digits of a number N. The number and X are given. To solve this problem, we have to find the length of the number, then cut the last x digits using modulus operator. After that cut all digits from the number except first x digits. Then get the difference, and return the result. Let the number is N = 568424. The X is 2 so first two digits are 56, and last two digits are 24. The difference is (56 - 24) = 32."
},
{
"code": null,
"e": 1737,
"s": 1541,
"text": "begin\n p := 10^X\n last := N mod p\n len := length of the number N\n while len is not same as X, do\n N := N / 10\n len := len -1\n done\n first := len\n return |first - last|\nend"
},
{
"code": null,
"e": 1748,
"s": 1737,
"text": " Live Demo"
},
{
"code": null,
"e": 2257,
"s": 1748,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint lengthCount(int n){\n return floor(log10(n) + 1);\n}\nint diffFirstLastDigits(int n, int x) {\n int first, last, p, len;\n p = pow(10, x);\n last = n % p;\n len = lengthCount(n);\n while(len != x){\n n /= 10;\n len--;\n }\n first = n;\n return abs(first - last);\n}\nmain() {\n int n, x;\n cout << \"Enter number and number of digits from first and last: \";\n cin >> n >> x;\n cout << \"Difference: \" << diffFirstLastDigits(n,x);\n}"
},
{
"code": null,
"e": 2337,
"s": 2257,
"text": "Enter number and number of digits from first and last: 568424 2 \nDifference: 32"
}
] |
Go For Loops | The for loop loops through a block of code a specified number of times.
The for loop is the only loop
available in Go.
Loops are handy if you want to run the same code over and over again, each time with a different value.
Each execution of a loop is called an iteration.
The for loop can take up to three statements:
statement1 Initializes the loop counter value.
statement2 Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
statement3 Increases the loop counter value.
Note: These statements don't need to be present as loops arguments. However, they need to be present in the code in some form.
This example will print the numbers from 0 to 4:
Result:
i:=0; - Initialize the loop counter (i), and set the start value to 0
i < 5; - Continue the loop as long as i is less than 5
i++ - Increase the loop counter value by 1 for each iteration
This example counts to 100 by tens:
Result:
i:=0; - Initialize the loop counter (i), and set the start value to 0
i <= 100; - Continue the loop as long as i is less than or equal to 100
i+=10 - Increase the loop counter value by 10 for each iteration
The continue statement is used to skip one
or more iterations in the loop. It then continues with the next iteration in the loop.
This example skips the value of 3:
Result:
The break statement is used to break/terminate the loop execution.
This example breaks out of the loop when i is equal to 3:
Result:
Note: continue and break are usually used with conditions.
It is possible to place a loop inside another loop.
Here, the "inner loop" will be executed one time for each iteration of the "outer loop":
Result:
The range keyword is used to more easily iterate
over an array, slice or map. It returns both the index and the value.
The range keyword is used like this:
This example uses range to iterate over an
array and print both the indexes and the values at each (idx
stores the index, val stores the value):
Result:
Tip: To only show the value or the index, you can omit the other output using an underscore (_).
Here, we want to omit the indexes (idx
stores the index, val stores the value):
Result:
Here, we want to omit the values (idx
stores the index, val stores the value):
Result:
Print i as long as i is less than 6.
package main
import ("fmt")
func main() {
i:=0; i < 6; {
fmt.Println(i)
}
}
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 72,
"s": 0,
"text": "The for loop loops through a block of code a specified number of times."
},
{
"code": null,
"e": 120,
"s": 72,
"text": "The for loop is the only loop \navailable in Go."
},
{
"code": null,
"e": 224,
"s": 120,
"text": "Loops are handy if you want to run the same code over and over again, each time with a different value."
},
{
"code": null,
"e": 273,
"s": 224,
"text": "Each execution of a loop is called an iteration."
},
{
"code": null,
"e": 319,
"s": 273,
"text": "The for loop can take up to three statements:"
},
{
"code": null,
"e": 366,
"s": 319,
"text": "statement1 Initializes the loop counter value."
},
{
"code": null,
"e": 498,
"s": 366,
"text": "statement2 Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends."
},
{
"code": null,
"e": 543,
"s": 498,
"text": "statement3 Increases the loop counter value."
},
{
"code": null,
"e": 670,
"s": 543,
"text": "Note: These statements don't need to be present as loops arguments. However, they need to be present in the code in some form."
},
{
"code": null,
"e": 721,
"s": 670,
"text": "This example will print the numbers from 0 to 4: "
},
{
"code": null,
"e": 729,
"s": 721,
"text": "Result:"
},
{
"code": null,
"e": 799,
"s": 729,
"text": "i:=0; - Initialize the loop counter (i), and set the start value to 0"
},
{
"code": null,
"e": 854,
"s": 799,
"text": "i < 5; - Continue the loop as long as i is less than 5"
},
{
"code": null,
"e": 916,
"s": 854,
"text": "i++ - Increase the loop counter value by 1 for each iteration"
},
{
"code": null,
"e": 953,
"s": 916,
"text": "This example counts to 100 by tens: "
},
{
"code": null,
"e": 961,
"s": 953,
"text": "Result:"
},
{
"code": null,
"e": 1031,
"s": 961,
"text": "i:=0; - Initialize the loop counter (i), and set the start value to 0"
},
{
"code": null,
"e": 1103,
"s": 1031,
"text": "i <= 100; - Continue the loop as long as i is less than or equal to 100"
},
{
"code": null,
"e": 1168,
"s": 1103,
"text": "i+=10 - Increase the loop counter value by 10 for each iteration"
},
{
"code": null,
"e": 1299,
"s": 1168,
"text": "The continue statement is used to skip one \nor more iterations in the loop. It then continues with the next iteration in the loop."
},
{
"code": null,
"e": 1334,
"s": 1299,
"text": "This example skips the value of 3:"
},
{
"code": null,
"e": 1342,
"s": 1334,
"text": "Result:"
},
{
"code": null,
"e": 1409,
"s": 1342,
"text": "The break statement is used to break/terminate the loop execution."
},
{
"code": null,
"e": 1467,
"s": 1409,
"text": "This example breaks out of the loop when i is equal to 3:"
},
{
"code": null,
"e": 1475,
"s": 1467,
"text": "Result:"
},
{
"code": null,
"e": 1534,
"s": 1475,
"text": "Note: continue and break are usually used with conditions."
},
{
"code": null,
"e": 1586,
"s": 1534,
"text": "It is possible to place a loop inside another loop."
},
{
"code": null,
"e": 1675,
"s": 1586,
"text": "Here, the \"inner loop\" will be executed one time for each iteration of the \"outer loop\":"
},
{
"code": null,
"e": 1683,
"s": 1675,
"text": "Result:"
},
{
"code": null,
"e": 1803,
"s": 1683,
"text": "The range keyword is used to more easily iterate \nover an array, slice or map. It returns both the index and the value."
},
{
"code": null,
"e": 1840,
"s": 1803,
"text": "The range keyword is used like this:"
},
{
"code": null,
"e": 1991,
"s": 1840,
"text": "This example uses range to iterate over an \n array and print both the indexes and the values at each (idx \n stores the index, val stores the value):"
},
{
"code": null,
"e": 1999,
"s": 1991,
"text": "Result:"
},
{
"code": null,
"e": 2096,
"s": 1999,
"text": "Tip: To only show the value or the index, you can omit the other output using an underscore (_)."
},
{
"code": null,
"e": 2179,
"s": 2096,
"text": "Here, we want to omit the indexes (idx \n stores the index, val stores the value):"
},
{
"code": null,
"e": 2187,
"s": 2179,
"text": "Result:"
},
{
"code": null,
"e": 2269,
"s": 2187,
"text": "Here, we want to omit the values (idx \n stores the index, val stores the value):"
},
{
"code": null,
"e": 2277,
"s": 2269,
"text": "Result:"
},
{
"code": null,
"e": 2314,
"s": 2277,
"text": "Print i as long as i is less than 6."
},
{
"code": null,
"e": 2405,
"s": 2314,
"text": "package main \nimport (\"fmt\") \nfunc main() {\n i:=0; i < 6; {\n fmt.Println(i)\n }\n}\n"
},
{
"code": null,
"e": 2424,
"s": 2405,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2457,
"s": 2424,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2499,
"s": 2457,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2606,
"s": 2499,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 2625,
"s": 2606,
"text": "[email protected]"
}
] |
Apex - if statement | An if statement consists of a Boolean expression followed by one or more statements.
if boolean_expression {
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement(after the closing curly brace) will be executed.
Suppose, our Chemical company has customers of two categories – Premium and Normal. Based on the customer type, we should provide them discount and other benefits like after sales service and support. Following is an implementation of this.
//Execute this code in Developer Console and see the Output
String customerName = 'Glenmarkone'; //premium customer
Decimal discountRate = 0;
Boolean premiumSupport = false;
if (customerName == 'Glenmarkone') {
discountRate = 0.1; //when condition is met this block will be executed
premiumSupport = true;
System.debug('Special Discount given as Customer is Premium');
}
As 'Glenmarkone' is a premium customer so the if block will be executed based on the condition.
14 Lectures
2 hours
Vijay Thapa
7 Lectures
2 hours
Uplatz
29 Lectures
6 hours
Ramnarayan Ramakrishnan
49 Lectures
3 hours
Ali Saleh Ali
10 Lectures
4 hours
Soham Ghosh
48 Lectures
4.5 hours
GUHARAJANM
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2137,
"s": 2052,
"text": "An if statement consists of a Boolean expression followed by one or more statements."
},
{
"code": null,
"e": 2233,
"s": 2137,
"text": "if boolean_expression {\n /* statement(s) will execute if the boolean expression is true */\n}\n"
},
{
"code": null,
"e": 2499,
"s": 2233,
"text": "If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement(after the closing curly brace) will be executed."
},
{
"code": null,
"e": 2740,
"s": 2499,
"text": "Suppose, our Chemical company has customers of two categories – Premium and Normal. Based on the customer type, we should provide them discount and other benefits like after sales service and support. Following is an implementation of this."
},
{
"code": null,
"e": 3121,
"s": 2740,
"text": "//Execute this code in Developer Console and see the Output\nString customerName = 'Glenmarkone'; //premium customer\nDecimal discountRate = 0;\nBoolean premiumSupport = false;\n\nif (customerName == 'Glenmarkone') {\n discountRate = 0.1; //when condition is met this block will be executed\n premiumSupport = true;\n System.debug('Special Discount given as Customer is Premium');\n}"
},
{
"code": null,
"e": 3217,
"s": 3121,
"text": "As 'Glenmarkone' is a premium customer so the if block will be executed based on the condition."
},
{
"code": null,
"e": 3250,
"s": 3217,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3263,
"s": 3250,
"text": " Vijay Thapa"
},
{
"code": null,
"e": 3295,
"s": 3263,
"text": "\n 7 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3303,
"s": 3295,
"text": " Uplatz"
},
{
"code": null,
"e": 3336,
"s": 3303,
"text": "\n 29 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3361,
"s": 3336,
"text": " Ramnarayan Ramakrishnan"
},
{
"code": null,
"e": 3394,
"s": 3361,
"text": "\n 49 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3409,
"s": 3394,
"text": " Ali Saleh Ali"
},
{
"code": null,
"e": 3442,
"s": 3409,
"text": "\n 10 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3455,
"s": 3442,
"text": " Soham Ghosh"
},
{
"code": null,
"e": 3490,
"s": 3455,
"text": "\n 48 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3502,
"s": 3490,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 3509,
"s": 3502,
"text": " Print"
},
{
"code": null,
"e": 3520,
"s": 3509,
"text": " Add Notes"
}
] |
jQuery Remove Elements | With jQuery, it is easy to remove existing HTML elements.
To remove elements and content, there are mainly two jQuery methods:
remove() - Removes the selected element (and its child elements)
empty() - Removes the child elements from the selected element
The jQuery remove() method removes the selected element(s) and its child
elements.
The jQuery empty() method removes the child elements of the selected element(s).
The jQuery remove() method also accepts one parameter, which allows you to
filter the elements to be removed.
The parameter can be any of the jQuery selector syntaxes.
The following example removes all <p> elements with class="test":
This example removes all <p> elements with class="test" and
class="demo":
Use a jQuery method to remove a <div> element.
$("div").();
Start the Exercise
For a complete overview of all jQuery HTML methods, please go to our
jQuery HTML/CSS Reference.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 58,
"s": 0,
"text": "With jQuery, it is easy to remove existing HTML elements."
},
{
"code": null,
"e": 127,
"s": 58,
"text": "To remove elements and content, there are mainly two jQuery methods:"
},
{
"code": null,
"e": 192,
"s": 127,
"text": "remove() - Removes the selected element (and its child elements)"
},
{
"code": null,
"e": 255,
"s": 192,
"text": "empty() - Removes the child elements from the selected element"
},
{
"code": null,
"e": 339,
"s": 255,
"text": "The jQuery remove() method removes the selected element(s) and its child \nelements."
},
{
"code": null,
"e": 420,
"s": 339,
"text": "The jQuery empty() method removes the child elements of the selected element(s)."
},
{
"code": null,
"e": 531,
"s": 420,
"text": "The jQuery remove() method also accepts one parameter, which allows you to \nfilter the elements to be removed."
},
{
"code": null,
"e": 589,
"s": 531,
"text": "The parameter can be any of the jQuery selector syntaxes."
},
{
"code": null,
"e": 658,
"s": 589,
"text": "The following example removes all <p> elements with class=\"test\": "
},
{
"code": null,
"e": 735,
"s": 658,
"text": "This example removes all <p> elements with class=\"test\" and \nclass=\"demo\": "
},
{
"code": null,
"e": 782,
"s": 735,
"text": "Use a jQuery method to remove a <div> element."
},
{
"code": null,
"e": 796,
"s": 782,
"text": "$(\"div\").();\n"
},
{
"code": null,
"e": 815,
"s": 796,
"text": "Start the Exercise"
},
{
"code": null,
"e": 911,
"s": 815,
"text": "For a complete overview of all jQuery HTML methods, please go to our\njQuery HTML/CSS Reference."
},
{
"code": null,
"e": 944,
"s": 911,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 986,
"s": 944,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1093,
"s": 986,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1112,
"s": 1093,
"text": "[email protected]"
}
] |
How to create a Venn diagram in R? | A Venn diagram helps to identify the common and uncommon elements between two or more than two sets of elements. This is also used in probability theory to visually represent the relationship between two or more events. To create a Venn diagram in R, we can make use of venn function of gplots package.
Consider the below vectors
x<-c(rep(c(1,2,3),times=c(4,5,8)),12,15,20)
y<-c(1:10,25)
Installing and loading gplots package −
install.packages("gplots")
library(gplots)
Creating the Venn diagram for x and y −
venn(list(x,y))
If we have three variables then we will just add the third variable in venn function as shown below −
z<-c(5:15,21)
venn(list(x,y,z)) | [
{
"code": null,
"e": 1365,
"s": 1062,
"text": "A Venn diagram helps to identify the common and uncommon elements between two or more than two sets of elements. This is also used in probability theory to visually represent the relationship between two or more events. To create a Venn diagram in R, we can make use of venn function of gplots package."
},
{
"code": null,
"e": 1392,
"s": 1365,
"text": "Consider the below vectors"
},
{
"code": null,
"e": 1450,
"s": 1392,
"text": "x<-c(rep(c(1,2,3),times=c(4,5,8)),12,15,20)\ny<-c(1:10,25)"
},
{
"code": null,
"e": 1490,
"s": 1450,
"text": "Installing and loading gplots package −"
},
{
"code": null,
"e": 1533,
"s": 1490,
"text": "install.packages(\"gplots\")\nlibrary(gplots)"
},
{
"code": null,
"e": 1573,
"s": 1533,
"text": "Creating the Venn diagram for x and y −"
},
{
"code": null,
"e": 1589,
"s": 1573,
"text": "venn(list(x,y))"
},
{
"code": null,
"e": 1691,
"s": 1589,
"text": "If we have three variables then we will just add the third variable in venn function as shown below −"
},
{
"code": null,
"e": 1723,
"s": 1691,
"text": "z<-c(5:15,21)\nvenn(list(x,y,z))"
}
] |
SAP UI5 - Views | Views are defined using SAP libraries as follows −
XML with HTML, mixed, or Standalone: Library- sap.ui.core.mvc.XMLView
JavaScript: Library- sap.ui.core.mvc.JSView
JSON: Library - sap.ui.core.mvc.JSONView
HTML: Library - sap.ui.core.mvc.HTMLView
Sap.ui.jsview(“sap.hcm.address”, {
getControllerName: function() {
return “sap.hcm.address”;
},
createContent: function(oController) {
var oButton = new sap.ui.commons.Button({ text: “Hello” });
oButton.attachPress(function() {
oController.Hello();
})
Return oButton;
}
});
<template data-controller-name = ”sap.hcm.address’>
<h1>title</h1>
<div> Embedded html </div>
<div class = ”test” data-sap-ui-type = ”sap.ui.commons.Button”
Id = ”Button1” data-text = ”Hello” Data-press = ”sayHello”>
</div>
</template>
Similarly, you can create JSON view derived from sap.ui.core.mvc.JsonView.
{
“type”:”sap.ui.core.mvc.JsonView”,
“controllerName”:”sap.hcm.address”,
............................
........................
.........................
}
The following table lists key features associated with MVC concept and comparison of different view types w.r.t the features.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2092,
"s": 2041,
"text": "Views are defined using SAP libraries as follows −"
},
{
"code": null,
"e": 2162,
"s": 2092,
"text": "XML with HTML, mixed, or Standalone: Library- sap.ui.core.mvc.XMLView"
},
{
"code": null,
"e": 2206,
"s": 2162,
"text": "JavaScript: Library- sap.ui.core.mvc.JSView"
},
{
"code": null,
"e": 2247,
"s": 2206,
"text": "JSON: Library - sap.ui.core.mvc.JSONView"
},
{
"code": null,
"e": 2288,
"s": 2247,
"text": "HTML: Library - sap.ui.core.mvc.HTMLView"
},
{
"code": null,
"e": 2613,
"s": 2288,
"text": "Sap.ui.jsview(“sap.hcm.address”, {\n getControllerName: function() {\n return “sap.hcm.address”;\n },\n createContent: function(oController) {\n var oButton = new sap.ui.commons.Button({ text: “Hello” });\n oButton.attachPress(function() {\n oController.Hello();\n })\n Return oButton;\n }\n});"
},
{
"code": null,
"e": 2868,
"s": 2613,
"text": "<template data-controller-name = ”sap.hcm.address’>\n <h1>title</h1>\n <div> Embedded html </div>\n <div class = ”test” data-sap-ui-type = ”sap.ui.commons.Button”\n Id = ”Button1” data-text = ”Hello” Data-press = ”sayHello”>\n </div>\n</template>"
},
{
"code": null,
"e": 2943,
"s": 2868,
"text": "Similarly, you can create JSON view derived from sap.ui.core.mvc.JsonView."
},
{
"code": null,
"e": 3114,
"s": 2943,
"text": "{\n “type”:”sap.ui.core.mvc.JsonView”,\n “controllerName”:”sap.hcm.address”,\n ............................\n ........................\n .........................\n}\n"
},
{
"code": null,
"e": 3240,
"s": 3114,
"text": "The following table lists key features associated with MVC concept and comparison of different view types w.r.t the features."
},
{
"code": null,
"e": 3273,
"s": 3240,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3287,
"s": 3273,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 3320,
"s": 3287,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3332,
"s": 3320,
"text": " Neha Gupta"
},
{
"code": null,
"e": 3367,
"s": 3332,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3382,
"s": 3367,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 3415,
"s": 3382,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3430,
"s": 3415,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 3465,
"s": 3430,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3477,
"s": 3465,
"text": " Neha Malik"
},
{
"code": null,
"e": 3512,
"s": 3477,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3524,
"s": 3512,
"text": " Neha Malik"
},
{
"code": null,
"e": 3531,
"s": 3524,
"text": " Print"
},
{
"code": null,
"e": 3542,
"s": 3531,
"text": " Add Notes"
}
] |
TypeScript - Array push() | push() method appends the given element(s) in the last of the array and returns the length of the new array.
array.push(element1, ..., elementN);
element1, ..., elementN − The elements to add to the end of the array.
Returns the length of the new array.
var numbers = new Array(1, 4, 9);
var length = numbers.push(10);
console.log("new numbers is : " + numbers );
length = numbers.push(20);
console.log("new numbers is : " + numbers );
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
new numbers is : 1,4,9,10
new numbers is : 1,4,9,10,20
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2157,
"s": 2048,
"text": "push() method appends the given element(s) in the last of the array and returns the length of the new array."
},
{
"code": null,
"e": 2195,
"s": 2157,
"text": "array.push(element1, ..., elementN);\n"
},
{
"code": null,
"e": 2266,
"s": 2195,
"text": "element1, ..., elementN − The elements to add to the end of the array."
},
{
"code": null,
"e": 2303,
"s": 2266,
"text": "Returns the length of the new array."
},
{
"code": null,
"e": 2491,
"s": 2303,
"text": "var numbers = new Array(1, 4, 9); \nvar length = numbers.push(10); \nconsole.log(\"new numbers is : \" + numbers ); \nlength = numbers.push(20); \nconsole.log(\"new numbers is : \" + numbers );\n"
},
{
"code": null,
"e": 2551,
"s": 2491,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 2578,
"s": 2551,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 2635,
"s": 2578,
"text": "new numbers is : 1,4,9,10 \nnew numbers is : 1,4,9,10,20\n"
},
{
"code": null,
"e": 2668,
"s": 2635,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2682,
"s": 2668,
"text": " Antonio Papa"
},
{
"code": null,
"e": 2715,
"s": 2682,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 2729,
"s": 2715,
"text": " Haider Malik"
},
{
"code": null,
"e": 2764,
"s": 2729,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2784,
"s": 2764,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2817,
"s": 2784,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2831,
"s": 2817,
"text": " Sean Bradley"
},
{
"code": null,
"e": 2866,
"s": 2831,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2882,
"s": 2866,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 2915,
"s": 2882,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2935,
"s": 2915,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 2942,
"s": 2935,
"text": " Print"
},
{
"code": null,
"e": 2953,
"s": 2942,
"text": " Add Notes"
}
] |
Check if a string can be obtained by rotating another string 2 places in Python | Suppose we have two strings s and t. We have to check whether we can get s by rotating t two place at any direction left or right.
So, if the input is like s = "kolkata" t = "takolka", then the output will be True as we can rotate "takolka" to the left side two times to get "kolkata".
To solve this, we will follow these steps −
if size of s is not same as size of t, thenreturn False
return False
right_rot := blank string
left_rot := blank string
l := size of t
left_rot := left_rot concatenate t[from index l - 2 to end] concatenate t[from index 0 to l - 3]
right_rot := right_rot concatenate t[from index 2 to end] concatenate t[from index 0 to 1]
return true when (s is same as right_rot or s is same as left_rot) otherwise false
Let us see the following implementation to get better understanding −
Live Demo
def solve(s, t):
if (len(s) != len(t)):
return False
right_rot = ""
left_rot = ""
l = len(t)
left_rot = (left_rot + t[l - 2:] + t[0: l - 2])
right_rot = right_rot + t[2:] + t[0:2]
return (s == right_rot or s == left_rot)
s = "kolkata"
t = "takolka"
print(solve(s, t))
"kolkata", "takolka"
True | [
{
"code": null,
"e": 1193,
"s": 1062,
"text": "Suppose we have two strings s and t. We have to check whether we can get s by rotating t two place at any direction left or right."
},
{
"code": null,
"e": 1348,
"s": 1193,
"text": "So, if the input is like s = \"kolkata\" t = \"takolka\", then the output will be True as we can rotate \"takolka\" to the left side two times to get \"kolkata\"."
},
{
"code": null,
"e": 1392,
"s": 1348,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1448,
"s": 1392,
"text": "if size of s is not same as size of t, thenreturn False"
},
{
"code": null,
"e": 1461,
"s": 1448,
"text": "return False"
},
{
"code": null,
"e": 1487,
"s": 1461,
"text": "right_rot := blank string"
},
{
"code": null,
"e": 1512,
"s": 1487,
"text": "left_rot := blank string"
},
{
"code": null,
"e": 1527,
"s": 1512,
"text": "l := size of t"
},
{
"code": null,
"e": 1624,
"s": 1527,
"text": "left_rot := left_rot concatenate t[from index l - 2 to end] concatenate t[from index 0 to l - 3]"
},
{
"code": null,
"e": 1715,
"s": 1624,
"text": "right_rot := right_rot concatenate t[from index 2 to end] concatenate t[from index 0 to 1]"
},
{
"code": null,
"e": 1798,
"s": 1715,
"text": "return true when (s is same as right_rot or s is same as left_rot) otherwise false"
},
{
"code": null,
"e": 1868,
"s": 1798,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1879,
"s": 1868,
"text": " Live Demo"
},
{
"code": null,
"e": 2174,
"s": 1879,
"text": "def solve(s, t):\n if (len(s) != len(t)):\n return False\n right_rot = \"\"\n left_rot = \"\"\n l = len(t)\n left_rot = (left_rot + t[l - 2:] + t[0: l - 2])\n right_rot = right_rot + t[2:] + t[0:2]\n return (s == right_rot or s == left_rot)\ns = \"kolkata\"\nt = \"takolka\"\nprint(solve(s, t))"
},
{
"code": null,
"e": 2195,
"s": 2174,
"text": "\"kolkata\", \"takolka\""
},
{
"code": null,
"e": 2200,
"s": 2195,
"text": "True"
}
] |
Program to find all possible strings typed using phone keypad in python | Suppose we have a string containing digits from 2-9. We have to find all possible letter combinations that the number could generate. One mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does map some characters but no letters.
For an example, if the given string is “49”, then the possible strings will be ['gw', 'gx', 'gy', 'gz', 'hw', 'hx', 'hy', 'hz', 'iw', 'ix', 'iy', 'iz']
To solve this, we will follow these steps:
Define an array called solve to solve the problem recursively
solve method takes digits, characters, result, current_string and current_level, the function will be like
if current_level = length of digits, then add current string after the result, and return
for all characters i in characters[digits[current_level]]perform solve(digits, characters, result, current_string + i, current_level + 1)
perform solve(digits, characters, result, current_string + i, current_level + 1)
The actual function will be like
if digits length is 0, then return empty list
define one map to hold numbers and corresponding characters as a string
result := an empty list
call solve(digits, characters, result, “”, 0)
Let us see the following implementation to get better understanding:
Live Demo
class Solution(object):
def letterCombinations(self, digits):
if len(digits) == 0:
return []
characters = {2:"abc",3:"def",4:"ghi",5:"jkl",6:"mno",7:"pqrs",8:"tuv",9:"wxyz"}
result = []
self.solve(digits,characters,result)
return result
def solve(self, digits, characters, result, current_string="",current_level = 0):
if current_level == len(digits):
result.append(current_string)
return
for i in characters[int(digits[current_level])]:
self.solve(digits,characters,result,current_string+i,current_level+1)
ob1 = Solution()
print(ob1.letterCombinations("49"))
"49"
['gw', 'gx', 'gy', 'gz', 'hw', 'hx', 'hy', 'hz', 'iw', 'ix', 'iy', 'iz'] | [
{
"code": null,
"e": 1334,
"s": 1062,
"text": "Suppose we have a string containing digits from 2-9. We have to find all possible letter combinations that the number could generate. One mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does map some characters but no letters."
},
{
"code": null,
"e": 1486,
"s": 1334,
"text": "For an example, if the given string is “49”, then the possible strings will be ['gw', 'gx', 'gy', 'gz', 'hw', 'hx', 'hy', 'hz', 'iw', 'ix', 'iy', 'iz']"
},
{
"code": null,
"e": 1529,
"s": 1486,
"text": "To solve this, we will follow these steps:"
},
{
"code": null,
"e": 1591,
"s": 1529,
"text": "Define an array called solve to solve the problem recursively"
},
{
"code": null,
"e": 1698,
"s": 1591,
"text": "solve method takes digits, characters, result, current_string and current_level, the function will be like"
},
{
"code": null,
"e": 1788,
"s": 1698,
"text": "if current_level = length of digits, then add current string after the result, and return"
},
{
"code": null,
"e": 1926,
"s": 1788,
"text": "for all characters i in characters[digits[current_level]]perform solve(digits, characters, result, current_string + i, current_level + 1)"
},
{
"code": null,
"e": 2007,
"s": 1926,
"text": "perform solve(digits, characters, result, current_string + i, current_level + 1)"
},
{
"code": null,
"e": 2040,
"s": 2007,
"text": "The actual function will be like"
},
{
"code": null,
"e": 2086,
"s": 2040,
"text": "if digits length is 0, then return empty list"
},
{
"code": null,
"e": 2158,
"s": 2086,
"text": "define one map to hold numbers and corresponding characters as a string"
},
{
"code": null,
"e": 2182,
"s": 2158,
"text": "result := an empty list"
},
{
"code": null,
"e": 2228,
"s": 2182,
"text": "call solve(digits, characters, result, “”, 0)"
},
{
"code": null,
"e": 2297,
"s": 2228,
"text": "Let us see the following implementation to get better understanding:"
},
{
"code": null,
"e": 2307,
"s": 2297,
"text": "Live Demo"
},
{
"code": null,
"e": 2939,
"s": 2307,
"text": "class Solution(object):\n def letterCombinations(self, digits):\n if len(digits) == 0:\n return []\n\n characters = {2:\"abc\",3:\"def\",4:\"ghi\",5:\"jkl\",6:\"mno\",7:\"pqrs\",8:\"tuv\",9:\"wxyz\"}\n result = []\n self.solve(digits,characters,result)\n return result\n def solve(self, digits, characters, result, current_string=\"\",current_level = 0):\n if current_level == len(digits):\n result.append(current_string)\n return\n for i in characters[int(digits[current_level])]:\nself.solve(digits,characters,result,current_string+i,current_level+1)\n\nob1 = Solution()\nprint(ob1.letterCombinations(\"49\"))"
},
{
"code": null,
"e": 2944,
"s": 2939,
"text": "\"49\""
},
{
"code": null,
"e": 3017,
"s": 2944,
"text": "['gw', 'gx', 'gy', 'gz', 'hw', 'hx', 'hy', 'hz', 'iw', 'ix', 'iy', 'iz']"
}
] |
Introduction to Principal Component Analysis (PCA) — with Python code | by Dhruvil Karani | Towards Data Science | Imagine a text data having 100000 sentences. The total number of unique words in the text is 10000 (vocabulary size). If each sentence is represented by a vector of length equal to the vocabulary size. In this vector of length 10000, each position belongs to a unique word. For the vector of our sentence, if a certain word occurs k times, the value of the element in the vector corresponding to the index of this word is k. For every other word in the vocabulary not present in our sentence, the vector element is 0. This is called one-hot encoding.
Now, if we create vectors for each of these sentences, we have a set of 100000 vectors. In a matrix form, we have a 100000*10000 size matrix. This means we have 109 elements in our matrix. In python, to get an estimate of the memory occupied,
import numpy as npimport syssys.getsizeof(np.zeros((100000,10000)))>>> 8000000112
The number, in bytes, translates to 8000 megabytes.
What if we are able to work on a smaller matrix, one having fewer but more important features. Say, a few 100 features that capture most information about the data. Having more features is usually good. But more features often include noise too. And noise makes any Machine Learning algorithm less robust, especially on small datasets (read about the curse of dimensionality to know more). Moreover, we would save 100–1000 times the memory we consume. This is important when you deploy applications to production.
With this aim, let’s discuss how PCA helps us solve this problem.
In Machine Learning, we need features for the algorithm to figure out patterns that help differentiate classes of data. More the number of features, more the variance (variation in data) and hence model finds it easy to make ‘splits’ or ‘boundaries’. But not all features provide useful information. They can have noise too. If our model starts fitting to this random noise, it would lose its robustness. So here’s the deal — We want to compose m features from the available feature space that give us maximum variance. Note that we want to compose and not just select m features as it is.
Say a data point is represented by a vector x and has n features originally.
Our job is to transform it into a vector z, having fewer dimensions than n, say m
This happens through a Linear Transformation. Specifically, we multiply a matrix to x that maps it to an m-dimensional space. Consider a matrix W of size n*m. Using W, we wish to transform x to z as —
A simple interpretation of the above equation — Suppose you have an original data frame with columns —
After PCA, if we select, say 3 components, the data frame looks something like —
Where,
c1,c2,.. and d1, d2,... are scalars. W matrix is
Consider an example diagram below. The axis pointing northeast has more spread covered along its direction. Then the second most ‘covering’ axis points northwest.
The above description is good enough for a small talk about PCA. But if you are curious about the calculation of W, this section is for you. You may skip it if you aren’t interested in the Math.
We discussed that PCA is about computing axes along which variance is maximized. Consider a single axis w, along which we wish to maximize the variance. Mathematically,
To calculate variance, we need mean. In statistics, it is better put as expectation, denoted by E. Expectation of a random variable is its mean. In our case we denote expectation of our original features x as μ. For our transformed features, z our expectation is wt*μ (see picture below)
If you are confused, refer the equation below, and take mean on LHS and RHS
Let mean of transformed features be
The variance of a sample of a random variable z is given by,
Expressed in terms of expectation and taking w out of the expectation operation (since it is a constant and not dependent on z)
Turns out, the variance of z is just wt*covariance of x (sigma) *w. Covariance is the variance of a multi-dimensional random variable, in our case, x. It is a square matrix of size k*k, where k is the dimension of x. It is a symmetric matrix. More on covariance matrix
Before we maximize the variance, we impose an important condition on the norm of our w matrix. The norm should be 1
Why? Otherwise, the easy way of maximizing variance is by just increasing the norm and not re-aligning the principal axis in a way that maximizes the variance. This condition is included using a Lagrange multiplier
If we differentiate the above expression, we get —
Take a look at the last expression. Covariance matrix multiplied by w is equal to a scalar alpha multiplied by w. This means, w is the eigenvector of the covariance matrix and alpha is the corresponding eigenvalue. Using this result,
If var(z) is to be maximized, then alpha has to be the largest of all eigenvalues. And the corresponding eigenvector is the principal component
This gives us the first principal component along which the variance explained is maximum compared to any other component. The above was the derivation for the first axis. Other axes are derived similarly. The point was to go a little deep in the math behind PCA.
The dataset we use is Coursera’s course reviews which is available on Kaggle. The code for this exercise is available on my GitHub repo.
As the name says, it consists of reviews (sentences) and ratings (1,2,3,4,5). We take 50,000 reviews, perform cleaning and vectorize them using TF-IDF.
TF-IDF is a scoring method that assigns a score to each word in the sentence. The score is high if the word does not commonly occur in all the reviews but occurs frequently overall. For example, the word course occurs frequently, but it occurs in almost every other review. So TF-IDF score for that word would below. On the other hand, the word poor occurs frequently and is specific to only negative reviews. So its score is higher.
So for every review, we have fixed length TF-IDF vector. The length of the vector is the size of the vocabulary. In our case, the TF-IDF matrix is of size 50000*5000. Moreover, more than 99% of the elements are 0. Because if a sentence has 10 words, only 10 elements of the 5000 will be non-zero.
We use PCA to reduce the dimensionality. But how to decide the number of components to take?
Let’s look at the plot of variance explained vs the number of components or axes
As you see, the first 250 components explain 50% of the variation. First 500 components explain 70%. As you can see, the incremental benefit diminishes. Of course, if you take 5000 components, the variance explained will be 100%. But then what’s the point of doing PCA?
— — — —
I have started my personal blog and I don’t intend to write more amazing articles on Medium. Support my blog by subscribing to thenlp.space | [
{
"code": null,
"e": 723,
"s": 172,
"text": "Imagine a text data having 100000 sentences. The total number of unique words in the text is 10000 (vocabulary size). If each sentence is represented by a vector of length equal to the vocabulary size. In this vector of length 10000, each position belongs to a unique word. For the vector of our sentence, if a certain word occurs k times, the value of the element in the vector corresponding to the index of this word is k. For every other word in the vocabulary not present in our sentence, the vector element is 0. This is called one-hot encoding."
},
{
"code": null,
"e": 966,
"s": 723,
"text": "Now, if we create vectors for each of these sentences, we have a set of 100000 vectors. In a matrix form, we have a 100000*10000 size matrix. This means we have 109 elements in our matrix. In python, to get an estimate of the memory occupied,"
},
{
"code": null,
"e": 1048,
"s": 966,
"text": "import numpy as npimport syssys.getsizeof(np.zeros((100000,10000)))>>> 8000000112"
},
{
"code": null,
"e": 1100,
"s": 1048,
"text": "The number, in bytes, translates to 8000 megabytes."
},
{
"code": null,
"e": 1614,
"s": 1100,
"text": "What if we are able to work on a smaller matrix, one having fewer but more important features. Say, a few 100 features that capture most information about the data. Having more features is usually good. But more features often include noise too. And noise makes any Machine Learning algorithm less robust, especially on small datasets (read about the curse of dimensionality to know more). Moreover, we would save 100–1000 times the memory we consume. This is important when you deploy applications to production."
},
{
"code": null,
"e": 1680,
"s": 1614,
"text": "With this aim, let’s discuss how PCA helps us solve this problem."
},
{
"code": null,
"e": 2270,
"s": 1680,
"text": "In Machine Learning, we need features for the algorithm to figure out patterns that help differentiate classes of data. More the number of features, more the variance (variation in data) and hence model finds it easy to make ‘splits’ or ‘boundaries’. But not all features provide useful information. They can have noise too. If our model starts fitting to this random noise, it would lose its robustness. So here’s the deal — We want to compose m features from the available feature space that give us maximum variance. Note that we want to compose and not just select m features as it is."
},
{
"code": null,
"e": 2347,
"s": 2270,
"text": "Say a data point is represented by a vector x and has n features originally."
},
{
"code": null,
"e": 2429,
"s": 2347,
"text": "Our job is to transform it into a vector z, having fewer dimensions than n, say m"
},
{
"code": null,
"e": 2630,
"s": 2429,
"text": "This happens through a Linear Transformation. Specifically, we multiply a matrix to x that maps it to an m-dimensional space. Consider a matrix W of size n*m. Using W, we wish to transform x to z as —"
},
{
"code": null,
"e": 2733,
"s": 2630,
"text": "A simple interpretation of the above equation — Suppose you have an original data frame with columns —"
},
{
"code": null,
"e": 2814,
"s": 2733,
"text": "After PCA, if we select, say 3 components, the data frame looks something like —"
},
{
"code": null,
"e": 2821,
"s": 2814,
"text": "Where,"
},
{
"code": null,
"e": 2870,
"s": 2821,
"text": "c1,c2,.. and d1, d2,... are scalars. W matrix is"
},
{
"code": null,
"e": 3033,
"s": 2870,
"text": "Consider an example diagram below. The axis pointing northeast has more spread covered along its direction. Then the second most ‘covering’ axis points northwest."
},
{
"code": null,
"e": 3228,
"s": 3033,
"text": "The above description is good enough for a small talk about PCA. But if you are curious about the calculation of W, this section is for you. You may skip it if you aren’t interested in the Math."
},
{
"code": null,
"e": 3397,
"s": 3228,
"text": "We discussed that PCA is about computing axes along which variance is maximized. Consider a single axis w, along which we wish to maximize the variance. Mathematically,"
},
{
"code": null,
"e": 3685,
"s": 3397,
"text": "To calculate variance, we need mean. In statistics, it is better put as expectation, denoted by E. Expectation of a random variable is its mean. In our case we denote expectation of our original features x as μ. For our transformed features, z our expectation is wt*μ (see picture below)"
},
{
"code": null,
"e": 3761,
"s": 3685,
"text": "If you are confused, refer the equation below, and take mean on LHS and RHS"
},
{
"code": null,
"e": 3797,
"s": 3761,
"text": "Let mean of transformed features be"
},
{
"code": null,
"e": 3858,
"s": 3797,
"text": "The variance of a sample of a random variable z is given by,"
},
{
"code": null,
"e": 3986,
"s": 3858,
"text": "Expressed in terms of expectation and taking w out of the expectation operation (since it is a constant and not dependent on z)"
},
{
"code": null,
"e": 4255,
"s": 3986,
"text": "Turns out, the variance of z is just wt*covariance of x (sigma) *w. Covariance is the variance of a multi-dimensional random variable, in our case, x. It is a square matrix of size k*k, where k is the dimension of x. It is a symmetric matrix. More on covariance matrix"
},
{
"code": null,
"e": 4371,
"s": 4255,
"text": "Before we maximize the variance, we impose an important condition on the norm of our w matrix. The norm should be 1"
},
{
"code": null,
"e": 4586,
"s": 4371,
"text": "Why? Otherwise, the easy way of maximizing variance is by just increasing the norm and not re-aligning the principal axis in a way that maximizes the variance. This condition is included using a Lagrange multiplier"
},
{
"code": null,
"e": 4637,
"s": 4586,
"text": "If we differentiate the above expression, we get —"
},
{
"code": null,
"e": 4871,
"s": 4637,
"text": "Take a look at the last expression. Covariance matrix multiplied by w is equal to a scalar alpha multiplied by w. This means, w is the eigenvector of the covariance matrix and alpha is the corresponding eigenvalue. Using this result,"
},
{
"code": null,
"e": 5015,
"s": 4871,
"text": "If var(z) is to be maximized, then alpha has to be the largest of all eigenvalues. And the corresponding eigenvector is the principal component"
},
{
"code": null,
"e": 5279,
"s": 5015,
"text": "This gives us the first principal component along which the variance explained is maximum compared to any other component. The above was the derivation for the first axis. Other axes are derived similarly. The point was to go a little deep in the math behind PCA."
},
{
"code": null,
"e": 5416,
"s": 5279,
"text": "The dataset we use is Coursera’s course reviews which is available on Kaggle. The code for this exercise is available on my GitHub repo."
},
{
"code": null,
"e": 5568,
"s": 5416,
"text": "As the name says, it consists of reviews (sentences) and ratings (1,2,3,4,5). We take 50,000 reviews, perform cleaning and vectorize them using TF-IDF."
},
{
"code": null,
"e": 6002,
"s": 5568,
"text": "TF-IDF is a scoring method that assigns a score to each word in the sentence. The score is high if the word does not commonly occur in all the reviews but occurs frequently overall. For example, the word course occurs frequently, but it occurs in almost every other review. So TF-IDF score for that word would below. On the other hand, the word poor occurs frequently and is specific to only negative reviews. So its score is higher."
},
{
"code": null,
"e": 6299,
"s": 6002,
"text": "So for every review, we have fixed length TF-IDF vector. The length of the vector is the size of the vocabulary. In our case, the TF-IDF matrix is of size 50000*5000. Moreover, more than 99% of the elements are 0. Because if a sentence has 10 words, only 10 elements of the 5000 will be non-zero."
},
{
"code": null,
"e": 6392,
"s": 6299,
"text": "We use PCA to reduce the dimensionality. But how to decide the number of components to take?"
},
{
"code": null,
"e": 6473,
"s": 6392,
"text": "Let’s look at the plot of variance explained vs the number of components or axes"
},
{
"code": null,
"e": 6743,
"s": 6473,
"text": "As you see, the first 250 components explain 50% of the variation. First 500 components explain 70%. As you can see, the incremental benefit diminishes. Of course, if you take 5000 components, the variance explained will be 100%. But then what’s the point of doing PCA?"
},
{
"code": null,
"e": 6751,
"s": 6743,
"text": "— — — —"
}
] |
How to get the current date to display in a Tkinter window? | To work with the date and time module, Python provides the 'datetime' package. Using 'datetime' package, we can display the date, manipulate the datetime object, and use it to write the additional functionality in an application.
To display the current date in a Tkinter window, we've to first import the datetime module in our environment. Once imported, you can create an instance of its object and display them using the label widget.
Here is an example of how you can show the current date in a Tkinter window.
# Import the required libraries
from tkinter import *
import datetime as dt
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Create an instance of datetime module
date=dt.datetime.now()
# Format the date
format_date=f"{date:%a, %b %d %Y}"
# Display the date in a a label widget
label=Label(win, text=format_date, font=("Calibri", 25))
label.pack()
win.mainloop()
Running the above code will display the current date in the window. | [
{
"code": null,
"e": 1292,
"s": 1062,
"text": "To work with the date and time module, Python provides the 'datetime' package. Using 'datetime' package, we can display the date, manipulate the datetime object, and use it to write the additional functionality in an application."
},
{
"code": null,
"e": 1500,
"s": 1292,
"text": "To display the current date in a Tkinter window, we've to first import the datetime module in our environment. Once imported, you can create an instance of its object and display them using the label widget."
},
{
"code": null,
"e": 1577,
"s": 1500,
"text": "Here is an example of how you can show the current date in a Tkinter window."
},
{
"code": null,
"e": 2017,
"s": 1577,
"text": "# Import the required libraries\nfrom tkinter import *\nimport datetime as dt\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Create an instance of datetime module\ndate=dt.datetime.now()\n\n# Format the date\nformat_date=f\"{date:%a, %b %d %Y}\"\n\n# Display the date in a a label widget\nlabel=Label(win, text=format_date, font=(\"Calibri\", 25))\nlabel.pack()\n\nwin.mainloop()"
},
{
"code": null,
"e": 2085,
"s": 2017,
"text": "Running the above code will display the current date in the window."
}
] |
Exploratory Data Analysis with pandas | by Roman Orac | Towards Data Science | As a Data Scientist, I use pandas daily and I am always amazed by how many functionalities it has. These 5 pandas tricks will make you better with Exploratory Data Analysis, which is an approach to analyzing data sets to summarize their main characteristics, often with visual methods. Many complex visualizations can be achieved with pandas and usually, there is no need to import other libraries. To run the examples download this Jupyter notebook.
Exploratory Data Analysis is an approach to analyzing data sets to summarize their main characteristics, often with visual methods
Here are a few links that might interest you:
- Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers
Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases.
To Step Up Your Pandas Game, see:
medium.com
Let’s create a pandas DataFrame with 5 columns and 1000 rows:
a1 and a2 have random samples drawn from a normal (Gaussian) distribution,
a3 has randomly distributed integers from a set of (0, 1, 2, 3, 4),
y1 has numbers spaced evenly on a log scale from 0 to 1,
y2 has randomly distributed integers from a set of (0, 1).
mu1, sigma1 = 0, 0.1mu2, sigma2 = 0.2, 0.2n = 1000df = pd.DataFrame( { "a1": pd.np.random.normal(mu1, sigma1, n), "a2": pd.np.random.normal(mu2, sigma2, n), "a3": pd.np.random.randint(0, 5, n), "y1": pd.np.logspace(0, 1, num=n), "y2": pd.np.random.randint(0, 2, n), })
Readers with Machine Learning background will recognize the notation where a1, a2 and a3 represent attributes and y1 and y2 represent target variables. In short, Machine Learning algorithms try to find patterns in the attributes and use them to predict the unseen target variable — but this is not the main focus of this blog post. The reason that we have two target variables (y1 and y2) in the DataFrame (one binary and one continuous) is to make examples easier to follow.
We reset the index, which adds the index column to the DataFrame to enumerates the rows.
df.reset_index(inplace=True)
When I first started working with pandas, the plotting functionality seemed clunky. I was so wrong on this one because pandas exposes full matplotlib functionality.
Pandas plot function returns matplotlib.axes.Axes or numpy.ndarray of them so we can additionally customize our plots. In the example below, we add a horizontal and a vertical red line to pandas line plot. This is useful if we need to:
add the average line to a histogram,
mark an important point on the plot, etc.
ax = df.y1.plot()ax.axhline(6, color="red", linestyle="--")ax.axvline(775, color="red", linestyle="--")
Pandas plot function also takes Axes argument on the input. This enables us to customize plots to our liking. In the example below, we create a two-by-two grid with different types of plots.
fig, ax = mpl.pyplot.subplots(2, 2, figsize=(14,7))df.plot(x="index", y="y1", ax=ax[0, 0])df.plot.scatter(x="index", y="y2", ax=ax[0, 1])df.plot.scatter(x="index", y="a3", ax=ax[1, 0])df.plot(x="index", y="a1", ax=ax[1, 1])
A histogram is an accurate representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable and was first introduced by Karl Pearson[1].
Pandas enables us to compare distributions of multiple variables on a single histogram with a single function call.
df[["a1", "a2"]].plot(bins=30, kind="hist")
To create two separate plots, we set subplots=True.
df[["a1", "a2"]].plot(bins=30, kind="hist", subplots=True)
A Probability density function (PDF) is a function whose value at any given sample in the set of possible values can be interpreted as a relative likelihood that the value of the random variable would equal that sample [2]. In other words, the value of the PDF at two different samples can be used to infer, in any particular draw of the random variable, how much more likely it is that the random variable would equal one sample compared to the other sample.
Note that in pandas, there is a density=1 argument that we can pass to hist function, but with it, we don’t get a PDF, because the y-axis is not on the scale from 0 to 1 as can be seen on the plot below. The reason for this is explained in numpy documentation: “Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability mass function.”.
df.a1.hist(bins=30, density=1)
To calculate a PDF for a variable, we use the weights argument of a hist function. We can observe on the plot below, that the maximum value of the y-axis is less than 1.
weights = pd.np.ones_like(df.a1.values) / len(df.a1.values)df.a1.hist(bins=30, weights=weights)
A cumulative histogram is a mapping that counts the cumulative number of observations in all of the bins up to the specified bin.
Let’s make a cumulative histogram for a1 column. We can observe on the plot below that there are approximately 500 data points where the x is smaller or equal to 0.0.
df.a1.hist(bins=30, cumulative=True)
A normalized cumulative histogram is what we call the Cumulative distribution function (CDF) in statistics. The CDF is the probability that the variable takes a value less than or equal to x. In the example below, the probability that x <= 0.0 is 0.5 and x <= 0.2 is approximately 0.98. Note that thedensitiy=1 argument works as expected with cumulative histograms.
df.a1.hist(bins=30, cumulative=True, density=1)
Pandas enables us to visualize data separated by the value of the specified column. Separating data by certain columns and observing differences in distributions is a common step in Exploratory Data Analysis. Let’s separate distributions of a1 and a2 columns by the y2 column and plot histograms.
df[['a1', 'a2']].hist(by=df.y2)
There is not much difference between separated distributions as the data was randomly generated.
We can do the same for the line plot.
df[['a1', 'a2']].plot(by=df.y2, subplots=True)
Some Machine Learning algorithms don’t work with multivariate attributes, like a3 column in our example. a3 column has 5 distinct values (0, 1, 2, 3, 4 and 5). To transform a multivariate attribute to multiple binary attributes, we can binarize the column, so that we get 5 attributes with 0 and 1 values.
Let’s look at the example below. The first three rows of a3 column have value 2. So a3_2 attribute has the first three rows marked with 1 and all other attributes are 0. The fourth row in a3 has a value 3, so a3_3 is 1 and all others are 0, etc.
df.a3.head()
df_a4_dummy = pd.get_dummies(df.a3, prefix='a3_')df_a4_dummy.head()
get_dummies function also enables us to drop the first column, so that we don’t store redundant information. Eg. when a3_1, a3_2, a3_3, a3_4 are all 0 we can assume that a3_0 should be 1 and we don’t need to store it.
pd.get_dummies(df.a3, prefix='a3_', drop_first=True).head()
Now that we have binarized the a3 column, let’s remove it from the DataFrame and add binarized attributes to it.
df = df.drop('a3', axis=1)df = pd.concat([df, df_a4_dummy], axis=1)
Sometimes we would like to compare a certain distribution with a linear line. Eg. To determine if monthly sales growth is higher than linear. When we observe that our data is linear, we can predict future values.
Pandas (with the help of numpy) enables us to fit a linear line to our data. This is a Linear Regression algorithm in Machine Learning, which tries to make the vertical distance between the line and the data points as small as possible. This is called “fitting the line to the data.”
The plot below shows the y1 column. Let’s draw a linear line that closely matches data points of the y1 column.
df.plot.scatter(x='index', y='y1', s=1)
The code below calculates the least-squares solution to a linear equation. The output of the function that we are interested in is the least-squares solution.
df['ones'] = pd.np.ones(len(df))m, c = pd.np.linalg.lstsq(df[['index', 'ones']], df['y1'], rcond=None)[0]
The equation for a line is y = m * x + c. Let’s use the equation and calculate the values for the line y that closely fits the y1 line.
df['y'] = df['index'].apply(lambda x: x * m + c)df[['y', 'y1']].plot()
Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning. | [
{
"code": null,
"e": 623,
"s": 172,
"text": "As a Data Scientist, I use pandas daily and I am always amazed by how many functionalities it has. These 5 pandas tricks will make you better with Exploratory Data Analysis, which is an approach to analyzing data sets to summarize their main characteristics, often with visual methods. Many complex visualizations can be achieved with pandas and usually, there is no need to import other libraries. To run the examples download this Jupyter notebook."
},
{
"code": null,
"e": 754,
"s": 623,
"text": "Exploratory Data Analysis is an approach to analyzing data sets to summarize their main characteristics, often with visual methods"
},
{
"code": null,
"e": 800,
"s": 754,
"text": "Here are a few links that might interest you:"
},
{
"code": null,
"e": 1130,
"s": 800,
"text": "- Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers"
},
{
"code": null,
"e": 1367,
"s": 1130,
"text": "Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases."
},
{
"code": null,
"e": 1401,
"s": 1367,
"text": "To Step Up Your Pandas Game, see:"
},
{
"code": null,
"e": 1412,
"s": 1401,
"text": "medium.com"
},
{
"code": null,
"e": 1474,
"s": 1412,
"text": "Let’s create a pandas DataFrame with 5 columns and 1000 rows:"
},
{
"code": null,
"e": 1549,
"s": 1474,
"text": "a1 and a2 have random samples drawn from a normal (Gaussian) distribution,"
},
{
"code": null,
"e": 1617,
"s": 1549,
"text": "a3 has randomly distributed integers from a set of (0, 1, 2, 3, 4),"
},
{
"code": null,
"e": 1674,
"s": 1617,
"text": "y1 has numbers spaced evenly on a log scale from 0 to 1,"
},
{
"code": null,
"e": 1733,
"s": 1674,
"text": "y2 has randomly distributed integers from a set of (0, 1)."
},
{
"code": null,
"e": 2043,
"s": 1733,
"text": "mu1, sigma1 = 0, 0.1mu2, sigma2 = 0.2, 0.2n = 1000df = pd.DataFrame( { \"a1\": pd.np.random.normal(mu1, sigma1, n), \"a2\": pd.np.random.normal(mu2, sigma2, n), \"a3\": pd.np.random.randint(0, 5, n), \"y1\": pd.np.logspace(0, 1, num=n), \"y2\": pd.np.random.randint(0, 2, n), })"
},
{
"code": null,
"e": 2519,
"s": 2043,
"text": "Readers with Machine Learning background will recognize the notation where a1, a2 and a3 represent attributes and y1 and y2 represent target variables. In short, Machine Learning algorithms try to find patterns in the attributes and use them to predict the unseen target variable — but this is not the main focus of this blog post. The reason that we have two target variables (y1 and y2) in the DataFrame (one binary and one continuous) is to make examples easier to follow."
},
{
"code": null,
"e": 2608,
"s": 2519,
"text": "We reset the index, which adds the index column to the DataFrame to enumerates the rows."
},
{
"code": null,
"e": 2637,
"s": 2608,
"text": "df.reset_index(inplace=True)"
},
{
"code": null,
"e": 2802,
"s": 2637,
"text": "When I first started working with pandas, the plotting functionality seemed clunky. I was so wrong on this one because pandas exposes full matplotlib functionality."
},
{
"code": null,
"e": 3038,
"s": 2802,
"text": "Pandas plot function returns matplotlib.axes.Axes or numpy.ndarray of them so we can additionally customize our plots. In the example below, we add a horizontal and a vertical red line to pandas line plot. This is useful if we need to:"
},
{
"code": null,
"e": 3075,
"s": 3038,
"text": "add the average line to a histogram,"
},
{
"code": null,
"e": 3117,
"s": 3075,
"text": "mark an important point on the plot, etc."
},
{
"code": null,
"e": 3221,
"s": 3117,
"text": "ax = df.y1.plot()ax.axhline(6, color=\"red\", linestyle=\"--\")ax.axvline(775, color=\"red\", linestyle=\"--\")"
},
{
"code": null,
"e": 3412,
"s": 3221,
"text": "Pandas plot function also takes Axes argument on the input. This enables us to customize plots to our liking. In the example below, we create a two-by-two grid with different types of plots."
},
{
"code": null,
"e": 3636,
"s": 3412,
"text": "fig, ax = mpl.pyplot.subplots(2, 2, figsize=(14,7))df.plot(x=\"index\", y=\"y1\", ax=ax[0, 0])df.plot.scatter(x=\"index\", y=\"y2\", ax=ax[0, 1])df.plot.scatter(x=\"index\", y=\"a3\", ax=ax[1, 0])df.plot(x=\"index\", y=\"a1\", ax=ax[1, 1])"
},
{
"code": null,
"e": 3837,
"s": 3636,
"text": "A histogram is an accurate representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable and was first introduced by Karl Pearson[1]."
},
{
"code": null,
"e": 3953,
"s": 3837,
"text": "Pandas enables us to compare distributions of multiple variables on a single histogram with a single function call."
},
{
"code": null,
"e": 3997,
"s": 3953,
"text": "df[[\"a1\", \"a2\"]].plot(bins=30, kind=\"hist\")"
},
{
"code": null,
"e": 4049,
"s": 3997,
"text": "To create two separate plots, we set subplots=True."
},
{
"code": null,
"e": 4108,
"s": 4049,
"text": "df[[\"a1\", \"a2\"]].plot(bins=30, kind=\"hist\", subplots=True)"
},
{
"code": null,
"e": 4568,
"s": 4108,
"text": "A Probability density function (PDF) is a function whose value at any given sample in the set of possible values can be interpreted as a relative likelihood that the value of the random variable would equal that sample [2]. In other words, the value of the PDF at two different samples can be used to infer, in any particular draw of the random variable, how much more likely it is that the random variable would equal one sample compared to the other sample."
},
{
"code": null,
"e": 4975,
"s": 4568,
"text": "Note that in pandas, there is a density=1 argument that we can pass to hist function, but with it, we don’t get a PDF, because the y-axis is not on the scale from 0 to 1 as can be seen on the plot below. The reason for this is explained in numpy documentation: “Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability mass function.”."
},
{
"code": null,
"e": 5006,
"s": 4975,
"text": "df.a1.hist(bins=30, density=1)"
},
{
"code": null,
"e": 5176,
"s": 5006,
"text": "To calculate a PDF for a variable, we use the weights argument of a hist function. We can observe on the plot below, that the maximum value of the y-axis is less than 1."
},
{
"code": null,
"e": 5272,
"s": 5176,
"text": "weights = pd.np.ones_like(df.a1.values) / len(df.a1.values)df.a1.hist(bins=30, weights=weights)"
},
{
"code": null,
"e": 5402,
"s": 5272,
"text": "A cumulative histogram is a mapping that counts the cumulative number of observations in all of the bins up to the specified bin."
},
{
"code": null,
"e": 5569,
"s": 5402,
"text": "Let’s make a cumulative histogram for a1 column. We can observe on the plot below that there are approximately 500 data points where the x is smaller or equal to 0.0."
},
{
"code": null,
"e": 5606,
"s": 5569,
"text": "df.a1.hist(bins=30, cumulative=True)"
},
{
"code": null,
"e": 5972,
"s": 5606,
"text": "A normalized cumulative histogram is what we call the Cumulative distribution function (CDF) in statistics. The CDF is the probability that the variable takes a value less than or equal to x. In the example below, the probability that x <= 0.0 is 0.5 and x <= 0.2 is approximately 0.98. Note that thedensitiy=1 argument works as expected with cumulative histograms."
},
{
"code": null,
"e": 6020,
"s": 5972,
"text": "df.a1.hist(bins=30, cumulative=True, density=1)"
},
{
"code": null,
"e": 6317,
"s": 6020,
"text": "Pandas enables us to visualize data separated by the value of the specified column. Separating data by certain columns and observing differences in distributions is a common step in Exploratory Data Analysis. Let’s separate distributions of a1 and a2 columns by the y2 column and plot histograms."
},
{
"code": null,
"e": 6349,
"s": 6317,
"text": "df[['a1', 'a2']].hist(by=df.y2)"
},
{
"code": null,
"e": 6446,
"s": 6349,
"text": "There is not much difference between separated distributions as the data was randomly generated."
},
{
"code": null,
"e": 6484,
"s": 6446,
"text": "We can do the same for the line plot."
},
{
"code": null,
"e": 6531,
"s": 6484,
"text": "df[['a1', 'a2']].plot(by=df.y2, subplots=True)"
},
{
"code": null,
"e": 6837,
"s": 6531,
"text": "Some Machine Learning algorithms don’t work with multivariate attributes, like a3 column in our example. a3 column has 5 distinct values (0, 1, 2, 3, 4 and 5). To transform a multivariate attribute to multiple binary attributes, we can binarize the column, so that we get 5 attributes with 0 and 1 values."
},
{
"code": null,
"e": 7083,
"s": 6837,
"text": "Let’s look at the example below. The first three rows of a3 column have value 2. So a3_2 attribute has the first three rows marked with 1 and all other attributes are 0. The fourth row in a3 has a value 3, so a3_3 is 1 and all others are 0, etc."
},
{
"code": null,
"e": 7096,
"s": 7083,
"text": "df.a3.head()"
},
{
"code": null,
"e": 7164,
"s": 7096,
"text": "df_a4_dummy = pd.get_dummies(df.a3, prefix='a3_')df_a4_dummy.head()"
},
{
"code": null,
"e": 7382,
"s": 7164,
"text": "get_dummies function also enables us to drop the first column, so that we don’t store redundant information. Eg. when a3_1, a3_2, a3_3, a3_4 are all 0 we can assume that a3_0 should be 1 and we don’t need to store it."
},
{
"code": null,
"e": 7442,
"s": 7382,
"text": "pd.get_dummies(df.a3, prefix='a3_', drop_first=True).head()"
},
{
"code": null,
"e": 7555,
"s": 7442,
"text": "Now that we have binarized the a3 column, let’s remove it from the DataFrame and add binarized attributes to it."
},
{
"code": null,
"e": 7623,
"s": 7555,
"text": "df = df.drop('a3', axis=1)df = pd.concat([df, df_a4_dummy], axis=1)"
},
{
"code": null,
"e": 7836,
"s": 7623,
"text": "Sometimes we would like to compare a certain distribution with a linear line. Eg. To determine if monthly sales growth is higher than linear. When we observe that our data is linear, we can predict future values."
},
{
"code": null,
"e": 8120,
"s": 7836,
"text": "Pandas (with the help of numpy) enables us to fit a linear line to our data. This is a Linear Regression algorithm in Machine Learning, which tries to make the vertical distance between the line and the data points as small as possible. This is called “fitting the line to the data.”"
},
{
"code": null,
"e": 8232,
"s": 8120,
"text": "The plot below shows the y1 column. Let’s draw a linear line that closely matches data points of the y1 column."
},
{
"code": null,
"e": 8272,
"s": 8232,
"text": "df.plot.scatter(x='index', y='y1', s=1)"
},
{
"code": null,
"e": 8431,
"s": 8272,
"text": "The code below calculates the least-squares solution to a linear equation. The output of the function that we are interested in is the least-squares solution."
},
{
"code": null,
"e": 8537,
"s": 8431,
"text": "df['ones'] = pd.np.ones(len(df))m, c = pd.np.linalg.lstsq(df[['index', 'ones']], df['y1'], rcond=None)[0]"
},
{
"code": null,
"e": 8673,
"s": 8537,
"text": "The equation for a line is y = m * x + c. Let’s use the equation and calculate the values for the line y that closely fits the y1 line."
},
{
"code": null,
"e": 8744,
"s": 8673,
"text": "df['y'] = df['index'].apply(lambda x: x * m + c)df[['y', 'y1']].plot()"
}
] |
A hands on an end to end data science project using Python | by Jonathan Leban | Towards Data Science | Machine learning, data science, prediction, you may have heard a lot of these words, but what exactly are they? In what situation is it useful?Born in the 1960s, Machine Learning is a branch of artificial intelligence that provides systems with the ability to learn models and make predictions such as predicting the price of a house based on its characteristics (location, area, number of rooms...) or predicting whether a tumor is benign or not. In the house problem, we want to predict a continuous value and this type of problem belongs to what we call the regression problem. In the case of the tumor, the result is a binary value or more generally a discrete value and this type of problem is called the classification problem. When tackling a data science problem, it is extremely important to know the type of outcome you are looking for to know whether you are tackling a regression or classification problem.
In this article, I write a guide to conducting an end-to-end machine learning project. As you can see in the graph below, which shows the different steps of a data science project problem, there are 6 steps. We will delve into each of them throughout the article.
To illustrate the different steps of a data science project, I will use a dataset which describes a sample of pulsar candidates collected during the High Time Resolution Universe Survey. Pulsars are a rare type of Neutron star that produce radio emission detectable here on Earth. They are of considerable scientific interest as probes of space-time, the inter-stellar medium, and states of matter . As pulsars rotate, their emission beam sweeps across the sky, and when this crosses our line of sight, produces a detectable pattern of broadband radio emission. As pulsars rotate rapidly, this pattern repeats periodically. Thus pulsar star involves looking for periodic radio signals with large radio telescopes. Each pulsar produces a slightly different emission pattern, which varies slightly with each rotation . Thus a potential signal detection known as a ‘candidate’, is averaged over many rotations of the pulsar, as determined by the length of an observation. In the absence of additional info, each candidate could potentially describe a real pulsar. However in practice, almost all detections are caused by radio frequency interference (RFI) and noise, making legitimate signals hard to find.
Here, using machine learning models is totally legitimate to predict whether a start is a pulsar star or not as the purely physics models have a lot of barriers to overcome. By using Machine Learning models we can achieve accurate results bending the complexity of the problem.Let’s see how we can do it!You can find the dataset here.
In this project, the idea is to predict if a star is a pulsar star or not. We can see clearly that the result of our models will be binary: 1 if the star is a pulsar star and 0 otherwise. Thus, we will implement classification models to answer this problem.
As we use Python, we will use the Pandas library to extract the data from the csv file. For the data visualization, the library seaborn is a very good one as a lot of tools for data science are already implemented. The matplotlib.pylab library is also useful to plot graphs.
import numpy as np import pandas as pd # for data visualizationimport seaborn as sns import matplotlib.pylab as plt
Then we can extract the data from the csv file and take a look at the different characteristics. One action you should always do is to check the number of elements in each characteristic. If the number of elements is different for some characteristics, you have to apply certain operations to fill the gap or if there are too many missing values, you have to abandon that characteristic.
pulsar_stars = pd.read_csv("pulsar_stars.csv") # read the data# to check if we have to clean the data print(pulsar_stars.apply(pd.Series.count))
We can see that they are 8 features which define a star and the target class is a binary value (1 if the candidate star is a pulsar star and 0 otherwise). All the different features have the same number of elements so no operations to fill the gap are necessary.
The next step is to split the data into the data that we will use to train the machine learning algorithm and the data we will use to test the performance of each of them.
# we set the seed for the random cursor random.seed(10) # we split the data X = pulsar_stars.drop(['target_class'], axis = 1) y = pulsar_stars['target_class'] X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.8, random_state = 10) X_columns = X_train.columns
Next we can take a look on the correlation between the different features but also on the link between one feature and the target class in order to see the impact on the result.
#correlation plotcorr = pulsar_stars.corr()sns.heatmap(corr)
We notice that the excess kurtosis of the integrated profile is the more correlated feature with the target_class. Now, we will look into the distribution of each variable to see if we have to apply a transformation to make it more valuable.
#create numeric plotsnum = [f for f in X_train.columns if X_train.dtypes[f] != 'object']nd = pd.melt(X_train, value_vars = num)n1 = sns.FacetGrid (nd, col='variable', col_wrap=3, height = 5.5, sharex=False, sharey = False)n1 = n1.map(sns.distplot, 'value')
Most of the variables have a gaussian distribution (you may think the data, for most of the features, follows a right-skewed distribution but it is only because the number of data is not big enough).
Now that we have a better understanding of the data we can pre-process it in order to feed our machine learning algorithms.
Since different characteristics have completely different scales, we need to standardize our data. This step is not necessary when the characteristics have the same scale, except for some algorithms such as PCA .
They are different ways to normalize the data:
scaler = StandardScaler()X_train = scaler.fit_transform(X_train)X_test = scaler.transform(X_test)
In this part, we implement different machine learning models that deal with classification problems and define measures to evaluate their performance.For the machine learning models, I will use the decision tree algorithm, the logistic regression algorithm, the random forest algorithm and the K-Nearest Neighbors algorithm. I will use time, precision, recall, weighted f1 score and AUC score to evaluate the models. I will explain my choices and the meaning of each measure in more detail.
Some of these models have hyperparameters, i.e. parameters whose value is set before the start of the learning process. One method is to establish lists of values that the hyperparameters can take and to search by grid according to as precise a metric as possible in order to find the best model. Another method would be to use Bayesian optimization (a more efficient method).
# we start by DecisionTreeClassifierdc = DecisionTreeClassifier(max_depth = 4)dc.fit(X_train, y_train)params = {'max_depth' : [2,4,8]}dcgrid = GridSearchCV(estimator = dc, param_grid = params, cv = KFold(5, random_state = 10) , scoring = 'accuracy')dcgrid.fit(X_train, y_train)# Then by LogisticRegressionlg = LogisticRegression(C=0.001, solver='liblinear')lg.fit(X_train, y_train)params = {'C':[0.01,0.1,1,10]}lggrid = GridSearchCV(estimator = lg, param_grid = params, cv = KFold(5, random_state = 10), scoring = 'accuracy')lggrid.fit(X_train, y_train)# then by RandomForestClassifierrf = RandomForestClassifier(n_estimators = 10, max_depth = 10)rf.fit(X_train, y_train)params = {'n_estimators' : [10, 20, 50, 100], 'max_depth' : [10, 50]}rfgrid = GridSearchCV(estimator = rf, param_grid = params, cv = KFold(5, random_state = 10), scoring = 'accuracy')rfgrid.fit(X_train, y_train)# then KNeighborsClassifierkn = KNeighborsClassifier(n_neighbors = 10, p = 2)kn.fit(X_train, y_train)params = {'n_neighbors' : [2, 5, 10, 50], 'weights' : ['uniform', 'distance'], 'p' :[1,2]}kngrid = GridSearchCV(estimator = kn, param_grid = params, cv = KFold(5, random_state = 10), scoring = 'accuracy')kngrid.fit(X_train, y_train)
Then we find the best models and we can also see the time needed to train these models which can be a metric used to choose our final model.
# we define the best models dc_best = dcgrid.best_estimator_lg_best = lggrid.best_estimator_rf_best = rfgrid.best_estimator_kn_best = kngrid.best_estimator_# now we will launch each model and see the time and the performance of each start = time.time()dc = dc_bestdc_best.fit(X_train, y_train)end = time.time()print('time for Decision Tree Classifier = ', end - start, 's')performance_df['Decision_tree']['time(s)'] = end - start# Then by LogisticRegressionstart = time.time()lg = lg_bestlg_best.fit(X_train, y_train)end = time.time()print('time for Logisitic Regression= ', end - start, 's')performance_df['Logistic_regression']['time(s)'] = end - start# then by RandomForestClassifierstart = time.time()rf = rf_bestrf_best.fit(X_train, y_train)end = time.time()print('time for Random Forst Classifier = ', end - start, 's')performance_df['Random_forest']['time(s)'] = end - start# then KNeighborsClassifierstart = time.time()kn = kn_bestkn_best.fit(X_train, y_train)end = time.time()print('time for K_Neighbors Classifier = ', end - start,'s')performance_df['K-NNeighbors']['time(s)'] = end - start
Now we can also evaluate the models along another metric which is the recall. The recall, also known as sensitivity, measures the strength of the model to predict a positive outcome — the proportion of 1s correctly identifies.
# we will calculate the scores of each model y_predict_dc = dc_best.predict(X_test)accuracy = accuracy_score(y_test, y_predict_dc)recall = recall_score(y_test, y_predict_dc)performance_df['Decision_tree']['accuracy'] = accuracyperformance_df['Decision_tree']['recall'] = recally_predict_lg = lg_best.predict(X_test)accuracy = accuracy_score(y_test, y_predict_lg)recall = recall_score(y_test, y_predict_lg)performance_df['Logistic_regression']['accuracy'] = accuracyperformance_df['Logistic_regression']['recall'] = recally_predict_rf = dc_best.predict(X_test)accuracy = accuracy_score(y_test, y_predict_rf)recall = recall_score(y_test, y_predict_rf)performance_df['Random_forest']['accuracy'] = accuracyperformance_df['Random_forest']['recall'] = recally_predict_kn = dc_best.predict(X_test)accuracy = accuracy_score(y_test, y_predict_kn)recall = recall_score(y_test, y_predict_kn)performance_df['K-NNeighbors']['accuracy'] = accuracyperformance_df['K-NNeighbors']['recall'] = recall
Then, we can compute the confusion matrix which is an error matrix:
# generate confusion matrix for Decision Tree classifier conf_mat_dc = confusion_matrix(y_test, y_predict_dc) # put it into a dataframe for seaborn plot function conf_math_dc_df = pd.DataFrame(conf_mat_dc) # Use a seaborn heatmap to plot confusion matrices # The dataframe is transposed to make Actual values on x-axis and predicted on y-axis # annot = True includes the numbers in each box # vmin and vmax just adjusts the color value fig, ax = plt.subplots(figsize = (7,7)) sns.heatmap(conf_math_dc_df.T, annot=True, annot_kws={"size": 15}, cmap="Oranges", vmin=0, vmax=800, fmt='.0f', linewidths=1, linecolor="white", cbar=False, xticklabels=["no pulsar star","pulsar star"], yticklabels=["no pulsar star","pulsar star"]) plt.ylabel("Predicted", fontsize=15) plt.xlabel("Actual", fontsize=15) ax.set_xticklabels(["no pulsar star","pulsar star"], fontsize=13) ax.set_yticklabels(["no pulsar star","pulsar star"], fontsize=13) plt.title("Confusion Matrix for 'Decision Tree' Classifier", fontsize=15) plt.show()print("")print(classification_report(y_test, y_predict_dc))
After doing this for the other models, we calculate a final measure which is the AUC curve. The AUC — ROC curve is a performance measure for classification problems at different thresholds. ROC is a probability curve and AUC is the degree or measure of separability. It indicates how well the model is able to distinguish between classes. The higher the AUC, the better the model is able to predict that 0s are 0s and 1s are 1s.
#Plotting the ROC curve#Generating points to plot on ROC curve (logistic model)dc_best_prob = dc_best.predict_proba(X_test)fpr_logis, tpr_logis, thresholds_logis = roc_curve(y_test, dc_best_prob[:, 1])fig, ax = plt.subplots(figsize = (10,7))#plotting the "guessing" modelplt.plot([0, 1], [0, 1], 'k--')#plotting the logistic modelplt.plot(fpr_logis, tpr_logis)plt.fill_between(fpr_logis, tpr_logis, alpha=0.2, color='b')plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')AUC = roc_auc_score(y_test, dc_best_prob[:, 1])plt.title('Decision Tree Classifier ROC curve: AUC={0:0.3f}'.format(AUC))plt.show()performance_df['Decision_tree']['AUC'] = AUC
Finally we end up with the following table:
Depending on our problem, the metrics don’t have the same weight on our results. The AUC score is the most important metric in our model as predicting a star as a non super star and making a mistake is what we want to avoid. Thus the logistics regression seems to be the most efficient model.
Based on the model we have chosen, we can vet the importance of the different features on the results.
# thus the logistic regression is the best model : we will keep it # Now we want to see the importance of each feature on the result dataframe_importance = pd.DataFrame()columns = X_train.columnsimportances = np.abs(lg_best.coef_[0])for i in range(len(columns)): dataframe_importance[columns[i]] = [importances[i]]dataframe_importance.insert(0, '', 'Importance features')dataframe_importance.head(10)
Sometimes we may have time constraints or computing power limits and we need to make the model easier. One way to do this is to make a feature selection. We can do this by using a statistical method such as the chi-square test or by using a dimensionality reduction algorithm such as PCA. Then we re-evaluate the model and we can conclude whether or not the constraints we have in terms of time and precision are taken into account.
Do not hesitate to spend a lot of time defining the problem. Once you become accustomed to the implementation techniques of data science projects, you will realize that this is the easiest part of your project.Another part that is quite tricky is data extraction and data cleaning. In the project I presented to you in this article, the data was super clean, but this is almost never the case.Finally, I hope you enjoyed the article and that this is a practical science, the best way to get familiar with it is to practice it. Choose a topic that interests you and put into practice what you’ve learned!
You can find the whole project with some other implementation as neural networks on my github.
PS: I am currently a Master of Engineering Student at Berkeley, and if you want to discuss about the topic, feel free to reach me. Here is my email. | [
{
"code": null,
"e": 1091,
"s": 172,
"text": "Machine learning, data science, prediction, you may have heard a lot of these words, but what exactly are they? In what situation is it useful?Born in the 1960s, Machine Learning is a branch of artificial intelligence that provides systems with the ability to learn models and make predictions such as predicting the price of a house based on its characteristics (location, area, number of rooms...) or predicting whether a tumor is benign or not. In the house problem, we want to predict a continuous value and this type of problem belongs to what we call the regression problem. In the case of the tumor, the result is a binary value or more generally a discrete value and this type of problem is called the classification problem. When tackling a data science problem, it is extremely important to know the type of outcome you are looking for to know whether you are tackling a regression or classification problem."
},
{
"code": null,
"e": 1355,
"s": 1091,
"text": "In this article, I write a guide to conducting an end-to-end machine learning project. As you can see in the graph below, which shows the different steps of a data science project problem, there are 6 steps. We will delve into each of them throughout the article."
},
{
"code": null,
"e": 2559,
"s": 1355,
"text": "To illustrate the different steps of a data science project, I will use a dataset which describes a sample of pulsar candidates collected during the High Time Resolution Universe Survey. Pulsars are a rare type of Neutron star that produce radio emission detectable here on Earth. They are of considerable scientific interest as probes of space-time, the inter-stellar medium, and states of matter . As pulsars rotate, their emission beam sweeps across the sky, and when this crosses our line of sight, produces a detectable pattern of broadband radio emission. As pulsars rotate rapidly, this pattern repeats periodically. Thus pulsar star involves looking for periodic radio signals with large radio telescopes. Each pulsar produces a slightly different emission pattern, which varies slightly with each rotation . Thus a potential signal detection known as a ‘candidate’, is averaged over many rotations of the pulsar, as determined by the length of an observation. In the absence of additional info, each candidate could potentially describe a real pulsar. However in practice, almost all detections are caused by radio frequency interference (RFI) and noise, making legitimate signals hard to find."
},
{
"code": null,
"e": 2894,
"s": 2559,
"text": "Here, using machine learning models is totally legitimate to predict whether a start is a pulsar star or not as the purely physics models have a lot of barriers to overcome. By using Machine Learning models we can achieve accurate results bending the complexity of the problem.Let’s see how we can do it!You can find the dataset here."
},
{
"code": null,
"e": 3152,
"s": 2894,
"text": "In this project, the idea is to predict if a star is a pulsar star or not. We can see clearly that the result of our models will be binary: 1 if the star is a pulsar star and 0 otherwise. Thus, we will implement classification models to answer this problem."
},
{
"code": null,
"e": 3427,
"s": 3152,
"text": "As we use Python, we will use the Pandas library to extract the data from the csv file. For the data visualization, the library seaborn is a very good one as a lot of tools for data science are already implemented. The matplotlib.pylab library is also useful to plot graphs."
},
{
"code": null,
"e": 3543,
"s": 3427,
"text": "import numpy as np import pandas as pd # for data visualizationimport seaborn as sns import matplotlib.pylab as plt"
},
{
"code": null,
"e": 3931,
"s": 3543,
"text": "Then we can extract the data from the csv file and take a look at the different characteristics. One action you should always do is to check the number of elements in each characteristic. If the number of elements is different for some characteristics, you have to apply certain operations to fill the gap or if there are too many missing values, you have to abandon that characteristic."
},
{
"code": null,
"e": 4076,
"s": 3931,
"text": "pulsar_stars = pd.read_csv(\"pulsar_stars.csv\") # read the data# to check if we have to clean the data print(pulsar_stars.apply(pd.Series.count))"
},
{
"code": null,
"e": 4339,
"s": 4076,
"text": "We can see that they are 8 features which define a star and the target class is a binary value (1 if the candidate star is a pulsar star and 0 otherwise). All the different features have the same number of elements so no operations to fill the gap are necessary."
},
{
"code": null,
"e": 4511,
"s": 4339,
"text": "The next step is to split the data into the data that we will use to train the machine learning algorithm and the data we will use to test the performance of each of them."
},
{
"code": null,
"e": 4791,
"s": 4511,
"text": "# we set the seed for the random cursor random.seed(10) # we split the data X = pulsar_stars.drop(['target_class'], axis = 1) y = pulsar_stars['target_class'] X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.8, random_state = 10) X_columns = X_train.columns"
},
{
"code": null,
"e": 4969,
"s": 4791,
"text": "Next we can take a look on the correlation between the different features but also on the link between one feature and the target class in order to see the impact on the result."
},
{
"code": null,
"e": 5030,
"s": 4969,
"text": "#correlation plotcorr = pulsar_stars.corr()sns.heatmap(corr)"
},
{
"code": null,
"e": 5272,
"s": 5030,
"text": "We notice that the excess kurtosis of the integrated profile is the more correlated feature with the target_class. Now, we will look into the distribution of each variable to see if we have to apply a transformation to make it more valuable."
},
{
"code": null,
"e": 5529,
"s": 5272,
"text": "#create numeric plotsnum = [f for f in X_train.columns if X_train.dtypes[f] != 'object']nd = pd.melt(X_train, value_vars = num)n1 = sns.FacetGrid (nd, col='variable', col_wrap=3, height = 5.5, sharex=False, sharey = False)n1 = n1.map(sns.distplot, 'value')"
},
{
"code": null,
"e": 5729,
"s": 5529,
"text": "Most of the variables have a gaussian distribution (you may think the data, for most of the features, follows a right-skewed distribution but it is only because the number of data is not big enough)."
},
{
"code": null,
"e": 5853,
"s": 5729,
"text": "Now that we have a better understanding of the data we can pre-process it in order to feed our machine learning algorithms."
},
{
"code": null,
"e": 6066,
"s": 5853,
"text": "Since different characteristics have completely different scales, we need to standardize our data. This step is not necessary when the characteristics have the same scale, except for some algorithms such as PCA ."
},
{
"code": null,
"e": 6113,
"s": 6066,
"text": "They are different ways to normalize the data:"
},
{
"code": null,
"e": 6211,
"s": 6113,
"text": "scaler = StandardScaler()X_train = scaler.fit_transform(X_train)X_test = scaler.transform(X_test)"
},
{
"code": null,
"e": 6702,
"s": 6211,
"text": "In this part, we implement different machine learning models that deal with classification problems and define measures to evaluate their performance.For the machine learning models, I will use the decision tree algorithm, the logistic regression algorithm, the random forest algorithm and the K-Nearest Neighbors algorithm. I will use time, precision, recall, weighted f1 score and AUC score to evaluate the models. I will explain my choices and the meaning of each measure in more detail."
},
{
"code": null,
"e": 7079,
"s": 6702,
"text": "Some of these models have hyperparameters, i.e. parameters whose value is set before the start of the learning process. One method is to establish lists of values that the hyperparameters can take and to search by grid according to as precise a metric as possible in order to find the best model. Another method would be to use Bayesian optimization (a more efficient method)."
},
{
"code": null,
"e": 8295,
"s": 7079,
"text": "# we start by DecisionTreeClassifierdc = DecisionTreeClassifier(max_depth = 4)dc.fit(X_train, y_train)params = {'max_depth' : [2,4,8]}dcgrid = GridSearchCV(estimator = dc, param_grid = params, cv = KFold(5, random_state = 10) , scoring = 'accuracy')dcgrid.fit(X_train, y_train)# Then by LogisticRegressionlg = LogisticRegression(C=0.001, solver='liblinear')lg.fit(X_train, y_train)params = {'C':[0.01,0.1,1,10]}lggrid = GridSearchCV(estimator = lg, param_grid = params, cv = KFold(5, random_state = 10), scoring = 'accuracy')lggrid.fit(X_train, y_train)# then by RandomForestClassifierrf = RandomForestClassifier(n_estimators = 10, max_depth = 10)rf.fit(X_train, y_train)params = {'n_estimators' : [10, 20, 50, 100], 'max_depth' : [10, 50]}rfgrid = GridSearchCV(estimator = rf, param_grid = params, cv = KFold(5, random_state = 10), scoring = 'accuracy')rfgrid.fit(X_train, y_train)# then KNeighborsClassifierkn = KNeighborsClassifier(n_neighbors = 10, p = 2)kn.fit(X_train, y_train)params = {'n_neighbors' : [2, 5, 10, 50], 'weights' : ['uniform', 'distance'], 'p' :[1,2]}kngrid = GridSearchCV(estimator = kn, param_grid = params, cv = KFold(5, random_state = 10), scoring = 'accuracy')kngrid.fit(X_train, y_train)"
},
{
"code": null,
"e": 8436,
"s": 8295,
"text": "Then we find the best models and we can also see the time needed to train these models which can be a metric used to choose our final model."
},
{
"code": null,
"e": 9537,
"s": 8436,
"text": "# we define the best models dc_best = dcgrid.best_estimator_lg_best = lggrid.best_estimator_rf_best = rfgrid.best_estimator_kn_best = kngrid.best_estimator_# now we will launch each model and see the time and the performance of each start = time.time()dc = dc_bestdc_best.fit(X_train, y_train)end = time.time()print('time for Decision Tree Classifier = ', end - start, 's')performance_df['Decision_tree']['time(s)'] = end - start# Then by LogisticRegressionstart = time.time()lg = lg_bestlg_best.fit(X_train, y_train)end = time.time()print('time for Logisitic Regression= ', end - start, 's')performance_df['Logistic_regression']['time(s)'] = end - start# then by RandomForestClassifierstart = time.time()rf = rf_bestrf_best.fit(X_train, y_train)end = time.time()print('time for Random Forst Classifier = ', end - start, 's')performance_df['Random_forest']['time(s)'] = end - start# then KNeighborsClassifierstart = time.time()kn = kn_bestkn_best.fit(X_train, y_train)end = time.time()print('time for K_Neighbors Classifier = ', end - start,'s')performance_df['K-NNeighbors']['time(s)'] = end - start"
},
{
"code": null,
"e": 9764,
"s": 9537,
"text": "Now we can also evaluate the models along another metric which is the recall. The recall, also known as sensitivity, measures the strength of the model to predict a positive outcome — the proportion of 1s correctly identifies."
},
{
"code": null,
"e": 10748,
"s": 9764,
"text": "# we will calculate the scores of each model y_predict_dc = dc_best.predict(X_test)accuracy = accuracy_score(y_test, y_predict_dc)recall = recall_score(y_test, y_predict_dc)performance_df['Decision_tree']['accuracy'] = accuracyperformance_df['Decision_tree']['recall'] = recally_predict_lg = lg_best.predict(X_test)accuracy = accuracy_score(y_test, y_predict_lg)recall = recall_score(y_test, y_predict_lg)performance_df['Logistic_regression']['accuracy'] = accuracyperformance_df['Logistic_regression']['recall'] = recally_predict_rf = dc_best.predict(X_test)accuracy = accuracy_score(y_test, y_predict_rf)recall = recall_score(y_test, y_predict_rf)performance_df['Random_forest']['accuracy'] = accuracyperformance_df['Random_forest']['recall'] = recally_predict_kn = dc_best.predict(X_test)accuracy = accuracy_score(y_test, y_predict_kn)recall = recall_score(y_test, y_predict_kn)performance_df['K-NNeighbors']['accuracy'] = accuracyperformance_df['K-NNeighbors']['recall'] = recall"
},
{
"code": null,
"e": 10816,
"s": 10748,
"text": "Then, we can compute the confusion matrix which is an error matrix:"
},
{
"code": null,
"e": 11916,
"s": 10816,
"text": "# generate confusion matrix for Decision Tree classifier conf_mat_dc = confusion_matrix(y_test, y_predict_dc) # put it into a dataframe for seaborn plot function conf_math_dc_df = pd.DataFrame(conf_mat_dc) # Use a seaborn heatmap to plot confusion matrices # The dataframe is transposed to make Actual values on x-axis and predicted on y-axis # annot = True includes the numbers in each box # vmin and vmax just adjusts the color value fig, ax = plt.subplots(figsize = (7,7)) sns.heatmap(conf_math_dc_df.T, annot=True, annot_kws={\"size\": 15}, cmap=\"Oranges\", vmin=0, vmax=800, fmt='.0f', linewidths=1, linecolor=\"white\", cbar=False, xticklabels=[\"no pulsar star\",\"pulsar star\"], yticklabels=[\"no pulsar star\",\"pulsar star\"]) plt.ylabel(\"Predicted\", fontsize=15) plt.xlabel(\"Actual\", fontsize=15) ax.set_xticklabels([\"no pulsar star\",\"pulsar star\"], fontsize=13) ax.set_yticklabels([\"no pulsar star\",\"pulsar star\"], fontsize=13) plt.title(\"Confusion Matrix for 'Decision Tree' Classifier\", fontsize=15) plt.show()print(\"\")print(classification_report(y_test, y_predict_dc))"
},
{
"code": null,
"e": 12345,
"s": 11916,
"text": "After doing this for the other models, we calculate a final measure which is the AUC curve. The AUC — ROC curve is a performance measure for classification problems at different thresholds. ROC is a probability curve and AUC is the degree or measure of separability. It indicates how well the model is able to distinguish between classes. The higher the AUC, the better the model is able to predict that 0s are 0s and 1s are 1s."
},
{
"code": null,
"e": 13005,
"s": 12345,
"text": "#Plotting the ROC curve#Generating points to plot on ROC curve (logistic model)dc_best_prob = dc_best.predict_proba(X_test)fpr_logis, tpr_logis, thresholds_logis = roc_curve(y_test, dc_best_prob[:, 1])fig, ax = plt.subplots(figsize = (10,7))#plotting the \"guessing\" modelplt.plot([0, 1], [0, 1], 'k--')#plotting the logistic modelplt.plot(fpr_logis, tpr_logis)plt.fill_between(fpr_logis, tpr_logis, alpha=0.2, color='b')plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')AUC = roc_auc_score(y_test, dc_best_prob[:, 1])plt.title('Decision Tree Classifier ROC curve: AUC={0:0.3f}'.format(AUC))plt.show()performance_df['Decision_tree']['AUC'] = AUC"
},
{
"code": null,
"e": 13049,
"s": 13005,
"text": "Finally we end up with the following table:"
},
{
"code": null,
"e": 13342,
"s": 13049,
"text": "Depending on our problem, the metrics don’t have the same weight on our results. The AUC score is the most important metric in our model as predicting a star as a non super star and making a mistake is what we want to avoid. Thus the logistics regression seems to be the most efficient model."
},
{
"code": null,
"e": 13445,
"s": 13342,
"text": "Based on the model we have chosen, we can vet the importance of the different features on the results."
},
{
"code": null,
"e": 13850,
"s": 13445,
"text": "# thus the logistic regression is the best model : we will keep it # Now we want to see the importance of each feature on the result dataframe_importance = pd.DataFrame()columns = X_train.columnsimportances = np.abs(lg_best.coef_[0])for i in range(len(columns)): dataframe_importance[columns[i]] = [importances[i]]dataframe_importance.insert(0, '', 'Importance features')dataframe_importance.head(10)"
},
{
"code": null,
"e": 14283,
"s": 13850,
"text": "Sometimes we may have time constraints or computing power limits and we need to make the model easier. One way to do this is to make a feature selection. We can do this by using a statistical method such as the chi-square test or by using a dimensionality reduction algorithm such as PCA. Then we re-evaluate the model and we can conclude whether or not the constraints we have in terms of time and precision are taken into account."
},
{
"code": null,
"e": 14887,
"s": 14283,
"text": "Do not hesitate to spend a lot of time defining the problem. Once you become accustomed to the implementation techniques of data science projects, you will realize that this is the easiest part of your project.Another part that is quite tricky is data extraction and data cleaning. In the project I presented to you in this article, the data was super clean, but this is almost never the case.Finally, I hope you enjoyed the article and that this is a practical science, the best way to get familiar with it is to practice it. Choose a topic that interests you and put into practice what you’ve learned!"
},
{
"code": null,
"e": 14982,
"s": 14887,
"text": "You can find the whole project with some other implementation as neural networks on my github."
}
] |
ASP.NET MVC - Helpers | In ASP.Net web forms, developers are using the toolbox for adding controls on any particular page. However, in ASP.NET MVC application there is no toolbox available to drag and drop HTML controls on the view. In ASP.NET MVC application, if you want to create a view it should contain HTML code. So those developers who are new to MVC especially with web forms background finds this a little hard.
To overcome this problem, ASP.NET MVC provides HtmlHelper class which contains different methods that help you create HTML controls programmatically. All HtmlHelper methods generate HTML and return the result as a string. The final HTML is generated at runtime by these functions. The HtmlHelper class is designed to generate UI and it should not be used in controllers or models.
There are different types of helper methods.
Createinputs − Creates inputs for text boxes and buttons.
Createinputs − Creates inputs for text boxes and buttons.
Createlinks − Creates links that are based on information from the routing tables.
Createlinks − Creates links that are based on information from the routing tables.
Createforms − Create form tags that can post back to our action, or to post back to an action on a different controller.
Createforms − Create form tags that can post back to our action, or to post back to an action on a different controller.
Action(String)
Overloaded. Invokes the specified child action method and returns the result as an HTML string. (Defined by ChildActionExtensions)
Action(String, Object)
Overloaded. Invokes the specified child action method with the specified parameters and returns the result as an HTML string. (Defined by ChildActionExtensions)
Action(String, RouteValueDictionary)
Overloaded. Invokes the specified child action method using the specified parameters and returns the result as an HTML string. (Defined by ChildActionExtensions)
Action(String, String)
Overloaded. Invokes the specified child action method using the specified controller name and returns the result as an HTML string. (Defined by ChildActionExtensions)
Action(String, String, Object)
Overloaded. Invokes the specified child action method using the specified parameters and controller name and returns the result as an HTML string. (Defined by ChildActionExtensions)
Action(String, String, RouteValueDictionary)
Overloaded. Invokes the specified child action method using the specified parameters and controller name and returns the result as an HTML string. (Defined by ChildActionExtensions)
ActionLink(String, String)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, Object)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, Object, Object)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, RouteValueDictionary)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, RouteValueDictionary, IDictionary<String, Object>)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, String)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, String, Object, Object)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, String, RouteValueDictionary, IDictionary<String, Object>)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, String, String, String, String, Object, Object)
Overloaded. (Defined by LinkExtensions)
ActionLink(String, String, String, String, String, String, RouteValueDictionary, IDictionary<String, Object>)
Overloaded. (Defined by LinkExtensions)
BeginForm()
Overloaded. Writes an opening <form> tag to the response. The form uses the POST method, and the request is processed by the action method for the view. (Defined by FormExtensions)
BeginForm(Object)
Overloaded. Writes an opening <form> tag to the response and includes the route values in the action attribute. The form uses the POST method, and the request is processed by the action method for the view. (Defined by FormExtensions)
BeginForm(RouteValueDictionary)
Overloaded. Writes an opening <form> tag to the response and includes the route values from the route value dictionary in the action attribute. The form uses the POST method, and the request is processed by the action method for the view. (Defined by FormExtensions.)
BeginForm(String, String)
Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the POST method. (Defined by FormExtensions)
BeginForm(String, String, FormMethod)
Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the specified HTTP method. (Defined by FormExtensions)
BeginForm(String, String, FormMethod, IDictionary<String, Object>)
Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the specified HTTP method and includes the HTML attributes from a dictionary. (Defined by FormExtensions)
BeginForm(String, String, FormMethod, Object)
Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the specified HTTP method and includes the HTML attributes. (Defined by FormExtensions)
BeginForm(String, String, Object)
Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values. The form uses the POST method. (Defined by FormExtensions)
BeginForm(String, String, Object, FormMethod)
Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller, action, and route values. The form uses the specified HTTP method. (Defined by FormExtensions)
BeginForm(String, String, Object, FormMethod, Object)
Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller, action, and route values. The form uses the specified HTTP method and includes the HTML attributes. (Defined by FormExtensions)
BeginForm(String, String, RouteValueDictionary)
Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values from the route value dictionary. The form uses the POST method. (Defined by FormExtensions)
BeginForm(String, String, RouteValueDictionary, FormMethod)
Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values from the route value dictionary. The form uses the specified HTTP method. (Defined by FormExtensions)
BeginForm(String, String, RouteValueDictionary, FormMethod, IDictionary<String, Object>)
Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values from the route value dictionary. The form uses the specified HTTP method, and includes the HTML attributes from the dictionary. (Defined by FormExtensions)
BeginRouteForm(Object)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(RouteValueDictionary)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, FormMethod)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, FormMethod, IDictionary<String, Object>)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, FormMethod, Object)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, Object)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, Object, FormMethod)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, Object, FormMethod, Object)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, RouteValueDictionary)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, RouteValueDictionary, FormMethod)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
BeginRouteForm(String, RouteValueDictionary, FormMethod, IDictionary<String, Object>)
Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)
CheckBox(String)
Overloaded. Returns a checkbox input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)
CheckBox(String, Boolean)
Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, and a value to indicate whether the check box is selected. (Defined by InputExtensions)
CheckBox(String, Boolean, IDictionary<String, Object>)
Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, a value to indicate whether the check box is selected, and the HTML attributes. (Defined by InputExtensions)
CheckBox(String, Boolean, Object)
Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, a value that indicates whether the check box is selected, and the HTML attributes. (Defined by InputExtensions)
CheckBox(String, IDictionary<String, Object>)
Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, and the HTML attributes. (Defined by InputExtensions)
CheckBox(String, Object)
Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, and the HTML attributes. (Defined by InputExtensions)
Display(String)
Overloaded. Returns HTML markup for each property in the object that is represented by a string expression. (Defined by DisplayExtensions)
Display(String, Object)
Overloaded. Returns HTML markup for each property in the object that is represented by a string expression, using additional view data. (Defined by DisplayExtensions)
Display(String, String)
Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template. (Defined by DisplayExtensions)
Display(String, String, Object)
Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template and additional view data. (Defined by DisplayExtensions)
Display(String, String, String)
Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template and an HTML field ID. (Defined by DisplayExtensions)
Display(String, String, String, Object)
Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template, HTML field ID, and additional view data. (Defined by DisplayExtensions)
DisplayForModel()
Overloaded. Returns HTML markup for each property in the model. (Defined by DisplayExtensions)
DisplayForModel(Object)
Overloaded. Returns HTML markup for each property in the model, using additional view data. (Defined by DisplayExtensions)
DisplayForModel(String)
Overloaded. Returns HTML markup for each property in the model using the specified template. (Defined by DisplayExtensions)
DisplayForModel(String, Object)
Overloaded. Returns HTML markup for each property in the model, using the specified template and additional view data. (Defined by DisplayExtensions)
DisplayForModel(String, String)
Overloaded. Returns HTML markup for each property in the model using the specified template and HTML field ID. (Defined by DisplayExtensions)
DisplayForModel(String, String, Object)
Overloaded. Returns HTML markup for each property in the model, using the specified template, an HTML field ID, and additional view data. (Defined by DisplayExtensions)
DisplayName(String)
Gets the display name. (Defined by DisplayNameExtensions)
DisplayNameForModel()
Gets the display name for the model. (Defined by DisplayNameExtensions)
DisplayText(String)
Returns HTML markup for each property in the object that is represented by the specified expression. (Defined by DisplayTextExtensions)
DropDownList(String)
Overloaded. Returns a single-selection select element using the specified HTML helper and the name of the form field. (Defined by SelectExtensions)
DropDownList(String, IEnumerable<SelectListItem>)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, and the specified list items. (Defined by SelectExtensions)
DropDownList(String, IEnumerable<SelectListItem>, IDictionary<String, Object>)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HTML attributes. (Defined by SelectExtensions)
DropDownList(String, IEnumerable<SelectListItem>, Object)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HTML attributes. (Defined by SelectExtensions)
DropDownList(String, IEnumerable<SelectListItem>, String)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and an option label. (Defined by SelectExtensions)
DropDownList(String, IEnumerable<SelectListItem>, String, IDictionary<String, Object>)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, an option label, and the specified HTML attributes. (Defined by SelectExtensions)
DropDownList(String, IEnumerable<SelectListItem>, String, Object)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, an option label, and the specified HTML attributes. (Defined by SelectExtensions)
DropDownList(String, String)
Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, and an option label. (Defined by SelectExtensions)
Editor(String)
Overloaded. Returns an HTML input element for each property in the object that is represented by the expression. (Defined by EditorExtensions)
Editor(String, Object)
Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using additional view data. (Defined by EditorExtensions)
Editor(String, String)
Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template. (Defined by EditorExtensions)
Editor(String, String, Object)
Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template and additional view data. (Defined by EditorExtensions)
Editor(String, String, String)
Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template and HTML field name. (Defined by EditorExtensions)
Editor(String, String, String, Object)
Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template, HTML field name, and additional view data. (Defined by EditorExtensions)
EditorForModel()
Overloaded. Returns an HTML input element for each property in the model. (Defined by EditorExtensions)
EditorForModel(Object)
Overloaded. Returns an HTML input element for each property in the model, using additional view data. (Defined by EditorExtensions)
EditorForModel(String)
Overloaded. Returns an HTML input element for each property in the model, using the specified template. (Defined by EditorExtensions)
EditorForModel(String, Object)
Overloaded. Returns an HTML input element for each property in the model, using the specified template and additional view data. (Defined by EditorExtensions)
EditorForModel(String, String)
Overloaded. Returns an HTML input element for each property in the model, using the specified template name and HTML field name. (Defined by EditorExtensions)
EditorForModel(String, String, Object)
Overloaded. Returns an HTML input element for each property in the model, using the template name, HTML field name, and additional view data. (Defined by EditorExtensions)
EndForm()
Renders the closing </form> tag to the response. (Defined by FormExtensions)
Hidden(String)
Overloaded. Returns a hidden input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)
Hidden(String, Object)
Overloaded. Returns a hidden input element by using the specified HTML helper, the name of the form field, and the value. (Defined by InputExtensions)
Hidden(String, Object, IDictionary<String, Object>)
Overloaded. Returns a hidden input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)
Hidden(String, Object, Object)
Overloaded. Returns a hidden input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)
Id(String)
Gets the ID of the HtmlHelper string. (Defined by NameExtensions)
IdForModel()
Gets the ID of the HtmlHelper string. (Defined by NameExtensions)
Label(String)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
Label(String, IDictionary<String, Object>)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
Label(String, Object)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
Label(String, String)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression using the label text. (Defined by LabelExtensions)
Label(String, String, IDictionary<String, Object>)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
Label(String, String, Object)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
LabelForModel()
Overloaded. Returns an HTML label element and the property name of the property that is represented by the model. (Defined by LabelExtensions)
LabelForModel(IDictionary<String, Object>)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
LabelForModel(Object)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
LabelForModel(String)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression using the label text. (Defined by LabelExtensions)
LabelForModel(String, IDictionary<String, Object>)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
LabelForModel(String, Object)
Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)
ListBox(String)
Overloaded. Returns a multi-select select element using the specified HTML helper and the name of the form field. (Defined by SelectExtensions)
ListBox(String, IEnumerable<SelectListItem>)
Overloaded. Returns a multi-select select element using the specified HTML helper, the name of the form field, and the specified list items. (Defined by SelectExtensions)
ListBox(String, IEnumerable<SelectListItem>, IDictionary<String, Object>)
Overloaded. Returns a multi-select select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HMTL attributes. (Defined by SelectExtensions)
ListBox(String, IEnumerable<SelectListItem>, Object)
Overloaded. Returns a multi-select select element using the specified HTML helper, the name of the form field, and the specified list items. (Defined by SelectExtensions)
Name(String)
Gets the full HTML field name for the object that is represented by the expression. (Defined by NameExtensions)
NameForModel()
Gets the full HTML field name for the object that is represented by the expression. (Defined by NameExtensions.)
Partial(String)
Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)
Partial(String, Object)
Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)
Partial(String, Object, ViewDataDictionary)
Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)
Partial(String, ViewDataDictionary)
Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)
Password(String)
Overloaded. Returns a password input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)
Password(String, Object)
Overloaded. Returns a password input element by using the specified HTML helper, the name of the form field, and the value. (Defined by InputExtensions)
Password(String, Object, IDictionary<String, Object>)
Overloaded. Returns a password input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)
Password(String, Object, Object)
Overloaded. Returns a password input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)
RadioButton(String, Object)
Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)
RadioButton(String, Object, Boolean)
Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)
RadioButton(String, Object, Boolean, IDictionary<String, Object>)
Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)
RadioButton(String, Object, Boolean, Object)
Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)
RadioButton(String, Object, IDictionary<String, Object>)
Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)
RadioButton(String, Object, Object)
Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)
RenderAction(String)
Overloaded. Invokes the specified child action method and renders the result inline in the parent view. (Defined by ChildActionExtensions)
RenderAction(String, Object)
Overloaded. Invokes the specified child action method using the specified parameters and renders the result inline in the parent view. (Defined by ChildActionExtensions)
RenderAction(String, RouteValueDictionary)
Overloaded. Invokes the specified child action method using the specified parameters and renders the result inline in the parent view. (Defined by ChildActionExtensions)
RenderAction(String, String)
Overloaded. Invokes the specified child action method using the specified controller name and renders the result inline in the parent view. (Defined by ChildActionExtensions)
RenderAction(String, String, Object)
Overloaded. Invokes the specified child action method using the specified parameters and controller name and renders the result inline in the parent view. (Defined by ChildActionExtensions)
RenderAction(String, String, RouteValueDictionary)
Overloaded. Invokes the specified child action method using the specified parameters and controller name and renders the result inline in the parent view. (Defined by ChildActionExtensions)
RenderPartial(String)
Overloaded. Renders the specified partial view by using the specified HTML helper. (Defined by RenderPartialExtensions)
RenderPartial(String, Object)
Overloaded. Renders the specified partial view, passing it a copy of the current ViewDataDictionary object, but with the Model property set to the specified model. (Defined by RenderPartialExtensions)
RenderPartial(String, Object, ViewDataDictionary)
Overloaded. Renders the specified partial view, replacing the partial view's ViewData property with the specified ViewDataDictionary object and setting the Model property of the view data to the specified model. (Defined by RenderPartialExtensions)
RenderPartial(String, ViewDataDictionary)
Overloaded. Renders the specified partial view, replacing its ViewData property with the specified ViewDataDictionary object. (Defined by RenderPartialExtensions)
RouteLink(String, Object)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, Object, Object)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, RouteValueDictionary)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, RouteValueDictionary, IDictionary<String, Object>)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String, Object)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String, Object, Object)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String, RouteValueDictionary)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String, RouteValueDictionary, IDictionary<String, Object>)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String, String, String, String, Object, Object)
Overloaded. (Defined by LinkExtensions)
RouteLink(String, String, String, String, String, RouteValueDictionary, IDictionary<String, Object>)
Overloaded. (Defined by LinkExtensions)
TextArea(String)
Overloaded. Returns the specified textarea element by using the specified HTML helper and the name of the form field. (Defined by TextAreaExtensions.)
TextArea(String, IDictionary<String, Object>)
Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, and the specified HTML attributes. (Defined by TextAreaExtensions)
TextArea(String, Object)
Overloaded. Returns the specified textarea element by using the specified HTML helper and HTML attributes. (Defined by TextAreaExtensions)
TextArea(String, String)
Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, and the text content. (Defined by TextAreaExtensions)
TextArea(String, String, IDictionary<String, Object>)
Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, and the specified HTML attributes. (Defined by TextAreaExtensions)
TextArea(String, String, Int32, Int32, IDictionary<String, Object>)
Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, the number of rows and columns, and the specified HTML attributes. (Defined by TextAreaExtensions)
TextArea(String, String, Int32, Int32, Object)
Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, the number of rows and columns, and the specified HTML attributes. (Defined by TextAreaExtensions)
TextArea(String, String, Object)
Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, and the specified HTML attributes. (Defined by TextAreaExtensions)
TextBox(String)
Overloaded. Returns a text input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)
TextBox(String, Object)
Overloaded. Returns a text input element by using the specified HTML helper, the name of the form field, and the value. (Defined by InputExtensions)
TextBox(String, Object, IDictionary<String, Object>)
Overloaded. Returns a text input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)
TextBox(String, Object, Object)
Overloaded. Returns a text input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)
TextBox(String, Object, String)
Overloaded. Returns a text input element. (Defined by InputExtensions)
TextBox(String, Object, String, IDictionary<String, Object>)
Overloaded. Returns a text input element. (Defined by InputExtensions)
TextBox(String, Object, String, Object)
Overloaded. Returns a text input element. (Defined by InputExtensions)
Validate(String)
Retrieves the validation metadata for the specified model and applies each rule to the data field. (Defined by ValidationExtensions)
ValidationMessage(String)
Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, IDictionary<String, Object>)
Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions.)
ValidationMessage(String, IDictionary<String, Object>, String)
Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, Object)
Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, Object, String)
Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, String)
Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, String, IDictionary<String, Object>)
Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, String, IDictionary<String, Object>, String)
Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, String, Object)
Overloaded. Displays a validation message if an error exists forthe specified field in the ModelStateDictionary object. (Definedby ValidationExtensions)
ValidationMessage(String, String, Object, String)
Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationMessage(String, String, String)
Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationSummary()
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationSummary(Boolean)
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)
ValidationSummary(Boolean, String)
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)
ValidationSummary(Boolean, String, IDictionary<String, Object>)
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)
ValidationSummary(Boolean, String, IDictionary<String, Object>, String)
Overloaded. (Defined by ValidationExtensions)
ValidationSummary(Boolean, String, Object)
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)
ValidationSummary(Boolean, String, Object, String)
Overloaded. (Defined by ValidationExtensions)
ValidationSummary(Boolean, String, String)
Overloaded. (Defined by ValidationExtensions)
ValidationSummary(String)
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationSummary(String, IDictionary<String, Object>)
Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationSummary(String, IDictionary<String, Object>, String)
Overloaded. (Defined by ValidationExtensions)
ValidationSummary(String, Object)
Overloaded. Returns an unordered list (ul element) of validation messages in the ModelStateDictionary object. (Defined by ValidationExtensions)
ValidationSummary(String, Object, String)
Overloaded. (Defined by ValidationExtensions)
ValidationSummary(String, String)
Overloaded. (Defined by ValidationExtensions)
Value(String)
Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)
Value(String, String)
Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)
ValueForModel()
Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)
ValueForModel(String)
Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)
If you look at the view from the last chapter which we have generated from EmployeeController index action, you will see the number of operations that started with Html, like Html.ActionLink and Html.DisplayNameFor, etc. as shown in the following code.
@model IEnumerable<MVCSimpleApp.Models.Employee>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>Index</title>
</head>
<body>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class = "table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.JoiningDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.JoiningDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
@Html.ActionLink("Details", "Details", new { id = item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>
</body>
</html>
This HTML is a property that we inherit from the ViewPage base class. So, it's available in all of our views and it returns an instance of a type called HTML Helper.
Let’s take a look at a simple example in which we will enable the user to edit the employee. Hence, this edit action will be using significant numbers of different HTML Helpers.
If you look at the above code, you will see at the end the following HTML Helper methods
@Html.ActionLink("Edit", "Edit", new { id = item.ID })
In the ActionLink helper, the first parameter is of the link which is “Edit”, the second parameter is the action method in the Controller, which is also “Edit”, and the third parameter ID is of any particular employee you want to edit.
Let’s change the EmployeeController class by adding a static list and also change the index action using the following code.
public static List<Employee> empList = new List<Employee>{
new Employee{
ID = 1,
Name = "Allan",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 23
},
new Employee{
ID = 2,
Name = "Carson",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 45
},
new Employee{
ID = 3,
Name = "Carson",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 37
},
new Employee{
ID = 4,
Name = "Laura",
JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
Age = 26
},
};
public ActionResult Index(){
var employees = from e in empList
orderby e.ID
select e;
return View(employees);
}
Let’s update the Edit action. You will see two Edit actions one for GET and one for POST. Let’s update the Edit action for Get, which has only Id in the parameter as shown in the following code.
// GET: Employee/Edit/5
public ActionResult Edit(int id){
List<Employee> empList = GetEmployeeList();
var employee = empList.Single(m => m.ID == id);
return View(employee);
}
Now, we know that we have action for Edit but we don’t have any view for these actions. So we need to add a View as well. To do this, right-click on the Edit action and select Add View.
You will see the default name for view. Select Edit from the Template dropdown and Employee from the Model class dropdown.
Following is the default implementation in the Edit view.
@model MVCSimpleApp.Models.Employee
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>Edit</title>
</head>
<body>
@using (Html.BeginForm()){
@Html.AntiForgeryToken()
<div class = "form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(
true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.ID)
<div class = "form-group">
@Html.LabelFor(
model => model.Name, htmlAttributes: new{
@class = "control-label col-md-2" })
<div class = "col-md-10">
@Html.EditorFor(model => model.Name, new{
htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new{
@class = "text-danger" })
</div>
</div>
<div class = "form-group">
@Html.LabelFor(
model => model.JoiningDate, htmlAttributes: new{
@class = "control-label col-md-2" })
<div class = "col-md-10">
@Html.EditorFor(
model => model.JoiningDate, new{
htmlAttributes = new{ @class = "form-control" } })
@Html.ValidationMessageFor(
model => model.JoiningDate, "", new{
@class = "text-danger" })
</div>
</div>
<div class = "form-group">
@Html.LabelFor(
model => model.Age, htmlAttributes: new{
@class = "control-label col-md-2" })
<div class = "col-md-10">
@Html.EditorFor(
model => model.Age, new{
htmlAttributes = new{ @class = "form-control" } })
@Html.ValidationMessageFor(
model => model.Age, "", new{
@class = "text-danger" })
</div>
</div>
<div class = "form-group">
<div class = "col-md-offset-2 col-md-10">
<input type = "submit" value = "Save" class = "btn btn-default"/>
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
As you can see that there are many helper methods used. So, here “HTML.BeginForm” writes an opening Form Tag. It also ensures that the method is going to be “Post”, when the user clicks on the “Save” button.
Html.BeginForm is very useful, because it enables you to change the URL, change the method, etc.
In the above code, you will see one more HTML helper and that is “@HTML.HiddenFor”, which emits the hidden field.
MVC Framework is smart enough to figure out that this ID field is mentioned in the model class and hence it needs to be prevented from getting edited, that is why it is marked as hidden.
The Html.LabelFor HTML Helper creates the labels on the screen. The Html.ValidationMessageFor helper displays proper error message if anything is wrongly entered while making the change.
We also need to change the Edit action for POST because once you update the employee then it will call this action.
// POST: Employee/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection){
try{
var employee = empList.Single(m => m.ID == id);
if (TryUpdateModel(employee)){
//To Do:- database code
return RedirectToAction("Index");
}
return View(employee);
}catch{
return View();
}
}
Let’s run this application and request for the following URL http://localhost:63004/employee. You will receive the following output.
Click on the edit link on any particular employee, let’s say click on Allan edit link. You will see the following view.
Let’s change the age from 23 to 29 and click ‘Save’ button, then you will see the updated age on the Index View.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2666,
"s": 2269,
"text": "In ASP.Net web forms, developers are using the toolbox for adding controls on any particular page. However, in ASP.NET MVC application there is no toolbox available to drag and drop HTML controls on the view. In ASP.NET MVC application, if you want to create a view it should contain HTML code. So those developers who are new to MVC especially with web forms background finds this a little hard."
},
{
"code": null,
"e": 3047,
"s": 2666,
"text": "To overcome this problem, ASP.NET MVC provides HtmlHelper class which contains different methods that help you create HTML controls programmatically. All HtmlHelper methods generate HTML and return the result as a string. The final HTML is generated at runtime by these functions. The HtmlHelper class is designed to generate UI and it should not be used in controllers or models."
},
{
"code": null,
"e": 3092,
"s": 3047,
"text": "There are different types of helper methods."
},
{
"code": null,
"e": 3150,
"s": 3092,
"text": "Createinputs − Creates inputs for text boxes and buttons."
},
{
"code": null,
"e": 3208,
"s": 3150,
"text": "Createinputs − Creates inputs for text boxes and buttons."
},
{
"code": null,
"e": 3291,
"s": 3208,
"text": "Createlinks − Creates links that are based on information from the routing tables."
},
{
"code": null,
"e": 3374,
"s": 3291,
"text": "Createlinks − Creates links that are based on information from the routing tables."
},
{
"code": null,
"e": 3495,
"s": 3374,
"text": "Createforms − Create form tags that can post back to our action, or to post back to an action on a different controller."
},
{
"code": null,
"e": 3616,
"s": 3495,
"text": "Createforms − Create form tags that can post back to our action, or to post back to an action on a different controller."
},
{
"code": null,
"e": 3631,
"s": 3616,
"text": "Action(String)"
},
{
"code": null,
"e": 3762,
"s": 3631,
"text": "Overloaded. Invokes the specified child action method and returns the result as an HTML string. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 3785,
"s": 3762,
"text": "Action(String, Object)"
},
{
"code": null,
"e": 3946,
"s": 3785,
"text": "Overloaded. Invokes the specified child action method with the specified parameters and returns the result as an HTML string. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 3983,
"s": 3946,
"text": "Action(String, RouteValueDictionary)"
},
{
"code": null,
"e": 4145,
"s": 3983,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and returns the result as an HTML string. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 4168,
"s": 4145,
"text": "Action(String, String)"
},
{
"code": null,
"e": 4335,
"s": 4168,
"text": "Overloaded. Invokes the specified child action method using the specified controller name and returns the result as an HTML string. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 4366,
"s": 4335,
"text": "Action(String, String, Object)"
},
{
"code": null,
"e": 4548,
"s": 4366,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and controller name and returns the result as an HTML string. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 4593,
"s": 4548,
"text": "Action(String, String, RouteValueDictionary)"
},
{
"code": null,
"e": 4775,
"s": 4593,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and controller name and returns the result as an HTML string. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 4802,
"s": 4775,
"text": "ActionLink(String, String)"
},
{
"code": null,
"e": 4842,
"s": 4802,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 4877,
"s": 4842,
"text": "ActionLink(String, String, Object)"
},
{
"code": null,
"e": 4917,
"s": 4877,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 4960,
"s": 4917,
"text": "ActionLink(String, String, Object, Object)"
},
{
"code": null,
"e": 5000,
"s": 4960,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 5049,
"s": 5000,
"text": "ActionLink(String, String, RouteValueDictionary)"
},
{
"code": null,
"e": 5089,
"s": 5049,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 5167,
"s": 5089,
"text": "ActionLink(String, String, RouteValueDictionary, IDictionary<String, Object>)"
},
{
"code": null,
"e": 5207,
"s": 5167,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 5242,
"s": 5207,
"text": "ActionLink(String, String, String)"
},
{
"code": null,
"e": 5282,
"s": 5242,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 5333,
"s": 5282,
"text": "ActionLink(String, String, String, Object, Object)"
},
{
"code": null,
"e": 5373,
"s": 5333,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 5459,
"s": 5373,
"text": "ActionLink(String, String, String, RouteValueDictionary, IDictionary<String, Object>)"
},
{
"code": null,
"e": 5499,
"s": 5459,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 5574,
"s": 5499,
"text": "ActionLink(String, String, String, String, String, String, Object, Object)"
},
{
"code": null,
"e": 5614,
"s": 5574,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 5724,
"s": 5614,
"text": "ActionLink(String, String, String, String, String, String, RouteValueDictionary, IDictionary<String, Object>)"
},
{
"code": null,
"e": 5764,
"s": 5724,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 5776,
"s": 5764,
"text": "BeginForm()"
},
{
"code": null,
"e": 5957,
"s": 5776,
"text": "Overloaded. Writes an opening <form> tag to the response. The form uses the POST method, and the request is processed by the action method for the view. (Defined by FormExtensions)"
},
{
"code": null,
"e": 5975,
"s": 5957,
"text": "BeginForm(Object)"
},
{
"code": null,
"e": 6210,
"s": 5975,
"text": "Overloaded. Writes an opening <form> tag to the response and includes the route values in the action attribute. The form uses the POST method, and the request is processed by the action method for the view. (Defined by FormExtensions)"
},
{
"code": null,
"e": 6242,
"s": 6210,
"text": "BeginForm(RouteValueDictionary)"
},
{
"code": null,
"e": 6510,
"s": 6242,
"text": "Overloaded. Writes an opening <form> tag to the response and includes the route values from the route value dictionary in the action attribute. The form uses the POST method, and the request is processed by the action method for the view. (Defined by FormExtensions.)"
},
{
"code": null,
"e": 6536,
"s": 6510,
"text": "BeginForm(String, String)"
},
{
"code": null,
"e": 6716,
"s": 6536,
"text": "Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the POST method. (Defined by FormExtensions)"
},
{
"code": null,
"e": 6754,
"s": 6716,
"text": "BeginForm(String, String, FormMethod)"
},
{
"code": null,
"e": 6944,
"s": 6754,
"text": "Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the specified HTTP method. (Defined by FormExtensions)"
},
{
"code": null,
"e": 7011,
"s": 6944,
"text": "BeginForm(String, String, FormMethod, IDictionary<String, Object>)"
},
{
"code": null,
"e": 7252,
"s": 7011,
"text": "Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the specified HTTP method and includes the HTML attributes from a dictionary. (Defined by FormExtensions)"
},
{
"code": null,
"e": 7298,
"s": 7252,
"text": "BeginForm(String, String, FormMethod, Object)"
},
{
"code": null,
"e": 7521,
"s": 7298,
"text": "Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the specified HTTP method and includes the HTML attributes. (Defined by FormExtensions)"
},
{
"code": null,
"e": 7555,
"s": 7521,
"text": "BeginForm(String, String, Object)"
},
{
"code": null,
"e": 7751,
"s": 7555,
"text": "Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values. The form uses the POST method. (Defined by FormExtensions)"
},
{
"code": null,
"e": 7797,
"s": 7751,
"text": "BeginForm(String, String, Object, FormMethod)"
},
{
"code": null,
"e": 8002,
"s": 7797,
"text": "Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller, action, and route values. The form uses the specified HTTP method. (Defined by FormExtensions)"
},
{
"code": null,
"e": 8056,
"s": 8002,
"text": "BeginForm(String, String, Object, FormMethod, Object)"
},
{
"code": null,
"e": 8294,
"s": 8056,
"text": "Overloaded. Writes an opening <form> tag to the response and sets the action tag to the specified controller, action, and route values. The form uses the specified HTTP method and includes the HTML attributes. (Defined by FormExtensions)"
},
{
"code": null,
"e": 8342,
"s": 8294,
"text": "BeginForm(String, String, RouteValueDictionary)"
},
{
"code": null,
"e": 8570,
"s": 8342,
"text": "Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values from the route value dictionary. The form uses the POST method. (Defined by FormExtensions)"
},
{
"code": null,
"e": 8630,
"s": 8570,
"text": "BeginForm(String, String, RouteValueDictionary, FormMethod)"
},
{
"code": null,
"e": 8868,
"s": 8630,
"text": "Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values from the route value dictionary. The form uses the specified HTTP method. (Defined by FormExtensions)"
},
{
"code": null,
"e": 8957,
"s": 8868,
"text": "BeginForm(String, String, RouteValueDictionary, FormMethod, IDictionary<String, Object>)"
},
{
"code": null,
"e": 9249,
"s": 8957,
"text": "Overloaded. Writes an opening <form> tag to the response, and sets the action tag to the specified controller, action, and route values from the route value dictionary. The form uses the specified HTTP method, and includes the HTML attributes from the dictionary. (Defined by FormExtensions)"
},
{
"code": null,
"e": 9272,
"s": 9249,
"text": "BeginRouteForm(Object)"
},
{
"code": null,
"e": 9441,
"s": 9272,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 9478,
"s": 9441,
"text": "BeginRouteForm(RouteValueDictionary)"
},
{
"code": null,
"e": 9647,
"s": 9478,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 9670,
"s": 9647,
"text": "BeginRouteForm(String)"
},
{
"code": null,
"e": 9839,
"s": 9670,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 9874,
"s": 9839,
"text": "BeginRouteForm(String, FormMethod)"
},
{
"code": null,
"e": 10043,
"s": 9874,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 10107,
"s": 10043,
"text": "BeginRouteForm(String, FormMethod, IDictionary<String, Object>)"
},
{
"code": null,
"e": 10276,
"s": 10107,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 10319,
"s": 10276,
"text": "BeginRouteForm(String, FormMethod, Object)"
},
{
"code": null,
"e": 10488,
"s": 10319,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 10519,
"s": 10488,
"text": "BeginRouteForm(String, Object)"
},
{
"code": null,
"e": 10688,
"s": 10519,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 10731,
"s": 10688,
"text": "BeginRouteForm(String, Object, FormMethod)"
},
{
"code": null,
"e": 10900,
"s": 10731,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 10951,
"s": 10900,
"text": "BeginRouteForm(String, Object, FormMethod, Object)"
},
{
"code": null,
"e": 11120,
"s": 10951,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 11165,
"s": 11120,
"text": "BeginRouteForm(String, RouteValueDictionary)"
},
{
"code": null,
"e": 11334,
"s": 11165,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 11391,
"s": 11334,
"text": "BeginRouteForm(String, RouteValueDictionary, FormMethod)"
},
{
"code": null,
"e": 11560,
"s": 11391,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 11646,
"s": 11560,
"text": "BeginRouteForm(String, RouteValueDictionary, FormMethod, IDictionary<String, Object>)"
},
{
"code": null,
"e": 11815,
"s": 11646,
"text": "Overloaded. Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by the route target. (Defined by FormExtensions)"
},
{
"code": null,
"e": 11832,
"s": 11815,
"text": "CheckBox(String)"
},
{
"code": null,
"e": 11973,
"s": 11832,
"text": "Overloaded. Returns a checkbox input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)"
},
{
"code": null,
"e": 11999,
"s": 11973,
"text": "CheckBox(String, Boolean)"
},
{
"code": null,
"e": 12196,
"s": 11999,
"text": "Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, and a value to indicate whether the check box is selected. (Defined by InputExtensions)"
},
{
"code": null,
"e": 12251,
"s": 12196,
"text": "CheckBox(String, Boolean, IDictionary<String, Object>)"
},
{
"code": null,
"e": 12469,
"s": 12251,
"text": "Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, a value to indicate whether the check box is selected, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 12503,
"s": 12469,
"text": "CheckBox(String, Boolean, Object)"
},
{
"code": null,
"e": 12724,
"s": 12503,
"text": "Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, a value that indicates whether the check box is selected, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 12770,
"s": 12724,
"text": "CheckBox(String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 12933,
"s": 12770,
"text": "Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 12958,
"s": 12933,
"text": "CheckBox(String, Object)"
},
{
"code": null,
"e": 13121,
"s": 12958,
"text": "Overloaded. Returns a checkbox input element by using the specified HTML helper, the name of the form field, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 13137,
"s": 13121,
"text": "Display(String)"
},
{
"code": null,
"e": 13276,
"s": 13137,
"text": "Overloaded. Returns HTML markup for each property in the object that is represented by a string expression. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 13300,
"s": 13276,
"text": "Display(String, Object)"
},
{
"code": null,
"e": 13467,
"s": 13300,
"text": "Overloaded. Returns HTML markup for each property in the object that is represented by a string expression, using additional view data. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 13491,
"s": 13467,
"text": "Display(String, String)"
},
{
"code": null,
"e": 13655,
"s": 13491,
"text": "Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 13687,
"s": 13655,
"text": "Display(String, String, Object)"
},
{
"code": null,
"e": 13876,
"s": 13687,
"text": "Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template and additional view data. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 13908,
"s": 13876,
"text": "Display(String, String, String)"
},
{
"code": null,
"e": 14093,
"s": 13908,
"text": "Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template and an HTML field ID. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 14133,
"s": 14093,
"text": "Display(String, String, String, Object)"
},
{
"code": null,
"e": 14338,
"s": 14133,
"text": "Overloaded. Returns HTML markup for each property in the object that is represented by the expression, using the specified template, HTML field ID, and additional view data. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 14356,
"s": 14338,
"text": "DisplayForModel()"
},
{
"code": null,
"e": 14451,
"s": 14356,
"text": "Overloaded. Returns HTML markup for each property in the model. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 14475,
"s": 14451,
"text": "DisplayForModel(Object)"
},
{
"code": null,
"e": 14598,
"s": 14475,
"text": "Overloaded. Returns HTML markup for each property in the model, using additional view data. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 14622,
"s": 14598,
"text": "DisplayForModel(String)"
},
{
"code": null,
"e": 14746,
"s": 14622,
"text": "Overloaded. Returns HTML markup for each property in the model using the specified template. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 14778,
"s": 14746,
"text": "DisplayForModel(String, Object)"
},
{
"code": null,
"e": 14928,
"s": 14778,
"text": "Overloaded. Returns HTML markup for each property in the model, using the specified template and additional view data. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 14960,
"s": 14928,
"text": "DisplayForModel(String, String)"
},
{
"code": null,
"e": 15102,
"s": 14960,
"text": "Overloaded. Returns HTML markup for each property in the model using the specified template and HTML field ID. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 15142,
"s": 15102,
"text": "DisplayForModel(String, String, Object)"
},
{
"code": null,
"e": 15311,
"s": 15142,
"text": "Overloaded. Returns HTML markup for each property in the model, using the specified template, an HTML field ID, and additional view data. (Defined by DisplayExtensions)"
},
{
"code": null,
"e": 15331,
"s": 15311,
"text": "DisplayName(String)"
},
{
"code": null,
"e": 15389,
"s": 15331,
"text": "Gets the display name. (Defined by DisplayNameExtensions)"
},
{
"code": null,
"e": 15411,
"s": 15389,
"text": "DisplayNameForModel()"
},
{
"code": null,
"e": 15483,
"s": 15411,
"text": "Gets the display name for the model. (Defined by DisplayNameExtensions)"
},
{
"code": null,
"e": 15503,
"s": 15483,
"text": "DisplayText(String)"
},
{
"code": null,
"e": 15639,
"s": 15503,
"text": "Returns HTML markup for each property in the object that is represented by the specified expression. (Defined by DisplayTextExtensions)"
},
{
"code": null,
"e": 15660,
"s": 15639,
"text": "DropDownList(String)"
},
{
"code": null,
"e": 15808,
"s": 15660,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper and the name of the form field. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 15858,
"s": 15808,
"text": "DropDownList(String, IEnumerable<SelectListItem>)"
},
{
"code": null,
"e": 16033,
"s": 15858,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, and the specified list items. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 16112,
"s": 16033,
"text": "DropDownList(String, IEnumerable<SelectListItem>, IDictionary<String, Object>)"
},
{
"code": null,
"e": 16318,
"s": 16112,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HTML attributes. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 16376,
"s": 16318,
"text": "DropDownList(String, IEnumerable<SelectListItem>, Object)"
},
{
"code": null,
"e": 16582,
"s": 16376,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HTML attributes. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 16640,
"s": 16582,
"text": "DropDownList(String, IEnumerable<SelectListItem>, String)"
},
{
"code": null,
"e": 16832,
"s": 16640,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and an option label. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 16919,
"s": 16832,
"text": "DropDownList(String, IEnumerable<SelectListItem>, String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 17142,
"s": 16919,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, an option label, and the specified HTML attributes. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 17208,
"s": 17142,
"text": "DropDownList(String, IEnumerable<SelectListItem>, String, Object)"
},
{
"code": null,
"e": 17431,
"s": 17208,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, an option label, and the specified HTML attributes. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 17460,
"s": 17431,
"text": "DropDownList(String, String)"
},
{
"code": null,
"e": 17626,
"s": 17460,
"text": "Overloaded. Returns a single-selection select element using the specified HTML helper, the name of the form field, and an option label. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 17641,
"s": 17626,
"text": "Editor(String)"
},
{
"code": null,
"e": 17784,
"s": 17641,
"text": "Overloaded. Returns an HTML input element for each property in the object that is represented by the expression. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 17807,
"s": 17784,
"text": "Editor(String, Object)"
},
{
"code": null,
"e": 17978,
"s": 17807,
"text": "Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using additional view data. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 18001,
"s": 17978,
"text": "Editor(String, String)"
},
{
"code": null,
"e": 18174,
"s": 18001,
"text": "Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 18205,
"s": 18174,
"text": "Editor(String, String, Object)"
},
{
"code": null,
"e": 18403,
"s": 18205,
"text": "Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template and additional view data. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 18434,
"s": 18403,
"text": "Editor(String, String, String)"
},
{
"code": null,
"e": 18627,
"s": 18434,
"text": "Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template and HTML field name. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 18666,
"s": 18627,
"text": "Editor(String, String, String, Object)"
},
{
"code": null,
"e": 18882,
"s": 18666,
"text": "Overloaded. Returns an HTML input element for each property in the object that is represented by the expression, using the specified template, HTML field name, and additional view data. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 18899,
"s": 18882,
"text": "EditorForModel()"
},
{
"code": null,
"e": 19003,
"s": 18899,
"text": "Overloaded. Returns an HTML input element for each property in the model. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 19026,
"s": 19003,
"text": "EditorForModel(Object)"
},
{
"code": null,
"e": 19158,
"s": 19026,
"text": "Overloaded. Returns an HTML input element for each property in the model, using additional view data. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 19181,
"s": 19158,
"text": "EditorForModel(String)"
},
{
"code": null,
"e": 19315,
"s": 19181,
"text": "Overloaded. Returns an HTML input element for each property in the model, using the specified template. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 19346,
"s": 19315,
"text": "EditorForModel(String, Object)"
},
{
"code": null,
"e": 19505,
"s": 19346,
"text": "Overloaded. Returns an HTML input element for each property in the model, using the specified template and additional view data. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 19536,
"s": 19505,
"text": "EditorForModel(String, String)"
},
{
"code": null,
"e": 19695,
"s": 19536,
"text": "Overloaded. Returns an HTML input element for each property in the model, using the specified template name and HTML field name. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 19734,
"s": 19695,
"text": "EditorForModel(String, String, Object)"
},
{
"code": null,
"e": 19906,
"s": 19734,
"text": "Overloaded. Returns an HTML input element for each property in the model, using the template name, HTML field name, and additional view data. (Defined by EditorExtensions)"
},
{
"code": null,
"e": 19916,
"s": 19906,
"text": "EndForm()"
},
{
"code": null,
"e": 19993,
"s": 19916,
"text": "Renders the closing </form> tag to the response. (Defined by FormExtensions)"
},
{
"code": null,
"e": 20008,
"s": 19993,
"text": "Hidden(String)"
},
{
"code": null,
"e": 20147,
"s": 20008,
"text": "Overloaded. Returns a hidden input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)"
},
{
"code": null,
"e": 20170,
"s": 20147,
"text": "Hidden(String, Object)"
},
{
"code": null,
"e": 20321,
"s": 20170,
"text": "Overloaded. Returns a hidden input element by using the specified HTML helper, the name of the form field, and the value. (Defined by InputExtensions)"
},
{
"code": null,
"e": 20373,
"s": 20321,
"text": "Hidden(String, Object, IDictionary<String, Object>)"
},
{
"code": null,
"e": 20545,
"s": 20373,
"text": "Overloaded. Returns a hidden input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 20576,
"s": 20545,
"text": "Hidden(String, Object, Object)"
},
{
"code": null,
"e": 20748,
"s": 20576,
"text": "Overloaded. Returns a hidden input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 20759,
"s": 20748,
"text": "Id(String)"
},
{
"code": null,
"e": 20825,
"s": 20759,
"text": "Gets the ID of the HtmlHelper string. (Defined by NameExtensions)"
},
{
"code": null,
"e": 20838,
"s": 20825,
"text": "IdForModel()"
},
{
"code": null,
"e": 20904,
"s": 20838,
"text": "Gets the ID of the HtmlHelper string. (Defined by NameExtensions)"
},
{
"code": null,
"e": 20918,
"s": 20904,
"text": "Label(String)"
},
{
"code": null,
"e": 21076,
"s": 20918,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 21119,
"s": 21076,
"text": "Label(String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 21277,
"s": 21119,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 21299,
"s": 21277,
"text": "Label(String, Object)"
},
{
"code": null,
"e": 21457,
"s": 21299,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 21479,
"s": 21457,
"text": "Label(String, String)"
},
{
"code": null,
"e": 21658,
"s": 21479,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression using the label text. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 21709,
"s": 21658,
"text": "Label(String, String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 21867,
"s": 21709,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 21897,
"s": 21867,
"text": "Label(String, String, Object)"
},
{
"code": null,
"e": 22055,
"s": 21897,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 22071,
"s": 22055,
"text": "LabelForModel()"
},
{
"code": null,
"e": 22214,
"s": 22071,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the model. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 22257,
"s": 22214,
"text": "LabelForModel(IDictionary<String, Object>)"
},
{
"code": null,
"e": 22415,
"s": 22257,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 22437,
"s": 22415,
"text": "LabelForModel(Object)"
},
{
"code": null,
"e": 22595,
"s": 22437,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 22617,
"s": 22595,
"text": "LabelForModel(String)"
},
{
"code": null,
"e": 22796,
"s": 22617,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression using the label text. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 22847,
"s": 22796,
"text": "LabelForModel(String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 23005,
"s": 22847,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 23035,
"s": 23005,
"text": "LabelForModel(String, Object)"
},
{
"code": null,
"e": 23193,
"s": 23035,
"text": "Overloaded. Returns an HTML label element and the property name of the property that is represented by the specified expression. (Defined by LabelExtensions)"
},
{
"code": null,
"e": 23209,
"s": 23193,
"text": "ListBox(String)"
},
{
"code": null,
"e": 23353,
"s": 23209,
"text": "Overloaded. Returns a multi-select select element using the specified HTML helper and the name of the form field. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 23398,
"s": 23353,
"text": "ListBox(String, IEnumerable<SelectListItem>)"
},
{
"code": null,
"e": 23569,
"s": 23398,
"text": "Overloaded. Returns a multi-select select element using the specified HTML helper, the name of the form field, and the specified list items. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 23643,
"s": 23569,
"text": "ListBox(String, IEnumerable<SelectListItem>, IDictionary<String, Object>)"
},
{
"code": null,
"e": 23845,
"s": 23643,
"text": "Overloaded. Returns a multi-select select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HMTL attributes. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 23898,
"s": 23845,
"text": "ListBox(String, IEnumerable<SelectListItem>, Object)"
},
{
"code": null,
"e": 24069,
"s": 23898,
"text": "Overloaded. Returns a multi-select select element using the specified HTML helper, the name of the form field, and the specified list items. (Defined by SelectExtensions)"
},
{
"code": null,
"e": 24082,
"s": 24069,
"text": "Name(String)"
},
{
"code": null,
"e": 24194,
"s": 24082,
"text": "Gets the full HTML field name for the object that is represented by the expression. (Defined by NameExtensions)"
},
{
"code": null,
"e": 24209,
"s": 24194,
"text": "NameForModel()"
},
{
"code": null,
"e": 24322,
"s": 24209,
"text": "Gets the full HTML field name for the object that is represented by the expression. (Defined by NameExtensions.)"
},
{
"code": null,
"e": 24338,
"s": 24322,
"text": "Partial(String)"
},
{
"code": null,
"e": 24442,
"s": 24338,
"text": "Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)"
},
{
"code": null,
"e": 24466,
"s": 24442,
"text": "Partial(String, Object)"
},
{
"code": null,
"e": 24570,
"s": 24466,
"text": "Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)"
},
{
"code": null,
"e": 24614,
"s": 24570,
"text": "Partial(String, Object, ViewDataDictionary)"
},
{
"code": null,
"e": 24718,
"s": 24614,
"text": "Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)"
},
{
"code": null,
"e": 24754,
"s": 24718,
"text": "Partial(String, ViewDataDictionary)"
},
{
"code": null,
"e": 24858,
"s": 24754,
"text": "Overloaded. Renders the specified partial view as an HTMLencoded string. (Defined by PartialExtensions)"
},
{
"code": null,
"e": 24875,
"s": 24858,
"text": "Password(String)"
},
{
"code": null,
"e": 25016,
"s": 24875,
"text": "Overloaded. Returns a password input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)"
},
{
"code": null,
"e": 25041,
"s": 25016,
"text": "Password(String, Object)"
},
{
"code": null,
"e": 25194,
"s": 25041,
"text": "Overloaded. Returns a password input element by using the specified HTML helper, the name of the form field, and the value. (Defined by InputExtensions)"
},
{
"code": null,
"e": 25248,
"s": 25194,
"text": "Password(String, Object, IDictionary<String, Object>)"
},
{
"code": null,
"e": 25422,
"s": 25248,
"text": "Overloaded. Returns a password input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 25455,
"s": 25422,
"text": "Password(String, Object, Object)"
},
{
"code": null,
"e": 25629,
"s": 25455,
"text": "Overloaded. Returns a password input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 25657,
"s": 25629,
"text": "RadioButton(String, Object)"
},
{
"code": null,
"e": 25787,
"s": 25657,
"text": "Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)"
},
{
"code": null,
"e": 25824,
"s": 25787,
"text": "RadioButton(String, Object, Boolean)"
},
{
"code": null,
"e": 25954,
"s": 25824,
"text": "Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)"
},
{
"code": null,
"e": 26020,
"s": 25954,
"text": "RadioButton(String, Object, Boolean, IDictionary<String, Object>)"
},
{
"code": null,
"e": 26150,
"s": 26020,
"text": "Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)"
},
{
"code": null,
"e": 26195,
"s": 26150,
"text": "RadioButton(String, Object, Boolean, Object)"
},
{
"code": null,
"e": 26325,
"s": 26195,
"text": "Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)"
},
{
"code": null,
"e": 26382,
"s": 26325,
"text": "RadioButton(String, Object, IDictionary<String, Object>)"
},
{
"code": null,
"e": 26512,
"s": 26382,
"text": "Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)"
},
{
"code": null,
"e": 26548,
"s": 26512,
"text": "RadioButton(String, Object, Object)"
},
{
"code": null,
"e": 26678,
"s": 26548,
"text": "Overloaded. Returns a radio button input element that is used to present mutually exclusive options. (Defined by InputExtensions)"
},
{
"code": null,
"e": 26699,
"s": 26678,
"text": "RenderAction(String)"
},
{
"code": null,
"e": 26838,
"s": 26699,
"text": "Overloaded. Invokes the specified child action method and renders the result inline in the parent view. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 26867,
"s": 26838,
"text": "RenderAction(String, Object)"
},
{
"code": null,
"e": 27037,
"s": 26867,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and renders the result inline in the parent view. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 27080,
"s": 27037,
"text": "RenderAction(String, RouteValueDictionary)"
},
{
"code": null,
"e": 27250,
"s": 27080,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and renders the result inline in the parent view. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 27279,
"s": 27250,
"text": "RenderAction(String, String)"
},
{
"code": null,
"e": 27454,
"s": 27279,
"text": "Overloaded. Invokes the specified child action method using the specified controller name and renders the result inline in the parent view. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 27491,
"s": 27454,
"text": "RenderAction(String, String, Object)"
},
{
"code": null,
"e": 27681,
"s": 27491,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and controller name and renders the result inline in the parent view. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 27732,
"s": 27681,
"text": "RenderAction(String, String, RouteValueDictionary)"
},
{
"code": null,
"e": 27922,
"s": 27732,
"text": "Overloaded. Invokes the specified child action method using the specified parameters and controller name and renders the result inline in the parent view. (Defined by ChildActionExtensions)"
},
{
"code": null,
"e": 27944,
"s": 27922,
"text": "RenderPartial(String)"
},
{
"code": null,
"e": 28064,
"s": 27944,
"text": "Overloaded. Renders the specified partial view by using the specified HTML helper. (Defined by RenderPartialExtensions)"
},
{
"code": null,
"e": 28094,
"s": 28064,
"text": "RenderPartial(String, Object)"
},
{
"code": null,
"e": 28295,
"s": 28094,
"text": "Overloaded. Renders the specified partial view, passing it a copy of the current ViewDataDictionary object, but with the Model property set to the specified model. (Defined by RenderPartialExtensions)"
},
{
"code": null,
"e": 28345,
"s": 28295,
"text": "RenderPartial(String, Object, ViewDataDictionary)"
},
{
"code": null,
"e": 28594,
"s": 28345,
"text": "Overloaded. Renders the specified partial view, replacing the partial view's ViewData property with the specified ViewDataDictionary object and setting the Model property of the view data to the specified model. (Defined by RenderPartialExtensions)"
},
{
"code": null,
"e": 28636,
"s": 28594,
"text": "RenderPartial(String, ViewDataDictionary)"
},
{
"code": null,
"e": 28799,
"s": 28636,
"text": "Overloaded. Renders the specified partial view, replacing its ViewData property with the specified ViewDataDictionary object. (Defined by RenderPartialExtensions)"
},
{
"code": null,
"e": 28825,
"s": 28799,
"text": "RouteLink(String, Object)"
},
{
"code": null,
"e": 28865,
"s": 28825,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 28899,
"s": 28865,
"text": "RouteLink(String, Object, Object)"
},
{
"code": null,
"e": 28939,
"s": 28899,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 28979,
"s": 28939,
"text": "RouteLink(String, RouteValueDictionary)"
},
{
"code": null,
"e": 29019,
"s": 28979,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 29088,
"s": 29019,
"text": "RouteLink(String, RouteValueDictionary, IDictionary<String, Object>)"
},
{
"code": null,
"e": 29128,
"s": 29088,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 29154,
"s": 29128,
"text": "RouteLink(String, String)"
},
{
"code": null,
"e": 29194,
"s": 29154,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 29228,
"s": 29194,
"text": "RouteLink(String, String, Object)"
},
{
"code": null,
"e": 29268,
"s": 29228,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 29310,
"s": 29268,
"text": "RouteLink(String, String, Object, Object)"
},
{
"code": null,
"e": 29350,
"s": 29310,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 29398,
"s": 29350,
"text": "RouteLink(String, String, RouteValueDictionary)"
},
{
"code": null,
"e": 29438,
"s": 29398,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 29515,
"s": 29438,
"text": "RouteLink(String, String, RouteValueDictionary, IDictionary<String, Object>)"
},
{
"code": null,
"e": 29555,
"s": 29515,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 29621,
"s": 29555,
"text": "RouteLink(String, String, String, String, String, Object, Object)"
},
{
"code": null,
"e": 29661,
"s": 29621,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 29762,
"s": 29661,
"text": "RouteLink(String, String, String, String, String, RouteValueDictionary, IDictionary<String, Object>)"
},
{
"code": null,
"e": 29802,
"s": 29762,
"text": "Overloaded. (Defined by LinkExtensions)"
},
{
"code": null,
"e": 29819,
"s": 29802,
"text": "TextArea(String)"
},
{
"code": null,
"e": 29970,
"s": 29819,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper and the name of the form field. (Defined by TextAreaExtensions.)"
},
{
"code": null,
"e": 30016,
"s": 29970,
"text": "TextArea(String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 30198,
"s": 30016,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, and the specified HTML attributes. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 30223,
"s": 30198,
"text": "TextArea(String, Object)"
},
{
"code": null,
"e": 30362,
"s": 30223,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper and HTML attributes. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 30387,
"s": 30362,
"text": "TextArea(String, String)"
},
{
"code": null,
"e": 30556,
"s": 30387,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, and the text content. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 30610,
"s": 30556,
"text": "TextArea(String, String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 30810,
"s": 30610,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, and the specified HTML attributes. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 30878,
"s": 30810,
"text": "TextArea(String, String, Int32, Int32, IDictionary<String, Object>)"
},
{
"code": null,
"e": 31110,
"s": 30878,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, the number of rows and columns, and the specified HTML attributes. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 31157,
"s": 31110,
"text": "TextArea(String, String, Int32, Int32, Object)"
},
{
"code": null,
"e": 31389,
"s": 31157,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, the number of rows and columns, and the specified HTML attributes. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 31422,
"s": 31389,
"text": "TextArea(String, String, Object)"
},
{
"code": null,
"e": 31622,
"s": 31422,
"text": "Overloaded. Returns the specified textarea element by using the specified HTML helper, the name of the form field, the text content, and the specified HTML attributes. (Defined by TextAreaExtensions)"
},
{
"code": null,
"e": 31638,
"s": 31622,
"text": "TextBox(String)"
},
{
"code": null,
"e": 31775,
"s": 31638,
"text": "Overloaded. Returns a text input element by using the specified HTML helper and the name of the form field. (Defined by InputExtensions)"
},
{
"code": null,
"e": 31799,
"s": 31775,
"text": "TextBox(String, Object)"
},
{
"code": null,
"e": 31948,
"s": 31799,
"text": "Overloaded. Returns a text input element by using the specified HTML helper, the name of the form field, and the value. (Defined by InputExtensions)"
},
{
"code": null,
"e": 32001,
"s": 31948,
"text": "TextBox(String, Object, IDictionary<String, Object>)"
},
{
"code": null,
"e": 32171,
"s": 32001,
"text": "Overloaded. Returns a text input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 32203,
"s": 32171,
"text": "TextBox(String, Object, Object)"
},
{
"code": null,
"e": 32373,
"s": 32203,
"text": "Overloaded. Returns a text input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. (Defined by InputExtensions)"
},
{
"code": null,
"e": 32405,
"s": 32373,
"text": "TextBox(String, Object, String)"
},
{
"code": null,
"e": 32476,
"s": 32405,
"text": "Overloaded. Returns a text input element. (Defined by InputExtensions)"
},
{
"code": null,
"e": 32537,
"s": 32476,
"text": "TextBox(String, Object, String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 32608,
"s": 32537,
"text": "Overloaded. Returns a text input element. (Defined by InputExtensions)"
},
{
"code": null,
"e": 32648,
"s": 32608,
"text": "TextBox(String, Object, String, Object)"
},
{
"code": null,
"e": 32719,
"s": 32648,
"text": "Overloaded. Returns a text input element. (Defined by InputExtensions)"
},
{
"code": null,
"e": 32736,
"s": 32719,
"text": "Validate(String)"
},
{
"code": null,
"e": 32869,
"s": 32736,
"text": "Retrieves the validation metadata for the specified model and applies each rule to the data field. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 32895,
"s": 32869,
"text": "ValidationMessage(String)"
},
{
"code": null,
"e": 33050,
"s": 32895,
"text": "Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 33105,
"s": 33050,
"text": "ValidationMessage(String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 33261,
"s": 33105,
"text": "Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions.)"
},
{
"code": null,
"e": 33324,
"s": 33261,
"text": "ValidationMessage(String, IDictionary<String, Object>, String)"
},
{
"code": null,
"e": 33479,
"s": 33324,
"text": "Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 33513,
"s": 33479,
"text": "ValidationMessage(String, Object)"
},
{
"code": null,
"e": 33668,
"s": 33513,
"text": "Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 33710,
"s": 33668,
"text": "ValidationMessage(String, Object, String)"
},
{
"code": null,
"e": 33865,
"s": 33710,
"text": "Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 33899,
"s": 33865,
"text": "ValidationMessage(String, String)"
},
{
"code": null,
"e": 34054,
"s": 33899,
"text": "Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 34117,
"s": 34054,
"text": "ValidationMessage(String, String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 34272,
"s": 34117,
"text": "Overloaded. Displays a validation message if an error exists for the specified field in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 34343,
"s": 34272,
"text": "ValidationMessage(String, String, IDictionary<String, Object>, String)"
},
{
"code": null,
"e": 34498,
"s": 34343,
"text": "Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 34540,
"s": 34498,
"text": "ValidationMessage(String, String, Object)"
},
{
"code": null,
"e": 34693,
"s": 34540,
"text": "Overloaded. Displays a validation message if an error exists forthe specified field in the ModelStateDictionary object. (Definedby ValidationExtensions)"
},
{
"code": null,
"e": 34743,
"s": 34693,
"text": "ValidationMessage(String, String, Object, String)"
},
{
"code": null,
"e": 34898,
"s": 34743,
"text": "Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 34940,
"s": 34898,
"text": "ValidationMessage(String, String, String)"
},
{
"code": null,
"e": 35095,
"s": 34940,
"text": "Overloaded. Displays a validation message if an error exists for the specified entry in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 35115,
"s": 35095,
"text": "ValidationSummary()"
},
{
"code": null,
"e": 35268,
"s": 35115,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 35295,
"s": 35268,
"text": "ValidationSummary(Boolean)"
},
{
"code": null,
"e": 35496,
"s": 35295,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 35531,
"s": 35496,
"text": "ValidationSummary(Boolean, String)"
},
{
"code": null,
"e": 35732,
"s": 35531,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 35796,
"s": 35732,
"text": "ValidationSummary(Boolean, String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 35997,
"s": 35796,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 36069,
"s": 35997,
"text": "ValidationSummary(Boolean, String, IDictionary<String, Object>, String)"
},
{
"code": null,
"e": 36115,
"s": 36069,
"text": "Overloaded. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 36158,
"s": 36115,
"text": "ValidationSummary(Boolean, String, Object)"
},
{
"code": null,
"e": 36359,
"s": 36158,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 36410,
"s": 36359,
"text": "ValidationSummary(Boolean, String, Object, String)"
},
{
"code": null,
"e": 36456,
"s": 36410,
"text": "Overloaded. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 36499,
"s": 36456,
"text": "ValidationSummary(Boolean, String, String)"
},
{
"code": null,
"e": 36545,
"s": 36499,
"text": "Overloaded. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 36571,
"s": 36545,
"text": "ValidationSummary(String)"
},
{
"code": null,
"e": 36724,
"s": 36571,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 36779,
"s": 36724,
"text": "ValidationSummary(String, IDictionary<String, Object>)"
},
{
"code": null,
"e": 36932,
"s": 36779,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 36995,
"s": 36932,
"text": "ValidationSummary(String, IDictionary<String, Object>, String)"
},
{
"code": null,
"e": 37041,
"s": 36995,
"text": "Overloaded. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 37075,
"s": 37041,
"text": "ValidationSummary(String, Object)"
},
{
"code": null,
"e": 37219,
"s": 37075,
"text": "Overloaded. Returns an unordered list (ul element) of validation messages in the ModelStateDictionary object. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 37261,
"s": 37219,
"text": "ValidationSummary(String, Object, String)"
},
{
"code": null,
"e": 37307,
"s": 37261,
"text": "Overloaded. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 37341,
"s": 37307,
"text": "ValidationSummary(String, String)"
},
{
"code": null,
"e": 37387,
"s": 37341,
"text": "Overloaded. (Defined by ValidationExtensions)"
},
{
"code": null,
"e": 37401,
"s": 37387,
"text": "Value(String)"
},
{
"code": null,
"e": 37553,
"s": 37401,
"text": "Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)"
},
{
"code": null,
"e": 37575,
"s": 37553,
"text": "Value(String, String)"
},
{
"code": null,
"e": 37727,
"s": 37575,
"text": "Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)"
},
{
"code": null,
"e": 37743,
"s": 37727,
"text": "ValueForModel()"
},
{
"code": null,
"e": 37895,
"s": 37743,
"text": "Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)"
},
{
"code": null,
"e": 37917,
"s": 37895,
"text": "ValueForModel(String)"
},
{
"code": null,
"e": 38069,
"s": 37917,
"text": "Overloaded. Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. (Defined by ValueExtensions)"
},
{
"code": null,
"e": 38322,
"s": 38069,
"text": "If you look at the view from the last chapter which we have generated from EmployeeController index action, you will see the number of operations that started with Html, like Html.ActionLink and Html.DisplayNameFor, etc. as shown in the following code."
},
{
"code": null,
"e": 39723,
"s": 38322,
"text": "@model IEnumerable<MVCSimpleApp.Models.Employee>\n@{\n Layout = null;\n} \n\n<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width\" />\n <title>Index</title>\n </head>\n\t\n <body>\n <p>\n @Html.ActionLink(\"Create New\", \"Create\")\n </p>\n\t\t\n <table class = \"table\">\n <tr>\n <th>\n @Html.DisplayNameFor(model => model.Name)\n </th>\n\t\t\t\t\n <th>\n @Html.DisplayNameFor(model => model.JoiningDate)\n </th>\n\t\t\t\t\n <th>\n @Html.DisplayNameFor(model => model.Age)\n </th>\n\t\t\t\t\n <th></th>\n </tr>\n\t\t\t\n @foreach (var item in Model) {\n <tr>\n <td>\n @Html.DisplayFor(modelItem => item.Name)\n </td>\n\t\t\t\t\t\n <td>\n @Html.DisplayFor(modelItem => item.JoiningDate)\n </td>\n\t\t\t\t\t\n <td>\n @Html.DisplayFor(modelItem => item.Age)\n </td>\n\t\t\t\t\t\n <td>\n @Html.ActionLink(\"Edit\", \"Edit\", new { id = item.ID }) |\n @Html.ActionLink(\"Details\", \"Details\", new { id = item.ID }) |\n @Html.ActionLink(\"Delete\", \"Delete\", new { id = item.ID })\n </td>\n </tr>\n }\n\t\t\t\n </table>\n </body>\n</html>"
},
{
"code": null,
"e": 39889,
"s": 39723,
"text": "This HTML is a property that we inherit from the ViewPage base class. So, it's available in all of our views and it returns an instance of a type called HTML Helper."
},
{
"code": null,
"e": 40067,
"s": 39889,
"text": "Let’s take a look at a simple example in which we will enable the user to edit the employee. Hence, this edit action will be using significant numbers of different HTML Helpers."
},
{
"code": null,
"e": 40156,
"s": 40067,
"text": "If you look at the above code, you will see at the end the following HTML Helper methods"
},
{
"code": null,
"e": 40212,
"s": 40156,
"text": "@Html.ActionLink(\"Edit\", \"Edit\", new { id = item.ID })\n"
},
{
"code": null,
"e": 40448,
"s": 40212,
"text": "In the ActionLink helper, the first parameter is of the link which is “Edit”, the second parameter is the action method in the Controller, which is also “Edit”, and the third parameter ID is of any particular employee you want to edit."
},
{
"code": null,
"e": 40573,
"s": 40448,
"text": "Let’s change the EmployeeController class by adding a static list and also change the index action using the following code."
},
{
"code": null,
"e": 41318,
"s": 40573,
"text": "public static List<Employee> empList = new List<Employee>{\n new Employee{\n ID = 1,\n Name = \"Allan\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 23\n },\n\t\n new Employee{\n ID = 2,\n Name = \"Carson\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 45\n },\n\t\n new Employee{\n ID = 3,\n Name = \"Carson\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 37\n },\n\t\n new Employee{\n ID = 4,\n Name = \"Laura\",\n JoiningDate = DateTime.Parse(DateTime.Today.ToString()),\n Age = 26\n },\n\t\n};\n\npublic ActionResult Index(){\n var employees = from e in empList\n orderby e.ID\n select e;\n return View(employees);\n}"
},
{
"code": null,
"e": 41513,
"s": 41318,
"text": "Let’s update the Edit action. You will see two Edit actions one for GET and one for POST. Let’s update the Edit action for Get, which has only Id in the parameter as shown in the following code."
},
{
"code": null,
"e": 41697,
"s": 41513,
"text": "// GET: Employee/Edit/5\npublic ActionResult Edit(int id){\n List<Employee> empList = GetEmployeeList();\n var employee = empList.Single(m => m.ID == id);\n return View(employee);\n}"
},
{
"code": null,
"e": 41883,
"s": 41697,
"text": "Now, we know that we have action for Edit but we don’t have any view for these actions. So we need to add a View as well. To do this, right-click on the Edit action and select Add View."
},
{
"code": null,
"e": 42006,
"s": 41883,
"text": "You will see the default name for view. Select Edit from the Template dropdown and Employee from the Model class dropdown."
},
{
"code": null,
"e": 42064,
"s": 42006,
"text": "Following is the default implementation in the Edit view."
},
{
"code": null,
"e": 44734,
"s": 42064,
"text": "@model MVCSimpleApp.Models.Employee\n@{\n Layout = null;\n}\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width\" />\n <title>Edit</title>\n </head>\n\t\n <body>\n @using (Html.BeginForm()){\n @Html.AntiForgeryToken()\n <div class = \"form-horizontal\">\n <h4>Employee</h4>\n <hr />\n @Html.ValidationSummary(\n true, \"\", new { @class = \"text-danger\" })\n\t\t\t\t\t\n @Html.HiddenFor(model => model.ID)\n\t\t\t\t\n <div class = \"form-group\">\n @Html.LabelFor(\n model => model.Name, htmlAttributes: new{\n @class = \"control-label col-md-2\" })\n\t\t\t\t\t\t\t\n <div class = \"col-md-10\">\n @Html.EditorFor(model => model.Name, new{\n htmlAttributes = new {\n @class = \"form-control\" } })\n\t\t\t\t\t\t\t\t\n @Html.ValidationMessageFor(model => model.Name, \"\", new{\n @class = \"text-danger\" })\n </div>\n\t\t\t\t\t\n </div>\n\t\t\t\t\n <div class = \"form-group\">\n @Html.LabelFor(\n model => model.JoiningDate, htmlAttributes: new{\n @class = \"control-label col-md-2\" })\n\t\t\t\t\t\t\t\n <div class = \"col-md-10\">\n @Html.EditorFor(\n model => model.JoiningDate, new{\n htmlAttributes = new{ @class = \"form-control\" } })\n\t\t\t\t\t\t\t\t\n @Html.ValidationMessageFor(\n model => model.JoiningDate, \"\", new{\n @class = \"text-danger\" })\n </div>\n\t\t\t\t\t\n </div>\n\t\t\t\t\n <div class = \"form-group\">\n @Html.LabelFor(\n model => model.Age, htmlAttributes: new{\n @class = \"control-label col-md-2\" })\n\t\t\t\t\t\t\t\n <div class = \"col-md-10\">\n @Html.EditorFor(\n model => model.Age, new{\n htmlAttributes = new{ @class = \"form-control\" } })\n\t\t\t\t\t\t\t\t\n @Html.ValidationMessageFor(\n model => model.Age, \"\", new{\n @class = \"text-danger\" })\n </div>\n\t\t\t\t\t\n </div>\n\t\t\t\t\n <div class = \"form-group\">\n <div class = \"col-md-offset-2 col-md-10\">\n <input type = \"submit\" value = \"Save\" class = \"btn btn-default\"/>\n </div>\n </div>\n\t\t\t\t\n </div>\n }\n\t\t\n <div>\n @Html.ActionLink(\"Back to List\", \"Index\")\n </div>\n\t\t\n </body>\n</html>"
},
{
"code": null,
"e": 44942,
"s": 44734,
"text": "As you can see that there are many helper methods used. So, here “HTML.BeginForm” writes an opening Form Tag. It also ensures that the method is going to be “Post”, when the user clicks on the “Save” button."
},
{
"code": null,
"e": 45039,
"s": 44942,
"text": "Html.BeginForm is very useful, because it enables you to change the URL, change the method, etc."
},
{
"code": null,
"e": 45153,
"s": 45039,
"text": "In the above code, you will see one more HTML helper and that is “@HTML.HiddenFor”, which emits the hidden field."
},
{
"code": null,
"e": 45340,
"s": 45153,
"text": "MVC Framework is smart enough to figure out that this ID field is mentioned in the model class and hence it needs to be prevented from getting edited, that is why it is marked as hidden."
},
{
"code": null,
"e": 45527,
"s": 45340,
"text": "The Html.LabelFor HTML Helper creates the labels on the screen. The Html.ValidationMessageFor helper displays proper error message if anything is wrongly entered while making the change."
},
{
"code": null,
"e": 45643,
"s": 45527,
"text": "We also need to change the Edit action for POST because once you update the employee then it will call this action."
},
{
"code": null,
"e": 45991,
"s": 45643,
"text": "// POST: Employee/Edit/5\n[HttpPost]\npublic ActionResult Edit(int id, FormCollection collection){\n try{\n var employee = empList.Single(m => m.ID == id);\n if (TryUpdateModel(employee)){\n //To Do:- database code\n return RedirectToAction(\"Index\");\n }\n return View(employee);\n }catch{\n return View();\n }\n}"
},
{
"code": null,
"e": 46124,
"s": 45991,
"text": "Let’s run this application and request for the following URL http://localhost:63004/employee. You will receive the following output."
},
{
"code": null,
"e": 46244,
"s": 46124,
"text": "Click on the edit link on any particular employee, let’s say click on Allan edit link. You will see the following view."
},
{
"code": null,
"e": 46357,
"s": 46244,
"text": "Let’s change the age from 23 to 29 and click ‘Save’ button, then you will see the updated age on the Index View."
},
{
"code": null,
"e": 46392,
"s": 46357,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 46406,
"s": 46392,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 46441,
"s": 46406,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 46464,
"s": 46441,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 46498,
"s": 46464,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 46518,
"s": 46498,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 46553,
"s": 46518,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 46570,
"s": 46553,
"text": " University Code"
},
{
"code": null,
"e": 46605,
"s": 46570,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 46622,
"s": 46605,
"text": " University Code"
},
{
"code": null,
"e": 46656,
"s": 46622,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 46671,
"s": 46656,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 46678,
"s": 46671,
"text": " Print"
},
{
"code": null,
"e": 46689,
"s": 46678,
"text": " Add Notes"
}
] |
ReactJS componentDidCatch() Method - GeeksforGeeks | 10 Aug, 2021
The componentDidCatch() method is invoked if some error occurs during the rendering phase of any lifecycle methods or any children components. This method is used to implement the Error Boundaries for the React application. It is called during the commit phase, so unlike getDerivedStateFromError() which was called during the render phase, side-effects are allowed in this method. This method is also used to log errors.
Syntax:
componentDidCatch(error, info)
Parameters: It accepts two parameters i.e, error, and info as described below:
error: It is the error that was thrown by the descendant component.
info: It stores the componentStack trace of which component has thrown this error.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
Example: Program to demonstrate the use of componentDidCatch() method.
Filename: App.js:
Javascript
import React, { Component } from 'react'; export default class App extends Component { // Initializing the state state = { error: false, }; componentDidCatch(error) { // Changing the state to true // if some error occurs this.setState({ error: true }); } render() { return ( <React.StrictMode> <div> {this.state.error ? <div>Some error</div> : <GFGComponent />} </div> </React.StrictMode> ); }} class GFGComponent extends Component { // GFGComponent throws error as state of // GFGCompnonent is not defined render() { return <h1>{this.state.heading}</h1>; }}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
output
Reference: https://reactjs.org/docs/react-component.html#componentdidcatch
saurabh1990aror
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Angular Libraries For Web Developers
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference between var, let and const keywords in JavaScript
How to Insert Form Data into Database using PHP ?
How to redirect to another page in ReactJS ?
How to execute PHP code using command line ?
How to pass data from child component to its parent in ReactJS ? | [
{
"code": null,
"e": 24836,
"s": 24808,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 25258,
"s": 24836,
"text": "The componentDidCatch() method is invoked if some error occurs during the rendering phase of any lifecycle methods or any children components. This method is used to implement the Error Boundaries for the React application. It is called during the commit phase, so unlike getDerivedStateFromError() which was called during the render phase, side-effects are allowed in this method. This method is also used to log errors."
},
{
"code": null,
"e": 25266,
"s": 25258,
"text": "Syntax:"
},
{
"code": null,
"e": 25297,
"s": 25266,
"text": "componentDidCatch(error, info)"
},
{
"code": null,
"e": 25376,
"s": 25297,
"text": "Parameters: It accepts two parameters i.e, error, and info as described below:"
},
{
"code": null,
"e": 25444,
"s": 25376,
"text": "error: It is the error that was thrown by the descendant component."
},
{
"code": null,
"e": 25527,
"s": 25444,
"text": "info: It stores the componentStack trace of which component has thrown this error."
},
{
"code": null,
"e": 25555,
"s": 25527,
"text": "Creating React Application:"
},
{
"code": null,
"e": 25619,
"s": 25555,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 25651,
"s": 25619,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 25752,
"s": 25651,
"text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:"
},
{
"code": null,
"e": 25766,
"s": 25752,
"text": "cd foldername"
},
{
"code": null,
"e": 25818,
"s": 25766,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 25836,
"s": 25818,
"text": "Project Structure"
},
{
"code": null,
"e": 25907,
"s": 25836,
"text": "Example: Program to demonstrate the use of componentDidCatch() method."
},
{
"code": null,
"e": 25927,
"s": 25907,
"text": "Filename: App.js: "
},
{
"code": null,
"e": 25938,
"s": 25927,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react'; export default class App extends Component { // Initializing the state state = { error: false, }; componentDidCatch(error) { // Changing the state to true // if some error occurs this.setState({ error: true }); } render() { return ( <React.StrictMode> <div> {this.state.error ? <div>Some error</div> : <GFGComponent />} </div> </React.StrictMode> ); }} class GFGComponent extends Component { // GFGComponent throws error as state of // GFGCompnonent is not defined render() { return <h1>{this.state.heading}</h1>; }}",
"e": 26576,
"s": 25938,
"text": null
},
{
"code": null,
"e": 26689,
"s": 26576,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 26699,
"s": 26689,
"text": "npm start"
},
{
"code": null,
"e": 26707,
"s": 26699,
"text": "Output:"
},
{
"code": null,
"e": 26714,
"s": 26707,
"text": "output"
},
{
"code": null,
"e": 26789,
"s": 26714,
"text": "Reference: https://reactjs.org/docs/react-component.html#componentdidcatch"
},
{
"code": null,
"e": 26805,
"s": 26789,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 26814,
"s": 26805,
"text": "react-js"
},
{
"code": null,
"e": 26831,
"s": 26814,
"text": "Web Technologies"
},
{
"code": null,
"e": 26929,
"s": 26831,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26938,
"s": 26929,
"text": "Comments"
},
{
"code": null,
"e": 26951,
"s": 26938,
"text": "Old Comments"
},
{
"code": null,
"e": 26993,
"s": 26951,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27036,
"s": 26993,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27080,
"s": 27036,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 27125,
"s": 27080,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27197,
"s": 27125,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27258,
"s": 27197,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27308,
"s": 27258,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27353,
"s": 27308,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 27398,
"s": 27353,
"text": "How to execute PHP code using command line ?"
}
] |
Java program to calculate the product of two numbers | The * operator in Java is used to multiply two numbers. Read required numbers from the user using Scanner class and multiply these two integers using the * operator.
import java.util.Scanner;
public class MultiplicationOfTwoNumbers {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of the first number ::");
int a = sc.nextInt();
System.out.println("Enter the value of the first number ::");
int b = sc.nextInt();
int result = a*b;
System.out.println("Product of the given two numbers is ::"+result);
}
}
Enter the value of the first number ::
55
Enter the value of the first number ::
66
Product of the given two numbers is ::3630 | [
{
"code": null,
"e": 1228,
"s": 1062,
"text": "The * operator in Java is used to multiply two numbers. Read required numbers from the user using Scanner class and multiply these two integers using the * operator."
},
{
"code": null,
"e": 1680,
"s": 1228,
"text": "import java.util.Scanner;\npublic class MultiplicationOfTwoNumbers {\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the value of the first number ::\");\n int a = sc.nextInt();\n System.out.println(\"Enter the value of the first number ::\");\n int b = sc.nextInt();\n int result = a*b;\n System.out.println(\"Product of the given two numbers is ::\"+result);\n }\n}"
},
{
"code": null,
"e": 1807,
"s": 1680,
"text": "Enter the value of the first number ::\n55\nEnter the value of the first number ::\n66\nProduct of the given two numbers is ::3630"
}
] |
Basic calculator program using C# | To create a calculator program in C#, you need to use Web Forms. Under that create buttons from 1-9, addition, subtraction, multiplication, etc.
Let us see the code for addition, subtraction, and multiplication. Firstly, we have declared two variables −
static float x, y;
Now, we will see how to set codes for calculation on individual button click: Our result textbox is tbResult since we have used Windows Form as well to display the calculator −
protected void add_Click(object sender, EventArgs e) {
x = Convert.ToInt32(tbResult.Text);
tbResult.Text = "";
y = '+';
tbResult.Text += y;
}
protected void sub_Click(object sender, EventArgs e) {
x = Convert.ToInt32(tbResult.Text);
tbResult.Text = "";
y = '-';
tbResult.Text += y;
}
protected void mul_Click(object sender, EventArgs e) {
x = Convert.ToInt32(tbResult.Text);
tbResult.Text = "";
y = '*';
tbResult.Text += y;
}
The following is the equal button code −
protected void eql_Click(object sender, EventArgs e) {
z = Convert.ToInt32(tbResult.Text);
tbResult.Text = "";
if (y == '/') {
p = x / z;
tbResult.Text += p;
x = d;
} else if (y == '+') {
p = x + z;
tbResult.Text += p;
a = d;
} else if (y == '-') {
p = x - z;
tbResult.Text += p;
x = p;
} else {
p = x * z;
tbResult.Text += p;
x = p;
}
} | [
{
"code": null,
"e": 1207,
"s": 1062,
"text": "To create a calculator program in C#, you need to use Web Forms. Under that create buttons from 1-9, addition, subtraction, multiplication, etc."
},
{
"code": null,
"e": 1316,
"s": 1207,
"text": "Let us see the code for addition, subtraction, and multiplication. Firstly, we have declared two variables −"
},
{
"code": null,
"e": 1335,
"s": 1316,
"text": "static float x, y;"
},
{
"code": null,
"e": 1512,
"s": 1335,
"text": "Now, we will see how to set codes for calculation on individual button click: Our result textbox is tbResult since we have used Windows Form as well to display the calculator −"
},
{
"code": null,
"e": 1974,
"s": 1512,
"text": "protected void add_Click(object sender, EventArgs e) {\n x = Convert.ToInt32(tbResult.Text);\n tbResult.Text = \"\";\n y = '+';\n tbResult.Text += y;\n}\nprotected void sub_Click(object sender, EventArgs e) {\n x = Convert.ToInt32(tbResult.Text);\n tbResult.Text = \"\";\n y = '-';\n tbResult.Text += y;\n}\nprotected void mul_Click(object sender, EventArgs e) {\n x = Convert.ToInt32(tbResult.Text);\n tbResult.Text = \"\";\n y = '*';\n tbResult.Text += y;\n}"
},
{
"code": null,
"e": 2015,
"s": 1974,
"text": "The following is the equal button code −"
},
{
"code": null,
"e": 2446,
"s": 2015,
"text": "protected void eql_Click(object sender, EventArgs e) {\n z = Convert.ToInt32(tbResult.Text);\n tbResult.Text = \"\";\n if (y == '/') {\n p = x / z;\n tbResult.Text += p;\n x = d;\n } else if (y == '+') {\n p = x + z;\n tbResult.Text += p;\n a = d;\n } else if (y == '-') {\n p = x - z;\n tbResult.Text += p;\n x = p;\n } else {\n p = x * z;\n tbResult.Text += p;\n x = p;\n }\n}"
}
] |
How to write JavaScript in an External File? | Create external JavaScript file with the extension .js. After creating, add it to the HTML file in the script tag. The src attribute is used to include that external JavaScript file.
If you have more than one external JavaScript file, then add it in the same web page to increase performance of the page.
Let’s say the following new.js is our external JavaScript file −
function display() {
alert("Hello World!");
}
Now add the external JavaScript file to the HTML web page −
<html>
<body>
<form>
<input type="button" value="Result" onclick="display()"/>
</form>
<script src="new.js">
</script>
</body>
</html> | [
{
"code": null,
"e": 1245,
"s": 1062,
"text": "Create external JavaScript file with the extension .js. After creating, add it to the HTML file in the script tag. The src attribute is used to include that external JavaScript file."
},
{
"code": null,
"e": 1367,
"s": 1245,
"text": "If you have more than one external JavaScript file, then add it in the same web page to increase performance of the page."
},
{
"code": null,
"e": 1432,
"s": 1367,
"text": "Let’s say the following new.js is our external JavaScript file −"
},
{
"code": null,
"e": 1481,
"s": 1432,
"text": "function display() {\n alert(\"Hello World!\");\n}"
},
{
"code": null,
"e": 1541,
"s": 1481,
"text": "Now add the external JavaScript file to the HTML web page −"
},
{
"code": null,
"e": 1712,
"s": 1541,
"text": "<html>\n <body>\n <form>\n <input type=\"button\" value=\"Result\" onclick=\"display()\"/>\n </form>\n <script src=\"new.js\">\n </script>\n </body>\n</html>"
}
] |
How to convert negative values in an R data frame to positive values? | Sometimes we need to use absolute values but few values in the data set are negative, therefore, we must convert them to positive. This can be done by using abs function. For example, if we have a data frame df with many columns and each of them having some negative values then those values can be converted to positive values by just using abs(df).
Consider the below data frame −
Live Demo
set.seed(41)
x1<-sample(-1:1,20,replace=TRUE)
x2<-sample(-5:1,20,replace=TRUE)
df1<-data.frame(x1,x2)
df1
x1 x2
1 1 -2
2 -1 -4
3 0 1
4 0 0
5 -1 -2
6 0 0
7 0 -4
8 0 -4
9 0 -2
10 1 -2
11 0 -1
12 1 -3
13 -1 -5
14 -1 0
15 0 -3
16 -1 -3
17 0 -5
18 -1 -2
19 -1 -5
20 -1 -4
Converting all the values in df1 to positive values −
> abs(df1)
x1 x2
1 1 2
2 1 4
3 0 1
4 0 0
5 1 2
6 0 0
7 0 4
8 0 4
9 0 2
10 1 2
11 0 1
12 1 3
13 1 5
14 1 0
15 0 3
16 1 3
17 0 5
18 1 2
19 1 5
20 1 4
Let’s have a look at another example −
Live Demo
y1<-sample(-10:10,20,replace=TRUE)
y2<-sample(-100:1,20)
y3<-sample(-100:-91,20,replace=TRUE)
y4<-sample(c(-100,-50,0,50,100),20,replace=TRUE)
df2<-data.frame(y1,y2,y3,y4)
df2
y1 y2 y3 y4
1 8 -12 -99 100
2 -2 -37 -93 -50
3 -5 -85 -93 -100
4 6 -16 -93 0
5 2 -51 -91 50
6 -5 -50 -94 100
7 0 -38 -92 100
8 -3 -20 -95 -50
9 1 -42 -96 100
10 -8 -31 -94 -50
11 -4 -75 -100 0
12 -5 -80 -94 100
13 0 -1 -95 0
14 2 -99 -99 50
15 9 -45 -97 -50
16 -6 -79 -93 50
17 -2 -52 -94 0
18 9 -82 -96 50
19 8 -32 -95 0
20 4 -11 -99 -100
Converting all the values in df2 to positive values −
abs(df2)
y1 y2 y3 y4
1 8 12 99 100
2 2 37 93 50
3 5 85 93 100
4 6 16 93 0
5 2 51 91 50
6 5 50 94 100
7 0 38 92 100
8 3 20 95 50
9 1 42 96 100
10 8 31 94 50
11 4 75 100 0
12 5 80 94 100
13 0 1 95 0
14 2 99 99 50
15 9 45 97 50
16 6 79 93 50
17 2 52 94 0
18 9 82 96 50
19 8 32 95 0
20 4 11 99 100 | [
{
"code": null,
"e": 1413,
"s": 1062,
"text": "Sometimes we need to use absolute values but few values in the data set are negative, therefore, we must convert them to positive. This can be done by using abs function. For example, if we have a data frame df with many columns and each of them having some negative values then those values can be converted to positive values by just using abs(df)."
},
{
"code": null,
"e": 1445,
"s": 1413,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1456,
"s": 1445,
"text": " Live Demo"
},
{
"code": null,
"e": 1562,
"s": 1456,
"text": "set.seed(41)\nx1<-sample(-1:1,20,replace=TRUE)\nx2<-sample(-5:1,20,replace=TRUE)\ndf1<-data.frame(x1,x2)\ndf1"
},
{
"code": null,
"e": 1745,
"s": 1562,
"text": " x1 x2\n1 1 -2\n2 -1 -4\n3 0 1\n4 0 0\n5 -1 -2\n6 0 0\n7 0 -4\n8 0 -4\n9 0 -2\n10 1 -2\n11 0 -1\n12 1 -3\n13 -1 -5\n14 -1 0\n15 0 -3\n16 -1 -3\n17 0 -5\n18 -1 -2\n19 -1 -5\n20 -1 -4"
},
{
"code": null,
"e": 1799,
"s": 1745,
"text": "Converting all the values in df1 to positive values −"
},
{
"code": null,
"e": 1810,
"s": 1799,
"text": "> abs(df1)"
},
{
"code": null,
"e": 1958,
"s": 1810,
"text": " x1 x2\n1 1 2\n2 1 4\n3 0 1\n4 0 0\n5 1 2\n6 0 0\n7 0 4\n8 0 4\n9 0 2\n10 1 2\n11 0 1\n12 1 3\n13 1 5\n14 1 0\n15 0 3\n16 1 3\n17 0 5\n18 1 2\n19 1 5\n20 1 4"
},
{
"code": null,
"e": 1997,
"s": 1958,
"text": "Let’s have a look at another example −"
},
{
"code": null,
"e": 2008,
"s": 1997,
"text": " Live Demo"
},
{
"code": null,
"e": 2184,
"s": 2008,
"text": "y1<-sample(-10:10,20,replace=TRUE)\ny2<-sample(-100:1,20)\ny3<-sample(-100:-91,20,replace=TRUE)\ny4<-sample(c(-100,-50,0,50,100),20,replace=TRUE)\ndf2<-data.frame(y1,y2,y3,y4)\ndf2"
},
{
"code": null,
"e": 2559,
"s": 2184,
"text": " y1 y2 y3 y4\n1 8 -12 -99 100\n2 -2 -37 -93 -50\n3 -5 -85 -93 -100\n4 6 -16 -93 0\n5 2 -51 -91 50\n6 -5 -50 -94 100\n7 0 -38 -92 100\n8 -3 -20 -95 -50\n9 1 -42 -96 100\n10 -8 -31 -94 -50\n11 -4 -75 -100 0\n12 -5 -80 -94 100\n13 0 -1 -95 0\n14 2 -99 -99 50\n15 9 -45 -97 -50\n16 -6 -79 -93 50\n17 -2 -52 -94 0\n18 9 -82 -96 50\n19 8 -32 -95 0\n20 4 -11 -99 -100"
},
{
"code": null,
"e": 2613,
"s": 2559,
"text": "Converting all the values in df2 to positive values −"
},
{
"code": null,
"e": 2622,
"s": 2613,
"text": "abs(df2)"
},
{
"code": null,
"e": 2918,
"s": 2622,
"text": " y1 y2 y3 y4\n1 8 12 99 100\n2 2 37 93 50\n3 5 85 93 100\n4 6 16 93 0\n5 2 51 91 50\n6 5 50 94 100\n7 0 38 92 100\n8 3 20 95 50\n9 1 42 96 100\n10 8 31 94 50\n11 4 75 100 0\n12 5 80 94 100\n13 0 1 95 0\n14 2 99 99 50\n15 9 45 97 50\n16 6 79 93 50\n17 2 52 94 0\n18 9 82 96 50\n19 8 32 95 0\n20 4 11 99 100"
}
] |
ELMo helps to further improve your sentence embeddings | by Edward Ma | Towards Data Science | In the last story, Contextualized Word Vectors (CoVe) is introduced which is the enhanced version of word embeddings. Peters et al. introduces Deep Contextualized Word Representations which aim at providing a better word representation for NLP tasks under different context. They call it as ELMo (Embeddings from Language Models).
After reading this post, you will understand:
Embeddings from Language Models Design
Architecture
Implementation
Take Away
ELMo use bidirectional language model (biLM) to learn both word (e.g., syntax and semantics) and linguistic context (i.e., to model polysemy). After pre-training, an internal state of vectors can be transferred to downstream NLP tasks. Peters et al. used 6 NLP tasks to evaluate the outcome from biLM.
Those tasks are Question Answering, Textual Entailment, Semantic Role Labeling, Coreference Resolution, Named Entity Extraction and Sentiment Analysis. All of them got a outperform result.
Different from traditional word embeddings, ELMo produced multiple word embeddings per single word for different scenarios. Higher-level layers capture context-dependent aspects of word embeddings while lower-level layers capture model aspects of syntax. In the simplest case, we only use top layer (1 layer only) from ELMo while we can also combine all layers into a single vector.
We can concatenate ELMo vector and token embeddings (word embeddings and/or character embeddings) to form a new embeddings as follow:
In the experiment, Peters et al. use L=2 (2 biLSTM layer) with 4096 units and 512 output dimension for context-dependent part while 2048 character n-gram constitutional filters and 512 output dimension for context insensitive part to build contextualized word embeddings.
Original authors are McCann et al. who implemented ELMo by Pytorch with python 3.6. There are Tensorflow, chainer and Keras versions available. I will use Keras version to demonstrate how we can convert text to vectors. For others, you can check out those githubs which is mentioned in Reference section.
The following examples show how we can use keras to implement it . Tensorflow Hub is a model hub which storing lots of different model. If you only need a pre-trained embeddings, you can leverage use the following code to retrieve it from Tensorflow Hub and transferring to Keras.
2 embeddings layer (there are 5 layers in total) can be chosen from Tensorflow Hub pre-trained model. The first one “elmo” which is the weighed sum of the 3 other layers. The second one is “default” which is a fixed mean-polling of all layers. You may find more information from here.
In my demo, there are 3 approaches to use ELMo pre-trained model. They are:
Weighted sum of the 3 layers with word embeddingsWeighted sum of the 3 layers without word embeddingsFixed mean-pooling without word embeddings
Weighted sum of the 3 layers with word embeddings
Weighted sum of the 3 layers without word embeddings
Fixed mean-pooling without word embeddings
1. Weighted sum of the 3 layers with word embeddings
# Input Layersword_input_layer = Input(shape=(None, ), dtype='int32')elmo_input_layer = Input(shape=(None, ), dtype=tf.string)# Output Layersword_output_layer = Embedding( input_dim=vocab_size, output_dim=256)(word_input_layer)elmo_output_layer = Lambda( elmo_embs.to_keras_layer, output_shape=(None, 1024))(elmo_input_layer)output_layer = Concatenate()( [word_output_layer, elmo_output_layer])output_layer = BatchNormalization()(output_layer)output_layer = LSTM( 256, dropout=0.2, recurrent_dropout=0.2)(output_layer)output_layer = Dense(4, activation='sigmoid')(output_layer)# Build Modelmodel = Model( inputs=[word_input_layer, elmo_input_layer], outputs=output_layer)model.compile( loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])model.summary()model.fit( [x_train_words, x_train_sentences], y_train,# validation_data=([x_test_words, x_test_sentences], y_test), epochs=10, batch_size=32)
Result
Accuracy:77.10%Average Precision: 0.78Average Recall: 0.77Average f1: 0.76
2. Weighted sum of the 3 layers without word embeddings
# Input Layerselmo_input_layer = Input(shape=(None, ), dtype=tf.string)# Output Layersoutput_layer = Lambda( elmo_embs.to_keras_layer, output_shape=(None, 1024))(elmo_input_layer)output_layer = BatchNormalization()(output_layer)output_layer = LSTM( 256, dropout=0.2, recurrent_dropout=0.2)(output_layer)output_layer = Dense(4, activation='sigmoid')(output_layer)# Build Modelmodel = Model( inputs=elmo_input_layer, outputs=output_layer)model.compile( loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])model.summary()model.fit( x_train_sentences, y_train,# validation_data=([x_test_words, x_test_sentences], y_test), epochs=10, batch_size=32)
Result
Accuracy:76.83%Average Precision: 0.78Average Recall: 0.77Average f1: 0.77
3. Fixed mean-pooling without word embeddings
# Input Layersinput_layer = Input(shape=(None,), dtype=tf.string)# Output Layersoutput_layer = Lambda( elmo_embs.to_keras_layer, output_shape=(1024,))(input_layer)output_layer = Dense( 256, activation='relu')(output_layer)output_layer = Dense(4, activation='sigmoid')(output_layer)model = Model(inputs=[input_layer], outputs=output_layer)model.compile( loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])model.summary()model.fit( x_train_sentences, y_train,# validation_data=([x_test_words, x_test_sentences], y_test), epochs=10, batch_size=32)
Result
Accuracy:74.37%Average Precision: 0.79Average Recall: 0.74Average f1: 0.75
To access all code, you can visit this github repo
CoVe needs label data to get the contextual word vectors while ELMo go for unsupervised way.
CoVe use only the last layer while ELMo use multiple layer for contextual word representations.
CoVe unable to resolve OOV issue. It suggests to use zero vectors to represent unknown word. ELMO can handle the OOV problem as it uses character embeddings to build word embeddings.
ELMo is quite time consuming to compute vectors. Per authors suggested, you can precompute token offline and lookup it during online prediction to reduce time spending.
I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science, Artificial Intelligence , especially in NLP and platform related. You can reach me from Medium Blog, LinkedIn or Github.
Peters M. E., Neumann M., Uyyer M., Gardner M., Clark C., Lee K., Zettlemoyer L.. Deep contextualized word representations. 2018. https://arxiv.org/pdf/1802.05365.pdf
ELMo in Pytorch (Original)
ELMo in Keras
ELMo in Tensorflow
ELMo in chainer | [
{
"code": null,
"e": 503,
"s": 172,
"text": "In the last story, Contextualized Word Vectors (CoVe) is introduced which is the enhanced version of word embeddings. Peters et al. introduces Deep Contextualized Word Representations which aim at providing a better word representation for NLP tasks under different context. They call it as ELMo (Embeddings from Language Models)."
},
{
"code": null,
"e": 549,
"s": 503,
"text": "After reading this post, you will understand:"
},
{
"code": null,
"e": 588,
"s": 549,
"text": "Embeddings from Language Models Design"
},
{
"code": null,
"e": 601,
"s": 588,
"text": "Architecture"
},
{
"code": null,
"e": 616,
"s": 601,
"text": "Implementation"
},
{
"code": null,
"e": 626,
"s": 616,
"text": "Take Away"
},
{
"code": null,
"e": 928,
"s": 626,
"text": "ELMo use bidirectional language model (biLM) to learn both word (e.g., syntax and semantics) and linguistic context (i.e., to model polysemy). After pre-training, an internal state of vectors can be transferred to downstream NLP tasks. Peters et al. used 6 NLP tasks to evaluate the outcome from biLM."
},
{
"code": null,
"e": 1117,
"s": 928,
"text": "Those tasks are Question Answering, Textual Entailment, Semantic Role Labeling, Coreference Resolution, Named Entity Extraction and Sentiment Analysis. All of them got a outperform result."
},
{
"code": null,
"e": 1500,
"s": 1117,
"text": "Different from traditional word embeddings, ELMo produced multiple word embeddings per single word for different scenarios. Higher-level layers capture context-dependent aspects of word embeddings while lower-level layers capture model aspects of syntax. In the simplest case, we only use top layer (1 layer only) from ELMo while we can also combine all layers into a single vector."
},
{
"code": null,
"e": 1634,
"s": 1500,
"text": "We can concatenate ELMo vector and token embeddings (word embeddings and/or character embeddings) to form a new embeddings as follow:"
},
{
"code": null,
"e": 1906,
"s": 1634,
"text": "In the experiment, Peters et al. use L=2 (2 biLSTM layer) with 4096 units and 512 output dimension for context-dependent part while 2048 character n-gram constitutional filters and 512 output dimension for context insensitive part to build contextualized word embeddings."
},
{
"code": null,
"e": 2211,
"s": 1906,
"text": "Original authors are McCann et al. who implemented ELMo by Pytorch with python 3.6. There are Tensorflow, chainer and Keras versions available. I will use Keras version to demonstrate how we can convert text to vectors. For others, you can check out those githubs which is mentioned in Reference section."
},
{
"code": null,
"e": 2492,
"s": 2211,
"text": "The following examples show how we can use keras to implement it . Tensorflow Hub is a model hub which storing lots of different model. If you only need a pre-trained embeddings, you can leverage use the following code to retrieve it from Tensorflow Hub and transferring to Keras."
},
{
"code": null,
"e": 2777,
"s": 2492,
"text": "2 embeddings layer (there are 5 layers in total) can be chosen from Tensorflow Hub pre-trained model. The first one “elmo” which is the weighed sum of the 3 other layers. The second one is “default” which is a fixed mean-polling of all layers. You may find more information from here."
},
{
"code": null,
"e": 2853,
"s": 2777,
"text": "In my demo, there are 3 approaches to use ELMo pre-trained model. They are:"
},
{
"code": null,
"e": 2997,
"s": 2853,
"text": "Weighted sum of the 3 layers with word embeddingsWeighted sum of the 3 layers without word embeddingsFixed mean-pooling without word embeddings"
},
{
"code": null,
"e": 3047,
"s": 2997,
"text": "Weighted sum of the 3 layers with word embeddings"
},
{
"code": null,
"e": 3100,
"s": 3047,
"text": "Weighted sum of the 3 layers without word embeddings"
},
{
"code": null,
"e": 3143,
"s": 3100,
"text": "Fixed mean-pooling without word embeddings"
},
{
"code": null,
"e": 3196,
"s": 3143,
"text": "1. Weighted sum of the 3 layers with word embeddings"
},
{
"code": null,
"e": 4160,
"s": 3196,
"text": "# Input Layersword_input_layer = Input(shape=(None, ), dtype='int32')elmo_input_layer = Input(shape=(None, ), dtype=tf.string)# Output Layersword_output_layer = Embedding( input_dim=vocab_size, output_dim=256)(word_input_layer)elmo_output_layer = Lambda( elmo_embs.to_keras_layer, output_shape=(None, 1024))(elmo_input_layer)output_layer = Concatenate()( [word_output_layer, elmo_output_layer])output_layer = BatchNormalization()(output_layer)output_layer = LSTM( 256, dropout=0.2, recurrent_dropout=0.2)(output_layer)output_layer = Dense(4, activation='sigmoid')(output_layer)# Build Modelmodel = Model( inputs=[word_input_layer, elmo_input_layer], outputs=output_layer)model.compile( loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])model.summary()model.fit( [x_train_words, x_train_sentences], y_train,# validation_data=([x_test_words, x_test_sentences], y_test), epochs=10, batch_size=32)"
},
{
"code": null,
"e": 4167,
"s": 4160,
"text": "Result"
},
{
"code": null,
"e": 4242,
"s": 4167,
"text": "Accuracy:77.10%Average Precision: 0.78Average Recall: 0.77Average f1: 0.76"
},
{
"code": null,
"e": 4298,
"s": 4242,
"text": "2. Weighted sum of the 3 layers without word embeddings"
},
{
"code": null,
"e": 5000,
"s": 4298,
"text": "# Input Layerselmo_input_layer = Input(shape=(None, ), dtype=tf.string)# Output Layersoutput_layer = Lambda( elmo_embs.to_keras_layer, output_shape=(None, 1024))(elmo_input_layer)output_layer = BatchNormalization()(output_layer)output_layer = LSTM( 256, dropout=0.2, recurrent_dropout=0.2)(output_layer)output_layer = Dense(4, activation='sigmoid')(output_layer)# Build Modelmodel = Model( inputs=elmo_input_layer, outputs=output_layer)model.compile( loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])model.summary()model.fit( x_train_sentences, y_train,# validation_data=([x_test_words, x_test_sentences], y_test), epochs=10, batch_size=32)"
},
{
"code": null,
"e": 5007,
"s": 5000,
"text": "Result"
},
{
"code": null,
"e": 5082,
"s": 5007,
"text": "Accuracy:76.83%Average Precision: 0.78Average Recall: 0.77Average f1: 0.77"
},
{
"code": null,
"e": 5128,
"s": 5082,
"text": "3. Fixed mean-pooling without word embeddings"
},
{
"code": null,
"e": 5729,
"s": 5128,
"text": "# Input Layersinput_layer = Input(shape=(None,), dtype=tf.string)# Output Layersoutput_layer = Lambda( elmo_embs.to_keras_layer, output_shape=(1024,))(input_layer)output_layer = Dense( 256, activation='relu')(output_layer)output_layer = Dense(4, activation='sigmoid')(output_layer)model = Model(inputs=[input_layer], outputs=output_layer)model.compile( loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])model.summary()model.fit( x_train_sentences, y_train,# validation_data=([x_test_words, x_test_sentences], y_test), epochs=10, batch_size=32)"
},
{
"code": null,
"e": 5736,
"s": 5729,
"text": "Result"
},
{
"code": null,
"e": 5811,
"s": 5736,
"text": "Accuracy:74.37%Average Precision: 0.79Average Recall: 0.74Average f1: 0.75"
},
{
"code": null,
"e": 5862,
"s": 5811,
"text": "To access all code, you can visit this github repo"
},
{
"code": null,
"e": 5955,
"s": 5862,
"text": "CoVe needs label data to get the contextual word vectors while ELMo go for unsupervised way."
},
{
"code": null,
"e": 6051,
"s": 5955,
"text": "CoVe use only the last layer while ELMo use multiple layer for contextual word representations."
},
{
"code": null,
"e": 6234,
"s": 6051,
"text": "CoVe unable to resolve OOV issue. It suggests to use zero vectors to represent unknown word. ELMO can handle the OOV problem as it uses character embeddings to build word embeddings."
},
{
"code": null,
"e": 6403,
"s": 6234,
"text": "ELMo is quite time consuming to compute vectors. Per authors suggested, you can precompute token offline and lookup it during online prediction to reduce time spending."
},
{
"code": null,
"e": 6603,
"s": 6403,
"text": "I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science, Artificial Intelligence , especially in NLP and platform related. You can reach me from Medium Blog, LinkedIn or Github."
},
{
"code": null,
"e": 6770,
"s": 6603,
"text": "Peters M. E., Neumann M., Uyyer M., Gardner M., Clark C., Lee K., Zettlemoyer L.. Deep contextualized word representations. 2018. https://arxiv.org/pdf/1802.05365.pdf"
},
{
"code": null,
"e": 6797,
"s": 6770,
"text": "ELMo in Pytorch (Original)"
},
{
"code": null,
"e": 6811,
"s": 6797,
"text": "ELMo in Keras"
},
{
"code": null,
"e": 6830,
"s": 6811,
"text": "ELMo in Tensorflow"
}
] |
Get Started With TensorFlow 2.0 and Linear Regression | by Shubham Panchal | Towards Data Science | TensorFlow 2.0 has been a major breakthrough in the TensorFlow family. It’s completely new and refurbished and also less creepy! We’ll create a simple Linear Regression model in TensorFlow 2.0 to explore some new changes. So, open up your code editors and let’s get started!
Also, open up this notebook for an interactive learning experience.
Attention! TensorFlow 2.0 is now available in the stable channel!
For viewing some basic concepts and their simpler explanations see,
Machine Learning Glossary | Google
ML Cheatsheet
Human-In-The-Loop Systems — All You Need To Know
Deploying TF Models on Heroku for Android Apps
Accessing App Usage History In Android
No, Kernels & Filters Are Not The Same
Deploying Pretrained TF Object Detection Models on Android
Realtime Selfie Segmentation In Android With MLKit
Grad-CAM: A Camera For Your Model’s Decision
MLP Mixer Is All You Need?
Age + Gender Estimation in Android with TensorFlow
Using FaceNet For On-Device Face Recognition With Android
Coding Feed-Forward Neural Networks in Kotlin (or Android)
Q-Learning With The Frozen Lake Environment In Android
Hyperparameter Optimization With Genetic Algorithms In Kotlin
Image Classification With TensorFlow 2.0 ( Without Keras )
Get Started With TensorFlow 2.0 and Linear Regression
Cityscape Image Segmentation With TensorFlow 2.0
4 Awesome Ways Of Loading ML Data In Google Colab
Neural Implanting With AutoEncoders and TensorFlow
Colorizing B/W Images With GANs in TensorFlow
Exploring Random Forests In Light Of Kotlin
Gaussian Naive Bayes ( for Iris Classification ) in Android
Sarcasm Detection using Word Embeddings in Android
Hands-on With Multiple Linear Regression on Android
Bayes Text Classification in Kotlin for Android without TensorFlow
How I made Skinly for Melanoma Detection in Android
Text Classification in Android with TensorFlow
Designing Decision Trees From Scratch on Android
Introducing TensorFlow Lite Android Support Library
Introducing Text2Summary: Text Summarization on Android
We’ll get some information on what Linear Regression at the first instance. In Linear Regression, we tend to find a best-fit line for your data.
The line could be defined in its slope-intercept form as:
m and c are the slope and y-intercept respectively. Where W and b are the weights and biases respectively for the 2nd equation.
To optimize our parameters w and b, we require a loss function. That’s where Mean Squared Error ( L1 / MSE ) comes in the picture.
Where N is the number of samples in the batch/dataset, y is the predicted outcome whereas y− ( y-hat ) is the target outcome.
Also, we will need the derivative of the Mean Squared Error function which is as follows:
Where N is the number of samples in the batch/dataset, y is the predicted outcome whereas y− ( y-hat ) is the target outcome.
Now, enters Gradient Descent through which we will update our parameters θ.
Where θ is our parameter, α is the learning rate or step size and loss is our loss function.
We optimize both w and b by obtaining their partial derivatives with respect to the loss function ( MSE ).
Where w and b are the parameters of optimization, h is the hypothesis function, loss is the loss function and MSE’ is the derivative of the Mean Squared Error loss function.
We are going to use the data from Graduate Admissions on Kaggle.com. It contains 6 continuous and 1 binary feature making a total of 7 features. The label or the expected outcome is the chance of admission for a student. This is our target variable.
We’ll download and parse the dataset into something which we really love train and validations datasets!
We define 3 methods with TensorFlow’s low-level APIs for :
Mean Squared Error functionThe derivative of Mean Squared Error functionHypothesis function/ Regression function
Mean Squared Error function
The derivative of Mean Squared Error function
Hypothesis function/ Regression function
which we have discussed earlier in raw Math.
Then, we initialize some hyperparameters for training and also create tf.data.Datasetobject to store and batch our data efficiently.
Noticed a TF 2.0 change? Earlier for TF 1.x versions, we used tf.data.Dataset.make_one_shot_iterator() method for creating an iterator. That’s changed and now we use tf.data.Dataset.__iter__()
Finally, we train the model for num_epochs epochs with a batch size of batch_size which makes a step size of num_samples/batch_size .
Changes: We do not need to run the ops and tensors via a tf.Session() object. TensorFlow 2.0 has Eager Execution enabled by default. To get the value of a tf.Tensor we only use the tf.Tensor.numpy() method.
Also, we can get a plot of epoch-loss using matplotlib.pyplt using,
import matplotlib.pyplot as pltplt.plot( epochs_plot , loss_plot ) plt.show()
And now for evaluating our model’s accuracy, we measure the Mean Absolute Error.
Changes: The tf.metrics now return an op ( operation ) instead of a Tensor. That’s good though!
ope that was a good introduction to TensorFlow 2.0 and linear regression. Thank You and happy Machine Learning! | [
{
"code": null,
"e": 447,
"s": 172,
"text": "TensorFlow 2.0 has been a major breakthrough in the TensorFlow family. It’s completely new and refurbished and also less creepy! We’ll create a simple Linear Regression model in TensorFlow 2.0 to explore some new changes. So, open up your code editors and let’s get started!"
},
{
"code": null,
"e": 515,
"s": 447,
"text": "Also, open up this notebook for an interactive learning experience."
},
{
"code": null,
"e": 581,
"s": 515,
"text": "Attention! TensorFlow 2.0 is now available in the stable channel!"
},
{
"code": null,
"e": 649,
"s": 581,
"text": "For viewing some basic concepts and their simpler explanations see,"
},
{
"code": null,
"e": 684,
"s": 649,
"text": "Machine Learning Glossary | Google"
},
{
"code": null,
"e": 698,
"s": 684,
"text": "ML Cheatsheet"
},
{
"code": null,
"e": 747,
"s": 698,
"text": "Human-In-The-Loop Systems — All You Need To Know"
},
{
"code": null,
"e": 794,
"s": 747,
"text": "Deploying TF Models on Heroku for Android Apps"
},
{
"code": null,
"e": 833,
"s": 794,
"text": "Accessing App Usage History In Android"
},
{
"code": null,
"e": 872,
"s": 833,
"text": "No, Kernels & Filters Are Not The Same"
},
{
"code": null,
"e": 931,
"s": 872,
"text": "Deploying Pretrained TF Object Detection Models on Android"
},
{
"code": null,
"e": 982,
"s": 931,
"text": "Realtime Selfie Segmentation In Android With MLKit"
},
{
"code": null,
"e": 1027,
"s": 982,
"text": "Grad-CAM: A Camera For Your Model’s Decision"
},
{
"code": null,
"e": 1054,
"s": 1027,
"text": "MLP Mixer Is All You Need?"
},
{
"code": null,
"e": 1105,
"s": 1054,
"text": "Age + Gender Estimation in Android with TensorFlow"
},
{
"code": null,
"e": 1163,
"s": 1105,
"text": "Using FaceNet For On-Device Face Recognition With Android"
},
{
"code": null,
"e": 1222,
"s": 1163,
"text": "Coding Feed-Forward Neural Networks in Kotlin (or Android)"
},
{
"code": null,
"e": 1277,
"s": 1222,
"text": "Q-Learning With The Frozen Lake Environment In Android"
},
{
"code": null,
"e": 1339,
"s": 1277,
"text": "Hyperparameter Optimization With Genetic Algorithms In Kotlin"
},
{
"code": null,
"e": 1398,
"s": 1339,
"text": "Image Classification With TensorFlow 2.0 ( Without Keras )"
},
{
"code": null,
"e": 1452,
"s": 1398,
"text": "Get Started With TensorFlow 2.0 and Linear Regression"
},
{
"code": null,
"e": 1501,
"s": 1452,
"text": "Cityscape Image Segmentation With TensorFlow 2.0"
},
{
"code": null,
"e": 1551,
"s": 1501,
"text": "4 Awesome Ways Of Loading ML Data In Google Colab"
},
{
"code": null,
"e": 1602,
"s": 1551,
"text": "Neural Implanting With AutoEncoders and TensorFlow"
},
{
"code": null,
"e": 1648,
"s": 1602,
"text": "Colorizing B/W Images With GANs in TensorFlow"
},
{
"code": null,
"e": 1692,
"s": 1648,
"text": "Exploring Random Forests In Light Of Kotlin"
},
{
"code": null,
"e": 1752,
"s": 1692,
"text": "Gaussian Naive Bayes ( for Iris Classification ) in Android"
},
{
"code": null,
"e": 1803,
"s": 1752,
"text": "Sarcasm Detection using Word Embeddings in Android"
},
{
"code": null,
"e": 1855,
"s": 1803,
"text": "Hands-on With Multiple Linear Regression on Android"
},
{
"code": null,
"e": 1922,
"s": 1855,
"text": "Bayes Text Classification in Kotlin for Android without TensorFlow"
},
{
"code": null,
"e": 1974,
"s": 1922,
"text": "How I made Skinly for Melanoma Detection in Android"
},
{
"code": null,
"e": 2021,
"s": 1974,
"text": "Text Classification in Android with TensorFlow"
},
{
"code": null,
"e": 2070,
"s": 2021,
"text": "Designing Decision Trees From Scratch on Android"
},
{
"code": null,
"e": 2122,
"s": 2070,
"text": "Introducing TensorFlow Lite Android Support Library"
},
{
"code": null,
"e": 2178,
"s": 2122,
"text": "Introducing Text2Summary: Text Summarization on Android"
},
{
"code": null,
"e": 2323,
"s": 2178,
"text": "We’ll get some information on what Linear Regression at the first instance. In Linear Regression, we tend to find a best-fit line for your data."
},
{
"code": null,
"e": 2381,
"s": 2323,
"text": "The line could be defined in its slope-intercept form as:"
},
{
"code": null,
"e": 2509,
"s": 2381,
"text": "m and c are the slope and y-intercept respectively. Where W and b are the weights and biases respectively for the 2nd equation."
},
{
"code": null,
"e": 2640,
"s": 2509,
"text": "To optimize our parameters w and b, we require a loss function. That’s where Mean Squared Error ( L1 / MSE ) comes in the picture."
},
{
"code": null,
"e": 2766,
"s": 2640,
"text": "Where N is the number of samples in the batch/dataset, y is the predicted outcome whereas y− ( y-hat ) is the target outcome."
},
{
"code": null,
"e": 2856,
"s": 2766,
"text": "Also, we will need the derivative of the Mean Squared Error function which is as follows:"
},
{
"code": null,
"e": 2982,
"s": 2856,
"text": "Where N is the number of samples in the batch/dataset, y is the predicted outcome whereas y− ( y-hat ) is the target outcome."
},
{
"code": null,
"e": 3058,
"s": 2982,
"text": "Now, enters Gradient Descent through which we will update our parameters θ."
},
{
"code": null,
"e": 3151,
"s": 3058,
"text": "Where θ is our parameter, α is the learning rate or step size and loss is our loss function."
},
{
"code": null,
"e": 3258,
"s": 3151,
"text": "We optimize both w and b by obtaining their partial derivatives with respect to the loss function ( MSE )."
},
{
"code": null,
"e": 3432,
"s": 3258,
"text": "Where w and b are the parameters of optimization, h is the hypothesis function, loss is the loss function and MSE’ is the derivative of the Mean Squared Error loss function."
},
{
"code": null,
"e": 3682,
"s": 3432,
"text": "We are going to use the data from Graduate Admissions on Kaggle.com. It contains 6 continuous and 1 binary feature making a total of 7 features. The label or the expected outcome is the chance of admission for a student. This is our target variable."
},
{
"code": null,
"e": 3787,
"s": 3682,
"text": "We’ll download and parse the dataset into something which we really love train and validations datasets!"
},
{
"code": null,
"e": 3846,
"s": 3787,
"text": "We define 3 methods with TensorFlow’s low-level APIs for :"
},
{
"code": null,
"e": 3959,
"s": 3846,
"text": "Mean Squared Error functionThe derivative of Mean Squared Error functionHypothesis function/ Regression function"
},
{
"code": null,
"e": 3987,
"s": 3959,
"text": "Mean Squared Error function"
},
{
"code": null,
"e": 4033,
"s": 3987,
"text": "The derivative of Mean Squared Error function"
},
{
"code": null,
"e": 4074,
"s": 4033,
"text": "Hypothesis function/ Regression function"
},
{
"code": null,
"e": 4119,
"s": 4074,
"text": "which we have discussed earlier in raw Math."
},
{
"code": null,
"e": 4252,
"s": 4119,
"text": "Then, we initialize some hyperparameters for training and also create tf.data.Datasetobject to store and batch our data efficiently."
},
{
"code": null,
"e": 4445,
"s": 4252,
"text": "Noticed a TF 2.0 change? Earlier for TF 1.x versions, we used tf.data.Dataset.make_one_shot_iterator() method for creating an iterator. That’s changed and now we use tf.data.Dataset.__iter__()"
},
{
"code": null,
"e": 4579,
"s": 4445,
"text": "Finally, we train the model for num_epochs epochs with a batch size of batch_size which makes a step size of num_samples/batch_size ."
},
{
"code": null,
"e": 4786,
"s": 4579,
"text": "Changes: We do not need to run the ops and tensors via a tf.Session() object. TensorFlow 2.0 has Eager Execution enabled by default. To get the value of a tf.Tensor we only use the tf.Tensor.numpy() method."
},
{
"code": null,
"e": 4854,
"s": 4786,
"text": "Also, we can get a plot of epoch-loss using matplotlib.pyplt using,"
},
{
"code": null,
"e": 4932,
"s": 4854,
"text": "import matplotlib.pyplot as pltplt.plot( epochs_plot , loss_plot ) plt.show()"
},
{
"code": null,
"e": 5013,
"s": 4932,
"text": "And now for evaluating our model’s accuracy, we measure the Mean Absolute Error."
},
{
"code": null,
"e": 5109,
"s": 5013,
"text": "Changes: The tf.metrics now return an op ( operation ) instead of a Tensor. That’s good though!"
}
] |
Smart Discounts with Logistic Regression | Machine Learning from Scratch (Part I) | by Venelin Valkov | Towards Data Science | TL;DR in this part you will build a Logistic Regression model using Python from scratch. In the process, you will learn about the Gradient descent algorithm and use it to train your model.
Smart Discounts with Logistic RegressionPredicting House Prices with Linear RegressionBuilding a Decision Tree from Scratch in PythonColor palette extraction with K-means clusteringMovie review sentiment analysis with Naive BayesMusic artist Recommender System using Stochastic Gradient DescentFashion product image classification using Neural NetworksBuild a taxi driving agent in a post-apocalyptic world using Reinforcement Learning
Smart Discounts with Logistic Regression
Predicting House Prices with Linear Regression
Building a Decision Tree from Scratch in Python
Color palette extraction with K-means clustering
Movie review sentiment analysis with Naive Bayes
Music artist Recommender System using Stochastic Gradient Descent
Fashion product image classification using Neural Networks
Build a taxi driving agent in a post-apocalyptic world using Reinforcement Learning
Let’s say you’re developing your online clothing store. Some of your customers are already paying full price. Some don’t. You want to create a promotional campaign and offer discount codes to some customers in the hopes that this might increase your sales. But you don’t want to send discounts to customers which are likely to pay full price. How should you pick the customers that will receive discounts?
Complete source code notebook (Google Colaboratory):
colab.research.google.com
You collected some data from your database(s), analytics packages, etc. Here’s what you might’ve come up with:
Let’s load the data into a Pandas data frame:
And have a look at it:
Note — the presented data is a simplification of a real dataset you might have. If your data is really simple, you might try simpler methods.
Logistic regression is used for classification problems when the dependant/target variable is binary. That is, its values are true or false. Logistic regression is one of the most popular and widely used algorithms in practice (see this).
Some problems that can be solved with Logistic regression include:
- Email — deciding if it is spam or not- Online transactions — fraudulent or not- Tumor classification — malignant or benign- Customer upgrade — will the customer buy the premium upgrade or not
We want to predict the outcome of a variable y, such that:
and set 0: negative class (e.g. email is not spam) or 1: positive class (e.g. email is spam).
Linear regression is another very popular model. It works under the assumption that the observed phenomena (your data) are explainable by a straight line.
The response variable y of the Linear regression is not restricted within the [0, 1] interval. That makes it pretty hard to take binary decisions based on its output. Thus, not suitable for our needs.
Given our problem, we want a model that uses 1 variable (predictor) (x_1 -amount_spent) to predict whether or not we should send a discount to the customer.
where the coefficients w_i are parameters of the model. Let the coefficient vector W be:
Then we can represent h_w(x) in a more compact form:
That is the Linear Regression model.
We want to build a model that outputs values that are between 0 and 1, so we want to come up with a hypothesis that satisfies:
For Logistic Regression we want to modify this and introduce another function g:
We’re going to define g as:
where
g is also known as the sigmoid function or the logistic function. After substitution, we end up with:
for our hypothesis.
Intuitively, we’re going to use the sigmoid function “over the” Linear regression model to bound it within [0;+1].
Recall that the sigmoid function is defined as:
Let’s translate it to a Python function:
A graphical representation of the sigmoid function:
It looks familiar, right? Notice how fast it converges to -1 or +1.
Let’s examine some approaches to find good parameters for our model. But what does good mean in this context?
We have a model that we can use to make decisions, but we still have to find the parameters W. To do that, we need an objective measurement of how good a given set of parameters are. For that purpose, we will use a loss (cost) function:
Which is also known as the Log loss or Cross-entropy loss function
We can compress the above function into one:
where
Let’s implement it in Python:
Let’s think of 3 numbers that represent the coefficients w0, w1, w2.
loss: 25.0 predicted: 0.999999999986112 actual: 0.0
Unfortunately, I am pretty lazy, and this approach seems like a bit too much work for me. Let’s go to the next one:
Alright, these days computers are pretty fast, 6+ core laptops are everywhere. Smartphones can be pretty performant, too! Let’s use that power for goodTM and try to find those pesky parameters by just trying out a lot of numbers:
0.0 0.0 0.0 6.661338147750941e-16 9.359180097590508e-141.3887890837434982e-11 2.0611535832696244e-09 3.059022736706331e-07 4.539889921682063e-05 0.006715348489118056 0.6931471805599397 5.006715348489103 10.000045398900186 15.000000305680194 19.999999966169824 24.99999582410784 30.001020555434774 34.945041100449046 inf inf
Amazing, the first parameter value we tried got us a loss of 0. Is it your lucky day or this will always be the case, though? The answer is left as an exercise for the reader :)
Gradient descent algorithms (yes, there are a lot of them) provide us with a way to find a minimum of some function f. They work by iteratively going in the direction of the descent as defined by the gradient.
In Machine Learning, we use gradient descent algorithms to find “good” parameters for our models (Logistic Regression, Linear Regression, Neural Networks, etc...).
How does it work? Starting somewhere, we take our first step downhill in the direction specified by the negative gradient. Next, we recalculate the negative gradient and take another step in the direction it specifies. This process continues until we get to a point where we can no longer move downhill — a local minimum.
Ok, but how can we find that gradient thing? We have to find the derivate of our cost function since our example is rather simple.
The first derivative of the sigmoid function is given by the following equation:
Complete derivation can be found here.
Recall that the cost function was given by the following equation:
Given
We obtain the first derivative of the cost function:
Now that we have the derivate, we can go back to our updating rule and use it there:
The parameter a is known as learning rate. High learning rate can converge quickly, but risks overshooting the lowest point. Low learning rate allows for confident moves in the direction of the negative gradient. However, it time-consuming so it will take us a lot of time to get to converge.
The algorithm we’re going to use works as follows:
Repeat until convergence { 1. Calculate gradient average 2. Multiply by learning rate 3. Subtract from weights}
Let’s do this in Python:
About that until convergence part. You might notice that we kinda brute-force our way around it. That is, we will run the algorithm for a preset amount of iterations. Another interesting point is the initialization of our weights W — initially set at zero.
Let’s put our implementation to the test, literally. But first, we need a function that helps us predict y given some data X (predict whether or not we should send a discount to a customer based on its spending):
Now for our simple test:
Note that we use reshape to add a dummy dimension to X. Further, after our call to predict, we round the results. Recall that the sigmoid function spits out (kinda like a dragon with an upset stomach) numbers in the [0; 1] range. We’re just going to round the result in order to obtain our 0 or 1 (yes or no) answers.
run_tests()
Here is the result of running our test case:
F
Well, that’s not good, after all that hustling we’re nowhere near achieving our goal of finding good parameters for our model. But, what went wrong?
Welcome to your first model debugging session! Let’s start by finding whether our algorithm improves over time. We can use our loss metric for that:
run_tests()
We pretty much copy & pasted our training code except that we’re printing the training loss every 10,000 iterations. Let’s have a look:
loss: 0.6931471805599453 loss: 0.41899283818630056 loss: 0.41899283818630056 loss: 0.41899283818630056 loss: 0.41899283818630056 loss: 0.41899283818630056 loss: 0.41899283818630056 loss: 0.41899283818630056 loss: 0.41899283818630056loss: 0.41899283818630056F........
Suspiciously enough, we found a possible cause for our problem on the first try! Our loss doesn’t get low enough, in other words, our algorithm gets stuck at some point that is not a good enough minimum for us. How can we fix this? Perhaps, try out different learning rate or initializing our parameter with a different value?
First, a smaller learning rate a :
run_tests()
With a=0.001 we obtain this:
loss: 0.42351356323845546 loss: 0.41899283818630056 loss: 0.41899283818630056 loss: 0.41899283818630056 loss: 0.41899283818630056 loss: 0.41899283818630056 loss: 0.41899283818630056 loss: 0.41899283818630056 loss: 0.41899283818630056 loss: 0.41899283818630056F.......
Not so successful, are we? How about adding one more parameter for our model to find/learn?
run_tests()
And for the results:
........---------------------------------------------------------Ran 8 tests in 0.686s OK
What we did here? We added a new element to our parameter vector W and set it’s initial value to 1. Seems like this turn things into our favor!
Knowing all of the details of the inner workings of the Gradient descent is good, but when solving problems in the wild, we might be hard pressed for time. In those situations, a simple & easy to use interface for fitting a Logistic Regression model might save us a lot of time. So, let’s build one!
But first, let’s write some tests:
run_tests()
We just packed all previously written functions into a tiny class. One huge advantage of this approach is the fact that we hide the complexity of the Gradient descent algorithm and the use of the parameters W.
Now that you’re done with the “hard” part let’s use the model to predict whether or not we should send discount codes.
Let’s recall our initial data:
Now let’s try our model on data obtained from 2 new customers:
Customer 1 - $10Customer 2 - $250
y_test
Recall that 1 means send code and 0 means do not send:
array([1., 0.])
Looks reasonable enough. Care to try out more cases?
You can find complete source code and run the code in your browser here:
colab.research.google.com
Well done! You have a complete (albeit simple) LogisticRegressor implementation that you can play with. Go on, have some fun with it!
Coming up next, you will implement a Linear regression model from scratch :)
Smart Discounts with Logistic RegressionPredicting House Prices with Linear RegressionBuilding a Decision Tree from Scratch in PythonColor palette extraction with K-means clusteringMovie review sentiment analysis with Naive BayesMusic artist Recommender System using Stochastic Gradient DescentFashion product image classification using Neural NetworksBuild a taxi driving agent in a post-apocalyptic world using Reinforcement Learning
Smart Discounts with Logistic Regression
Predicting House Prices with Linear Regression
Building a Decision Tree from Scratch in Python
Color palette extraction with K-means clustering
Movie review sentiment analysis with Naive Bayes
Music artist Recommender System using Stochastic Gradient Descent
Fashion product image classification using Neural Networks
Build a taxi driving agent in a post-apocalyptic world using Reinforcement Learning
Like what you read? Do you want to learn even more about Machine Learning? | [
{
"code": null,
"e": 361,
"s": 172,
"text": "TL;DR in this part you will build a Logistic Regression model using Python from scratch. In the process, you will learn about the Gradient descent algorithm and use it to train your model."
},
{
"code": null,
"e": 797,
"s": 361,
"text": "Smart Discounts with Logistic RegressionPredicting House Prices with Linear RegressionBuilding a Decision Tree from Scratch in PythonColor palette extraction with K-means clusteringMovie review sentiment analysis with Naive BayesMusic artist Recommender System using Stochastic Gradient DescentFashion product image classification using Neural NetworksBuild a taxi driving agent in a post-apocalyptic world using Reinforcement Learning"
},
{
"code": null,
"e": 838,
"s": 797,
"text": "Smart Discounts with Logistic Regression"
},
{
"code": null,
"e": 885,
"s": 838,
"text": "Predicting House Prices with Linear Regression"
},
{
"code": null,
"e": 933,
"s": 885,
"text": "Building a Decision Tree from Scratch in Python"
},
{
"code": null,
"e": 982,
"s": 933,
"text": "Color palette extraction with K-means clustering"
},
{
"code": null,
"e": 1031,
"s": 982,
"text": "Movie review sentiment analysis with Naive Bayes"
},
{
"code": null,
"e": 1097,
"s": 1031,
"text": "Music artist Recommender System using Stochastic Gradient Descent"
},
{
"code": null,
"e": 1156,
"s": 1097,
"text": "Fashion product image classification using Neural Networks"
},
{
"code": null,
"e": 1240,
"s": 1156,
"text": "Build a taxi driving agent in a post-apocalyptic world using Reinforcement Learning"
},
{
"code": null,
"e": 1646,
"s": 1240,
"text": "Let’s say you’re developing your online clothing store. Some of your customers are already paying full price. Some don’t. You want to create a promotional campaign and offer discount codes to some customers in the hopes that this might increase your sales. But you don’t want to send discounts to customers which are likely to pay full price. How should you pick the customers that will receive discounts?"
},
{
"code": null,
"e": 1699,
"s": 1646,
"text": "Complete source code notebook (Google Colaboratory):"
},
{
"code": null,
"e": 1725,
"s": 1699,
"text": "colab.research.google.com"
},
{
"code": null,
"e": 1836,
"s": 1725,
"text": "You collected some data from your database(s), analytics packages, etc. Here’s what you might’ve come up with:"
},
{
"code": null,
"e": 1882,
"s": 1836,
"text": "Let’s load the data into a Pandas data frame:"
},
{
"code": null,
"e": 1905,
"s": 1882,
"text": "And have a look at it:"
},
{
"code": null,
"e": 2047,
"s": 1905,
"text": "Note — the presented data is a simplification of a real dataset you might have. If your data is really simple, you might try simpler methods."
},
{
"code": null,
"e": 2286,
"s": 2047,
"text": "Logistic regression is used for classification problems when the dependant/target variable is binary. That is, its values are true or false. Logistic regression is one of the most popular and widely used algorithms in practice (see this)."
},
{
"code": null,
"e": 2353,
"s": 2286,
"text": "Some problems that can be solved with Logistic regression include:"
},
{
"code": null,
"e": 2547,
"s": 2353,
"text": "- Email — deciding if it is spam or not- Online transactions — fraudulent or not- Tumor classification — malignant or benign- Customer upgrade — will the customer buy the premium upgrade or not"
},
{
"code": null,
"e": 2606,
"s": 2547,
"text": "We want to predict the outcome of a variable y, such that:"
},
{
"code": null,
"e": 2700,
"s": 2606,
"text": "and set 0: negative class (e.g. email is not spam) or 1: positive class (e.g. email is spam)."
},
{
"code": null,
"e": 2855,
"s": 2700,
"text": "Linear regression is another very popular model. It works under the assumption that the observed phenomena (your data) are explainable by a straight line."
},
{
"code": null,
"e": 3056,
"s": 2855,
"text": "The response variable y of the Linear regression is not restricted within the [0, 1] interval. That makes it pretty hard to take binary decisions based on its output. Thus, not suitable for our needs."
},
{
"code": null,
"e": 3213,
"s": 3056,
"text": "Given our problem, we want a model that uses 1 variable (predictor) (x_1 -amount_spent) to predict whether or not we should send a discount to the customer."
},
{
"code": null,
"e": 3302,
"s": 3213,
"text": "where the coefficients w_i are parameters of the model. Let the coefficient vector W be:"
},
{
"code": null,
"e": 3355,
"s": 3302,
"text": "Then we can represent h_w(x) in a more compact form:"
},
{
"code": null,
"e": 3392,
"s": 3355,
"text": "That is the Linear Regression model."
},
{
"code": null,
"e": 3519,
"s": 3392,
"text": "We want to build a model that outputs values that are between 0 and 1, so we want to come up with a hypothesis that satisfies:"
},
{
"code": null,
"e": 3600,
"s": 3519,
"text": "For Logistic Regression we want to modify this and introduce another function g:"
},
{
"code": null,
"e": 3628,
"s": 3600,
"text": "We’re going to define g as:"
},
{
"code": null,
"e": 3634,
"s": 3628,
"text": "where"
},
{
"code": null,
"e": 3736,
"s": 3634,
"text": "g is also known as the sigmoid function or the logistic function. After substitution, we end up with:"
},
{
"code": null,
"e": 3756,
"s": 3736,
"text": "for our hypothesis."
},
{
"code": null,
"e": 3871,
"s": 3756,
"text": "Intuitively, we’re going to use the sigmoid function “over the” Linear regression model to bound it within [0;+1]."
},
{
"code": null,
"e": 3919,
"s": 3871,
"text": "Recall that the sigmoid function is defined as:"
},
{
"code": null,
"e": 3960,
"s": 3919,
"text": "Let’s translate it to a Python function:"
},
{
"code": null,
"e": 4012,
"s": 3960,
"text": "A graphical representation of the sigmoid function:"
},
{
"code": null,
"e": 4080,
"s": 4012,
"text": "It looks familiar, right? Notice how fast it converges to -1 or +1."
},
{
"code": null,
"e": 4190,
"s": 4080,
"text": "Let’s examine some approaches to find good parameters for our model. But what does good mean in this context?"
},
{
"code": null,
"e": 4427,
"s": 4190,
"text": "We have a model that we can use to make decisions, but we still have to find the parameters W. To do that, we need an objective measurement of how good a given set of parameters are. For that purpose, we will use a loss (cost) function:"
},
{
"code": null,
"e": 4494,
"s": 4427,
"text": "Which is also known as the Log loss or Cross-entropy loss function"
},
{
"code": null,
"e": 4539,
"s": 4494,
"text": "We can compress the above function into one:"
},
{
"code": null,
"e": 4545,
"s": 4539,
"text": "where"
},
{
"code": null,
"e": 4575,
"s": 4545,
"text": "Let’s implement it in Python:"
},
{
"code": null,
"e": 4644,
"s": 4575,
"text": "Let’s think of 3 numbers that represent the coefficients w0, w1, w2."
},
{
"code": null,
"e": 4696,
"s": 4644,
"text": "loss: 25.0 predicted: 0.999999999986112 actual: 0.0"
},
{
"code": null,
"e": 4812,
"s": 4696,
"text": "Unfortunately, I am pretty lazy, and this approach seems like a bit too much work for me. Let’s go to the next one:"
},
{
"code": null,
"e": 5042,
"s": 4812,
"text": "Alright, these days computers are pretty fast, 6+ core laptops are everywhere. Smartphones can be pretty performant, too! Let’s use that power for goodTM and try to find those pesky parameters by just trying out a lot of numbers:"
},
{
"code": null,
"e": 5366,
"s": 5042,
"text": "0.0 0.0 0.0 6.661338147750941e-16 9.359180097590508e-141.3887890837434982e-11 2.0611535832696244e-09 3.059022736706331e-07 4.539889921682063e-05 0.006715348489118056 0.6931471805599397 5.006715348489103 10.000045398900186 15.000000305680194 19.999999966169824 24.99999582410784 30.001020555434774 34.945041100449046 inf inf"
},
{
"code": null,
"e": 5544,
"s": 5366,
"text": "Amazing, the first parameter value we tried got us a loss of 0. Is it your lucky day or this will always be the case, though? The answer is left as an exercise for the reader :)"
},
{
"code": null,
"e": 5754,
"s": 5544,
"text": "Gradient descent algorithms (yes, there are a lot of them) provide us with a way to find a minimum of some function f. They work by iteratively going in the direction of the descent as defined by the gradient."
},
{
"code": null,
"e": 5918,
"s": 5754,
"text": "In Machine Learning, we use gradient descent algorithms to find “good” parameters for our models (Logistic Regression, Linear Regression, Neural Networks, etc...)."
},
{
"code": null,
"e": 6240,
"s": 5918,
"text": "How does it work? Starting somewhere, we take our first step downhill in the direction specified by the negative gradient. Next, we recalculate the negative gradient and take another step in the direction it specifies. This process continues until we get to a point where we can no longer move downhill — a local minimum."
},
{
"code": null,
"e": 6371,
"s": 6240,
"text": "Ok, but how can we find that gradient thing? We have to find the derivate of our cost function since our example is rather simple."
},
{
"code": null,
"e": 6452,
"s": 6371,
"text": "The first derivative of the sigmoid function is given by the following equation:"
},
{
"code": null,
"e": 6491,
"s": 6452,
"text": "Complete derivation can be found here."
},
{
"code": null,
"e": 6558,
"s": 6491,
"text": "Recall that the cost function was given by the following equation:"
},
{
"code": null,
"e": 6564,
"s": 6558,
"text": "Given"
},
{
"code": null,
"e": 6617,
"s": 6564,
"text": "We obtain the first derivative of the cost function:"
},
{
"code": null,
"e": 6702,
"s": 6617,
"text": "Now that we have the derivate, we can go back to our updating rule and use it there:"
},
{
"code": null,
"e": 6995,
"s": 6702,
"text": "The parameter a is known as learning rate. High learning rate can converge quickly, but risks overshooting the lowest point. Low learning rate allows for confident moves in the direction of the negative gradient. However, it time-consuming so it will take us a lot of time to get to converge."
},
{
"code": null,
"e": 7046,
"s": 6995,
"text": "The algorithm we’re going to use works as follows:"
},
{
"code": null,
"e": 7161,
"s": 7046,
"text": "Repeat until convergence { 1. Calculate gradient average 2. Multiply by learning rate 3. Subtract from weights}"
},
{
"code": null,
"e": 7186,
"s": 7161,
"text": "Let’s do this in Python:"
},
{
"code": null,
"e": 7443,
"s": 7186,
"text": "About that until convergence part. You might notice that we kinda brute-force our way around it. That is, we will run the algorithm for a preset amount of iterations. Another interesting point is the initialization of our weights W — initially set at zero."
},
{
"code": null,
"e": 7656,
"s": 7443,
"text": "Let’s put our implementation to the test, literally. But first, we need a function that helps us predict y given some data X (predict whether or not we should send a discount to a customer based on its spending):"
},
{
"code": null,
"e": 7681,
"s": 7656,
"text": "Now for our simple test:"
},
{
"code": null,
"e": 7999,
"s": 7681,
"text": "Note that we use reshape to add a dummy dimension to X. Further, after our call to predict, we round the results. Recall that the sigmoid function spits out (kinda like a dragon with an upset stomach) numbers in the [0; 1] range. We’re just going to round the result in order to obtain our 0 or 1 (yes or no) answers."
},
{
"code": null,
"e": 8011,
"s": 7999,
"text": "run_tests()"
},
{
"code": null,
"e": 8056,
"s": 8011,
"text": "Here is the result of running our test case:"
},
{
"code": null,
"e": 8058,
"s": 8056,
"text": "F"
},
{
"code": null,
"e": 8207,
"s": 8058,
"text": "Well, that’s not good, after all that hustling we’re nowhere near achieving our goal of finding good parameters for our model. But, what went wrong?"
},
{
"code": null,
"e": 8356,
"s": 8207,
"text": "Welcome to your first model debugging session! Let’s start by finding whether our algorithm improves over time. We can use our loss metric for that:"
},
{
"code": null,
"e": 8368,
"s": 8356,
"text": "run_tests()"
},
{
"code": null,
"e": 8504,
"s": 8368,
"text": "We pretty much copy & pasted our training code except that we’re printing the training loss every 10,000 iterations. Let’s have a look:"
},
{
"code": null,
"e": 8779,
"s": 8504,
"text": "loss: 0.6931471805599453 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056loss: 0.41899283818630056F........"
},
{
"code": null,
"e": 9106,
"s": 8779,
"text": "Suspiciously enough, we found a possible cause for our problem on the first try! Our loss doesn’t get low enough, in other words, our algorithm gets stuck at some point that is not a good enough minimum for us. How can we fix this? Perhaps, try out different learning rate or initializing our parameter with a different value?"
},
{
"code": null,
"e": 9141,
"s": 9106,
"text": "First, a smaller learning rate a :"
},
{
"code": null,
"e": 9153,
"s": 9141,
"text": "run_tests()"
},
{
"code": null,
"e": 9182,
"s": 9153,
"text": "With a=0.001 we obtain this:"
},
{
"code": null,
"e": 9459,
"s": 9182,
"text": "loss: 0.42351356323845546 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056 \tloss: 0.41899283818630056F......."
},
{
"code": null,
"e": 9551,
"s": 9459,
"text": "Not so successful, are we? How about adding one more parameter for our model to find/learn?"
},
{
"code": null,
"e": 9563,
"s": 9551,
"text": "run_tests()"
},
{
"code": null,
"e": 9584,
"s": 9563,
"text": "And for the results:"
},
{
"code": null,
"e": 9675,
"s": 9584,
"text": "........---------------------------------------------------------Ran 8 tests in 0.686s OK"
},
{
"code": null,
"e": 9819,
"s": 9675,
"text": "What we did here? We added a new element to our parameter vector W and set it’s initial value to 1. Seems like this turn things into our favor!"
},
{
"code": null,
"e": 10119,
"s": 9819,
"text": "Knowing all of the details of the inner workings of the Gradient descent is good, but when solving problems in the wild, we might be hard pressed for time. In those situations, a simple & easy to use interface for fitting a Logistic Regression model might save us a lot of time. So, let’s build one!"
},
{
"code": null,
"e": 10154,
"s": 10119,
"text": "But first, let’s write some tests:"
},
{
"code": null,
"e": 10166,
"s": 10154,
"text": "run_tests()"
},
{
"code": null,
"e": 10376,
"s": 10166,
"text": "We just packed all previously written functions into a tiny class. One huge advantage of this approach is the fact that we hide the complexity of the Gradient descent algorithm and the use of the parameters W."
},
{
"code": null,
"e": 10495,
"s": 10376,
"text": "Now that you’re done with the “hard” part let’s use the model to predict whether or not we should send discount codes."
},
{
"code": null,
"e": 10526,
"s": 10495,
"text": "Let’s recall our initial data:"
},
{
"code": null,
"e": 10589,
"s": 10526,
"text": "Now let’s try our model on data obtained from 2 new customers:"
},
{
"code": null,
"e": 10623,
"s": 10589,
"text": "Customer 1 - $10Customer 2 - $250"
},
{
"code": null,
"e": 10630,
"s": 10623,
"text": "y_test"
},
{
"code": null,
"e": 10685,
"s": 10630,
"text": "Recall that 1 means send code and 0 means do not send:"
},
{
"code": null,
"e": 10701,
"s": 10685,
"text": "array([1., 0.])"
},
{
"code": null,
"e": 10754,
"s": 10701,
"text": "Looks reasonable enough. Care to try out more cases?"
},
{
"code": null,
"e": 10827,
"s": 10754,
"text": "You can find complete source code and run the code in your browser here:"
},
{
"code": null,
"e": 10853,
"s": 10827,
"text": "colab.research.google.com"
},
{
"code": null,
"e": 10987,
"s": 10853,
"text": "Well done! You have a complete (albeit simple) LogisticRegressor implementation that you can play with. Go on, have some fun with it!"
},
{
"code": null,
"e": 11064,
"s": 10987,
"text": "Coming up next, you will implement a Linear regression model from scratch :)"
},
{
"code": null,
"e": 11500,
"s": 11064,
"text": "Smart Discounts with Logistic RegressionPredicting House Prices with Linear RegressionBuilding a Decision Tree from Scratch in PythonColor palette extraction with K-means clusteringMovie review sentiment analysis with Naive BayesMusic artist Recommender System using Stochastic Gradient DescentFashion product image classification using Neural NetworksBuild a taxi driving agent in a post-apocalyptic world using Reinforcement Learning"
},
{
"code": null,
"e": 11541,
"s": 11500,
"text": "Smart Discounts with Logistic Regression"
},
{
"code": null,
"e": 11588,
"s": 11541,
"text": "Predicting House Prices with Linear Regression"
},
{
"code": null,
"e": 11636,
"s": 11588,
"text": "Building a Decision Tree from Scratch in Python"
},
{
"code": null,
"e": 11685,
"s": 11636,
"text": "Color palette extraction with K-means clustering"
},
{
"code": null,
"e": 11734,
"s": 11685,
"text": "Movie review sentiment analysis with Naive Bayes"
},
{
"code": null,
"e": 11800,
"s": 11734,
"text": "Music artist Recommender System using Stochastic Gradient Descent"
},
{
"code": null,
"e": 11859,
"s": 11800,
"text": "Fashion product image classification using Neural Networks"
},
{
"code": null,
"e": 11943,
"s": 11859,
"text": "Build a taxi driving agent in a post-apocalyptic world using Reinforcement Learning"
}
] |
First uppercase letter in a string (Iterative and Recursive) in C++ | In this tutorial, we are going to learn how find the first uppercase letter in the given string. Let's see an example.
Input −Tutorialspoint
Output −T
Let's see the steps to solve the problem using iterative method.
Initialize the string.
Initialize the string.
Iterate over the string.
Iterate over the string.
Check whether the current character is uppercase or not using isupper method.
Check whether the current character is uppercase or not using isupper method.
If the character is uppercase than return the current character.
If the character is uppercase than return the current character.
Let's see the code.
Live Demo
#include <bits/stdc++.h>
using namespace std;
char firstUpperCaseChar(string str) {
for (int i = 0; i < str.length(); i++)
if (isupper(str[i])) {
return str[i];
}
return 0;
}
int main() {
string str = "Tutorialspoint";
char result = firstUpperCaseChar(str);
if (result == 0) {
cout << "No uppercase letter" << endl;
}
else {
cout << result << endl;
}
return 0;
}
If you run the above code, then you will get the following result.
T
Let's see the steps to solve the problem using recursive method.
Initialize the string.
Initialize the string.
Write a recursive function which accepts two parameter string and index.
Write a recursive function which accepts two parameter string and index.
If the current character is end of the string then return.
If the current character is end of the string then return.
If the current character is uppercase then return the current character.
If the current character is uppercase then return the current character.
Let's see the code.
Live Demo
#include <bits/stdc++.h>
using namespace std;
char firstUpperCaseChar(string str, int i = 0) {
if (str[i] == '\0') {
return 0;
}
if (isupper(str[i])) {
return str[i];
}
return firstUpperCaseChar(str, i + 1);
}
int main() {
string str = "Tutorialspoint";
char result = firstUpperCaseChar(str);
if (result == 0) {
cout << "No uppercase letter";
}
else {
cout << result << endl;
}
return 0;
}
If you run the above code, then you will get the following result.
T
If you have any queries in the tutorial, mention them in the comment section. | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "In this tutorial, we are going to learn how find the first uppercase letter in the given string. Let's see an example."
},
{
"code": null,
"e": 1203,
"s": 1181,
"text": "Input −Tutorialspoint"
},
{
"code": null,
"e": 1213,
"s": 1203,
"text": "Output −T"
},
{
"code": null,
"e": 1278,
"s": 1213,
"text": "Let's see the steps to solve the problem using iterative method."
},
{
"code": null,
"e": 1301,
"s": 1278,
"text": "Initialize the string."
},
{
"code": null,
"e": 1324,
"s": 1301,
"text": "Initialize the string."
},
{
"code": null,
"e": 1349,
"s": 1324,
"text": "Iterate over the string."
},
{
"code": null,
"e": 1374,
"s": 1349,
"text": "Iterate over the string."
},
{
"code": null,
"e": 1452,
"s": 1374,
"text": "Check whether the current character is uppercase or not using isupper method."
},
{
"code": null,
"e": 1530,
"s": 1452,
"text": "Check whether the current character is uppercase or not using isupper method."
},
{
"code": null,
"e": 1595,
"s": 1530,
"text": "If the character is uppercase than return the current character."
},
{
"code": null,
"e": 1660,
"s": 1595,
"text": "If the character is uppercase than return the current character."
},
{
"code": null,
"e": 1680,
"s": 1660,
"text": "Let's see the code."
},
{
"code": null,
"e": 1691,
"s": 1680,
"text": " Live Demo"
},
{
"code": null,
"e": 2147,
"s": 1691,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nchar firstUpperCaseChar(string str) {\n for (int i = 0; i < str.length(); i++)\n if (isupper(str[i])) {\n return str[i];\n }\n return 0;\n }\n int main() {\n string str = \"Tutorialspoint\";\n char result = firstUpperCaseChar(str);\n if (result == 0) {\n cout << \"No uppercase letter\" << endl;\n }\n else {\n cout << result << endl;\n }\n return 0;\n}"
},
{
"code": null,
"e": 2214,
"s": 2147,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 2216,
"s": 2214,
"text": "T"
},
{
"code": null,
"e": 2281,
"s": 2216,
"text": "Let's see the steps to solve the problem using recursive method."
},
{
"code": null,
"e": 2304,
"s": 2281,
"text": "Initialize the string."
},
{
"code": null,
"e": 2327,
"s": 2304,
"text": "Initialize the string."
},
{
"code": null,
"e": 2400,
"s": 2327,
"text": "Write a recursive function which accepts two parameter string and index."
},
{
"code": null,
"e": 2473,
"s": 2400,
"text": "Write a recursive function which accepts two parameter string and index."
},
{
"code": null,
"e": 2532,
"s": 2473,
"text": "If the current character is end of the string then return."
},
{
"code": null,
"e": 2591,
"s": 2532,
"text": "If the current character is end of the string then return."
},
{
"code": null,
"e": 2664,
"s": 2591,
"text": "If the current character is uppercase then return the current character."
},
{
"code": null,
"e": 2737,
"s": 2664,
"text": "If the current character is uppercase then return the current character."
},
{
"code": null,
"e": 2757,
"s": 2737,
"text": "Let's see the code."
},
{
"code": null,
"e": 2768,
"s": 2757,
"text": " Live Demo"
},
{
"code": null,
"e": 3218,
"s": 2768,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nchar firstUpperCaseChar(string str, int i = 0) {\n if (str[i] == '\\0') {\n return 0;\n }\n if (isupper(str[i])) {\n return str[i];\n }\n return firstUpperCaseChar(str, i + 1);\n}\nint main() {\n string str = \"Tutorialspoint\";\n char result = firstUpperCaseChar(str);\n if (result == 0) {\n cout << \"No uppercase letter\";\n }\n else {\n cout << result << endl;\n }\n return 0;\n}"
},
{
"code": null,
"e": 3285,
"s": 3218,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 3287,
"s": 3285,
"text": "T"
},
{
"code": null,
"e": 3365,
"s": 3287,
"text": "If you have any queries in the tutorial, mention them in the comment section."
}
] |
Kotlin - Arrays | Arrays are used to store multiple items of the same data-type in a single variable, such as an integer or string under a single variable name.
For example, if we need to store names of 1000 employees, then instead of creating 1000 different string variables, we can simply define an array of string whose capacity will be 1000.
Like any other modern programming languages, Kotlin also supports arrays and provide a wide range of array properties and support functions to manipulate arrays.
To create an array in Kotlin, we use the arrayOf() function, and place the values in a comma-separated list inside it:
val fruits = arrayOf("Apple", "Mango", "Banana", "Orange")
Optionally we can provide a data type as follows:
val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")
Alternatively, the arrayOfNulls() function can be used to create an array of a given size filled with null elements.
Kotlin also has some built-in factory methods to create arrays of primitive data types. For example, the factory method to create an integer array is:
val num = intArrayOf(1, 2, 3, 4)
Other factory methods available for creating arrays:
byteArrayOf()
byteArrayOf()
charArrayOf()
charArrayOf()
shortArrayOf()
shortArrayOf()
longArrayOf()
longArrayOf()
We can access an array element by using the index number inside square brackets. Kotlin array index starts with zero (0). So if you want to access 4th element of the array then you will need to give 3 as the index.
fun main(args: Array<String>) {
val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")
println( fruits [0])
println( fruits [3])
}
When you run the above Kotlin program, it will generate the following output:
Apple
Orange
Kotlin also provides get() and set() member functions to get and set the value at a particular index. Check the following example:
fun main(args: Array<String>) {
val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")
println( fruits.get(0))
println( fruits.get(3))
// Set the value at 3rd index
fruits.set(3, "Guava")
println( fruits.get(3))
}
When you run the above Kotlin program, it will generate the following output:
Apple
Orange
Guava
Kotlin provides array property called size which returns the size i.e. length of the array.
fun main(args: Array<String>) {
val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")
println( "Size of fruits array " + fruits.size )
}
When you run the above Kotlin program, it will generate the following output:
Size of fruits array 4
We can also use count() member function to get the size of the array.
We can use for loop to loop through an array.
fun main(args: Array<String>) {
val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")
for( item in fruits ){
println( item )
}
}
When you run the above Kotlin program, it will generate the following output:
Apple
Mango
Banana
Orange
We can use the in operator alongwith if...else to check if an element exists in an array.
fun main(args: Array<String>) {
val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")
if ("Mango" in fruits){
println( "Mango exists in fruits" )
}else{
println( "Mango does not exist in fruits" )
}
}
When you run the above Kotlin program, it will generate the following output:
Mango exists in fruits
Kotlin allows to store duplicate values in an array, but same time you can get a set of distinct values stored in the array using distinct() member function.
fun main(args: Array<String>) {
val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange", "Apple")
val distinct = fruits.distinct()
for( item in distinct ){
println( item )
}
}
When you run the above Kotlin program, it will generate the following output:
Apple
Mango
Banana
Orange
We can use drop() or dropLast() member functions to drop elements from the beginning or from the last respectively.
fun main(args: Array<String>) {
val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange", "Apple")
val result = fruits.drop(2) // drops first two elements.
for( item in result ){
println( item )
}
}
When you run the above Kotlin program, it will generate the following output:
Banana
Orange
Apple
We can use isEmpty() member function to check if an array is empty or not. This function returns true if the array is empty.
fun main(args: Array<String>) {
val fruits = arrayOf<String>()
println( "Array is empty : " + fruits.isEmpty())
}
When you run the above Kotlin program, it will generate the following output:
"Array is empty : true
Q 1 - Which of the following is true about Kotlin Arrays?
A - Kotlin arrays are capable to store all data types.
B - Kotlin arrays can be created using either arrayOf() or arrayOfNulls() functions.
C - Kotlin provides a rich set of properties and functions to manipulate arrays.
D - All of the above
All the mentioned statements are correct about Kotlin Arrays.
Q 2 - What will be the output of the following code segment?
fun main(args: Array<String>) {
val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")
println( fruits [2])
}
A - Apple
B - Mango
C - Banana
D - None of the above
Kotlin index starts from 0, so at 2 index we will find 3rd element which is Banana.
Q 3 - How to get the size of a Kotlin array?
A - Using length() function
B - Using size property
C - Using count() function
D - B and C both
Option D is correct because we can get the size of an array using either size property or count() function.
68 Lectures
4.5 hours
Arnab Chakraborty
71 Lectures
5.5 hours
Frahaan Hussain
18 Lectures
1.5 hours
Mahmoud Ramadan
49 Lectures
6 hours
Catalin Stefan
49 Lectures
2.5 hours
Skillbakerystudios
22 Lectures
1 hours
CLEMENT OCHIENG
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2568,
"s": 2425,
"text": "Arrays are used to store multiple items of the same data-type in a single variable, such as an integer or string under a single variable name."
},
{
"code": null,
"e": 2753,
"s": 2568,
"text": "For example, if we need to store names of 1000 employees, then instead of creating 1000 different string variables, we can simply define an array of string whose capacity will be 1000."
},
{
"code": null,
"e": 2915,
"s": 2753,
"text": "Like any other modern programming languages, Kotlin also supports arrays and provide a wide range of array properties and support functions to manipulate arrays."
},
{
"code": null,
"e": 3034,
"s": 2915,
"text": "To create an array in Kotlin, we use the arrayOf() function, and place the values in a comma-separated list inside it:"
},
{
"code": null,
"e": 3094,
"s": 3034,
"text": "val fruits = arrayOf(\"Apple\", \"Mango\", \"Banana\", \"Orange\")\n"
},
{
"code": null,
"e": 3144,
"s": 3094,
"text": "Optionally we can provide a data type as follows:"
},
{
"code": null,
"e": 3212,
"s": 3144,
"text": "val fruits = arrayOf<String>(\"Apple\", \"Mango\", \"Banana\", \"Orange\")\n"
},
{
"code": null,
"e": 3329,
"s": 3212,
"text": "Alternatively, the arrayOfNulls() function can be used to create an array of a given size filled with null elements."
},
{
"code": null,
"e": 3480,
"s": 3329,
"text": "Kotlin also has some built-in factory methods to create arrays of primitive data types. For example, the factory method to create an integer array is:"
},
{
"code": null,
"e": 3514,
"s": 3480,
"text": "val num = intArrayOf(1, 2, 3, 4)\n"
},
{
"code": null,
"e": 3567,
"s": 3514,
"text": "Other factory methods available for creating arrays:"
},
{
"code": null,
"e": 3581,
"s": 3567,
"text": "byteArrayOf()"
},
{
"code": null,
"e": 3595,
"s": 3581,
"text": "byteArrayOf()"
},
{
"code": null,
"e": 3609,
"s": 3595,
"text": "charArrayOf()"
},
{
"code": null,
"e": 3623,
"s": 3609,
"text": "charArrayOf()"
},
{
"code": null,
"e": 3638,
"s": 3623,
"text": "shortArrayOf()"
},
{
"code": null,
"e": 3653,
"s": 3638,
"text": "shortArrayOf()"
},
{
"code": null,
"e": 3667,
"s": 3653,
"text": "longArrayOf()"
},
{
"code": null,
"e": 3681,
"s": 3667,
"text": "longArrayOf()"
},
{
"code": null,
"e": 3896,
"s": 3681,
"text": "We can access an array element by using the index number inside square brackets. Kotlin array index starts with zero (0). So if you want to access 4th element of the array then you will need to give 3 as the index."
},
{
"code": null,
"e": 4056,
"s": 3896,
"text": "fun main(args: Array<String>) {\n val fruits = arrayOf<String>(\"Apple\", \"Mango\", \"Banana\", \"Orange\")\n \n println( fruits [0])\n println( fruits [3])\n \n}\n"
},
{
"code": null,
"e": 4134,
"s": 4056,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4148,
"s": 4134,
"text": "Apple\nOrange\n"
},
{
"code": null,
"e": 4279,
"s": 4148,
"text": "Kotlin also provides get() and set() member functions to get and set the value at a particular index. Check the following example:"
},
{
"code": null,
"e": 4532,
"s": 4279,
"text": "fun main(args: Array<String>) {\n val fruits = arrayOf<String>(\"Apple\", \"Mango\", \"Banana\", \"Orange\")\n \n println( fruits.get(0))\n println( fruits.get(3))\n \n // Set the value at 3rd index\n fruits.set(3, \"Guava\")\n println( fruits.get(3)) \n}\n"
},
{
"code": null,
"e": 4610,
"s": 4532,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4630,
"s": 4610,
"text": "Apple\nOrange\nGuava\n"
},
{
"code": null,
"e": 4723,
"s": 4630,
"text": "Kotlin provides array property called size which returns the size i.e. length of the array. "
},
{
"code": null,
"e": 4884,
"s": 4723,
"text": "fun main(args: Array<String>) {\n val fruits = arrayOf<String>(\"Apple\", \"Mango\", \"Banana\", \"Orange\")\n \n println( \"Size of fruits array \" + fruits.size )\n\n}\n"
},
{
"code": null,
"e": 4962,
"s": 4884,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4986,
"s": 4962,
"text": "Size of fruits array 4\n"
},
{
"code": null,
"e": 5056,
"s": 4986,
"text": "We can also use count() member function to get the size of the array."
},
{
"code": null,
"e": 5102,
"s": 5056,
"text": "We can use for loop to loop through an array."
},
{
"code": null,
"e": 5267,
"s": 5102,
"text": "fun main(args: Array<String>) {\n val fruits = arrayOf<String>(\"Apple\", \"Mango\", \"Banana\", \"Orange\")\n \n for( item in fruits ){\n println( item )\n }\n \n}\n"
},
{
"code": null,
"e": 5345,
"s": 5267,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 5372,
"s": 5345,
"text": "Apple\nMango\nBanana\nOrange\n"
},
{
"code": null,
"e": 5462,
"s": 5372,
"text": "We can use the in operator alongwith if...else to check if an element exists in an array."
},
{
"code": null,
"e": 5708,
"s": 5462,
"text": "fun main(args: Array<String>) {\n val fruits = arrayOf<String>(\"Apple\", \"Mango\", \"Banana\", \"Orange\")\n \n if (\"Mango\" in fruits){\n println( \"Mango exists in fruits\" )\n }else{\n println( \"Mango does not exist in fruits\" )\n }\n \n}\n"
},
{
"code": null,
"e": 5786,
"s": 5708,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 5810,
"s": 5786,
"text": "Mango exists in fruits\n"
},
{
"code": null,
"e": 5968,
"s": 5810,
"text": "Kotlin allows to store duplicate values in an array, but same time you can get a set of distinct values stored in the array using distinct() member function."
},
{
"code": null,
"e": 6177,
"s": 5968,
"text": "fun main(args: Array<String>) {\n val fruits = arrayOf<String>(\"Apple\", \"Mango\", \"Banana\", \"Orange\", \"Apple\")\n \n val distinct = fruits.distinct()\n for( item in distinct ){\n println( item )\n }\n}\n"
},
{
"code": null,
"e": 6255,
"s": 6177,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 6282,
"s": 6255,
"text": "Apple\nMango\nBanana\nOrange\n"
},
{
"code": null,
"e": 6398,
"s": 6282,
"text": "We can use drop() or dropLast() member functions to drop elements from the beginning or from the last respectively."
},
{
"code": null,
"e": 6629,
"s": 6398,
"text": "fun main(args: Array<String>) {\n val fruits = arrayOf<String>(\"Apple\", \"Mango\", \"Banana\", \"Orange\", \"Apple\")\n \n val result = fruits.drop(2) // drops first two elements.\n for( item in result ){\n println( item )\n }\n}\n"
},
{
"code": null,
"e": 6707,
"s": 6629,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 6728,
"s": 6707,
"text": "Banana\nOrange\nApple\n"
},
{
"code": null,
"e": 6853,
"s": 6728,
"text": "We can use isEmpty() member function to check if an array is empty or not. This function returns true if the array is empty."
},
{
"code": null,
"e": 6978,
"s": 6853,
"text": "fun main(args: Array<String>) {\n val fruits = arrayOf<String>()\n println( \"Array is empty : \" + fruits.isEmpty())\n \n}\n"
},
{
"code": null,
"e": 7056,
"s": 6978,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 7080,
"s": 7056,
"text": "\"Array is empty : true\n"
},
{
"code": null,
"e": 7138,
"s": 7080,
"text": "Q 1 - Which of the following is true about Kotlin Arrays?"
},
{
"code": null,
"e": 7193,
"s": 7138,
"text": "A - Kotlin arrays are capable to store all data types."
},
{
"code": null,
"e": 7278,
"s": 7193,
"text": "B - Kotlin arrays can be created using either arrayOf() or arrayOfNulls() functions."
},
{
"code": null,
"e": 7359,
"s": 7278,
"text": "C - Kotlin provides a rich set of properties and functions to manipulate arrays."
},
{
"code": null,
"e": 7380,
"s": 7359,
"text": "D - All of the above"
},
{
"code": null,
"e": 7442,
"s": 7380,
"text": "All the mentioned statements are correct about Kotlin Arrays."
},
{
"code": null,
"e": 7503,
"s": 7442,
"text": "Q 2 - What will be the output of the following code segment?"
},
{
"code": null,
"e": 7634,
"s": 7503,
"text": "fun main(args: Array<String>) {\n val fruits = arrayOf<String>(\"Apple\", \"Mango\", \"Banana\", \"Orange\")\n\n println( fruits [2])\n\n}\n"
},
{
"code": null,
"e": 7644,
"s": 7634,
"text": "A - Apple"
},
{
"code": null,
"e": 7654,
"s": 7644,
"text": "B - Mango"
},
{
"code": null,
"e": 7665,
"s": 7654,
"text": "C - Banana"
},
{
"code": null,
"e": 7687,
"s": 7665,
"text": "D - None of the above"
},
{
"code": null,
"e": 7771,
"s": 7687,
"text": "Kotlin index starts from 0, so at 2 index we will find 3rd element which is Banana."
},
{
"code": null,
"e": 7816,
"s": 7771,
"text": "Q 3 - How to get the size of a Kotlin array?"
},
{
"code": null,
"e": 7844,
"s": 7816,
"text": "A - Using length() function"
},
{
"code": null,
"e": 7868,
"s": 7844,
"text": "B - Using size property"
},
{
"code": null,
"e": 7895,
"s": 7868,
"text": "C - Using count() function"
},
{
"code": null,
"e": 7912,
"s": 7895,
"text": "D - B and C both"
},
{
"code": null,
"e": 8020,
"s": 7912,
"text": "Option D is correct because we can get the size of an array using either size property or count() function."
},
{
"code": null,
"e": 8055,
"s": 8020,
"text": "\n 68 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8074,
"s": 8055,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8109,
"s": 8074,
"text": "\n 71 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8126,
"s": 8109,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8161,
"s": 8126,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8178,
"s": 8161,
"text": " Mahmoud Ramadan"
},
{
"code": null,
"e": 8211,
"s": 8178,
"text": "\n 49 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 8227,
"s": 8211,
"text": " Catalin Stefan"
},
{
"code": null,
"e": 8262,
"s": 8227,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8282,
"s": 8262,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 8315,
"s": 8282,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8332,
"s": 8315,
"text": " CLEMENT OCHIENG"
},
{
"code": null,
"e": 8339,
"s": 8332,
"text": " Print"
},
{
"code": null,
"e": 8350,
"s": 8339,
"text": " Add Notes"
}
] |
Shortest Path with Alternating Colors in Python | Suppose we have directed graph, with nodes labelled 0, 1, ..., n-1. In this graph, each edge is colored with either red or blue colors, and there could be self-edges or parallel edges. Each [i, j] in red_edges indicates a red directed edge from node i to node j. Similarly, each [i, j] in blue_edges indicates a blue directed edge from node i to node j. We have to find an array answer of length n, where each answer[X] is the length of the shortest path from node 0 to node X such that the edge colors alternate along the path (or -1 if such a path doesn't exist).
So if the input is like n = 3, red_edges = [[0,1],[1,2]] and blue_edges = [], then the output will be [0, 1, -1]
To solve this, we will follow these steps −
Define a method called bfs(), this will take re, be, f and n
Define a method called bfs(), this will take re, be, f and n
define a set called visited, define a queue and insert a triplet [0, f, 0]
define a set called visited, define a queue and insert a triplet [0, f, 0]
while q is not emptyset triplet current, color, step as q[0], and delete from qcolor := complement the value of color (true to false and vice versa)res[current] := min of res[current] and stepif color is non-zero, thenfor each i in re[current]if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into qotherwise when color is 0, thenfor each i in be[current]if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q
while q is not empty
set triplet current, color, step as q[0], and delete from q
set triplet current, color, step as q[0], and delete from q
color := complement the value of color (true to false and vice versa)
color := complement the value of color (true to false and vice versa)
res[current] := min of res[current] and step
res[current] := min of res[current] and step
if color is non-zero, thenfor each i in re[current]if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q
if color is non-zero, then
for each i in re[current]if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q
for each i in re[current]
if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q
if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q
otherwise when color is 0, thenfor each i in be[current]if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q
otherwise when color is 0, then
for each i in be[current]if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q
for each i in be[current]
if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q
if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q
In the main method −
In the main method −
res := an array of infinity values and its size is n
res := an array of infinity values and its size is n
re and be := arrays of n empty arrays
re and be := arrays of n empty arrays
for each element i in r: insert i[1] into re[i[0]]
for each element i in r: insert i[1] into re[i[0]]
for each element i in b: insert i[1] into be[i[0]]
for each element i in b: insert i[1] into be[i[0]]
call bfs(re, be, false, n) and call bfs(re, be, true, n)
call bfs(re, be, false, n) and call bfs(re, be, true, n)
for i in range 0 to length of res – 1if res[i] = inf, then res[i] := -1
for i in range 0 to length of res – 1
if res[i] = inf, then res[i] := -1
if res[i] = inf, then res[i] := -1
return res
return res
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def shortestAlternatingPaths(self, n, r, b):
self.res = [float("inf")] * n
re = [[] for i in range(n) ]
be = [[] for i in range(n) ]
for i in r:
re[i[0]].append(i[1])
for i in b:
be[i[0]].append(i[1])
self.bfs(re,be,False,n)
self.bfs(re,be,True,n)
for i in range(len(self.res)):
if self.res[i] == float('inf'):
self.res[i]=-1
return self.res
def bfs(self,re,be,f,n):
visited = set()
queue = [[0,f,0]]
while queue:
current,color,step = queue[0]
queue.pop(0)
color = not color
self.res[current] = min(self.res[current],step)
if color:
for i in re[current]:
if (i,color) not in visited:
visited.add((i,color))
queue.append([i,color,step+1])
elif not color:
for i in be[current]:
if (i,color) not in visited:
visited.add((i,color))
queue.append([i,color,step+1])
ob = Solution()
print(ob.shortestAlternatingPaths(3, [[0,1], [1,2]], []))
3
[[0,1],[1,2]]
[]
[0,1,-1] | [
{
"code": null,
"e": 1628,
"s": 1062,
"text": "Suppose we have directed graph, with nodes labelled 0, 1, ..., n-1. In this graph, each edge is colored with either red or blue colors, and there could be self-edges or parallel edges. Each [i, j] in red_edges indicates a red directed edge from node i to node j. Similarly, each [i, j] in blue_edges indicates a blue directed edge from node i to node j. We have to find an array answer of length n, where each answer[X] is the length of the shortest path from node 0 to node X such that the edge colors alternate along the path (or -1 if such a path doesn't exist)."
},
{
"code": null,
"e": 1741,
"s": 1628,
"text": "So if the input is like n = 3, red_edges = [[0,1],[1,2]] and blue_edges = [], then the output will be [0, 1, -1]"
},
{
"code": null,
"e": 1785,
"s": 1741,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1846,
"s": 1785,
"text": "Define a method called bfs(), this will take re, be, f and n"
},
{
"code": null,
"e": 1907,
"s": 1846,
"text": "Define a method called bfs(), this will take re, be, f and n"
},
{
"code": null,
"e": 1982,
"s": 1907,
"text": "define a set called visited, define a queue and insert a triplet [0, f, 0]"
},
{
"code": null,
"e": 2057,
"s": 1982,
"text": "define a set called visited, define a queue and insert a triplet [0, f, 0]"
},
{
"code": null,
"e": 2581,
"s": 2057,
"text": "while q is not emptyset triplet current, color, step as q[0], and delete from qcolor := complement the value of color (true to false and vice versa)res[current] := min of res[current] and stepif color is non-zero, thenfor each i in re[current]if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into qotherwise when color is 0, thenfor each i in be[current]if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q"
},
{
"code": null,
"e": 2602,
"s": 2581,
"text": "while q is not empty"
},
{
"code": null,
"e": 2662,
"s": 2602,
"text": "set triplet current, color, step as q[0], and delete from q"
},
{
"code": null,
"e": 2722,
"s": 2662,
"text": "set triplet current, color, step as q[0], and delete from q"
},
{
"code": null,
"e": 2792,
"s": 2722,
"text": "color := complement the value of color (true to false and vice versa)"
},
{
"code": null,
"e": 2862,
"s": 2792,
"text": "color := complement the value of color (true to false and vice versa)"
},
{
"code": null,
"e": 2907,
"s": 2862,
"text": "res[current] := min of res[current] and step"
},
{
"code": null,
"e": 2952,
"s": 2907,
"text": "res[current] := min of res[current] and step"
},
{
"code": null,
"e": 3116,
"s": 2952,
"text": "if color is non-zero, thenfor each i in re[current]if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q"
},
{
"code": null,
"e": 3143,
"s": 3116,
"text": "if color is non-zero, then"
},
{
"code": null,
"e": 3281,
"s": 3143,
"text": "for each i in re[current]if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q"
},
{
"code": null,
"e": 3307,
"s": 3281,
"text": "for each i in re[current]"
},
{
"code": null,
"e": 3420,
"s": 3307,
"text": "if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q"
},
{
"code": null,
"e": 3533,
"s": 3420,
"text": "if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q"
},
{
"code": null,
"e": 3702,
"s": 3533,
"text": "otherwise when color is 0, thenfor each i in be[current]if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q"
},
{
"code": null,
"e": 3734,
"s": 3702,
"text": "otherwise when color is 0, then"
},
{
"code": null,
"e": 3872,
"s": 3734,
"text": "for each i in be[current]if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q"
},
{
"code": null,
"e": 3898,
"s": 3872,
"text": "for each i in be[current]"
},
{
"code": null,
"e": 4011,
"s": 3898,
"text": "if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q"
},
{
"code": null,
"e": 4124,
"s": 4011,
"text": "if pair (i, color) is not in visited, then insert (i, color) into visited and insert [i, color, step + 1] into q"
},
{
"code": null,
"e": 4145,
"s": 4124,
"text": "In the main method −"
},
{
"code": null,
"e": 4166,
"s": 4145,
"text": "In the main method −"
},
{
"code": null,
"e": 4219,
"s": 4166,
"text": "res := an array of infinity values and its size is n"
},
{
"code": null,
"e": 4272,
"s": 4219,
"text": "res := an array of infinity values and its size is n"
},
{
"code": null,
"e": 4310,
"s": 4272,
"text": "re and be := arrays of n empty arrays"
},
{
"code": null,
"e": 4348,
"s": 4310,
"text": "re and be := arrays of n empty arrays"
},
{
"code": null,
"e": 4399,
"s": 4348,
"text": "for each element i in r: insert i[1] into re[i[0]]"
},
{
"code": null,
"e": 4450,
"s": 4399,
"text": "for each element i in r: insert i[1] into re[i[0]]"
},
{
"code": null,
"e": 4501,
"s": 4450,
"text": "for each element i in b: insert i[1] into be[i[0]]"
},
{
"code": null,
"e": 4552,
"s": 4501,
"text": "for each element i in b: insert i[1] into be[i[0]]"
},
{
"code": null,
"e": 4609,
"s": 4552,
"text": "call bfs(re, be, false, n) and call bfs(re, be, true, n)"
},
{
"code": null,
"e": 4666,
"s": 4609,
"text": "call bfs(re, be, false, n) and call bfs(re, be, true, n)"
},
{
"code": null,
"e": 4738,
"s": 4666,
"text": "for i in range 0 to length of res – 1if res[i] = inf, then res[i] := -1"
},
{
"code": null,
"e": 4776,
"s": 4738,
"text": "for i in range 0 to length of res – 1"
},
{
"code": null,
"e": 4811,
"s": 4776,
"text": "if res[i] = inf, then res[i] := -1"
},
{
"code": null,
"e": 4846,
"s": 4811,
"text": "if res[i] = inf, then res[i] := -1"
},
{
"code": null,
"e": 4857,
"s": 4846,
"text": "return res"
},
{
"code": null,
"e": 4868,
"s": 4857,
"text": "return res"
},
{
"code": null,
"e": 4938,
"s": 4868,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 4949,
"s": 4938,
"text": " Live Demo"
},
{
"code": null,
"e": 6103,
"s": 4949,
"text": "class Solution(object):\n def shortestAlternatingPaths(self, n, r, b):\n self.res = [float(\"inf\")] * n\n re = [[] for i in range(n) ]\n be = [[] for i in range(n) ]\n for i in r:\n re[i[0]].append(i[1])\n for i in b:\n be[i[0]].append(i[1])\n self.bfs(re,be,False,n)\n self.bfs(re,be,True,n)\n for i in range(len(self.res)):\n if self.res[i] == float('inf'):\n self.res[i]=-1\n return self.res\n def bfs(self,re,be,f,n):\n visited = set()\n queue = [[0,f,0]]\n while queue:\n current,color,step = queue[0]\n queue.pop(0)\n color = not color\n self.res[current] = min(self.res[current],step)\n if color:\n for i in re[current]:\n if (i,color) not in visited:\n visited.add((i,color))\n queue.append([i,color,step+1])\n elif not color:\n for i in be[current]:\n if (i,color) not in visited:\n visited.add((i,color))\n queue.append([i,color,step+1])\nob = Solution()\nprint(ob.shortestAlternatingPaths(3, [[0,1], [1,2]], []))"
},
{
"code": null,
"e": 6122,
"s": 6103,
"text": "3\n[[0,1],[1,2]]\n[]"
},
{
"code": null,
"e": 6131,
"s": 6122,
"text": "[0,1,-1]"
}
] |
Graphs and its traversal algorithms | In this section we will see what is a graph data structure, and the traversal algorithms of it.
The graph is one non-linear data structure. That is consists of some nodes and their connected edges. The edges may be director or undirected. This graph can be represented as G(V, E). The following graph can be represented as G({A, B, C, D, E}, {(A, B), (B, D), (D, E), (B, C), (C, A)})
The graph has two types of traversal algorithms. These are called the Breadth First Search and Depth First Search.
The Breadth First Search (BFS) traversal is an algorithm, which is used to visit all of the nodes of a given graph. In this traversal algorithm one node is selected and then all of the adjacent nodes are visited one by one. After completing all of the adjacent vertices, it moves further to check another vertices and checks its adjacent vertices again.
bfs(vertices, start)
Input: The list of vertices, and the start vertex.
Output: Traverse all of the nodes, if the graph is connected.
Begin
define an empty queue que
at first mark all nodes status as unvisited
add the start vertex into the que
while que is not empty, do
delete item from que and set to u
display the vertex u
for all vertices 1 adjacent with u, do
if vertices[i] is unvisited, then
mark vertices[i] as temporarily visited
add v into the queue
mark
done
mark u as completely visited
done
End
The Depth First Search (DFS) is a graph traversal algorithm. In this algorithm one starting vertex is given, and when an adjacent vertex is found, it moves to that adjacent vertex first and try to traverse in the same manner.
dfs(vertices, start)
Input: The list of all vertices, and the start node.
Output: Traverse all nodes in the graph.
Begin
initially make the state to unvisited for all nodes
push start into the stack
while stack is not empty, do
pop element from stack and set to u
display the node u
if u is not visited, then
mark u as visited
for all nodes i connected to u, do
if ith vertex is unvisited, then
push ith vertex into the stack
mark ith vertex as visited
done
done
End | [
{
"code": null,
"e": 1158,
"s": 1062,
"text": "In this section we will see what is a graph data structure, and the traversal algorithms of it."
},
{
"code": null,
"e": 1446,
"s": 1158,
"text": "The graph is one non-linear data structure. That is consists of some nodes and their connected edges. The edges may be director or undirected. This graph can be represented as G(V, E). The following graph can be represented as G({A, B, C, D, E}, {(A, B), (B, D), (D, E), (B, C), (C, A)})"
},
{
"code": null,
"e": 1561,
"s": 1446,
"text": "The graph has two types of traversal algorithms. These are called the Breadth First Search and Depth First Search."
},
{
"code": null,
"e": 1915,
"s": 1561,
"text": "The Breadth First Search (BFS) traversal is an algorithm, which is used to visit all of the nodes of a given graph. In this traversal algorithm one node is selected and then all of the adjacent nodes are visited one by one. After completing all of the adjacent vertices, it moves further to check another vertices and checks its adjacent vertices again."
},
{
"code": null,
"e": 2510,
"s": 1915,
"text": "bfs(vertices, start)\nInput: The list of vertices, and the start vertex.\nOutput: Traverse all of the nodes, if the graph is connected.\nBegin\n define an empty queue que\n at first mark all nodes status as unvisited\n add the start vertex into the que\n while que is not empty, do\n delete item from que and set to u\n display the vertex u\n for all vertices 1 adjacent with u, do\n if vertices[i] is unvisited, then\n mark vertices[i] as temporarily visited\n add v into the queue\n mark\n done\n mark u as completely visited\n done\nEnd"
},
{
"code": null,
"e": 2736,
"s": 2510,
"text": "The Depth First Search (DFS) is a graph traversal algorithm. In this algorithm one starting vertex is given, and when an adjacent vertex is found, it moves to that adjacent vertex first and try to traverse in the same manner."
},
{
"code": null,
"e": 3302,
"s": 2736,
"text": "dfs(vertices, start)\nInput: The list of all vertices, and the start node.\nOutput: Traverse all nodes in the graph.\nBegin\n initially make the state to unvisited for all nodes\n push start into the stack\n while stack is not empty, do\n pop element from stack and set to u\n display the node u\n if u is not visited, then\n mark u as visited\n for all nodes i connected to u, do\n if ith vertex is unvisited, then\n push ith vertex into the stack\n mark ith vertex as visited\n done\n done\nEnd"
}
] |
Assertions in C/C++ | Here we will see what is assertions in C/C++. The C library macro void assert(int expression) allows diagnostic information to be written to the standard error file. In other words, it can be used to add diagnostics in your C program.
Following is the declaration for assert() Macro.
void assert(int expression);
The parameter of this assert() is expression − This can be a variable or any C expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr (standard error stream to display error messages and diagnostics) and aborts program execution.
#include <assert.h>
#include <stdio.h>
int main () {
int a;
char str[50];
printf("Enter an integer value: ");
scanf("%d", &a);
assert(a >= 10);
printf("Integer entered is %d\n", a);
printf("Enter string: ");
scanf("%s", &str);
assert(str != NULL);
printf("String entered is: %s\n", str);
return(0);
}
Enter an integer value: 11
Integer entered is 11
Enter string: tutorialspoint
String entered is: tutorialspoint | [
{
"code": null,
"e": 1297,
"s": 1062,
"text": "Here we will see what is assertions in C/C++. The C library macro void assert(int expression) allows diagnostic information to be written to the standard error file. In other words, it can be used to add diagnostics in your C program."
},
{
"code": null,
"e": 1346,
"s": 1297,
"text": "Following is the declaration for assert() Macro."
},
{
"code": null,
"e": 1375,
"s": 1346,
"text": "void assert(int expression);"
},
{
"code": null,
"e": 1697,
"s": 1375,
"text": "The parameter of this assert() is expression − This can be a variable or any C expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr (standard error stream to display error messages and diagnostics) and aborts program execution."
},
{
"code": null,
"e": 2031,
"s": 1697,
"text": "#include <assert.h>\n#include <stdio.h>\nint main () {\n int a;\n char str[50];\n printf(\"Enter an integer value: \");\n scanf(\"%d\", &a);\n assert(a >= 10);\n printf(\"Integer entered is %d\\n\", a);\n printf(\"Enter string: \");\n scanf(\"%s\", &str);\n assert(str != NULL);\n printf(\"String entered is: %s\\n\", str);\n return(0);\n}"
},
{
"code": null,
"e": 2143,
"s": 2031,
"text": "Enter an integer value: 11\nInteger entered is 11\nEnter string: tutorialspoint\nString entered is: tutorialspoint"
}
] |
Error-free import of CSV files using Pandas DataFrame | by Syed Huma Shah | Towards Data Science | Data is at the centre of a Machine Learning pipeline. In order to leverage an algorithm’s full capacity, data must be first cleaned and wrangled properly.
The first step of data cleaning/wrangling is loading the file and then establishing a connection via the path of a file. There are different types of delimited files like tab-separated file, comma-separated file, multi-character delimited file etc. The delimitations indicate how the data is to be separated within columns whether through comma, tab or semicolon etc. The most commonly used files are tab-separated and comma-separated files.
Data wrangling and cleaning accounts for about 50 to 70% of the Data analytics professionals’ time within the whole ML pipeline. The first step is to import the file to a Pandas DataFrame. However, this step constitutes the most encountered errors. People often get stuck in this particular step and come across errors like
EmptyDataError: No columns to parse from file
The common errors occur, mainly, due to :
· Wrong file delimiters mentioned.
· File path not formed properly.
· Wrong syntax or separator used to specify the file path.
· Wrong file directory mentioned.
· File Connection not formed.
Data analytics professionals cannot afford more time being drained into an already time-consuming step. While loading the file, certain important steps must be followed which will save time and cut through the hassle of scouring through a plethora of information to find the solution to your specific problem. Therefore, I have laid out some steps to avoid any error while importing and loading a data file using pandas DataFrame.
Reading and importing the CSV file is not so simple as one may surmise. Here are some tips which must be kept in mind once you start loading your file to build your Machine Learning model.
1. Check your separation type in settings:
For Windows
Go to Control Panel
Click on Regional and Language Options
Click on Regional Options tab
Click on Customize/Additional settings
Type a comma into the ‘List separator’ box (,)
Click ‘OK’ twice to confirm the change
Note: This only works if the ‘Decimal symbol’ is also not a comma.
For MacOS
Go to System Preferences
Click on Language & Region and then go to the Advanced option
Change the ‘Decimal Separator’ to one of the below scenarios
For MacOS, if the Decimal Separator is a period (.) then the CSV separator will be a comma. If the Decimal Separator is a comma (,) then the CSV separator will be a semicolon.
2. Check the preview of the file:
The preview of the file can also be checked and it can be seen how the data is being separated, whether by tab separation or comma separation. One can check the preview either in Jupyter notebook or Microsoft Excel.
3. Specify correctly all the arguments:
Having taken a look at the preview and checking the separation specified for your computer. We now have to fill in the right arguments which need to be mentioned in the “pd.read_csv” function based on the type of file as the type of delimiter( tab-separated etc), blank header (in that case header= none) etc.
Pandas.read.csv has many arguments which need to be taken into account for the file to be read properly.
pandas.read_csv(filepath_or_buffer, sep=<object object>, delimiter=None, header=’infer’, names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression=’infer’, thousands=None, decimal=’.’, lineterminator=None, quotechar=’”’, quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, error_bad_lines=True, warn_bad_lines=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None, storage_options=None)
This is the list of all the arguments, but we are most concerned with the following:
sep: This specifies the type of separation between the data values. The default is ‘,’. After checking the preview and the system settings, we know the type of file. The most common type of separator/delimiter is comma, tab and colon. Therefore, it is to be specified as sep= ‘,’ , sep= ‘ ’, sep= ‘;’ This tells the pandas DataFrame how to distribute data into columns
After checking for any required arguments which need to be put, if the issue persists. Then the issue might be with the file path.
4. Check Filepath:
This argument is used to describe the path object or file-like object for the particular data file, basically its location. The Input is a string. A URL can be input as well, the valid schemes are HTTP, FTP, s3, gs, and file.
The file location is to be mentioned correctly. Most often, people are unaware of the working directory and end up mentioning the wrong file path. In that case, we have to check the working directory to ensure that the specified file path is correctly described. Write the code shown below to check the working directory.
This will print the working directory. Then, we have to only specify the location after your working directory.
We can change the working directory also using the below line of code. After specifying the new directory, we have to specify the path.
5. Check separator used to specify file location:
Often times an error occurs while changing the working directory as well. This arises due to not writing the separator according to the proper syntax.
First of all. Check the separator using the below command.
Then use the separator at the beginning of the directory location only and not at the end. Kindly, note that this separator(/) syntax specification is true for MacOS and might not be true for Windows.
Now after specifying the location correctly we have changed it.
Now we have to specify the path. Since we are familiar with the working directory. We have to only specify the location succeeding the working directory.
If your file is in the working directory then only mention the file name as shown below.
But if your file is present in some other folder then you can either specify the succeeding folders after the working directory e.g. your working directory is “/Users/username” and your file is in a folder named ‘huma’ in ‘documents’ then you would write the below code:
path = ‘Documents/huma/filename.csv’
6. Check the file is on the path:
Now check whether your file is present in the described path using the below code. We will get our answer as either ‘true’ or ‘false’.
7. Print the file data to cross-check:
Now, we can check whether our data file has loaded correctly using the below code.
With these tips in hand, you may not face any problem in loading your CSV file using Pandas DataFrame again. | [
{
"code": null,
"e": 327,
"s": 172,
"text": "Data is at the centre of a Machine Learning pipeline. In order to leverage an algorithm’s full capacity, data must be first cleaned and wrangled properly."
},
{
"code": null,
"e": 769,
"s": 327,
"text": "The first step of data cleaning/wrangling is loading the file and then establishing a connection via the path of a file. There are different types of delimited files like tab-separated file, comma-separated file, multi-character delimited file etc. The delimitations indicate how the data is to be separated within columns whether through comma, tab or semicolon etc. The most commonly used files are tab-separated and comma-separated files."
},
{
"code": null,
"e": 1093,
"s": 769,
"text": "Data wrangling and cleaning accounts for about 50 to 70% of the Data analytics professionals’ time within the whole ML pipeline. The first step is to import the file to a Pandas DataFrame. However, this step constitutes the most encountered errors. People often get stuck in this particular step and come across errors like"
},
{
"code": null,
"e": 1139,
"s": 1093,
"text": "EmptyDataError: No columns to parse from file"
},
{
"code": null,
"e": 1181,
"s": 1139,
"text": "The common errors occur, mainly, due to :"
},
{
"code": null,
"e": 1216,
"s": 1181,
"text": "· Wrong file delimiters mentioned."
},
{
"code": null,
"e": 1249,
"s": 1216,
"text": "· File path not formed properly."
},
{
"code": null,
"e": 1308,
"s": 1249,
"text": "· Wrong syntax or separator used to specify the file path."
},
{
"code": null,
"e": 1342,
"s": 1308,
"text": "· Wrong file directory mentioned."
},
{
"code": null,
"e": 1372,
"s": 1342,
"text": "· File Connection not formed."
},
{
"code": null,
"e": 1803,
"s": 1372,
"text": "Data analytics professionals cannot afford more time being drained into an already time-consuming step. While loading the file, certain important steps must be followed which will save time and cut through the hassle of scouring through a plethora of information to find the solution to your specific problem. Therefore, I have laid out some steps to avoid any error while importing and loading a data file using pandas DataFrame."
},
{
"code": null,
"e": 1992,
"s": 1803,
"text": "Reading and importing the CSV file is not so simple as one may surmise. Here are some tips which must be kept in mind once you start loading your file to build your Machine Learning model."
},
{
"code": null,
"e": 2035,
"s": 1992,
"text": "1. Check your separation type in settings:"
},
{
"code": null,
"e": 2047,
"s": 2035,
"text": "For Windows"
},
{
"code": null,
"e": 2067,
"s": 2047,
"text": "Go to Control Panel"
},
{
"code": null,
"e": 2106,
"s": 2067,
"text": "Click on Regional and Language Options"
},
{
"code": null,
"e": 2136,
"s": 2106,
"text": "Click on Regional Options tab"
},
{
"code": null,
"e": 2175,
"s": 2136,
"text": "Click on Customize/Additional settings"
},
{
"code": null,
"e": 2222,
"s": 2175,
"text": "Type a comma into the ‘List separator’ box (,)"
},
{
"code": null,
"e": 2261,
"s": 2222,
"text": "Click ‘OK’ twice to confirm the change"
},
{
"code": null,
"e": 2328,
"s": 2261,
"text": "Note: This only works if the ‘Decimal symbol’ is also not a comma."
},
{
"code": null,
"e": 2338,
"s": 2328,
"text": "For MacOS"
},
{
"code": null,
"e": 2363,
"s": 2338,
"text": "Go to System Preferences"
},
{
"code": null,
"e": 2425,
"s": 2363,
"text": "Click on Language & Region and then go to the Advanced option"
},
{
"code": null,
"e": 2486,
"s": 2425,
"text": "Change the ‘Decimal Separator’ to one of the below scenarios"
},
{
"code": null,
"e": 2662,
"s": 2486,
"text": "For MacOS, if the Decimal Separator is a period (.) then the CSV separator will be a comma. If the Decimal Separator is a comma (,) then the CSV separator will be a semicolon."
},
{
"code": null,
"e": 2696,
"s": 2662,
"text": "2. Check the preview of the file:"
},
{
"code": null,
"e": 2912,
"s": 2696,
"text": "The preview of the file can also be checked and it can be seen how the data is being separated, whether by tab separation or comma separation. One can check the preview either in Jupyter notebook or Microsoft Excel."
},
{
"code": null,
"e": 2952,
"s": 2912,
"text": "3. Specify correctly all the arguments:"
},
{
"code": null,
"e": 3262,
"s": 2952,
"text": "Having taken a look at the preview and checking the separation specified for your computer. We now have to fill in the right arguments which need to be mentioned in the “pd.read_csv” function based on the type of file as the type of delimiter( tab-separated etc), blank header (in that case header= none) etc."
},
{
"code": null,
"e": 3367,
"s": 3262,
"text": "Pandas.read.csv has many arguments which need to be taken into account for the file to be read properly."
},
{
"code": null,
"e": 4259,
"s": 3367,
"text": "pandas.read_csv(filepath_or_buffer, sep=<object object>, delimiter=None, header=’infer’, names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression=’infer’, thousands=None, decimal=’.’, lineterminator=None, quotechar=’”’, quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, error_bad_lines=True, warn_bad_lines=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None, storage_options=None)"
},
{
"code": null,
"e": 4344,
"s": 4259,
"text": "This is the list of all the arguments, but we are most concerned with the following:"
},
{
"code": null,
"e": 4713,
"s": 4344,
"text": "sep: This specifies the type of separation between the data values. The default is ‘,’. After checking the preview and the system settings, we know the type of file. The most common type of separator/delimiter is comma, tab and colon. Therefore, it is to be specified as sep= ‘,’ , sep= ‘ ’, sep= ‘;’ This tells the pandas DataFrame how to distribute data into columns"
},
{
"code": null,
"e": 4844,
"s": 4713,
"text": "After checking for any required arguments which need to be put, if the issue persists. Then the issue might be with the file path."
},
{
"code": null,
"e": 4863,
"s": 4844,
"text": "4. Check Filepath:"
},
{
"code": null,
"e": 5089,
"s": 4863,
"text": "This argument is used to describe the path object or file-like object for the particular data file, basically its location. The Input is a string. A URL can be input as well, the valid schemes are HTTP, FTP, s3, gs, and file."
},
{
"code": null,
"e": 5411,
"s": 5089,
"text": "The file location is to be mentioned correctly. Most often, people are unaware of the working directory and end up mentioning the wrong file path. In that case, we have to check the working directory to ensure that the specified file path is correctly described. Write the code shown below to check the working directory."
},
{
"code": null,
"e": 5523,
"s": 5411,
"text": "This will print the working directory. Then, we have to only specify the location after your working directory."
},
{
"code": null,
"e": 5659,
"s": 5523,
"text": "We can change the working directory also using the below line of code. After specifying the new directory, we have to specify the path."
},
{
"code": null,
"e": 5709,
"s": 5659,
"text": "5. Check separator used to specify file location:"
},
{
"code": null,
"e": 5860,
"s": 5709,
"text": "Often times an error occurs while changing the working directory as well. This arises due to not writing the separator according to the proper syntax."
},
{
"code": null,
"e": 5919,
"s": 5860,
"text": "First of all. Check the separator using the below command."
},
{
"code": null,
"e": 6120,
"s": 5919,
"text": "Then use the separator at the beginning of the directory location only and not at the end. Kindly, note that this separator(/) syntax specification is true for MacOS and might not be true for Windows."
},
{
"code": null,
"e": 6184,
"s": 6120,
"text": "Now after specifying the location correctly we have changed it."
},
{
"code": null,
"e": 6338,
"s": 6184,
"text": "Now we have to specify the path. Since we are familiar with the working directory. We have to only specify the location succeeding the working directory."
},
{
"code": null,
"e": 6427,
"s": 6338,
"text": "If your file is in the working directory then only mention the file name as shown below."
},
{
"code": null,
"e": 6698,
"s": 6427,
"text": "But if your file is present in some other folder then you can either specify the succeeding folders after the working directory e.g. your working directory is “/Users/username” and your file is in a folder named ‘huma’ in ‘documents’ then you would write the below code:"
},
{
"code": null,
"e": 6735,
"s": 6698,
"text": "path = ‘Documents/huma/filename.csv’"
},
{
"code": null,
"e": 6769,
"s": 6735,
"text": "6. Check the file is on the path:"
},
{
"code": null,
"e": 6904,
"s": 6769,
"text": "Now check whether your file is present in the described path using the below code. We will get our answer as either ‘true’ or ‘false’."
},
{
"code": null,
"e": 6943,
"s": 6904,
"text": "7. Print the file data to cross-check:"
},
{
"code": null,
"e": 7026,
"s": 6943,
"text": "Now, we can check whether our data file has loaded correctly using the below code."
}
] |
DIY Deep Learning Projects. Inspired by the great work of Akshay... | by Favio Vázquez | Towards Data Science | Akshay Bahadur is one of the great examples that the Data Science community at LinkedIn gave. There are great people in other platforms like Quora, StackOverflow, Youtube, here, and in lots of forums and platforms helping each other in many areas of science, philosophy, math, language and of course Data Science and its companions.
But I think in the past ~3 years, the LinkedIn community has excel on sharing great content in the Data Science space, from sharing experiences to detailed posts on how to do Machine Learning or Deep Learning in the real world. I always recommend to people entering in this area to be a part of a community, and LinkedIn is on the best, you will find me there all the time :).
The research in the Deep Learning space for classifying things in images, detecting them and do actions when they “see” something has been very important in this decade, with amazing results like surpassing human level performance for some problems.
In this article I will show you every post Akshay Bahadur has done in the space of Computer Vision (CV) and Deep Learning (DL). If you are not familiar with any of those terms you can learn more about them here:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
github.com
From Akshay:
To perform video tracking an algorithm analyzes sequential video frames and outputs the movement of targets between the frames. There are a variety of algorithms, each having strengths and weaknesses. Considering the intended use is important when choosing which algorithm to use. There are two major components of a visual tracking system: target representation and localization, as well as filtering and data association.
Video tracking is the process of locating a moving object (or multiple objects) over time using a camera. It has a variety of uses, some of which are: human-computer interaction, security and surveillance, video communication and compression, augmented reality, traffic control, medical imaging and video editing.
This is all the code you need to reproduce it:
import numpy as npimport cv2import argparsefrom collections import dequecap=cv2.VideoCapture(0)pts = deque(maxlen=64)Lower_green = np.array([110,50,50])Upper_green = np.array([130,255,255])while True: ret, img=cap.read() hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV) kernel=np.ones((5,5),np.uint8) mask=cv2.inRange(hsv,Lower_green,Upper_green) mask = cv2.erode(mask, kernel, iterations=2) mask=cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernel) #mask=cv2.morphologyEx(mask,cv2.MORPH_CLOSE,kernel) mask = cv2.dilate(mask, kernel, iterations=1) res=cv2.bitwise_and(img,img,mask=mask) cnts,heir=cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2:] center = None if len(cnts) > 0: c = max(cnts, key=cv2.contourArea) ((x, y), radius) = cv2.minEnclosingCircle(c) M = cv2.moments(c) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) if radius > 5: cv2.circle(img, (int(x), int(y)), int(radius),(0, 255, 255), 2) cv2.circle(img, center, 5, (0, 0, 255), -1) pts.appendleft(center) for i in xrange (1,len(pts)): if pts[i-1]is None or pts[i] is None: continue thick = int(np.sqrt(len(pts) / float(i + 1)) * 2.5) cv2.line(img, pts[i-1],pts[i],(0,0,225),thick) cv2.imshow("Frame", img) cv2.imshow("mask",mask) cv2.imshow("res",res) k=cv2.waitKey(30) & 0xFF if k==32: break# cleanup the camera and close any open windowscap.release()cv2.destroyAllWindows()
Yep, 54 lines of code. Very simple right? You will need to have OpenCV installed in your computer, if you have Mac check this out:
www.learnopencv.com
If you have Ubuntu:
docs.opencv.org
and if you have Windows:
docs.opencv.org
github.com
This can be used by riders who tend to drive for a longer period of time that may lead to accidents. This code can detect your eyes and alert when the user is drowsy.
cv2immutilsdlibscipy
cv2
immutils
dlib
scipy
Each eye is represented by 6 (x, y)-coordinates, starting at the left-corner of the eye (as if you were looking at the person), and then working clockwise around the eye:.
It checks 20 consecutive frames and if the Eye Aspect ratio is lesst than 0.25, Alert is generated.
github.com
This code helps you classify different digits using softmax regression. You can install Conda for python which resolves all the dependencies for machine learning.
Softmax Regression (synonyms: Multinomial Logistic, Maximum Entropy Classifier, or just Multi-class Logistic Regression) is a generalization of logistic regression that we can use for multi-class classification (under the assumption that the classes are mutually exclusive). In contrast, we use the (standard) Logistic Regression model in binary classification tasks.
The dataset used was MNIST with images of size 28 X 28, and the plan here is to classify digits from 0 to 9 using Logistic Regression, Shallow Network and Deep Neural Network.
One of the best parts here is that he coded three models using Numpy including optimization, forward and back propagation and just everything.
For Logistic Regression:
For a Shallow Neural Network:
And finally with a Deep Neural Network:
To run the code, type python Dig-Rec.py
python Dig-Rec.py
To run the code, type python Digit-Recognizer.py
python Digit-Recognizer.py
github.com
This code helps you classify different alphabets of hindi language (Devanagiri) using Convnets. You can install Conda for python which resolves all the dependencies for machine learning.
I have used convolutional neural networks. I am using Tensorflow as the framework and Keras API for providing a high level of abstraction.
CONV2D → MAXPOOL → CONV2D → MAXPOOL →FC →Softmax → Classification
You can go for additional conv layers.Add regularization to prevent overfitting.You can add additional images to the training set for increasing the accuracy.
You can go for additional conv layers.
Add regularization to prevent overfitting.
You can add additional images to the training set for increasing the accuracy.
Dataset- DHCD (Devnagari Character Dataset) with i mages of size 32 X 32 and usage of Convolutional Network.
To run the code, type python Dev-Rec.py
python Dev-Rec.py
github.com
This code helps in facial recognition using facenets (https://arxiv.org/pdf/1503.03832.pdf). The concept of facenets was originally presented in a research paper. The main concepts talked about triplet loss function to compare images of different person. This concept uses inception network which has been taken from source and fr_utils.py is taken from deeplearning.ai for reference. I have added several functionalities of my own for providing stability and better detection.
You can install Conda for python which resolves all the dependencies for machine learning and you’ll need:
numpymatplotlibcv2kerasdlibh5pyscipy
A facial recognition system is a technology capable of identifying or verifying a person from a digital image or a video frame from a video source. There are multiples methods in which facial recognition systems work, but in general, they work by comparing selected facial features from given image with faces within a database.
Detecting face only when your eyes are opened. (Security measure).Using face align functionality from dlib to predict effectively while live streaming.
Detecting face only when your eyes are opened. (Security measure).
Using face align functionality from dlib to predict effectively while live streaming.
Network Used- Inception NetworkOriginal Paper — Facenet by Google
Network Used- Inception Network
Original Paper — Facenet by Google
If you want to train the network , run Train-inception.py, however you don't need to do that since I have already trained the model and saved it as face-rec_Google.h5 file which gets loaded at runtime.Now you need to have images in your database. The code check /images folder for that. You can either paste your pictures there or you can click it using web cam. For doing that, run create-face.py the images get stored in /incept folder. You have to manually paste them in /images folderRun rec-feat.py for running the application.
If you want to train the network , run Train-inception.py, however you don't need to do that since I have already trained the model and saved it as face-rec_Google.h5 file which gets loaded at runtime.
Now you need to have images in your database. The code check /images folder for that. You can either paste your pictures there or you can click it using web cam. For doing that, run create-face.py the images get stored in /incept folder. You have to manually paste them in /images folder
Run rec-feat.py for running the application.
github.com
This code helps you to recognize and classify different emojis. As of now, we are only supporting hand emojis.
You can install Conda for python which resolves all the dependencies for machine learning and you’ll need:
numpymatplotlibcv2kerasdlibh5pyscipy
Emojis are ideograms and smileys used in electronic messages and web pages. Emoji exist in various genres, including facial expressions, common objects, places and types of weather, and animals. They are much like emoticons, but emoji are actual pictures instead of typographics.
Filters to detect hand.CNN for training the model.
Filters to detect hand.
CNN for training the model.
Network Used- Convolutional Neural Network
Network Used- Convolutional Neural Network
First, you have to create a gesture database. For that, run CreateGest.py. Enter the gesture name and you will get 2 frames displayed. Look at the contour frame and adjust your hand to make sure that you capture the features of your hand. Press 'c' for capturing the images. It will take 1200 images of one gesture. Try moving your hand a little within the frame to make sure that your model doesn't overfit at the time of training.Repeat this for all the features you want.Run CreateCSV.py for converting the images to a CSV fileIf you want to train the model, run ‘TrainEmojinator.py’Finally, run Emojinator.py for testing your model via webcam.
First, you have to create a gesture database. For that, run CreateGest.py. Enter the gesture name and you will get 2 frames displayed. Look at the contour frame and adjust your hand to make sure that you capture the features of your hand. Press 'c' for capturing the images. It will take 1200 images of one gesture. Try moving your hand a little within the frame to make sure that your model doesn't overfit at the time of training.
Repeat this for all the features you want.
Run CreateCSV.py for converting the images to a CSV file
If you want to train the model, run ‘TrainEmojinator.py’
Finally, run Emojinator.py for testing your model via webcam.
Akshay Bahadur and Raghav Patnecha.
I can only say I’m incredibly impress on these projects, all of them you can run them on your computer, or more easily on Deep Cognition’s platform if you don’t want to install anything, and it can run online.
I want to thank Akshay and his friends for making this great Open Source contributions and for all the others that will come. Try them, run them, and get inspired. This is only a small example of the amazing things DL and CV can do, and is up to you to take this an turn it into something that can help the world become a better place.
Never give up, we need everyone to be interested in lots of different things. I think we can change the world for the better, improve our lives, the way we work, think and solve problems, and if we channel all the resources we have right now to make these area of knowledge to work together for a greater good, we can make a huge positive impact in the world and our lives.
Thanks for reading this. I hope you found something interesting here :)
If you have questions just add me in twitter:
twitter.com
and LinkedIn:
linkedin.com
See you there :)
I’m a Physicist and computer engineer working on Big Data, Data Science and Computational Cosmology. I have a passion for science, philosophy, programming, and Data Science. Right now I’m working on Data Science, Machine Learning and Deep Learning as the Principal Data Scientist at Oxxo. I love new challenges, working with a good team and interesting problems to solve. I’m part of Apache Spark collaboration, helping in MLLib, Core and the Documentation. Love applying my knowledge and expertise in science, data analysis, visualization and data processing to help the world become a better place. | [
{
"code": null,
"e": 505,
"s": 172,
"text": "Akshay Bahadur is one of the great examples that the Data Science community at LinkedIn gave. There are great people in other platforms like Quora, StackOverflow, Youtube, here, and in lots of forums and platforms helping each other in many areas of science, philosophy, math, language and of course Data Science and its companions."
},
{
"code": null,
"e": 882,
"s": 505,
"text": "But I think in the past ~3 years, the LinkedIn community has excel on sharing great content in the Data Science space, from sharing experiences to detailed posts on how to do Machine Learning or Deep Learning in the real world. I always recommend to people entering in this area to be a part of a community, and LinkedIn is on the best, you will find me there all the time :)."
},
{
"code": null,
"e": 1132,
"s": 882,
"text": "The research in the Deep Learning space for classifying things in images, detecting them and do actions when they “see” something has been very important in this decade, with amazing results like surpassing human level performance for some problems."
},
{
"code": null,
"e": 1344,
"s": 1132,
"text": "In this article I will show you every post Akshay Bahadur has done in the space of Computer Vision (CV) and Deep Learning (DL). If you are not familiar with any of those terms you can learn more about them here:"
},
{
"code": null,
"e": 1367,
"s": 1344,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1390,
"s": 1367,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1413,
"s": 1390,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1436,
"s": 1413,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1447,
"s": 1436,
"text": "github.com"
},
{
"code": null,
"e": 1460,
"s": 1447,
"text": "From Akshay:"
},
{
"code": null,
"e": 1884,
"s": 1460,
"text": "To perform video tracking an algorithm analyzes sequential video frames and outputs the movement of targets between the frames. There are a variety of algorithms, each having strengths and weaknesses. Considering the intended use is important when choosing which algorithm to use. There are two major components of a visual tracking system: target representation and localization, as well as filtering and data association."
},
{
"code": null,
"e": 2198,
"s": 1884,
"text": "Video tracking is the process of locating a moving object (or multiple objects) over time using a camera. It has a variety of uses, some of which are: human-computer interaction, security and surveillance, video communication and compression, augmented reality, traffic control, medical imaging and video editing."
},
{
"code": null,
"e": 2245,
"s": 2198,
"text": "This is all the code you need to reproduce it:"
},
{
"code": null,
"e": 3636,
"s": 2245,
"text": "import numpy as npimport cv2import argparsefrom collections import dequecap=cv2.VideoCapture(0)pts = deque(maxlen=64)Lower_green = np.array([110,50,50])Upper_green = np.array([130,255,255])while True:\tret, img=cap.read()\thsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\tkernel=np.ones((5,5),np.uint8)\tmask=cv2.inRange(hsv,Lower_green,Upper_green)\tmask = cv2.erode(mask, kernel, iterations=2)\tmask=cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernel)\t#mask=cv2.morphologyEx(mask,cv2.MORPH_CLOSE,kernel)\tmask = cv2.dilate(mask, kernel, iterations=1)\tres=cv2.bitwise_and(img,img,mask=mask)\tcnts,heir=cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2:]\tcenter = None \tif len(cnts) > 0:\t\tc = max(cnts, key=cv2.contourArea)\t\t((x, y), radius) = cv2.minEnclosingCircle(c)\t\tM = cv2.moments(c)\t\tcenter = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"])) \t\tif radius > 5:\t\t\tcv2.circle(img, (int(x), int(y)), int(radius),(0, 255, 255), 2)\t\t\tcv2.circle(img, center, 5, (0, 0, 255), -1)\t\t\tpts.appendleft(center)\tfor i in xrange (1,len(pts)):\t\tif pts[i-1]is None or pts[i] is None:\t\t\tcontinue\t\tthick = int(np.sqrt(len(pts) / float(i + 1)) * 2.5)\t\tcv2.line(img, pts[i-1],pts[i],(0,0,225),thick)\t\t\t\tcv2.imshow(\"Frame\", img)\tcv2.imshow(\"mask\",mask)\tcv2.imshow(\"res\",res)\t\t\tk=cv2.waitKey(30) & 0xFF\tif k==32:\t\tbreak# cleanup the camera and close any open windowscap.release()cv2.destroyAllWindows()"
},
{
"code": null,
"e": 3767,
"s": 3636,
"text": "Yep, 54 lines of code. Very simple right? You will need to have OpenCV installed in your computer, if you have Mac check this out:"
},
{
"code": null,
"e": 3787,
"s": 3767,
"text": "www.learnopencv.com"
},
{
"code": null,
"e": 3807,
"s": 3787,
"text": "If you have Ubuntu:"
},
{
"code": null,
"e": 3823,
"s": 3807,
"text": "docs.opencv.org"
},
{
"code": null,
"e": 3848,
"s": 3823,
"text": "and if you have Windows:"
},
{
"code": null,
"e": 3864,
"s": 3848,
"text": "docs.opencv.org"
},
{
"code": null,
"e": 3875,
"s": 3864,
"text": "github.com"
},
{
"code": null,
"e": 4042,
"s": 3875,
"text": "This can be used by riders who tend to drive for a longer period of time that may lead to accidents. This code can detect your eyes and alert when the user is drowsy."
},
{
"code": null,
"e": 4063,
"s": 4042,
"text": "cv2immutilsdlibscipy"
},
{
"code": null,
"e": 4067,
"s": 4063,
"text": "cv2"
},
{
"code": null,
"e": 4076,
"s": 4067,
"text": "immutils"
},
{
"code": null,
"e": 4081,
"s": 4076,
"text": "dlib"
},
{
"code": null,
"e": 4087,
"s": 4081,
"text": "scipy"
},
{
"code": null,
"e": 4259,
"s": 4087,
"text": "Each eye is represented by 6 (x, y)-coordinates, starting at the left-corner of the eye (as if you were looking at the person), and then working clockwise around the eye:."
},
{
"code": null,
"e": 4359,
"s": 4259,
"text": "It checks 20 consecutive frames and if the Eye Aspect ratio is lesst than 0.25, Alert is generated."
},
{
"code": null,
"e": 4370,
"s": 4359,
"text": "github.com"
},
{
"code": null,
"e": 4533,
"s": 4370,
"text": "This code helps you classify different digits using softmax regression. You can install Conda for python which resolves all the dependencies for machine learning."
},
{
"code": null,
"e": 4901,
"s": 4533,
"text": "Softmax Regression (synonyms: Multinomial Logistic, Maximum Entropy Classifier, or just Multi-class Logistic Regression) is a generalization of logistic regression that we can use for multi-class classification (under the assumption that the classes are mutually exclusive). In contrast, we use the (standard) Logistic Regression model in binary classification tasks."
},
{
"code": null,
"e": 5077,
"s": 4901,
"text": "The dataset used was MNIST with images of size 28 X 28, and the plan here is to classify digits from 0 to 9 using Logistic Regression, Shallow Network and Deep Neural Network."
},
{
"code": null,
"e": 5220,
"s": 5077,
"text": "One of the best parts here is that he coded three models using Numpy including optimization, forward and back propagation and just everything."
},
{
"code": null,
"e": 5245,
"s": 5220,
"text": "For Logistic Regression:"
},
{
"code": null,
"e": 5275,
"s": 5245,
"text": "For a Shallow Neural Network:"
},
{
"code": null,
"e": 5315,
"s": 5275,
"text": "And finally with a Deep Neural Network:"
},
{
"code": null,
"e": 5355,
"s": 5315,
"text": "To run the code, type python Dig-Rec.py"
},
{
"code": null,
"e": 5373,
"s": 5355,
"text": "python Dig-Rec.py"
},
{
"code": null,
"e": 5422,
"s": 5373,
"text": "To run the code, type python Digit-Recognizer.py"
},
{
"code": null,
"e": 5449,
"s": 5422,
"text": "python Digit-Recognizer.py"
},
{
"code": null,
"e": 5460,
"s": 5449,
"text": "github.com"
},
{
"code": null,
"e": 5647,
"s": 5460,
"text": "This code helps you classify different alphabets of hindi language (Devanagiri) using Convnets. You can install Conda for python which resolves all the dependencies for machine learning."
},
{
"code": null,
"e": 5786,
"s": 5647,
"text": "I have used convolutional neural networks. I am using Tensorflow as the framework and Keras API for providing a high level of abstraction."
},
{
"code": null,
"e": 5852,
"s": 5786,
"text": "CONV2D → MAXPOOL → CONV2D → MAXPOOL →FC →Softmax → Classification"
},
{
"code": null,
"e": 6011,
"s": 5852,
"text": "You can go for additional conv layers.Add regularization to prevent overfitting.You can add additional images to the training set for increasing the accuracy."
},
{
"code": null,
"e": 6050,
"s": 6011,
"text": "You can go for additional conv layers."
},
{
"code": null,
"e": 6093,
"s": 6050,
"text": "Add regularization to prevent overfitting."
},
{
"code": null,
"e": 6172,
"s": 6093,
"text": "You can add additional images to the training set for increasing the accuracy."
},
{
"code": null,
"e": 6281,
"s": 6172,
"text": "Dataset- DHCD (Devnagari Character Dataset) with i mages of size 32 X 32 and usage of Convolutional Network."
},
{
"code": null,
"e": 6321,
"s": 6281,
"text": "To run the code, type python Dev-Rec.py"
},
{
"code": null,
"e": 6339,
"s": 6321,
"text": "python Dev-Rec.py"
},
{
"code": null,
"e": 6350,
"s": 6339,
"text": "github.com"
},
{
"code": null,
"e": 6828,
"s": 6350,
"text": "This code helps in facial recognition using facenets (https://arxiv.org/pdf/1503.03832.pdf). The concept of facenets was originally presented in a research paper. The main concepts talked about triplet loss function to compare images of different person. This concept uses inception network which has been taken from source and fr_utils.py is taken from deeplearning.ai for reference. I have added several functionalities of my own for providing stability and better detection."
},
{
"code": null,
"e": 6935,
"s": 6828,
"text": "You can install Conda for python which resolves all the dependencies for machine learning and you’ll need:"
},
{
"code": null,
"e": 6972,
"s": 6935,
"text": "numpymatplotlibcv2kerasdlibh5pyscipy"
},
{
"code": null,
"e": 7301,
"s": 6972,
"text": "A facial recognition system is a technology capable of identifying or verifying a person from a digital image or a video frame from a video source. There are multiples methods in which facial recognition systems work, but in general, they work by comparing selected facial features from given image with faces within a database."
},
{
"code": null,
"e": 7453,
"s": 7301,
"text": "Detecting face only when your eyes are opened. (Security measure).Using face align functionality from dlib to predict effectively while live streaming."
},
{
"code": null,
"e": 7520,
"s": 7453,
"text": "Detecting face only when your eyes are opened. (Security measure)."
},
{
"code": null,
"e": 7606,
"s": 7520,
"text": "Using face align functionality from dlib to predict effectively while live streaming."
},
{
"code": null,
"e": 7672,
"s": 7606,
"text": "Network Used- Inception NetworkOriginal Paper — Facenet by Google"
},
{
"code": null,
"e": 7704,
"s": 7672,
"text": "Network Used- Inception Network"
},
{
"code": null,
"e": 7739,
"s": 7704,
"text": "Original Paper — Facenet by Google"
},
{
"code": null,
"e": 8272,
"s": 7739,
"text": "If you want to train the network , run Train-inception.py, however you don't need to do that since I have already trained the model and saved it as face-rec_Google.h5 file which gets loaded at runtime.Now you need to have images in your database. The code check /images folder for that. You can either paste your pictures there or you can click it using web cam. For doing that, run create-face.py the images get stored in /incept folder. You have to manually paste them in /images folderRun rec-feat.py for running the application."
},
{
"code": null,
"e": 8474,
"s": 8272,
"text": "If you want to train the network , run Train-inception.py, however you don't need to do that since I have already trained the model and saved it as face-rec_Google.h5 file which gets loaded at runtime."
},
{
"code": null,
"e": 8762,
"s": 8474,
"text": "Now you need to have images in your database. The code check /images folder for that. You can either paste your pictures there or you can click it using web cam. For doing that, run create-face.py the images get stored in /incept folder. You have to manually paste them in /images folder"
},
{
"code": null,
"e": 8807,
"s": 8762,
"text": "Run rec-feat.py for running the application."
},
{
"code": null,
"e": 8818,
"s": 8807,
"text": "github.com"
},
{
"code": null,
"e": 8929,
"s": 8818,
"text": "This code helps you to recognize and classify different emojis. As of now, we are only supporting hand emojis."
},
{
"code": null,
"e": 9036,
"s": 8929,
"text": "You can install Conda for python which resolves all the dependencies for machine learning and you’ll need:"
},
{
"code": null,
"e": 9073,
"s": 9036,
"text": "numpymatplotlibcv2kerasdlibh5pyscipy"
},
{
"code": null,
"e": 9353,
"s": 9073,
"text": "Emojis are ideograms and smileys used in electronic messages and web pages. Emoji exist in various genres, including facial expressions, common objects, places and types of weather, and animals. They are much like emoticons, but emoji are actual pictures instead of typographics."
},
{
"code": null,
"e": 9404,
"s": 9353,
"text": "Filters to detect hand.CNN for training the model."
},
{
"code": null,
"e": 9428,
"s": 9404,
"text": "Filters to detect hand."
},
{
"code": null,
"e": 9456,
"s": 9428,
"text": "CNN for training the model."
},
{
"code": null,
"e": 9499,
"s": 9456,
"text": "Network Used- Convolutional Neural Network"
},
{
"code": null,
"e": 9542,
"s": 9499,
"text": "Network Used- Convolutional Neural Network"
},
{
"code": null,
"e": 10190,
"s": 9542,
"text": "First, you have to create a gesture database. For that, run CreateGest.py. Enter the gesture name and you will get 2 frames displayed. Look at the contour frame and adjust your hand to make sure that you capture the features of your hand. Press 'c' for capturing the images. It will take 1200 images of one gesture. Try moving your hand a little within the frame to make sure that your model doesn't overfit at the time of training.Repeat this for all the features you want.Run CreateCSV.py for converting the images to a CSV fileIf you want to train the model, run ‘TrainEmojinator.py’Finally, run Emojinator.py for testing your model via webcam."
},
{
"code": null,
"e": 10623,
"s": 10190,
"text": "First, you have to create a gesture database. For that, run CreateGest.py. Enter the gesture name and you will get 2 frames displayed. Look at the contour frame and adjust your hand to make sure that you capture the features of your hand. Press 'c' for capturing the images. It will take 1200 images of one gesture. Try moving your hand a little within the frame to make sure that your model doesn't overfit at the time of training."
},
{
"code": null,
"e": 10666,
"s": 10623,
"text": "Repeat this for all the features you want."
},
{
"code": null,
"e": 10723,
"s": 10666,
"text": "Run CreateCSV.py for converting the images to a CSV file"
},
{
"code": null,
"e": 10780,
"s": 10723,
"text": "If you want to train the model, run ‘TrainEmojinator.py’"
},
{
"code": null,
"e": 10842,
"s": 10780,
"text": "Finally, run Emojinator.py for testing your model via webcam."
},
{
"code": null,
"e": 10878,
"s": 10842,
"text": "Akshay Bahadur and Raghav Patnecha."
},
{
"code": null,
"e": 11088,
"s": 10878,
"text": "I can only say I’m incredibly impress on these projects, all of them you can run them on your computer, or more easily on Deep Cognition’s platform if you don’t want to install anything, and it can run online."
},
{
"code": null,
"e": 11424,
"s": 11088,
"text": "I want to thank Akshay and his friends for making this great Open Source contributions and for all the others that will come. Try them, run them, and get inspired. This is only a small example of the amazing things DL and CV can do, and is up to you to take this an turn it into something that can help the world become a better place."
},
{
"code": null,
"e": 11798,
"s": 11424,
"text": "Never give up, we need everyone to be interested in lots of different things. I think we can change the world for the better, improve our lives, the way we work, think and solve problems, and if we channel all the resources we have right now to make these area of knowledge to work together for a greater good, we can make a huge positive impact in the world and our lives."
},
{
"code": null,
"e": 11870,
"s": 11798,
"text": "Thanks for reading this. I hope you found something interesting here :)"
},
{
"code": null,
"e": 11916,
"s": 11870,
"text": "If you have questions just add me in twitter:"
},
{
"code": null,
"e": 11928,
"s": 11916,
"text": "twitter.com"
},
{
"code": null,
"e": 11942,
"s": 11928,
"text": "and LinkedIn:"
},
{
"code": null,
"e": 11955,
"s": 11942,
"text": "linkedin.com"
},
{
"code": null,
"e": 11972,
"s": 11955,
"text": "See you there :)"
}
] |
How to set hamburger items on the right in bootstrap 4 ? - GeeksforGeeks | 30 Nov, 2019
In Bootstrap 4, NavBar is an essential component for menu purposes. To align menu items to right by using float-right class is works well in Bootstrap 3, but it doesn’t work in Bootstrap 4 because the navbar is now flexbox. The following approach will explain clearly.
In Bootstrap 4, NavBar contains so many items like text, link text, disable the link, dropdown buttons, forms, etc. To align text, link text, disable link and dropdown buttons to the right use class=”text-right”. But for forms use form class=”flex-row-reverse” to align right within NavBar. Using CSS properties might also help to align right within NavBar if the default class not needed.
Below example illustrates how to set hamburger items on the right in bootstrap 4.
Example:
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <center> <div class="container"> <h1 style="color:green;padding:13px;"> GeeksforGeeeks </h1> <h3>Hamburger items on the right in bootstrap 4</h3> <br> <nav class="navbar navbar-expand-lg navbar-dark justify-content-between text-white" style="background-color: #0074D9;"> <a class="navbar-brand" href="#"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/gfg_transparent_white_small.png" width="30" height="30" class="d-inline-block align-top" alt=""> GeeksforGeeeks BS4 Navbar </a> <button class="navbar-toggler bg-light" type="button" data-toggle="collapse" data-target="#navbarNavDropdown01" aria-controls="navbarNavDropdown01" aria-expanded="false" aria-label="Toggle navigation" style="outline-color:white"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse bg-info m-2 p-4" id="navbarNavDropdown01"> <!-- form item of menu for search purpose --> <form class="form-inline flex-row-reverse "> <button class="btn btn-success my-2 my-sm-0 bg-primary" type="submit"> Search </button> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> </form> <!-- Active item text of menu --> <ul class="navbar-nav text-right mr-4"> <li class="nav-item active"> <a class="nav-link" href="#"> Home<span class="sr-only">(current)</span> </a> </li> <!-- inactive link text item of menu --> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <!-- dropdown item of menu --> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <!-- dropdown sub items of menu --> <div class="dropdown-menu text-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#"> Action </a> <a class="dropdown-item" href="#"> Another action </a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#"> Something else here </a> </div> </li> <!-- disable link text item of menu --> <li class="nav-item "> <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true"> Disabled </a> </li> </ul> </div> </nav> </div> </center></body> </html>
Output:
Reference: https://getbootstrap.com/docs/4.0/components/navbar/
Bootstrap-4
Bootstrap-Misc
Picked
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to change the background color of the active nav-item?
How to Use Bootstrap with React?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 24834,
"s": 24806,
"text": "\n30 Nov, 2019"
},
{
"code": null,
"e": 25103,
"s": 24834,
"text": "In Bootstrap 4, NavBar is an essential component for menu purposes. To align menu items to right by using float-right class is works well in Bootstrap 3, but it doesn’t work in Bootstrap 4 because the navbar is now flexbox. The following approach will explain clearly."
},
{
"code": null,
"e": 25493,
"s": 25103,
"text": "In Bootstrap 4, NavBar contains so many items like text, link text, disable the link, dropdown buttons, forms, etc. To align text, link text, disable link and dropdown buttons to the right use class=”text-right”. But for forms use form class=”flex-row-reverse” to align right within NavBar. Using CSS properties might also help to align right within NavBar if the default class not needed."
},
{
"code": null,
"e": 25575,
"s": 25493,
"text": "Below example illustrates how to set hamburger items on the right in bootstrap 4."
},
{
"code": null,
"e": 25584,
"s": 25575,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <center> <div class=\"container\"> <h1 style=\"color:green;padding:13px;\"> GeeksforGeeeks </h1> <h3>Hamburger items on the right in bootstrap 4</h3> <br> <nav class=\"navbar navbar-expand-lg navbar-dark justify-content-between text-white\" style=\"background-color: #0074D9;\"> <a class=\"navbar-brand\" href=\"#\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/gfg_transparent_white_small.png\" width=\"30\" height=\"30\" class=\"d-inline-block align-top\" alt=\"\"> GeeksforGeeeks BS4 Navbar </a> <button class=\"navbar-toggler bg-light\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarNavDropdown01\" aria-controls=\"navbarNavDropdown01\" aria-expanded=\"false\" aria-label=\"Toggle navigation\" style=\"outline-color:white\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse bg-info m-2 p-4\" id=\"navbarNavDropdown01\"> <!-- form item of menu for search purpose --> <form class=\"form-inline flex-row-reverse \"> <button class=\"btn btn-success my-2 my-sm-0 bg-primary\" type=\"submit\"> Search </button> <input class=\"form-control mr-sm-2\" type=\"search\" placeholder=\"Search\" aria-label=\"Search\"> </form> <!-- Active item text of menu --> <ul class=\"navbar-nav text-right mr-4\"> <li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\"> Home<span class=\"sr-only\">(current)</span> </a> </li> <!-- inactive link text item of menu --> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">Link</a> </li> <!-- dropdown item of menu --> <li class=\"nav-item dropdown\"> <a class=\"nav-link dropdown-toggle\" href=\"#\" id=\"navbarDropdown\" role=\"button\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\"> Dropdown </a> <!-- dropdown sub items of menu --> <div class=\"dropdown-menu text-right\" aria-labelledby=\"navbarDropdown\"> <a class=\"dropdown-item\" href=\"#\"> Action </a> <a class=\"dropdown-item\" href=\"#\"> Another action </a> <div class=\"dropdown-divider\"></div> <a class=\"dropdown-item\" href=\"#\"> Something else here </a> </div> </li> <!-- disable link text item of menu --> <li class=\"nav-item \"> <a class=\"nav-link disabled\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\"> Disabled </a> </li> </ul> </div> </nav> </div> </center></body> </html>",
"e": 30490,
"s": 25584,
"text": null
},
{
"code": null,
"e": 30498,
"s": 30490,
"text": "Output:"
},
{
"code": null,
"e": 30562,
"s": 30498,
"text": "Reference: https://getbootstrap.com/docs/4.0/components/navbar/"
},
{
"code": null,
"e": 30574,
"s": 30562,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 30589,
"s": 30574,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 30596,
"s": 30589,
"text": "Picked"
},
{
"code": null,
"e": 30606,
"s": 30596,
"text": "Bootstrap"
},
{
"code": null,
"e": 30623,
"s": 30606,
"text": "Web Technologies"
},
{
"code": null,
"e": 30650,
"s": 30623,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30748,
"s": 30650,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30789,
"s": 30748,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 30830,
"s": 30789,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 30893,
"s": 30830,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 30952,
"s": 30893,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 30985,
"s": 30952,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 31027,
"s": 30985,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 31060,
"s": 31027,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31103,
"s": 31060,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31153,
"s": 31103,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
'dd' command in Linux - GeeksforGeeks | 10 Apr, 2022
dd is a command-line utility for Unix and Unix-like operating systems whose primary purpose is to convert and copy files.
On Unix, device drivers for hardware (such as hard disk drives) and special device files (such as /dev/zero and /dev/random) appear in the file system just like normal files.
dd can also read and/or write from/to these files, provided that function is implemented in their respective drivers
As a result, dd can be used for tasks such as backing up the boot sector of a hard drive, and obtaining a fixed amount of random data.
The dd program can also perform conversions on the data as it is copied, including byte order swapping and conversion to and from the ASCII and EBCDIC text encodings.
Usage : The command line syntax of dd differs from many other Unix programs, in that it uses the syntax option=value for its command line options, rather than the more-standard -option value or –option=value formats. By default, dd reads from stdin and writes to stdout, but these can be changed by using the if (input file) and of (output file) options.
Some practical examples on dd command :
To backup the entire harddisk : To backup an entire copy of a hard disk to another hard disk connected to the same system, execute the dd command as shown. In this dd command example, the UNIX device name of the source hard disk is /dev/hda, and device name of the target hard disk is /dev/hdb.# dd if=/dev/sda of=/dev/sdb
“if” represents inputfile, and “of” represents output file. So the exact copy of /dev/sda will be available in /dev/sdb.If there are any errors, the above command will fail. If you give the parameter “conv=noerror” then it will continue to copy if there are read errors.Input file and output file should be mentioned very carefully. Just in case, you mention source device in the target and vice versa, you might loss all your data.To copy, hard drive to hard drive using dd command given below, sync option allows you to copy everything using synchronized I/O.# dd if=/dev/sda of=/dev/sdb conv=noerror, sync
To backup a Partition : You can use the device name of a partition in the input file, and in the output either you can specify your target path or image file as shown in the dd command.# dd if=/dev/hda1 of=~/partition.img
To create an image of a Hard Disk : Instead of taking a backup of the hard disk, you can create an image file of the hard disk and save it in other storage devices. There are many advantages of backing up your data to a disk image, one being the ease of use. This method is typically faster than other types of backups, enabling you to quickly restore data following an unexpected catastrophe.It creates the image of a hard disk /dev/hda.# dd if=/dev/hda of=~/hdadisk.img
To restore using the Hard Disk Image : To restore a hard disk with the image file of an another hard disk, the following dd command can be used# dd if=hdadisk.img of=/dev/hdb
The image file hdadisk.img file, is the image of a /dev/hda, so the above command will restore the image of /dev/hda to /dev/hdb.To create CDROM Backup : dd command allows you to create an iso file from a source file. So we can insert the CD and enter dd command to create an iso file of a CD content.# dd if=/dev/cdrom of=tgsservice.iso bs=2048
dd command reads one block of input and process it and writes it into an output file. You can specify the block size for input and output file. In the above dd command example, the parameter “bs” specifies the block size for the both the input and output file. So dd uses 2048bytes as a block size in the above command.
To backup the entire harddisk : To backup an entire copy of a hard disk to another hard disk connected to the same system, execute the dd command as shown. In this dd command example, the UNIX device name of the source hard disk is /dev/hda, and device name of the target hard disk is /dev/hdb.# dd if=/dev/sda of=/dev/sdb
“if” represents inputfile, and “of” represents output file. So the exact copy of /dev/sda will be available in /dev/sdb.If there are any errors, the above command will fail. If you give the parameter “conv=noerror” then it will continue to copy if there are read errors.Input file and output file should be mentioned very carefully. Just in case, you mention source device in the target and vice versa, you might loss all your data.To copy, hard drive to hard drive using dd command given below, sync option allows you to copy everything using synchronized I/O.# dd if=/dev/sda of=/dev/sdb conv=noerror, sync
# dd if=/dev/sda of=/dev/sdb
“if” represents inputfile, and “of” represents output file. So the exact copy of /dev/sda will be available in /dev/sdb.
If there are any errors, the above command will fail. If you give the parameter “conv=noerror” then it will continue to copy if there are read errors.
Input file and output file should be mentioned very carefully. Just in case, you mention source device in the target and vice versa, you might loss all your data.
To copy, hard drive to hard drive using dd command given below, sync option allows you to copy everything using synchronized I/O.# dd if=/dev/sda of=/dev/sdb conv=noerror, sync
# dd if=/dev/sda of=/dev/sdb conv=noerror, sync
To backup a Partition : You can use the device name of a partition in the input file, and in the output either you can specify your target path or image file as shown in the dd command.# dd if=/dev/hda1 of=~/partition.img
# dd if=/dev/hda1 of=~/partition.img
To create an image of a Hard Disk : Instead of taking a backup of the hard disk, you can create an image file of the hard disk and save it in other storage devices. There are many advantages of backing up your data to a disk image, one being the ease of use. This method is typically faster than other types of backups, enabling you to quickly restore data following an unexpected catastrophe.It creates the image of a hard disk /dev/hda.# dd if=/dev/hda of=~/hdadisk.img
# dd if=/dev/hda of=~/hdadisk.img
To restore using the Hard Disk Image : To restore a hard disk with the image file of an another hard disk, the following dd command can be used# dd if=hdadisk.img of=/dev/hdb
The image file hdadisk.img file, is the image of a /dev/hda, so the above command will restore the image of /dev/hda to /dev/hdb.
# dd if=hdadisk.img of=/dev/hdb
The image file hdadisk.img file, is the image of a /dev/hda, so the above command will restore the image of /dev/hda to /dev/hdb.
To create CDROM Backup : dd command allows you to create an iso file from a source file. So we can insert the CD and enter dd command to create an iso file of a CD content.# dd if=/dev/cdrom of=tgsservice.iso bs=2048
dd command reads one block of input and process it and writes it into an output file. You can specify the block size for input and output file. In the above dd command example, the parameter “bs” specifies the block size for the both the input and output file. So dd uses 2048bytes as a block size in the above command.
# dd if=/dev/cdrom of=tgsservice.iso bs=2048
dd command reads one block of input and process it and writes it into an output file. You can specify the block size for input and output file. In the above dd command example, the parameter “bs” specifies the block size for the both the input and output file. So dd uses 2048bytes as a block size in the above command.
References :
dd command in Unix.
dd man page.
This article is contributed by Kishlay Verma. 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.
bbeaudoin
linux-command
Linux-file-commands
Linux-Unix
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
Tail command in Linux with examples
How to Find the Wi-Fi Password Using CMD in Windows?
How to Run a Python Script using Docker?
Docker - COPY Instruction
Running Python script on GPU.
Setting up the environment in Java | [
{
"code": null,
"e": 24002,
"s": 23974,
"text": "\n10 Apr, 2022"
},
{
"code": null,
"e": 24124,
"s": 24002,
"text": "dd is a command-line utility for Unix and Unix-like operating systems whose primary purpose is to convert and copy files."
},
{
"code": null,
"e": 24299,
"s": 24124,
"text": "On Unix, device drivers for hardware (such as hard disk drives) and special device files (such as /dev/zero and /dev/random) appear in the file system just like normal files."
},
{
"code": null,
"e": 24416,
"s": 24299,
"text": "dd can also read and/or write from/to these files, provided that function is implemented in their respective drivers"
},
{
"code": null,
"e": 24551,
"s": 24416,
"text": "As a result, dd can be used for tasks such as backing up the boot sector of a hard drive, and obtaining a fixed amount of random data."
},
{
"code": null,
"e": 24718,
"s": 24551,
"text": "The dd program can also perform conversions on the data as it is copied, including byte order swapping and conversion to and from the ASCII and EBCDIC text encodings."
},
{
"code": null,
"e": 25073,
"s": 24718,
"text": "Usage : The command line syntax of dd differs from many other Unix programs, in that it uses the syntax option=value for its command line options, rather than the more-standard -option value or –option=value formats. By default, dd reads from stdin and writes to stdout, but these can be changed by using the if (input file) and of (output file) options."
},
{
"code": null,
"e": 25113,
"s": 25073,
"text": "Some practical examples on dd command :"
},
{
"code": null,
"e": 27580,
"s": 25113,
"text": "To backup the entire harddisk : To backup an entire copy of a hard disk to another hard disk connected to the same system, execute the dd command as shown. In this dd command example, the UNIX device name of the source hard disk is /dev/hda, and device name of the target hard disk is /dev/hdb.# dd if=/dev/sda of=/dev/sdb\n“if” represents inputfile, and “of” represents output file. So the exact copy of /dev/sda will be available in /dev/sdb.If there are any errors, the above command will fail. If you give the parameter “conv=noerror” then it will continue to copy if there are read errors.Input file and output file should be mentioned very carefully. Just in case, you mention source device in the target and vice versa, you might loss all your data.To copy, hard drive to hard drive using dd command given below, sync option allows you to copy everything using synchronized I/O.# dd if=/dev/sda of=/dev/sdb conv=noerror, sync\nTo backup a Partition : You can use the device name of a partition in the input file, and in the output either you can specify your target path or image file as shown in the dd command.# dd if=/dev/hda1 of=~/partition.img\nTo create an image of a Hard Disk : Instead of taking a backup of the hard disk, you can create an image file of the hard disk and save it in other storage devices. There are many advantages of backing up your data to a disk image, one being the ease of use. This method is typically faster than other types of backups, enabling you to quickly restore data following an unexpected catastrophe.It creates the image of a hard disk /dev/hda.# dd if=/dev/hda of=~/hdadisk.img\nTo restore using the Hard Disk Image : To restore a hard disk with the image file of an another hard disk, the following dd command can be used# dd if=hdadisk.img of=/dev/hdb\nThe image file hdadisk.img file, is the image of a /dev/hda, so the above command will restore the image of /dev/hda to /dev/hdb.To create CDROM Backup : dd command allows you to create an iso file from a source file. So we can insert the CD and enter dd command to create an iso file of a CD content.# dd if=/dev/cdrom of=tgsservice.iso bs=2048\ndd command reads one block of input and process it and writes it into an output file. You can specify the block size for input and output file. In the above dd command example, the parameter “bs” specifies the block size for the both the input and output file. So dd uses 2048bytes as a block size in the above command."
},
{
"code": null,
"e": 28513,
"s": 27580,
"text": "To backup the entire harddisk : To backup an entire copy of a hard disk to another hard disk connected to the same system, execute the dd command as shown. In this dd command example, the UNIX device name of the source hard disk is /dev/hda, and device name of the target hard disk is /dev/hdb.# dd if=/dev/sda of=/dev/sdb\n“if” represents inputfile, and “of” represents output file. So the exact copy of /dev/sda will be available in /dev/sdb.If there are any errors, the above command will fail. If you give the parameter “conv=noerror” then it will continue to copy if there are read errors.Input file and output file should be mentioned very carefully. Just in case, you mention source device in the target and vice versa, you might loss all your data.To copy, hard drive to hard drive using dd command given below, sync option allows you to copy everything using synchronized I/O.# dd if=/dev/sda of=/dev/sdb conv=noerror, sync\n"
},
{
"code": null,
"e": 28543,
"s": 28513,
"text": "# dd if=/dev/sda of=/dev/sdb\n"
},
{
"code": null,
"e": 28664,
"s": 28543,
"text": "“if” represents inputfile, and “of” represents output file. So the exact copy of /dev/sda will be available in /dev/sdb."
},
{
"code": null,
"e": 28815,
"s": 28664,
"text": "If there are any errors, the above command will fail. If you give the parameter “conv=noerror” then it will continue to copy if there are read errors."
},
{
"code": null,
"e": 28978,
"s": 28815,
"text": "Input file and output file should be mentioned very carefully. Just in case, you mention source device in the target and vice versa, you might loss all your data."
},
{
"code": null,
"e": 29156,
"s": 28978,
"text": "To copy, hard drive to hard drive using dd command given below, sync option allows you to copy everything using synchronized I/O.# dd if=/dev/sda of=/dev/sdb conv=noerror, sync\n"
},
{
"code": null,
"e": 29205,
"s": 29156,
"text": "# dd if=/dev/sda of=/dev/sdb conv=noerror, sync\n"
},
{
"code": null,
"e": 29428,
"s": 29205,
"text": "To backup a Partition : You can use the device name of a partition in the input file, and in the output either you can specify your target path or image file as shown in the dd command.# dd if=/dev/hda1 of=~/partition.img\n"
},
{
"code": null,
"e": 29466,
"s": 29428,
"text": "# dd if=/dev/hda1 of=~/partition.img\n"
},
{
"code": null,
"e": 29939,
"s": 29466,
"text": "To create an image of a Hard Disk : Instead of taking a backup of the hard disk, you can create an image file of the hard disk and save it in other storage devices. There are many advantages of backing up your data to a disk image, one being the ease of use. This method is typically faster than other types of backups, enabling you to quickly restore data following an unexpected catastrophe.It creates the image of a hard disk /dev/hda.# dd if=/dev/hda of=~/hdadisk.img\n"
},
{
"code": null,
"e": 29974,
"s": 29939,
"text": "# dd if=/dev/hda of=~/hdadisk.img\n"
},
{
"code": null,
"e": 30279,
"s": 29974,
"text": "To restore using the Hard Disk Image : To restore a hard disk with the image file of an another hard disk, the following dd command can be used# dd if=hdadisk.img of=/dev/hdb\nThe image file hdadisk.img file, is the image of a /dev/hda, so the above command will restore the image of /dev/hda to /dev/hdb."
},
{
"code": null,
"e": 30312,
"s": 30279,
"text": "# dd if=hdadisk.img of=/dev/hdb\n"
},
{
"code": null,
"e": 30442,
"s": 30312,
"text": "The image file hdadisk.img file, is the image of a /dev/hda, so the above command will restore the image of /dev/hda to /dev/hdb."
},
{
"code": null,
"e": 30979,
"s": 30442,
"text": "To create CDROM Backup : dd command allows you to create an iso file from a source file. So we can insert the CD and enter dd command to create an iso file of a CD content.# dd if=/dev/cdrom of=tgsservice.iso bs=2048\ndd command reads one block of input and process it and writes it into an output file. You can specify the block size for input and output file. In the above dd command example, the parameter “bs” specifies the block size for the both the input and output file. So dd uses 2048bytes as a block size in the above command."
},
{
"code": null,
"e": 31025,
"s": 30979,
"text": "# dd if=/dev/cdrom of=tgsservice.iso bs=2048\n"
},
{
"code": null,
"e": 31345,
"s": 31025,
"text": "dd command reads one block of input and process it and writes it into an output file. You can specify the block size for input and output file. In the above dd command example, the parameter “bs” specifies the block size for the both the input and output file. So dd uses 2048bytes as a block size in the above command."
},
{
"code": null,
"e": 31358,
"s": 31345,
"text": "References :"
},
{
"code": null,
"e": 31378,
"s": 31358,
"text": "dd command in Unix."
},
{
"code": null,
"e": 31391,
"s": 31378,
"text": "dd man page."
},
{
"code": null,
"e": 31688,
"s": 31391,
"text": "This article is contributed by Kishlay Verma. 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": 31813,
"s": 31688,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31823,
"s": 31813,
"text": "bbeaudoin"
},
{
"code": null,
"e": 31837,
"s": 31823,
"text": "linux-command"
},
{
"code": null,
"e": 31857,
"s": 31837,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 31868,
"s": 31857,
"text": "Linux-Unix"
},
{
"code": null,
"e": 31877,
"s": 31868,
"text": "TechTips"
},
{
"code": null,
"e": 31975,
"s": 31877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32010,
"s": 31975,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 32048,
"s": 32010,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 32086,
"s": 32048,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 32121,
"s": 32086,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 32157,
"s": 32121,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 32210,
"s": 32157,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 32251,
"s": 32210,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 32277,
"s": 32251,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 32307,
"s": 32277,
"text": "Running Python script on GPU."
}
] |
Query for documents where array size is greater than 1 in MongoDB? | You can use length to query for documents where array size is greater than 1:
db.yourCollectionName.find({$where:"this.yourArrayDocumentName.length > 1"}).pretty();
To understand the above syntax, let us create a collection with some documents. The query is
as follows to create a collection with documents:
>db.arrayLengthGreaterThanOne.insertOne({"StudentName":"Larry","StudentTechnicalSubje
ct":["Java","C","C++"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6d6c4c0c3d5054b766a76a")
}
>db.arrayLengthGreaterThanOne.insertOne({"StudentName":"Maxwell","StudentTechnicalSu
bject":["MongoDB"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6d6c660c3d5054b766a76b")
}
>db.arrayLengthGreaterThanOne.insertOne({"StudentName":"Maxwell","StudentTechnicalSu
bject":["MySQL","SQL Server","PL/SQL"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6d6c800c3d5054b766a76c")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.arrayLengthGreaterThanOne.find().pretty();
The following is the output:
{
"_id" : ObjectId("5c6d6c4c0c3d5054b766a76a"),
"StudentName" : "Larry",
"StudentTechnicalSubject" : [
"Java",
"C",
"C++"
]
}
{
"_id" : ObjectId("5c6d6c660c3d5054b766a76b"),
"StudentName" : "Maxwell",
"StudentTechnicalSubject" : [
"MongoDB"
]
}
{
"_id" : ObjectId("5c6d6c800c3d5054b766a76c"),
"StudentName" : "Maxwell",
"StudentTechnicalSubject" : [
"MySQL",
"SQL Server",
"PL/SQL"
]
}
Here is the query for documents where array size is greater than 1. The below query will give all documents where array size is greater than 1:
> db.arrayLengthGreaterThanOne.find({$where:"this.StudentTechnicalSubject.length > 1"}).pretty();
The following is the output:
{
"_id" : ObjectId("5c6d6c4c0c3d5054b766a76a"),
"StudentName" : "Larry",
"StudentTechnicalSubject" : [
"Java",
"C",
"C++"
]
}
{
"_id" : ObjectId("5c6d6c800c3d5054b766a76c"),
"StudentName" : "Maxwell",
"StudentTechnicalSubject" : [
"MySQL",
"SQL Server",
"PL/SQL"
]
} | [
{
"code": null,
"e": 1140,
"s": 1062,
"text": "You can use length to query for documents where array size is greater than 1:"
},
{
"code": null,
"e": 1227,
"s": 1140,
"text": "db.yourCollectionName.find({$where:\"this.yourArrayDocumentName.length > 1\"}).pretty();"
},
{
"code": null,
"e": 1370,
"s": 1227,
"text": "To understand the above syntax, let us create a collection with some documents. The query is\nas follows to create a collection with documents:"
},
{
"code": null,
"e": 1971,
"s": 1370,
"text": ">db.arrayLengthGreaterThanOne.insertOne({\"StudentName\":\"Larry\",\"StudentTechnicalSubje\nct\":[\"Java\",\"C\",\"C++\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6d6c4c0c3d5054b766a76a\")\n}\n>db.arrayLengthGreaterThanOne.insertOne({\"StudentName\":\"Maxwell\",\"StudentTechnicalSu\nbject\":[\"MongoDB\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6d6c660c3d5054b766a76b\")\n}\n>db.arrayLengthGreaterThanOne.insertOne({\"StudentName\":\"Maxwell\",\"StudentTechnicalSu\nbject\":[\"MySQL\",\"SQL Server\",\"PL/SQL\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6d6c800c3d5054b766a76c\")\n}"
},
{
"code": null,
"e": 2068,
"s": 1971,
"text": "Display all documents from a collection with the help of find() method. The query is as follows:"
},
{
"code": null,
"e": 2116,
"s": 2068,
"text": "> db.arrayLengthGreaterThanOne.find().pretty();"
},
{
"code": null,
"e": 2145,
"s": 2116,
"text": "The following is the output:"
},
{
"code": null,
"e": 2609,
"s": 2145,
"text": "{\n \"_id\" : ObjectId(\"5c6d6c4c0c3d5054b766a76a\"),\n \"StudentName\" : \"Larry\",\n \"StudentTechnicalSubject\" : [\n \"Java\",\n \"C\",\n \"C++\"\n ]\n}\n{\n \"_id\" : ObjectId(\"5c6d6c660c3d5054b766a76b\"),\n \"StudentName\" : \"Maxwell\",\n \"StudentTechnicalSubject\" : [\n \"MongoDB\"\n ]\n}\n{\n \"_id\" : ObjectId(\"5c6d6c800c3d5054b766a76c\"),\n \"StudentName\" : \"Maxwell\",\n \"StudentTechnicalSubject\" : [\n \"MySQL\",\n \"SQL Server\",\n \"PL/SQL\"\n ]\n}"
},
{
"code": null,
"e": 2753,
"s": 2609,
"text": "Here is the query for documents where array size is greater than 1. The below query will give all documents where array size is greater than 1:"
},
{
"code": null,
"e": 2851,
"s": 2753,
"text": "> db.arrayLengthGreaterThanOne.find({$where:\"this.StudentTechnicalSubject.length > 1\"}).pretty();"
},
{
"code": null,
"e": 2880,
"s": 2851,
"text": "The following is the output:"
},
{
"code": null,
"e": 3207,
"s": 2880,
"text": "{\n \"_id\" : ObjectId(\"5c6d6c4c0c3d5054b766a76a\"),\n \"StudentName\" : \"Larry\",\n \"StudentTechnicalSubject\" : [\n \"Java\",\n \"C\",\n \"C++\"\n ]\n}\n{\n \"_id\" : ObjectId(\"5c6d6c800c3d5054b766a76c\"),\n \"StudentName\" : \"Maxwell\",\n \"StudentTechnicalSubject\" : [\n \"MySQL\",\n \"SQL Server\",\n \"PL/SQL\"\n ]\n}"
}
] |
Java Generics - List | Java has provided generic support in List interface.
List<T> list = new ArrayList<T>();
Where
list − object of List interface.
list − object of List interface.
T − The generic type parameter passed during list declaration.
T − The generic type parameter passed during list declaration.
The T is a type parameter passed to the generic interface List and its implemenation class ArrayList.
Create the following java program using any editor of your choice.
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GenericsTester {
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<Integer>();
integerList.add(Integer.valueOf(10));
integerList.add(Integer.valueOf(11));
List<String> stringList = new ArrayList<String>();
stringList.add("Hello World");
stringList.add("Hi World");
System.out.printf("Integer Value :%d\n", integerList.get(0));
System.out.printf("String Value :%s\n", stringList.get(0));
for(Integer data: integerList) {
System.out.printf("Integer Value :%d\n", data);
}
Iterator<String> stringIterator = stringList.iterator();
while(stringIterator.hasNext()) {
System.out.printf("String Value :%s\n", stringIterator.next());
}
}
}
This will produce the following result −
Integer Value :10
String Value :Hello World
Integer Value :10
Integer Value :11
String Value :Hello World
String Value :Hi World
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2693,
"s": 2640,
"text": "Java has provided generic support in List interface."
},
{
"code": null,
"e": 2729,
"s": 2693,
"text": "List<T> list = new ArrayList<T>();\n"
},
{
"code": null,
"e": 2735,
"s": 2729,
"text": "Where"
},
{
"code": null,
"e": 2768,
"s": 2735,
"text": "list − object of List interface."
},
{
"code": null,
"e": 2801,
"s": 2768,
"text": "list − object of List interface."
},
{
"code": null,
"e": 2864,
"s": 2801,
"text": "T − The generic type parameter passed during list declaration."
},
{
"code": null,
"e": 2927,
"s": 2864,
"text": "T − The generic type parameter passed during list declaration."
},
{
"code": null,
"e": 3029,
"s": 2927,
"text": "The T is a type parameter passed to the generic interface List and its implemenation class ArrayList."
},
{
"code": null,
"e": 3096,
"s": 3029,
"text": "Create the following java program using any editor of your choice."
},
{
"code": null,
"e": 3999,
"s": 3096,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\npublic class GenericsTester {\n public static void main(String[] args) {\n\n List<Integer> integerList = new ArrayList<Integer>();\n \n integerList.add(Integer.valueOf(10));\n integerList.add(Integer.valueOf(11));\n\n List<String> stringList = new ArrayList<String>();\n \n stringList.add(\"Hello World\");\n stringList.add(\"Hi World\");\n \n\n System.out.printf(\"Integer Value :%d\\n\", integerList.get(0));\n System.out.printf(\"String Value :%s\\n\", stringList.get(0));\n\n for(Integer data: integerList) {\n System.out.printf(\"Integer Value :%d\\n\", data);\n }\n\n Iterator<String> stringIterator = stringList.iterator();\n\n while(stringIterator.hasNext()) {\n System.out.printf(\"String Value :%s\\n\", stringIterator.next());\n }\n } \n}"
},
{
"code": null,
"e": 4040,
"s": 3999,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4170,
"s": 4040,
"text": "Integer Value :10\nString Value :Hello World\nInteger Value :10\nInteger Value :11\nString Value :Hello World\nString Value :Hi World\n"
},
{
"code": null,
"e": 4203,
"s": 4170,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4219,
"s": 4203,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4252,
"s": 4219,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4268,
"s": 4252,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4303,
"s": 4268,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4317,
"s": 4303,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4351,
"s": 4317,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4365,
"s": 4351,
"text": " Tushar Kale"
},
{
"code": null,
"e": 4402,
"s": 4365,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4417,
"s": 4402,
"text": " Monica Mittal"
},
{
"code": null,
"e": 4450,
"s": 4417,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4469,
"s": 4450,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4476,
"s": 4469,
"text": " Print"
},
{
"code": null,
"e": 4487,
"s": 4476,
"text": " Add Notes"
}
] |
Local Development Set-Up of PostgreSQL with Docker | by Cesar Flores | Towards Data Science | When you are facing a project or a tech assignment on which you have to work with SQL, you either need access to a DB or you need to install it in your local. Either of them is very annoying, so I’m explaining what I normally do when I face this situation, while I wait for the full infrastructure and access to be provided.
In this short post, I will guide you through the process of running a PostgreSQL container along with a pgAdmin container. After that, I will show you how to connect to the database instance using the pgAdmin portal to run your queries. You can use this as a simple setup for development purposes with SQL, as part of your application or simply to practice your SQL skills.
I will be using Docker (version 19.03.8), so make sure you have it installed on your machine.
What we will do here is to first download the PostgreSQL image, check that the image is ready and finally run the image with specific parameters.
You can download the Docker official image for Postgres from the docker hub repository by running the following in your command line.
$ docker pull postgres
You can find the documentation of the image here: PostgreSQL Image Documentation.
After downloading the image you can check that is available to use:
$ docker images>>>REPOSITORY TAG IMAGE ID CREATED SIZEpostgres latest 9907cacf0c01 2 weeks ago 314MB
We will create a local folder and mount it as a data volume for our running container to store all the database files in a known location for you. In the “run” command, we will map also the ports from the host to the running container and a password for the Postgres default user.
## 1. Create a folder in a known location for you$ mkdir ${HOME}/postgres-data/## 2. run the postgres image$ docker run -d \ --name dev-postgres \ -e POSTGRES_PASSWORD=Pass2020! \ -v ${HOME}/postgres-data/:/var/lib/postgresql/data \ -p 5432:5432 postgres## 3. check that the container is running$ docker ps>>>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESdfa570d6e843 postgres "docker-entrypoint.s..." 27 hours ago Up 3 seconds 0.0.0.0:5432->5432/tcp postgres-test
Great, you have a running PostgreSQL instance and you should be able to enter the container from your command line and test the database instance:
$ docker exec -it dev-postgres bash>>> Now you are in the container's bash console. Connect to the databaseroot@dfa570d6e843:/# psql -h localhost -U postgres>>>psql (12.2 (Debian 12.2-2.pgdg100+1))Type "help" for help.postgres-# \lList of databasesName | Owner | Encoding | Collate | Ctype | ...-----------+----------+----------+------------+------------+------postgres | postgres | UTF8 | en_US.utf8 | en_US.utf8 | ...
You should see the Postgres database and a similar output as the one above.
That’s all for the database service, let’s set up the DB admin tool now.
pgAdmin is the most popular and feature-rich Open Source administration and development platform for PostgreSQL. You will use it to manage the DB instance as well as to run your queries against the tables of it.
You will be using this docker image to deploy it in a container. Get the image and run the instance of the image with the following commands:
$ docker pull dpage/pgadmin4$ docker run \ -p 80:80 \ -e '[email protected]' \ -e 'PGADMIN_DEFAULT_PASSWORD=SuperSecret' \ --name dev-pgadmin \ -d dpage/pgadmin4
The parameters that we are passing to the docker run command are:
-p 80:80: This parameter tells docker to map the port 80 in the container to port 80 in your computer (Docker host)
-e 'PGADMIN_DEFAULT_EMAIL: Environment variable for default user’s email, you will use this to log in the portal afterwards
-e 'PGADMIN_DEFAULT_PASSWORD': Environment variable for default user’s password
-d: This parameters tells docker to start the container in detached mode
dpage/pgadmin4: This parameter tells docker to use the image that we have previously downloaded
Let’s check that the container is up and running, you should also see the previous container running:
$ docker ps>>>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES7b15fe4c1cbd dpage/pgadmin4 "/entrypoint.sh" 43 hours ago Up 5 seconds 0.0.0.0:80->80/tcp, 443/tcp dev-pgadmin
That’s all you have all the services up and running. The next step is to connect from the pgAdmin console to the PostgreSQL instance.
We haven’t defined any network for these containers so they should be running on the default one, and if you try to access the database or the web portal through their ports, connecting via ‘localhost’ or ‘127.0.0.1’ would work just fine; but if you try connecting from one container to the other, you might encounter some connectivity issues.
We will need to look for the IP address of the PostgreSQL container on our host, you can run this command for it:
$ docker inspect dev-postgres -f "{{json .NetworkSettings.Networks }}"
docker inspect return low-level information of Docker objects, in this case, the ‘dev-postgres’ instance’s IP Adress. The -f parameter is to format the output as a JSON given a Go template. The output should look like this:
{"bridge":{"IPAMConfig":null,"Links":null,"Aliases":null,"NetworkID":"60c21f5cfcaaff424a0e4a22463dc8f9a285993de04e7ac19ce5fd96bba56a47","EndpointID":"be6e45b659c30bd12aa766d7003a2887607053684b68574e426f8823104b18a2","Gateway":"172.17.0.1","IPAddress":"172.17.0.2","IPPrefixLen":16,"IPv6Gateway":"","GlobalIPv6Address":"","GlobalIPv6PrefixLen":0,"MacAddress":"02:42:ac:11:00:02","DriverOpts":null}}
Copy the IPAddress value into the clipboard, which is 172.17.0.2 in my case, you will need to define the connection in the pgAdmin tool.
The next step is to go to your web browser and type http://localhost:80.
You should type the user email and the password you wrote when running the container.
Once you are in the portal, you will need to add a new server by clicking on the “Add New Server” and adding the right information on the pop-up window, make sure you add the IPAdress that you copied previously in the Host name/address under the Connection tab.
Once you have created the connection you should see the server on the right side of your screen. At this moment you are ready to start building your databases and tables, uploading data and querying for your analysis or applications.
Let’s recap on what we have done so far:
independently run a PostgreSQL instance with Dockerindependently run a pgAdmin server with DockerSetup the connection between the pgAdmin and PostgreSQL
independently run a PostgreSQL instance with Docker
independently run a pgAdmin server with Docker
Setup the connection between the pgAdmin and PostgreSQL
You should be ready to start developing your databases, tables and queries on pgAdmin directly to your PostgreSQL. You can use the UI to import files directly to the tables.
Something else that you can do here is to connect to this database from a Python application on your local and then load the results to this Postgres database and query the tables using either python or the pgAdmin tool. It is up to you how you use this stack, the good thing is that you don’t need to wait for an infra guy to give you access to a database to start working on your main objective, which is your analysis, app, feature or simply SQL training (even for your next technical interview assignment).
You can also do all this setup using a Docker-compose file, where you define the PostgreSQL service and pgAdmin service along with the environment variables, volume and port mapping and run docker-compose up. The results should be the same.
I hope this article provided you with enough information about how to set up an SQL instance on your computer with Docker to directly work with databases, tables and queries. Let me know if you have any questions or suggestions, I’ll be happy to follow-up with you. | [
{
"code": null,
"e": 497,
"s": 172,
"text": "When you are facing a project or a tech assignment on which you have to work with SQL, you either need access to a DB or you need to install it in your local. Either of them is very annoying, so I’m explaining what I normally do when I face this situation, while I wait for the full infrastructure and access to be provided."
},
{
"code": null,
"e": 871,
"s": 497,
"text": "In this short post, I will guide you through the process of running a PostgreSQL container along with a pgAdmin container. After that, I will show you how to connect to the database instance using the pgAdmin portal to run your queries. You can use this as a simple setup for development purposes with SQL, as part of your application or simply to practice your SQL skills."
},
{
"code": null,
"e": 965,
"s": 871,
"text": "I will be using Docker (version 19.03.8), so make sure you have it installed on your machine."
},
{
"code": null,
"e": 1111,
"s": 965,
"text": "What we will do here is to first download the PostgreSQL image, check that the image is ready and finally run the image with specific parameters."
},
{
"code": null,
"e": 1245,
"s": 1111,
"text": "You can download the Docker official image for Postgres from the docker hub repository by running the following in your command line."
},
{
"code": null,
"e": 1268,
"s": 1245,
"text": "$ docker pull postgres"
},
{
"code": null,
"e": 1350,
"s": 1268,
"text": "You can find the documentation of the image here: PostgreSQL Image Documentation."
},
{
"code": null,
"e": 1418,
"s": 1350,
"text": "After downloading the image you can check that is available to use:"
},
{
"code": null,
"e": 1556,
"s": 1418,
"text": "$ docker images>>>REPOSITORY TAG IMAGE ID CREATED SIZEpostgres latest 9907cacf0c01 2 weeks ago 314MB"
},
{
"code": null,
"e": 1837,
"s": 1556,
"text": "We will create a local folder and mount it as a data volume for our running container to store all the database files in a known location for you. In the “run” command, we will map also the ports from the host to the running container and a password for the Postgres default user."
},
{
"code": null,
"e": 2441,
"s": 1837,
"text": "## 1. Create a folder in a known location for you$ mkdir ${HOME}/postgres-data/## 2. run the postgres image$ docker run -d \\\t--name dev-postgres \\\t-e POSTGRES_PASSWORD=Pass2020! \\\t-v ${HOME}/postgres-data/:/var/lib/postgresql/data \\ -p 5432:5432 postgres## 3. check that the container is running$ docker ps>>>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESdfa570d6e843 postgres \"docker-entrypoint.s...\" 27 hours ago Up 3 seconds 0.0.0.0:5432->5432/tcp postgres-test"
},
{
"code": null,
"e": 2588,
"s": 2441,
"text": "Great, you have a running PostgreSQL instance and you should be able to enter the container from your command line and test the database instance:"
},
{
"code": null,
"e": 3035,
"s": 2588,
"text": "$ docker exec -it dev-postgres bash>>> Now you are in the container's bash console. Connect to the databaseroot@dfa570d6e843:/# psql -h localhost -U postgres>>>psql (12.2 (Debian 12.2-2.pgdg100+1))Type \"help\" for help.postgres-# \\lList of databasesName | Owner | Encoding | Collate | Ctype | ...-----------+----------+----------+------------+------------+------postgres | postgres | UTF8 | en_US.utf8 | en_US.utf8 | ..."
},
{
"code": null,
"e": 3111,
"s": 3035,
"text": "You should see the Postgres database and a similar output as the one above."
},
{
"code": null,
"e": 3184,
"s": 3111,
"text": "That’s all for the database service, let’s set up the DB admin tool now."
},
{
"code": null,
"e": 3396,
"s": 3184,
"text": "pgAdmin is the most popular and feature-rich Open Source administration and development platform for PostgreSQL. You will use it to manage the DB instance as well as to run your queries against the tables of it."
},
{
"code": null,
"e": 3538,
"s": 3396,
"text": "You will be using this docker image to deploy it in a container. Get the image and run the instance of the image with the following commands:"
},
{
"code": null,
"e": 3739,
"s": 3538,
"text": "$ docker pull dpage/pgadmin4$ docker run \\ -p 80:80 \\ -e '[email protected]' \\ -e 'PGADMIN_DEFAULT_PASSWORD=SuperSecret' \\ --name dev-pgadmin \\ -d dpage/pgadmin4"
},
{
"code": null,
"e": 3805,
"s": 3739,
"text": "The parameters that we are passing to the docker run command are:"
},
{
"code": null,
"e": 3921,
"s": 3805,
"text": "-p 80:80: This parameter tells docker to map the port 80 in the container to port 80 in your computer (Docker host)"
},
{
"code": null,
"e": 4045,
"s": 3921,
"text": "-e 'PGADMIN_DEFAULT_EMAIL: Environment variable for default user’s email, you will use this to log in the portal afterwards"
},
{
"code": null,
"e": 4125,
"s": 4045,
"text": "-e 'PGADMIN_DEFAULT_PASSWORD': Environment variable for default user’s password"
},
{
"code": null,
"e": 4198,
"s": 4125,
"text": "-d: This parameters tells docker to start the container in detached mode"
},
{
"code": null,
"e": 4294,
"s": 4198,
"text": "dpage/pgadmin4: This parameter tells docker to use the image that we have previously downloaded"
},
{
"code": null,
"e": 4396,
"s": 4294,
"text": "Let’s check that the container is up and running, you should also see the previous container running:"
},
{
"code": null,
"e": 4697,
"s": 4396,
"text": "$ docker ps>>>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES7b15fe4c1cbd dpage/pgadmin4 \"/entrypoint.sh\" 43 hours ago Up 5 seconds 0.0.0.0:80->80/tcp, 443/tcp dev-pgadmin"
},
{
"code": null,
"e": 4831,
"s": 4697,
"text": "That’s all you have all the services up and running. The next step is to connect from the pgAdmin console to the PostgreSQL instance."
},
{
"code": null,
"e": 5175,
"s": 4831,
"text": "We haven’t defined any network for these containers so they should be running on the default one, and if you try to access the database or the web portal through their ports, connecting via ‘localhost’ or ‘127.0.0.1’ would work just fine; but if you try connecting from one container to the other, you might encounter some connectivity issues."
},
{
"code": null,
"e": 5289,
"s": 5175,
"text": "We will need to look for the IP address of the PostgreSQL container on our host, you can run this command for it:"
},
{
"code": null,
"e": 5360,
"s": 5289,
"text": "$ docker inspect dev-postgres -f \"{{json .NetworkSettings.Networks }}\""
},
{
"code": null,
"e": 5584,
"s": 5360,
"text": "docker inspect return low-level information of Docker objects, in this case, the ‘dev-postgres’ instance’s IP Adress. The -f parameter is to format the output as a JSON given a Go template. The output should look like this:"
},
{
"code": null,
"e": 5982,
"s": 5584,
"text": "{\"bridge\":{\"IPAMConfig\":null,\"Links\":null,\"Aliases\":null,\"NetworkID\":\"60c21f5cfcaaff424a0e4a22463dc8f9a285993de04e7ac19ce5fd96bba56a47\",\"EndpointID\":\"be6e45b659c30bd12aa766d7003a2887607053684b68574e426f8823104b18a2\",\"Gateway\":\"172.17.0.1\",\"IPAddress\":\"172.17.0.2\",\"IPPrefixLen\":16,\"IPv6Gateway\":\"\",\"GlobalIPv6Address\":\"\",\"GlobalIPv6PrefixLen\":0,\"MacAddress\":\"02:42:ac:11:00:02\",\"DriverOpts\":null}}"
},
{
"code": null,
"e": 6119,
"s": 5982,
"text": "Copy the IPAddress value into the clipboard, which is 172.17.0.2 in my case, you will need to define the connection in the pgAdmin tool."
},
{
"code": null,
"e": 6192,
"s": 6119,
"text": "The next step is to go to your web browser and type http://localhost:80."
},
{
"code": null,
"e": 6278,
"s": 6192,
"text": "You should type the user email and the password you wrote when running the container."
},
{
"code": null,
"e": 6540,
"s": 6278,
"text": "Once you are in the portal, you will need to add a new server by clicking on the “Add New Server” and adding the right information on the pop-up window, make sure you add the IPAdress that you copied previously in the Host name/address under the Connection tab."
},
{
"code": null,
"e": 6774,
"s": 6540,
"text": "Once you have created the connection you should see the server on the right side of your screen. At this moment you are ready to start building your databases and tables, uploading data and querying for your analysis or applications."
},
{
"code": null,
"e": 6815,
"s": 6774,
"text": "Let’s recap on what we have done so far:"
},
{
"code": null,
"e": 6968,
"s": 6815,
"text": "independently run a PostgreSQL instance with Dockerindependently run a pgAdmin server with DockerSetup the connection between the pgAdmin and PostgreSQL"
},
{
"code": null,
"e": 7020,
"s": 6968,
"text": "independently run a PostgreSQL instance with Docker"
},
{
"code": null,
"e": 7067,
"s": 7020,
"text": "independently run a pgAdmin server with Docker"
},
{
"code": null,
"e": 7123,
"s": 7067,
"text": "Setup the connection between the pgAdmin and PostgreSQL"
},
{
"code": null,
"e": 7297,
"s": 7123,
"text": "You should be ready to start developing your databases, tables and queries on pgAdmin directly to your PostgreSQL. You can use the UI to import files directly to the tables."
},
{
"code": null,
"e": 7808,
"s": 7297,
"text": "Something else that you can do here is to connect to this database from a Python application on your local and then load the results to this Postgres database and query the tables using either python or the pgAdmin tool. It is up to you how you use this stack, the good thing is that you don’t need to wait for an infra guy to give you access to a database to start working on your main objective, which is your analysis, app, feature or simply SQL training (even for your next technical interview assignment)."
},
{
"code": null,
"e": 8049,
"s": 7808,
"text": "You can also do all this setup using a Docker-compose file, where you define the PostgreSQL service and pgAdmin service along with the environment variables, volume and port mapping and run docker-compose up. The results should be the same."
}
] |
Structure Your Data Science Projects | by Baran Köseoğlu | Towards Data Science | Data science has some key differences, as compared to software development. For example, data science projects focus on exploration and discovery, whereas software development typically focuses on implementing a solution to a well-defined problem. The ambiguities rarely occur in defining the requirements of a software product, understanding the customer needs, while even the scope may be changed for a data-driven solution.
You can find many other differences between data science and software development, however engineers in both fields need to work on a consistent and well-structured project layout. Afterall data science projects include source code like any other software system to build a software product which is the model itself. Structuring the source code and the data associated with the project has many advantages. The main benefits of structuring your data science work include:
Collaboration across the data science team becomes easier. When everyone in the team follows the same project structure, it becomes very easy to detect the changes made by others and contribute to these changes.Reproducibility. Models should be reproducible not only to keep track of the model versioning but also to easily revert back to older versions in case of model failures. Documenting your work in a reproducible fashion makes it possible to determine if the new model performs better than the previous ones.Efficiency. I have many times checked the old jupyter notebooks to reuse some of the functions for the new projects. I can tell by experience that iterating through an average of ten notebooks, assuming you have a good memory, to find a 20 line piece of code can be frustrating. Submitting the code I have written in a consistent structure avoids self-repeating and duplication.Data management. Raw data should be separated from interim and processed data. This will ensure that any team member working on the project can easily reproduce the models built. The time spent to find the respective datasets used in one of the model building stages is highly reduced.
Collaboration across the data science team becomes easier. When everyone in the team follows the same project structure, it becomes very easy to detect the changes made by others and contribute to these changes.
Reproducibility. Models should be reproducible not only to keep track of the model versioning but also to easily revert back to older versions in case of model failures. Documenting your work in a reproducible fashion makes it possible to determine if the new model performs better than the previous ones.
Efficiency. I have many times checked the old jupyter notebooks to reuse some of the functions for the new projects. I can tell by experience that iterating through an average of ten notebooks, assuming you have a good memory, to find a 20 line piece of code can be frustrating. Submitting the code I have written in a consistent structure avoids self-repeating and duplication.
Data management. Raw data should be separated from interim and processed data. This will ensure that any team member working on the project can easily reproduce the models built. The time spent to find the respective datasets used in one of the model building stages is highly reduced.
Although to succeed in having reproducibility for your data science projects has many other dependencies, for example, if you don’t override your raw data used for model building, in the following section, I will share some of the tools that can help you develop a consistent project structure, which facilitates reproducibility for data science projects.
Cookiecutter
Cookiecutter is a command-line utility that creates projects from project templates. You can create your own project template, or use an existing one. What makes this tool so powerful is the way you can easily import a template and use only the parts that work for you the best.
In this post, I am going to talk more about cookiecutter data science template. Installation is easy and straightforward. To install, run the following:
pip install cookiecutter
To work on a template, you just fetch it using command-line:
cookiecutter https://github.com/drivendata/cookiecutter-data-science
The tool asks for a number of configuration options and then you are good to go.
The project structure looks like the following:
├── LICENSE├── Makefile <- Makefile with commands like `make data` or `make train`├── README.md <- The top-level README for developers using this project.├── data│ ├── external <- Data from third party sources.│ ├── interim <- Intermediate data that has been transformed.│ ├── processed <- The final, canonical data sets for modeling.│ └── raw <- The original, immutable data dump.│├── docs <- A default Sphinx project; see sphinx-doc.org for details│├── models <- Trained and serialized models, model predictions, or model summaries│├── notebooks <- Jupyter notebooks. Naming convention is a number (for ordering),the creator's initials, and a short `-` delimited description, e.g.│ `1.0-jqp-initial-data-exploration`.│├── references <- Data dictionaries, manuals, and all other explanatory materials.│├── reports <- Generated analysis as HTML, PDF, LaTeX, etc.│ └── figures <- Generated graphics and figures to be used in reporting│├── requirements.txt <- The requirements file for reproducing the analysis environment│├── setup.py <- makes project pip installable (pip install -e .) so src can be imported├── src <- Source code for use in this project.│ ├── __init__.py <- Makes src a Python module│ ││ ├── data <- Scripts to download or generate data│ │ └── make_dataset.py│ ││ ├── features <- Scripts to turn raw data into features for modeling│ │ └── build_features.py│ ││ ├── models <- Scripts to train models and then use trained models to make│ │ │ predictions│ │ ├── predict_model.py│ │ └── train_model.py│ ││ └── visualization <- Scripts to create exploratory and results oriented visualizations│ └── visualize.py│└── tox.ini <- tox file with settings for running tox; see tox.testrun.org
Folders
The generated project template structure lets you to organize your source code, data, files and reports for your data science flow. This structure easies the process of tracking changes made to the project. There are five folders that I will explain in more detail:
Data. Data should be segmented in order to reproduce the same result in the future. The data that you have today to build your machine learning model may not be the same data that you will have in the future, ie. the data may be overwritten, or lost in the worst case. In order to have reproducible machine learning pipelines, it is very important to keep your raw data immutable. Any progress made on the raw data should be properly documented and that’s where the data folder comes into play. You don’t need to name your files as final_17_02_2020.csv, final2_17_02_2020.csv anymore to keep track of the changes.
Models. Models are the end products of a machine learning pipeline. They should be stored under a consistent folder structure to ensure that the exact copies of the models can be reproduced in the future.
Notebooks. A lot of data science projects are done in Jupyter notebooks which allow the readers to understand the project pipeline. These notebooks are likely to be filled with lots of functions, and code blocks, which makes even the creators forget about the functionality of the code blocks. Storing your functions, code blocks and results in separate folders allows you to segment the project further and easies to follow the project logic in a notebook.
Reports. A data science project not only produces a model but also figures, and charts as part of data analysis flow. These can be parallel lines, bar charts, scatter plots, etc. You should store generated graphics and figures to be able to report them easily when needed.
Src. Src folder is where you put the functions used in your pipeline. These functions can be stashed according to their similarity in functionality like a software product. You can easily test and debug your functions, while using them becomes as easy as importing them in your notebooks.
I modified one of the earlier projects I worked on for illustration purposes of how to utilize this tool. The repository is not optimized for a machine learning flow, though you can easily grasp the idea of organizing your data science projects following the link.
Makefile
GNU make is a tool that controls the generation of executables and non-source files of a program. It utilizes makefiles which lists all non-source files to be built in order to produce an expected outcome of a program. Makefiles help data scientists to set up their workflow immensely. Most of the time after a data science project is delivered, developers have a hard time remembering the steps taken to build the end product. Makefiles help data scientists to document the pipeline to reproduce the models built. This tool, therefore, should be in the toolbox of a data scientist.
Makefile not only provides reproducibility but also it easies the collaboration in a data science team. A team member, who would be setting up the environment and install the requirements using multiple numbers of commands can now do it in one line:
#oldvirtualenv exsource ex/bin/activatepip install -r requirements.txt#newmake requirements
Watermark
Watermark is an IPython extension that prints date and time stamps, version numbers and hardware information in any IPython shell or Jupyter Notebook session. It provides a simple way to keep track of tools, libraries, authors involved in a project. For large projects, using tools like watermark would be a very simple and inefficient method to keep track of changes made.
To install and use watermark, run the following command:
pip install watermark%load_ext watermark
Here is a demonstration of how it can be used to print out library versions. You can find more information in their documentation:
%watermark -d -m -v -p numpy,matplotlib,sklearn,pandas
Final Thoughts
I can tell by experience that data science projects generally do not have a standardized structure. However, the tools I described in this post can help you create reproducible data science projects, which will increase collaboration, efficiency, and project management in your data team.
If you have any questions regarding the post or any questions about data science in general, you can find me on Linkedin.
Thanks for reading! | [
{
"code": null,
"e": 598,
"s": 171,
"text": "Data science has some key differences, as compared to software development. For example, data science projects focus on exploration and discovery, whereas software development typically focuses on implementing a solution to a well-defined problem. The ambiguities rarely occur in defining the requirements of a software product, understanding the customer needs, while even the scope may be changed for a data-driven solution."
},
{
"code": null,
"e": 1071,
"s": 598,
"text": "You can find many other differences between data science and software development, however engineers in both fields need to work on a consistent and well-structured project layout. Afterall data science projects include source code like any other software system to build a software product which is the model itself. Structuring the source code and the data associated with the project has many advantages. The main benefits of structuring your data science work include:"
},
{
"code": null,
"e": 2251,
"s": 1071,
"text": "Collaboration across the data science team becomes easier. When everyone in the team follows the same project structure, it becomes very easy to detect the changes made by others and contribute to these changes.Reproducibility. Models should be reproducible not only to keep track of the model versioning but also to easily revert back to older versions in case of model failures. Documenting your work in a reproducible fashion makes it possible to determine if the new model performs better than the previous ones.Efficiency. I have many times checked the old jupyter notebooks to reuse some of the functions for the new projects. I can tell by experience that iterating through an average of ten notebooks, assuming you have a good memory, to find a 20 line piece of code can be frustrating. Submitting the code I have written in a consistent structure avoids self-repeating and duplication.Data management. Raw data should be separated from interim and processed data. This will ensure that any team member working on the project can easily reproduce the models built. The time spent to find the respective datasets used in one of the model building stages is highly reduced."
},
{
"code": null,
"e": 2463,
"s": 2251,
"text": "Collaboration across the data science team becomes easier. When everyone in the team follows the same project structure, it becomes very easy to detect the changes made by others and contribute to these changes."
},
{
"code": null,
"e": 2769,
"s": 2463,
"text": "Reproducibility. Models should be reproducible not only to keep track of the model versioning but also to easily revert back to older versions in case of model failures. Documenting your work in a reproducible fashion makes it possible to determine if the new model performs better than the previous ones."
},
{
"code": null,
"e": 3148,
"s": 2769,
"text": "Efficiency. I have many times checked the old jupyter notebooks to reuse some of the functions for the new projects. I can tell by experience that iterating through an average of ten notebooks, assuming you have a good memory, to find a 20 line piece of code can be frustrating. Submitting the code I have written in a consistent structure avoids self-repeating and duplication."
},
{
"code": null,
"e": 3434,
"s": 3148,
"text": "Data management. Raw data should be separated from interim and processed data. This will ensure that any team member working on the project can easily reproduce the models built. The time spent to find the respective datasets used in one of the model building stages is highly reduced."
},
{
"code": null,
"e": 3790,
"s": 3434,
"text": "Although to succeed in having reproducibility for your data science projects has many other dependencies, for example, if you don’t override your raw data used for model building, in the following section, I will share some of the tools that can help you develop a consistent project structure, which facilitates reproducibility for data science projects."
},
{
"code": null,
"e": 3803,
"s": 3790,
"text": "Cookiecutter"
},
{
"code": null,
"e": 4082,
"s": 3803,
"text": "Cookiecutter is a command-line utility that creates projects from project templates. You can create your own project template, or use an existing one. What makes this tool so powerful is the way you can easily import a template and use only the parts that work for you the best."
},
{
"code": null,
"e": 4235,
"s": 4082,
"text": "In this post, I am going to talk more about cookiecutter data science template. Installation is easy and straightforward. To install, run the following:"
},
{
"code": null,
"e": 4260,
"s": 4235,
"text": "pip install cookiecutter"
},
{
"code": null,
"e": 4321,
"s": 4260,
"text": "To work on a template, you just fetch it using command-line:"
},
{
"code": null,
"e": 4390,
"s": 4321,
"text": "cookiecutter https://github.com/drivendata/cookiecutter-data-science"
},
{
"code": null,
"e": 4471,
"s": 4390,
"text": "The tool asks for a number of configuration options and then you are good to go."
},
{
"code": null,
"e": 4519,
"s": 4471,
"text": "The project structure looks like the following:"
},
{
"code": null,
"e": 6491,
"s": 4519,
"text": "├── LICENSE├── Makefile <- Makefile with commands like `make data` or `make train`├── README.md <- The top-level README for developers using this project.├── data│ ├── external <- Data from third party sources.│ ├── interim <- Intermediate data that has been transformed.│ ├── processed <- The final, canonical data sets for modeling.│ └── raw <- The original, immutable data dump.│├── docs <- A default Sphinx project; see sphinx-doc.org for details│├── models <- Trained and serialized models, model predictions, or model summaries│├── notebooks <- Jupyter notebooks. Naming convention is a number (for ordering),the creator's initials, and a short `-` delimited description, e.g.│ `1.0-jqp-initial-data-exploration`.│├── references <- Data dictionaries, manuals, and all other explanatory materials.│├── reports <- Generated analysis as HTML, PDF, LaTeX, etc.│ └── figures <- Generated graphics and figures to be used in reporting│├── requirements.txt <- The requirements file for reproducing the analysis environment│├── setup.py <- makes project pip installable (pip install -e .) so src can be imported├── src <- Source code for use in this project.│ ├── __init__.py <- Makes src a Python module│ ││ ├── data <- Scripts to download or generate data│ │ └── make_dataset.py│ ││ ├── features <- Scripts to turn raw data into features for modeling│ │ └── build_features.py│ ││ ├── models <- Scripts to train models and then use trained models to make│ │ │ predictions│ │ ├── predict_model.py│ │ └── train_model.py│ ││ └── visualization <- Scripts to create exploratory and results oriented visualizations│ └── visualize.py│└── tox.ini <- tox file with settings for running tox; see tox.testrun.org"
},
{
"code": null,
"e": 6499,
"s": 6491,
"text": "Folders"
},
{
"code": null,
"e": 6765,
"s": 6499,
"text": "The generated project template structure lets you to organize your source code, data, files and reports for your data science flow. This structure easies the process of tracking changes made to the project. There are five folders that I will explain in more detail:"
},
{
"code": null,
"e": 7379,
"s": 6765,
"text": "Data. Data should be segmented in order to reproduce the same result in the future. The data that you have today to build your machine learning model may not be the same data that you will have in the future, ie. the data may be overwritten, or lost in the worst case. In order to have reproducible machine learning pipelines, it is very important to keep your raw data immutable. Any progress made on the raw data should be properly documented and that’s where the data folder comes into play. You don’t need to name your files as final_17_02_2020.csv, final2_17_02_2020.csv anymore to keep track of the changes."
},
{
"code": null,
"e": 7584,
"s": 7379,
"text": "Models. Models are the end products of a machine learning pipeline. They should be stored under a consistent folder structure to ensure that the exact copies of the models can be reproduced in the future."
},
{
"code": null,
"e": 8042,
"s": 7584,
"text": "Notebooks. A lot of data science projects are done in Jupyter notebooks which allow the readers to understand the project pipeline. These notebooks are likely to be filled with lots of functions, and code blocks, which makes even the creators forget about the functionality of the code blocks. Storing your functions, code blocks and results in separate folders allows you to segment the project further and easies to follow the project logic in a notebook."
},
{
"code": null,
"e": 8315,
"s": 8042,
"text": "Reports. A data science project not only produces a model but also figures, and charts as part of data analysis flow. These can be parallel lines, bar charts, scatter plots, etc. You should store generated graphics and figures to be able to report them easily when needed."
},
{
"code": null,
"e": 8604,
"s": 8315,
"text": "Src. Src folder is where you put the functions used in your pipeline. These functions can be stashed according to their similarity in functionality like a software product. You can easily test and debug your functions, while using them becomes as easy as importing them in your notebooks."
},
{
"code": null,
"e": 8869,
"s": 8604,
"text": "I modified one of the earlier projects I worked on for illustration purposes of how to utilize this tool. The repository is not optimized for a machine learning flow, though you can easily grasp the idea of organizing your data science projects following the link."
},
{
"code": null,
"e": 8878,
"s": 8869,
"text": "Makefile"
},
{
"code": null,
"e": 9461,
"s": 8878,
"text": "GNU make is a tool that controls the generation of executables and non-source files of a program. It utilizes makefiles which lists all non-source files to be built in order to produce an expected outcome of a program. Makefiles help data scientists to set up their workflow immensely. Most of the time after a data science project is delivered, developers have a hard time remembering the steps taken to build the end product. Makefiles help data scientists to document the pipeline to reproduce the models built. This tool, therefore, should be in the toolbox of a data scientist."
},
{
"code": null,
"e": 9711,
"s": 9461,
"text": "Makefile not only provides reproducibility but also it easies the collaboration in a data science team. A team member, who would be setting up the environment and install the requirements using multiple numbers of commands can now do it in one line:"
},
{
"code": null,
"e": 9803,
"s": 9711,
"text": "#oldvirtualenv exsource ex/bin/activatepip install -r requirements.txt#newmake requirements"
},
{
"code": null,
"e": 9813,
"s": 9803,
"text": "Watermark"
},
{
"code": null,
"e": 10187,
"s": 9813,
"text": "Watermark is an IPython extension that prints date and time stamps, version numbers and hardware information in any IPython shell or Jupyter Notebook session. It provides a simple way to keep track of tools, libraries, authors involved in a project. For large projects, using tools like watermark would be a very simple and inefficient method to keep track of changes made."
},
{
"code": null,
"e": 10244,
"s": 10187,
"text": "To install and use watermark, run the following command:"
},
{
"code": null,
"e": 10285,
"s": 10244,
"text": "pip install watermark%load_ext watermark"
},
{
"code": null,
"e": 10416,
"s": 10285,
"text": "Here is a demonstration of how it can be used to print out library versions. You can find more information in their documentation:"
},
{
"code": null,
"e": 10471,
"s": 10416,
"text": "%watermark -d -m -v -p numpy,matplotlib,sklearn,pandas"
},
{
"code": null,
"e": 10486,
"s": 10471,
"text": "Final Thoughts"
},
{
"code": null,
"e": 10775,
"s": 10486,
"text": "I can tell by experience that data science projects generally do not have a standardized structure. However, the tools I described in this post can help you create reproducible data science projects, which will increase collaboration, efficiency, and project management in your data team."
},
{
"code": null,
"e": 10897,
"s": 10775,
"text": "If you have any questions regarding the post or any questions about data science in general, you can find me on Linkedin."
}
] |
Unix / Linux - Shell Basic Operators | There are various operators supported by each shell. We will discuss in detail about Bourne shell (default shell) in this chapter.
We will now discuss the following operators −
Arithmetic Operators
Relational Operators
Boolean Operators
String Operators
File Test Operators
Bourne shell didn't originally have any mechanism to perform simple arithmetic operations but it uses external programs, either awk or expr.
The following example shows how to add two numbers −
#!/bin/sh
val=`expr 2 + 2`
echo "Total value : $val"
The above script will generate the following result −
Total value : 4
The following points need to be considered while adding −
There must be spaces between operators and expressions. For example, 2+2 is not correct; it should be written as 2 + 2.
There must be spaces between operators and expressions. For example, 2+2 is not correct; it should be written as 2 + 2.
The complete expression should be enclosed between ‘ ‘, called the backtick.
The complete expression should be enclosed between ‘ ‘, called the backtick.
The following arithmetic operators are supported by Bourne Shell.
Assume variable a holds 10 and variable b holds 20 then −
Show Examples
It is very important to understand that all the conditional expressions should be inside square braces with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is incorrect.
All the arithmetical calculations are done using long integers.
Bourne Shell supports the following relational operators that are specific to numeric values. These operators do not work for string values unless their value is numeric.
For example, following operators will work to check a relation between 10 and 20 as well as in between "10" and "20" but not in between "ten" and "twenty".
Assume variable a holds 10 and variable b holds 20 then −
Show Examples
It is very important to understand that all the conditional expressions should be placed inside square braces with spaces around them. For example, [ $a <= $b ] is correct whereas, [$a <= $b] is incorrect.
The following Boolean operators are supported by the Bourne Shell.
Assume variable a holds 10 and variable b holds 20 then −
Show Examples
The following string operators are supported by Bourne Shell.
Assume variable a holds "abc" and variable b holds "efg" then −
Show Examples
We have a few operators that can be used to test various properties associated with a Unix file.
Assume a variable file holds an existing file name "test" the size of which is 100 bytes and has read, write and execute permission on −
Show Examples
Following link will give you a brief idea on C Shell Operators −
C Shell Operators
Following link helps you understand Korn Shell Operators −
Korn Shell Operators
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2878,
"s": 2747,
"text": "There are various operators supported by each shell. We will discuss in detail about Bourne shell (default shell) in this chapter."
},
{
"code": null,
"e": 2924,
"s": 2878,
"text": "We will now discuss the following operators −"
},
{
"code": null,
"e": 2945,
"s": 2924,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 2966,
"s": 2945,
"text": "Relational Operators"
},
{
"code": null,
"e": 2984,
"s": 2966,
"text": "Boolean Operators"
},
{
"code": null,
"e": 3001,
"s": 2984,
"text": "String Operators"
},
{
"code": null,
"e": 3021,
"s": 3001,
"text": "File Test Operators"
},
{
"code": null,
"e": 3162,
"s": 3021,
"text": "Bourne shell didn't originally have any mechanism to perform simple arithmetic operations but it uses external programs, either awk or expr."
},
{
"code": null,
"e": 3215,
"s": 3162,
"text": "The following example shows how to add two numbers −"
},
{
"code": null,
"e": 3269,
"s": 3215,
"text": "#!/bin/sh\n\nval=`expr 2 + 2`\necho \"Total value : $val\""
},
{
"code": null,
"e": 3323,
"s": 3269,
"text": "The above script will generate the following result −"
},
{
"code": null,
"e": 3340,
"s": 3323,
"text": "Total value : 4\n"
},
{
"code": null,
"e": 3398,
"s": 3340,
"text": "The following points need to be considered while adding −"
},
{
"code": null,
"e": 3518,
"s": 3398,
"text": "There must be spaces between operators and expressions. For example, 2+2 is not correct; it should be written as 2 + 2."
},
{
"code": null,
"e": 3638,
"s": 3518,
"text": "There must be spaces between operators and expressions. For example, 2+2 is not correct; it should be written as 2 + 2."
},
{
"code": null,
"e": 3715,
"s": 3638,
"text": "The complete expression should be enclosed between ‘ ‘, called the backtick."
},
{
"code": null,
"e": 3792,
"s": 3715,
"text": "The complete expression should be enclosed between ‘ ‘, called the backtick."
},
{
"code": null,
"e": 3858,
"s": 3792,
"text": "The following arithmetic operators are supported by Bourne Shell."
},
{
"code": null,
"e": 3916,
"s": 3858,
"text": "Assume variable a holds 10 and variable b holds 20 then −"
},
{
"code": null,
"e": 3930,
"s": 3916,
"text": "Show Examples"
},
{
"code": null,
"e": 4126,
"s": 3930,
"text": "It is very important to understand that all the conditional expressions should be inside square braces with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is incorrect."
},
{
"code": null,
"e": 4190,
"s": 4126,
"text": "All the arithmetical calculations are done using long integers."
},
{
"code": null,
"e": 4361,
"s": 4190,
"text": "Bourne Shell supports the following relational operators that are specific to numeric values. These operators do not work for string values unless their value is numeric."
},
{
"code": null,
"e": 4517,
"s": 4361,
"text": "For example, following operators will work to check a relation between 10 and 20 as well as in between \"10\" and \"20\" but not in between \"ten\" and \"twenty\"."
},
{
"code": null,
"e": 4575,
"s": 4517,
"text": "Assume variable a holds 10 and variable b holds 20 then −"
},
{
"code": null,
"e": 4589,
"s": 4575,
"text": "Show Examples"
},
{
"code": null,
"e": 4795,
"s": 4589,
"text": "It is very important to understand that all the conditional expressions should be placed inside square braces with spaces around them. For example, [ $a <= $b ] is correct whereas, [$a <= $b] is incorrect."
},
{
"code": null,
"e": 4863,
"s": 4795,
"text": "The following Boolean operators are supported by the Bourne Shell. "
},
{
"code": null,
"e": 4921,
"s": 4863,
"text": "Assume variable a holds 10 and variable b holds 20 then −"
},
{
"code": null,
"e": 4935,
"s": 4921,
"text": "Show Examples"
},
{
"code": null,
"e": 4997,
"s": 4935,
"text": "The following string operators are supported by Bourne Shell."
},
{
"code": null,
"e": 5061,
"s": 4997,
"text": "Assume variable a holds \"abc\" and variable b holds \"efg\" then −"
},
{
"code": null,
"e": 5075,
"s": 5061,
"text": "Show Examples"
},
{
"code": null,
"e": 5172,
"s": 5075,
"text": "We have a few operators that can be used to test various properties associated with a Unix file."
},
{
"code": null,
"e": 5309,
"s": 5172,
"text": "Assume a variable file holds an existing file name \"test\" the size of which is 100 bytes and has read, write and execute permission on −"
},
{
"code": null,
"e": 5323,
"s": 5309,
"text": "Show Examples"
},
{
"code": null,
"e": 5388,
"s": 5323,
"text": "Following link will give you a brief idea on C Shell Operators −"
},
{
"code": null,
"e": 5406,
"s": 5388,
"text": "C Shell Operators"
},
{
"code": null,
"e": 5465,
"s": 5406,
"text": "Following link helps you understand Korn Shell Operators −"
},
{
"code": null,
"e": 5486,
"s": 5465,
"text": "Korn Shell Operators"
},
{
"code": null,
"e": 5521,
"s": 5486,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 5549,
"s": 5521,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5583,
"s": 5549,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5600,
"s": 5583,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5633,
"s": 5600,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5644,
"s": 5633,
"text": " Pradeep D"
},
{
"code": null,
"e": 5679,
"s": 5644,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5695,
"s": 5679,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 5728,
"s": 5695,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5740,
"s": 5728,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 5772,
"s": 5740,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5780,
"s": 5772,
"text": " Uplatz"
},
{
"code": null,
"e": 5787,
"s": 5780,
"text": " Print"
},
{
"code": null,
"e": 5798,
"s": 5787,
"text": " Add Notes"
}
] |
Musical Genre Classification with Convolutional Neural Networks | by Leland Roberts | Towards Data Science | As a lover of both music and data, the idea of combining the two sounded enticing. Innovative companies such as Spotify and Shazam have been able to leverage music data in a clever way to provide amazing services to users! I wanted to try my hand at working with audio data and try to build a model that could automatically classify a song by its genre. The code for my project can be found here.
An automatic genre classification algorithm could greatly increase efficiency for music databases such as AllMusic. It could also help music recommender systems and playlist generators that companies like Spotify and Pandora use. It’s also a really fun problem to play around with if you love music and data!
There are two major challenges with this problem:
Musical genres are loosely defined. So much so that people often argue over the genre of a song.It is a nontrivial task to extract differentiating features from audio data that could be fed into a model.
Musical genres are loosely defined. So much so that people often argue over the genre of a song.
It is a nontrivial task to extract differentiating features from audio data that could be fed into a model.
The first problem we have no control over. This is the nature of musical genres, and something that will be a limitation. The second problem has been heavily researched in the field of Music Information Retrieval (MIR), which is dedicated to the task of extracting useful information from audio signals.
If you take the time to really think about it, this is a hard problem! How do we turn vibrations in air pressure into information we can gain insights from?
I spent a lot of time researching this question. In order to build a model that could classify a song by its genre, I needed to find good features. An interesting feature that kept coming up was the mel spectrogram.
The mel spectrogram can be thought of as a visual representation of an audio signal. Specifically, it represents how the spectrum of frequencies vary over time. I wrote an article (here) that goes into depth on this topic if you would like to learn more. For the tl;dr folks out there, here is a brief summary:
The Fourier transform is a mathematical formula that allows us to convert an audio signal into the frequency domain. It gives the amplitude at each frequency, and we call this the spectrum. Since frequency content typically varies over time, we perform the Fourier transform on overlapping windowed segments of the signal to get a visual of the spectrum of frequencies over time. This is called the spectrogram. Finally, since humans do not perceive frequency on a linear scale, we map the frequencies to the mel scale (a measure of pitch), which makes it so that equal distances in pitch sound equally distant to the human ear. What we get is the mel spectrogram.
The best part? It can be generated with only a few lines of code in Python.
import librosay, sr = librosa.load('./example_data/blues.00000.wav')mel_spect = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=2048, hop_length=1024)mel_spect = librosa.power_to_db(spect, ref=np.max)librosa.display.specshow(mel_spect, y_axis='mel', fmax=8000, x_axis='time');
Pretty amazing, huh? We now have a way to visually represent a song. Let’s take a look at some mel spectrograms from songs of different genres.
This is awesome! Some of the idiosyncratic differences in genres are captured in the mel spectrogram, which means they could make great features.
What we have essentially done is turned the problem into an image classification task. This is great because there’s a model that was made specifically for this task: the convolutional neural network (CNN). This leads me to the main question of my project: how accurate can a convolutional neural network identify musical genres using mel spectrograms?
Let’s get into it!
The dataset I used was the GTZAN Genre Collection (found here). This dataset was used in a well known paper on genre classification in 2002. The dataset includes 10 different genres (blues, classical, country, disco, hip hop, jazz, metal, pop, reggae, and rock) with 100 songs per genre (each 30 second samples). Since they were all .wav files, I was able to use the librosa library to load them into a Jupyter Notebook.
As seen above, computing the mel spectrogram using librosa is fairly straightforward. I was able to write a function that computes the mel spectrogram for each audio file and stores them in a numpy array. It returns that array as well as an array with the corresponding genre labels.
Now that we have our features and targets, we can create a holdout, or validation, set. I chose to hold out 20% for testing.
Before constructing the model, a few steps have to be taken:
Values of the mel spectrograms should be scaled so that they are between 0 and 1 for computational efficiency.The data is currently 1000 rows of mel spectrograms that are 128 x 660. We need to reshape this to be 1000 rows of 128 x 660 x 1 to represent that there is a single color channel. If our image had three color channels, RGB, we would need this additional dimension to be 3.Target values have to be one-hot-encoded in order to be fed into a neural network.
Values of the mel spectrograms should be scaled so that they are between 0 and 1 for computational efficiency.
The data is currently 1000 rows of mel spectrograms that are 128 x 660. We need to reshape this to be 1000 rows of 128 x 660 x 1 to represent that there is a single color channel. If our image had three color channels, RGB, we would need this additional dimension to be 3.
Target values have to be one-hot-encoded in order to be fed into a neural network.
It is important that we complete these steps after creating our holdout set to prevent data leakage. Now we are ready to do some modeling!
Before running a CNN, I wanted to train a feed forward neural network (FFNN) for comparison. CNNs have additional layers for edge detection that make them well suited for image classification problems, but they tend to be more computationally expensive than FFNNs. If a FFNN could perform just as well, there would be no need to use a CNN. Since the main focus of this post is the CNN, I won’t go into the details of the model here, but the best FFNN model achieved a test score of 45%.
As suspected, the CNN model did much better! The best CNN model (based on test score accuracy) achieved a score of 68%. That’s not too shabby, especially considering the difficulty of the problem, but it still isn’t great. The training score was 84%, so the model was overfit. This means that it was tuning really well to the training data and not generalizing as well to new data. Even so, it’s certainly learning.
I tried several different architectures to try to improve the model, and most of them achieved accuracies between 55 and 65 percent, but I couldn’t get it much above that. Most of the models became increasingly overfit after about 15 epochs, so increasing the number of epochs did not seem like a good option.
Here is a summary of the final architecture:
Input layer: 128 x 660 neurons (128 mel scales and 660 time windows)Convolutional layer: 16 different 3 x 3 filtersMax pooling layer: 2 x 4Convolutional layer: 32 different 3 x 3 filtersMax pooling layer: 2 x 4Dense layer: 64 neuronsOutput layer: 10 neurons for the 10 different genres
Input layer: 128 x 660 neurons (128 mel scales and 660 time windows)
Convolutional layer: 16 different 3 x 3 filters
Max pooling layer: 2 x 4
Convolutional layer: 32 different 3 x 3 filters
Max pooling layer: 2 x 4
Dense layer: 64 neurons
Output layer: 10 neurons for the 10 different genres
All of the hidden layers used the RELU activation function and the output layer used the softmax function. The loss was calculated using the categorical crossentropy function. Dropout was also used to prevent overfitting.
To look deeper into what was happening with the model, I computed a confusion matrix to visualize the model’s predictions against the actual values. What I found was really interesting!
The model hardly ever predicted blues, and only correctly classified 35% of blues songs, but a majority of the misclassifications were jazz and rock. This makes a lot of sense! Jazz and blues are very similar styles of music, and rock music was heavily influenced by, and really came out of, blues music.
The model also had a tough time distinguishing between reggae and hiphop. Half of the misclassifications for reggae were hiphop and vise versa. Again, this makes sense since reggae music heavily influenced hiphop music and share similar characteristics.
The model misclassified several genres as rock, particularly blues and country. It’s no wonder though because there are so many sub-genres of rock music that branch into other genres. Blues rock is very popular as well as southern rock which has country influences.
This is actually really good news! Our model is running into the same difficulties that a human would. It’s clearly learning some of the distinguishing factors of the musical genres, but it is having trouble with genres that share characteristics with other genres. Again, this goes back to the first problem, and that is the nature of musical genres. They are difficult to distinguish!
Even so, I’d say that for a computer, 68% accuracy isn’t all that bad, but I do believe there’s room for improvement. I can confidently say that the CNN did better than the FFNN, and that it was able to learn and predict with decent accuracy the genre of a song.
What happens if we remove some of the genres that share characteristics with other genres? Will the model perform better? How does it do with a binary classification? These were some of the questions still burning in my mind. If you’d like to dive deeper into these questions, stay tuned for my next post.
To be continued... | [
{
"code": null,
"e": 569,
"s": 172,
"text": "As a lover of both music and data, the idea of combining the two sounded enticing. Innovative companies such as Spotify and Shazam have been able to leverage music data in a clever way to provide amazing services to users! I wanted to try my hand at working with audio data and try to build a model that could automatically classify a song by its genre. The code for my project can be found here."
},
{
"code": null,
"e": 878,
"s": 569,
"text": "An automatic genre classification algorithm could greatly increase efficiency for music databases such as AllMusic. It could also help music recommender systems and playlist generators that companies like Spotify and Pandora use. It’s also a really fun problem to play around with if you love music and data!"
},
{
"code": null,
"e": 928,
"s": 878,
"text": "There are two major challenges with this problem:"
},
{
"code": null,
"e": 1132,
"s": 928,
"text": "Musical genres are loosely defined. So much so that people often argue over the genre of a song.It is a nontrivial task to extract differentiating features from audio data that could be fed into a model."
},
{
"code": null,
"e": 1229,
"s": 1132,
"text": "Musical genres are loosely defined. So much so that people often argue over the genre of a song."
},
{
"code": null,
"e": 1337,
"s": 1229,
"text": "It is a nontrivial task to extract differentiating features from audio data that could be fed into a model."
},
{
"code": null,
"e": 1641,
"s": 1337,
"text": "The first problem we have no control over. This is the nature of musical genres, and something that will be a limitation. The second problem has been heavily researched in the field of Music Information Retrieval (MIR), which is dedicated to the task of extracting useful information from audio signals."
},
{
"code": null,
"e": 1798,
"s": 1641,
"text": "If you take the time to really think about it, this is a hard problem! How do we turn vibrations in air pressure into information we can gain insights from?"
},
{
"code": null,
"e": 2014,
"s": 1798,
"text": "I spent a lot of time researching this question. In order to build a model that could classify a song by its genre, I needed to find good features. An interesting feature that kept coming up was the mel spectrogram."
},
{
"code": null,
"e": 2325,
"s": 2014,
"text": "The mel spectrogram can be thought of as a visual representation of an audio signal. Specifically, it represents how the spectrum of frequencies vary over time. I wrote an article (here) that goes into depth on this topic if you would like to learn more. For the tl;dr folks out there, here is a brief summary:"
},
{
"code": null,
"e": 2990,
"s": 2325,
"text": "The Fourier transform is a mathematical formula that allows us to convert an audio signal into the frequency domain. It gives the amplitude at each frequency, and we call this the spectrum. Since frequency content typically varies over time, we perform the Fourier transform on overlapping windowed segments of the signal to get a visual of the spectrum of frequencies over time. This is called the spectrogram. Finally, since humans do not perceive frequency on a linear scale, we map the frequencies to the mel scale (a measure of pitch), which makes it so that equal distances in pitch sound equally distant to the human ear. What we get is the mel spectrogram."
},
{
"code": null,
"e": 3066,
"s": 2990,
"text": "The best part? It can be generated with only a few lines of code in Python."
},
{
"code": null,
"e": 3344,
"s": 3066,
"text": "import librosay, sr = librosa.load('./example_data/blues.00000.wav')mel_spect = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=2048, hop_length=1024)mel_spect = librosa.power_to_db(spect, ref=np.max)librosa.display.specshow(mel_spect, y_axis='mel', fmax=8000, x_axis='time');"
},
{
"code": null,
"e": 3488,
"s": 3344,
"text": "Pretty amazing, huh? We now have a way to visually represent a song. Let’s take a look at some mel spectrograms from songs of different genres."
},
{
"code": null,
"e": 3634,
"s": 3488,
"text": "This is awesome! Some of the idiosyncratic differences in genres are captured in the mel spectrogram, which means they could make great features."
},
{
"code": null,
"e": 3987,
"s": 3634,
"text": "What we have essentially done is turned the problem into an image classification task. This is great because there’s a model that was made specifically for this task: the convolutional neural network (CNN). This leads me to the main question of my project: how accurate can a convolutional neural network identify musical genres using mel spectrograms?"
},
{
"code": null,
"e": 4006,
"s": 3987,
"text": "Let’s get into it!"
},
{
"code": null,
"e": 4427,
"s": 4006,
"text": "The dataset I used was the GTZAN Genre Collection (found here). This dataset was used in a well known paper on genre classification in 2002. The dataset includes 10 different genres (blues, classical, country, disco, hip hop, jazz, metal, pop, reggae, and rock) with 100 songs per genre (each 30 second samples). Since they were all .wav files, I was able to use the librosa library to load them into a Jupyter Notebook."
},
{
"code": null,
"e": 4711,
"s": 4427,
"text": "As seen above, computing the mel spectrogram using librosa is fairly straightforward. I was able to write a function that computes the mel spectrogram for each audio file and stores them in a numpy array. It returns that array as well as an array with the corresponding genre labels."
},
{
"code": null,
"e": 4836,
"s": 4711,
"text": "Now that we have our features and targets, we can create a holdout, or validation, set. I chose to hold out 20% for testing."
},
{
"code": null,
"e": 4897,
"s": 4836,
"text": "Before constructing the model, a few steps have to be taken:"
},
{
"code": null,
"e": 5362,
"s": 4897,
"text": "Values of the mel spectrograms should be scaled so that they are between 0 and 1 for computational efficiency.The data is currently 1000 rows of mel spectrograms that are 128 x 660. We need to reshape this to be 1000 rows of 128 x 660 x 1 to represent that there is a single color channel. If our image had three color channels, RGB, we would need this additional dimension to be 3.Target values have to be one-hot-encoded in order to be fed into a neural network."
},
{
"code": null,
"e": 5473,
"s": 5362,
"text": "Values of the mel spectrograms should be scaled so that they are between 0 and 1 for computational efficiency."
},
{
"code": null,
"e": 5746,
"s": 5473,
"text": "The data is currently 1000 rows of mel spectrograms that are 128 x 660. We need to reshape this to be 1000 rows of 128 x 660 x 1 to represent that there is a single color channel. If our image had three color channels, RGB, we would need this additional dimension to be 3."
},
{
"code": null,
"e": 5829,
"s": 5746,
"text": "Target values have to be one-hot-encoded in order to be fed into a neural network."
},
{
"code": null,
"e": 5968,
"s": 5829,
"text": "It is important that we complete these steps after creating our holdout set to prevent data leakage. Now we are ready to do some modeling!"
},
{
"code": null,
"e": 6455,
"s": 5968,
"text": "Before running a CNN, I wanted to train a feed forward neural network (FFNN) for comparison. CNNs have additional layers for edge detection that make them well suited for image classification problems, but they tend to be more computationally expensive than FFNNs. If a FFNN could perform just as well, there would be no need to use a CNN. Since the main focus of this post is the CNN, I won’t go into the details of the model here, but the best FFNN model achieved a test score of 45%."
},
{
"code": null,
"e": 6871,
"s": 6455,
"text": "As suspected, the CNN model did much better! The best CNN model (based on test score accuracy) achieved a score of 68%. That’s not too shabby, especially considering the difficulty of the problem, but it still isn’t great. The training score was 84%, so the model was overfit. This means that it was tuning really well to the training data and not generalizing as well to new data. Even so, it’s certainly learning."
},
{
"code": null,
"e": 7181,
"s": 6871,
"text": "I tried several different architectures to try to improve the model, and most of them achieved accuracies between 55 and 65 percent, but I couldn’t get it much above that. Most of the models became increasingly overfit after about 15 epochs, so increasing the number of epochs did not seem like a good option."
},
{
"code": null,
"e": 7226,
"s": 7181,
"text": "Here is a summary of the final architecture:"
},
{
"code": null,
"e": 7512,
"s": 7226,
"text": "Input layer: 128 x 660 neurons (128 mel scales and 660 time windows)Convolutional layer: 16 different 3 x 3 filtersMax pooling layer: 2 x 4Convolutional layer: 32 different 3 x 3 filtersMax pooling layer: 2 x 4Dense layer: 64 neuronsOutput layer: 10 neurons for the 10 different genres"
},
{
"code": null,
"e": 7581,
"s": 7512,
"text": "Input layer: 128 x 660 neurons (128 mel scales and 660 time windows)"
},
{
"code": null,
"e": 7629,
"s": 7581,
"text": "Convolutional layer: 16 different 3 x 3 filters"
},
{
"code": null,
"e": 7654,
"s": 7629,
"text": "Max pooling layer: 2 x 4"
},
{
"code": null,
"e": 7702,
"s": 7654,
"text": "Convolutional layer: 32 different 3 x 3 filters"
},
{
"code": null,
"e": 7727,
"s": 7702,
"text": "Max pooling layer: 2 x 4"
},
{
"code": null,
"e": 7751,
"s": 7727,
"text": "Dense layer: 64 neurons"
},
{
"code": null,
"e": 7804,
"s": 7751,
"text": "Output layer: 10 neurons for the 10 different genres"
},
{
"code": null,
"e": 8026,
"s": 7804,
"text": "All of the hidden layers used the RELU activation function and the output layer used the softmax function. The loss was calculated using the categorical crossentropy function. Dropout was also used to prevent overfitting."
},
{
"code": null,
"e": 8212,
"s": 8026,
"text": "To look deeper into what was happening with the model, I computed a confusion matrix to visualize the model’s predictions against the actual values. What I found was really interesting!"
},
{
"code": null,
"e": 8517,
"s": 8212,
"text": "The model hardly ever predicted blues, and only correctly classified 35% of blues songs, but a majority of the misclassifications were jazz and rock. This makes a lot of sense! Jazz and blues are very similar styles of music, and rock music was heavily influenced by, and really came out of, blues music."
},
{
"code": null,
"e": 8771,
"s": 8517,
"text": "The model also had a tough time distinguishing between reggae and hiphop. Half of the misclassifications for reggae were hiphop and vise versa. Again, this makes sense since reggae music heavily influenced hiphop music and share similar characteristics."
},
{
"code": null,
"e": 9037,
"s": 8771,
"text": "The model misclassified several genres as rock, particularly blues and country. It’s no wonder though because there are so many sub-genres of rock music that branch into other genres. Blues rock is very popular as well as southern rock which has country influences."
},
{
"code": null,
"e": 9424,
"s": 9037,
"text": "This is actually really good news! Our model is running into the same difficulties that a human would. It’s clearly learning some of the distinguishing factors of the musical genres, but it is having trouble with genres that share characteristics with other genres. Again, this goes back to the first problem, and that is the nature of musical genres. They are difficult to distinguish!"
},
{
"code": null,
"e": 9687,
"s": 9424,
"text": "Even so, I’d say that for a computer, 68% accuracy isn’t all that bad, but I do believe there’s room for improvement. I can confidently say that the CNN did better than the FFNN, and that it was able to learn and predict with decent accuracy the genre of a song."
},
{
"code": null,
"e": 9993,
"s": 9687,
"text": "What happens if we remove some of the genres that share characteristics with other genres? Will the model perform better? How does it do with a binary classification? These were some of the questions still burning in my mind. If you’d like to dive deeper into these questions, stay tuned for my next post."
}
] |
Accelerating Data Exploration. Using data describe for exploratory... | by Himanshu Sharma | Towards Data Science | Exploratory data analysis is one of the important initial steps for creating a better understanding of a dataset and the underlying data. It helps us in understanding what the data is all about, what are the different features of the dataset, understanding the association between different data points, etc.
Exploration of data beforehand gives us an edge while creating a Machine learning or deep learning model. It not only helps in understanding the data correlation but also helps in analyzing the statistical properties and any hidden pattern in the dataset.
EDA generally consumes a lot of time and effort because we need to create different bars and graphs to visualize and analyze the data. What if I tell you that you can perform EDA in significantly less time and effort? Yes, it is possible and we can create different plots in single lines of code.
Data Describe is an open-source python library that can be used to easily understand and analyze the dataset by creating different visualizations.
In this article, we will use Data Describe to perform EDA easily and effortlessly.
Let’s get started...
We will start by installing a Data Describe using pip. The command given below will do that.
!pip install data_describe
In this step, we will import the required libraries and functions to create a machine learning model and dashboard. We will be using the IRIS dataset for this article so we will be importing that from sklearn. The link for the dataset is given below:
scikit-learn.org
import pandas as pdfrom sklearn.datasets import load_irisdat = load_iris()df = pd.DataFrame(dat['data'], columns=dat['feature_names'])df['outcome'] = dat['target']df.head()
Now we will start with the Data Exploration. We will start by analyzing the statistical summary and then creating different graphs and plots.
a. Statistical Summary
dd.data_summary(df)
Here we can analyze the statistical summary which shows the Median, Mode, Quartiles, etc of the dataset.
b. Heatmap
dd.data_heatmap(df)
c. Correlation Matrix
dd.correlation_matrix(df)
The correlation matrix helps in understanding the correlation between the data points.
d. Distribution Plot
The Distribution Plot shows the distribution of the dataset, which can help us in understanding the skewness of the dataset. We will be using the ipywidget python library to plot the distribution plot of all the data points.
from IPython.display import displayfor col in df.columns: display(dd.distribution(df, plot_all=True).plot_distribution(col))
e. Scatter Plot
dd.scatter_plots(df, plot_mode='matrix')
f. Cluster Plot
Cluster Plot helps in visualizing the clusters of the target variable.
dd.cluster(df)
g. Feature Importance
This is one of the most important plots which helps us to identify the most important features in the dataset. We will be using the RanbdomForest Classifier for feature importance.
These are some of the plots and graphs that we can create using data Describe for analyzing and visualizing the dataset. Go ahead try this with different datasets and create different plots easily and effortlessly. In case you find any difficulty please let me know in the response section.
This article is in collaboration with Piyush Ingale.
Thanks for reading! If you want to get in touch with me, feel free to reach me at [email protected] or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science. | [
{
"code": null,
"e": 480,
"s": 171,
"text": "Exploratory data analysis is one of the important initial steps for creating a better understanding of a dataset and the underlying data. It helps us in understanding what the data is all about, what are the different features of the dataset, understanding the association between different data points, etc."
},
{
"code": null,
"e": 736,
"s": 480,
"text": "Exploration of data beforehand gives us an edge while creating a Machine learning or deep learning model. It not only helps in understanding the data correlation but also helps in analyzing the statistical properties and any hidden pattern in the dataset."
},
{
"code": null,
"e": 1033,
"s": 736,
"text": "EDA generally consumes a lot of time and effort because we need to create different bars and graphs to visualize and analyze the data. What if I tell you that you can perform EDA in significantly less time and effort? Yes, it is possible and we can create different plots in single lines of code."
},
{
"code": null,
"e": 1180,
"s": 1033,
"text": "Data Describe is an open-source python library that can be used to easily understand and analyze the dataset by creating different visualizations."
},
{
"code": null,
"e": 1263,
"s": 1180,
"text": "In this article, we will use Data Describe to perform EDA easily and effortlessly."
},
{
"code": null,
"e": 1284,
"s": 1263,
"text": "Let’s get started..."
},
{
"code": null,
"e": 1377,
"s": 1284,
"text": "We will start by installing a Data Describe using pip. The command given below will do that."
},
{
"code": null,
"e": 1404,
"s": 1377,
"text": "!pip install data_describe"
},
{
"code": null,
"e": 1655,
"s": 1404,
"text": "In this step, we will import the required libraries and functions to create a machine learning model and dashboard. We will be using the IRIS dataset for this article so we will be importing that from sklearn. The link for the dataset is given below:"
},
{
"code": null,
"e": 1672,
"s": 1655,
"text": "scikit-learn.org"
},
{
"code": null,
"e": 1845,
"s": 1672,
"text": "import pandas as pdfrom sklearn.datasets import load_irisdat = load_iris()df = pd.DataFrame(dat['data'], columns=dat['feature_names'])df['outcome'] = dat['target']df.head()"
},
{
"code": null,
"e": 1987,
"s": 1845,
"text": "Now we will start with the Data Exploration. We will start by analyzing the statistical summary and then creating different graphs and plots."
},
{
"code": null,
"e": 2010,
"s": 1987,
"text": "a. Statistical Summary"
},
{
"code": null,
"e": 2030,
"s": 2010,
"text": "dd.data_summary(df)"
},
{
"code": null,
"e": 2135,
"s": 2030,
"text": "Here we can analyze the statistical summary which shows the Median, Mode, Quartiles, etc of the dataset."
},
{
"code": null,
"e": 2146,
"s": 2135,
"text": "b. Heatmap"
},
{
"code": null,
"e": 2166,
"s": 2146,
"text": "dd.data_heatmap(df)"
},
{
"code": null,
"e": 2188,
"s": 2166,
"text": "c. Correlation Matrix"
},
{
"code": null,
"e": 2214,
"s": 2188,
"text": "dd.correlation_matrix(df)"
},
{
"code": null,
"e": 2301,
"s": 2214,
"text": "The correlation matrix helps in understanding the correlation between the data points."
},
{
"code": null,
"e": 2322,
"s": 2301,
"text": "d. Distribution Plot"
},
{
"code": null,
"e": 2547,
"s": 2322,
"text": "The Distribution Plot shows the distribution of the dataset, which can help us in understanding the skewness of the dataset. We will be using the ipywidget python library to plot the distribution plot of all the data points."
},
{
"code": null,
"e": 2708,
"s": 2547,
"text": "from IPython.display import displayfor col in df.columns: display(dd.distribution(df, plot_all=True).plot_distribution(col))"
},
{
"code": null,
"e": 2724,
"s": 2708,
"text": "e. Scatter Plot"
},
{
"code": null,
"e": 2765,
"s": 2724,
"text": "dd.scatter_plots(df, plot_mode='matrix')"
},
{
"code": null,
"e": 2781,
"s": 2765,
"text": "f. Cluster Plot"
},
{
"code": null,
"e": 2852,
"s": 2781,
"text": "Cluster Plot helps in visualizing the clusters of the target variable."
},
{
"code": null,
"e": 2867,
"s": 2852,
"text": "dd.cluster(df)"
},
{
"code": null,
"e": 2889,
"s": 2867,
"text": "g. Feature Importance"
},
{
"code": null,
"e": 3070,
"s": 2889,
"text": "This is one of the most important plots which helps us to identify the most important features in the dataset. We will be using the RanbdomForest Classifier for feature importance."
},
{
"code": null,
"e": 3361,
"s": 3070,
"text": "These are some of the plots and graphs that we can create using data Describe for analyzing and visualizing the dataset. Go ahead try this with different datasets and create different plots easily and effortlessly. In case you find any difficulty please let me know in the response section."
},
{
"code": null,
"e": 3414,
"s": 3361,
"text": "This article is in collaboration with Piyush Ingale."
}
] |
Arduino - Serial Peripheral Interface | A Serial Peripheral Interface (SPI) bus is a system for serial communication, which uses up to four conductors, commonly three. One conductor is used for data receiving, one for data sending, one for synchronization and one alternatively for selecting a device to communicate with. It is a full duplex connection, which means that the data is sent and received simultaneously. The maximum baud rate is higher than that in the I2C communication system.
SPI uses the following four wires −
SCK − This is the serial clock driven by the master.
SCK − This is the serial clock driven by the master.
MOSI − This is the master output / slave input driven by the master.
MOSI − This is the master output / slave input driven by the master.
MISO − This is the master input / slave output driven by the master.
MISO − This is the master input / slave output driven by the master.
SS − This is the slave-selection wire.
SS − This is the slave-selection wire.
The following functions are used. You have to include the SPI.h.
SPI.begin() − Initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high.
SPI.begin() − Initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high.
SPI.setClockDivider(divider) − To set the SPI clock divider relative to the system clock. On AVR based boards, the dividers available are 2, 4, 8, 16, 32, 64 or 128. The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to one-quarter of the frequency of the system clock (5 Mhz for the boards at 20 MHz).
SPI.setClockDivider(divider) − To set the SPI clock divider relative to the system clock. On AVR based boards, the dividers available are 2, 4, 8, 16, 32, 64 or 128. The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to one-quarter of the frequency of the system clock (5 Mhz for the boards at 20 MHz).
Divider − It could be (SPI_CLOCK_DIV2, SPI_CLOCK_DIV4, SPI_CLOCK_DIV8, SPI_CLOCK_DIV16, SPI_CLOCK_DIV32, SPI_CLOCK_DIV64, SPI_CLOCK_DIV128).
Divider − It could be (SPI_CLOCK_DIV2, SPI_CLOCK_DIV4, SPI_CLOCK_DIV8, SPI_CLOCK_DIV16, SPI_CLOCK_DIV32, SPI_CLOCK_DIV64, SPI_CLOCK_DIV128).
SPI.transfer(val) − SPI transfer is based on a simultaneous send and receive: the received data is returned in receivedVal.
SPI.transfer(val) − SPI transfer is based on a simultaneous send and receive: the received data is returned in receivedVal.
SPI.beginTransaction(SPISettings(speedMaximum, dataOrder, dataMode)) − speedMaximum is the clock, dataOrder(MSBFIRST or LSBFIRST), dataMode(SPI_MODE0, SPI_MODE1, SPI_MODE2, or SPI_MODE3).
SPI.beginTransaction(SPISettings(speedMaximum, dataOrder, dataMode)) − speedMaximum is the clock, dataOrder(MSBFIRST or LSBFIRST), dataMode(SPI_MODE0, SPI_MODE1, SPI_MODE2, or SPI_MODE3).
We have four modes of operation in SPI as follows −
Mode 0 (the default) − Clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0).
Mode 0 (the default) − Clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0).
Mode 1 − Clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1).
Mode 1 − Clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1).
Mode 2 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0).
Mode 2 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0).
Mode 3 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1).
Mode 3 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1).
SPI.attachInterrupt(handler) − Function to be called when a slave device receives data from the master.
SPI.attachInterrupt(handler) − Function to be called when a slave device receives data from the master.
Now, we will connect two Arduino UNO boards together; one as a master and the other as a slave.
(SS) : pin 10
(MOSI) : pin 11
(MISO) : pin 12
(SCK) : pin 13
The ground is common. Following is the diagrammatic representation of the connection between both the boards −
Let us see examples of SPI as Master and SPI as Slave.
#include <SPI.h>
void setup (void) {
Serial.begin(115200); //set baud rate to 115200 for usart
digitalWrite(SS, HIGH); // disable Slave Select
SPI.begin ();
SPI.setClockDivider(SPI_CLOCK_DIV8);//divide the clock by 8
}
void loop (void) {
char c;
digitalWrite(SS, LOW); // enable Slave Select
// send test string
for (const char * p = "Hello, world!\r" ; c = *p; p++) {
SPI.transfer (c);
Serial.print(c);
}
digitalWrite(SS, HIGH); // disable Slave Select
delay(2000);
}
#include <SPI.h>
char buff [50];
volatile byte indx;
volatile boolean process;
void setup (void) {
Serial.begin (115200);
pinMode(MISO, OUTPUT); // have to send on master in so it set as output
SPCR |= _BV(SPE); // turn on SPI in slave mode
indx = 0; // buffer empty
process = false;
SPI.attachInterrupt(); // turn on interrupt
}
ISR (SPI_STC_vect) // SPI interrupt routine {
byte c = SPDR; // read byte from SPI Data Register
if (indx < sizeof buff) {
buff [indx++] = c; // save data in the next index in the array buff
if (c == '\r') //check for the end of the word
process = true;
}
}
void loop (void) {
if (process) {
process = false; //reset the process
Serial.println (buff); //print the array on serial monitor
indx= 0; //reset button to zero
}
}
65 Lectures
6.5 hours
Amit Rana
43 Lectures
3 hours
Amit Rana
20 Lectures
2 hours
Ashraf Said
19 Lectures
1.5 hours
Ashraf Said
11 Lectures
47 mins
Ashraf Said
9 Lectures
41 mins
Ashraf Said
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3322,
"s": 2870,
"text": "A Serial Peripheral Interface (SPI) bus is a system for serial communication, which uses up to four conductors, commonly three. One conductor is used for data receiving, one for data sending, one for synchronization and one alternatively for selecting a device to communicate with. It is a full duplex connection, which means that the data is sent and received simultaneously. The maximum baud rate is higher than that in the I2C communication system."
},
{
"code": null,
"e": 3358,
"s": 3322,
"text": "SPI uses the following four wires −"
},
{
"code": null,
"e": 3411,
"s": 3358,
"text": "SCK − This is the serial clock driven by the master."
},
{
"code": null,
"e": 3464,
"s": 3411,
"text": "SCK − This is the serial clock driven by the master."
},
{
"code": null,
"e": 3533,
"s": 3464,
"text": "MOSI − This is the master output / slave input driven by the master."
},
{
"code": null,
"e": 3602,
"s": 3533,
"text": "MOSI − This is the master output / slave input driven by the master."
},
{
"code": null,
"e": 3671,
"s": 3602,
"text": "MISO − This is the master input / slave output driven by the master."
},
{
"code": null,
"e": 3740,
"s": 3671,
"text": "MISO − This is the master input / slave output driven by the master."
},
{
"code": null,
"e": 3779,
"s": 3740,
"text": "SS − This is the slave-selection wire."
},
{
"code": null,
"e": 3818,
"s": 3779,
"text": "SS − This is the slave-selection wire."
},
{
"code": null,
"e": 3883,
"s": 3818,
"text": "The following functions are used. You have to include the SPI.h."
},
{
"code": null,
"e": 4001,
"s": 3883,
"text": "SPI.begin() − Initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high."
},
{
"code": null,
"e": 4119,
"s": 4001,
"text": "SPI.begin() − Initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high."
},
{
"code": null,
"e": 4435,
"s": 4119,
"text": "SPI.setClockDivider(divider) − To set the SPI clock divider relative to the system clock. On AVR based boards, the dividers available are 2, 4, 8, 16, 32, 64 or 128. The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to one-quarter of the frequency of the system clock (5 Mhz for the boards at 20 MHz)."
},
{
"code": null,
"e": 4751,
"s": 4435,
"text": "SPI.setClockDivider(divider) − To set the SPI clock divider relative to the system clock. On AVR based boards, the dividers available are 2, 4, 8, 16, 32, 64 or 128. The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to one-quarter of the frequency of the system clock (5 Mhz for the boards at 20 MHz)."
},
{
"code": null,
"e": 4892,
"s": 4751,
"text": "Divider − It could be (SPI_CLOCK_DIV2, SPI_CLOCK_DIV4, SPI_CLOCK_DIV8, SPI_CLOCK_DIV16, SPI_CLOCK_DIV32, SPI_CLOCK_DIV64, SPI_CLOCK_DIV128)."
},
{
"code": null,
"e": 5033,
"s": 4892,
"text": "Divider − It could be (SPI_CLOCK_DIV2, SPI_CLOCK_DIV4, SPI_CLOCK_DIV8, SPI_CLOCK_DIV16, SPI_CLOCK_DIV32, SPI_CLOCK_DIV64, SPI_CLOCK_DIV128)."
},
{
"code": null,
"e": 5157,
"s": 5033,
"text": "SPI.transfer(val) − SPI transfer is based on a simultaneous send and receive: the received data is returned in receivedVal."
},
{
"code": null,
"e": 5281,
"s": 5157,
"text": "SPI.transfer(val) − SPI transfer is based on a simultaneous send and receive: the received data is returned in receivedVal."
},
{
"code": null,
"e": 5469,
"s": 5281,
"text": "SPI.beginTransaction(SPISettings(speedMaximum, dataOrder, dataMode)) − speedMaximum is the clock, dataOrder(MSBFIRST or LSBFIRST), dataMode(SPI_MODE0, SPI_MODE1, SPI_MODE2, or SPI_MODE3)."
},
{
"code": null,
"e": 5657,
"s": 5469,
"text": "SPI.beginTransaction(SPISettings(speedMaximum, dataOrder, dataMode)) − speedMaximum is the clock, dataOrder(MSBFIRST or LSBFIRST), dataMode(SPI_MODE0, SPI_MODE1, SPI_MODE2, or SPI_MODE3)."
},
{
"code": null,
"e": 5709,
"s": 5657,
"text": "We have four modes of operation in SPI as follows −"
},
{
"code": null,
"e": 5852,
"s": 5709,
"text": "Mode 0 (the default) − Clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0)."
},
{
"code": null,
"e": 5995,
"s": 5852,
"text": "Mode 0 (the default) − Clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0)."
},
{
"code": null,
"e": 6125,
"s": 5995,
"text": "Mode 1 − Clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1)."
},
{
"code": null,
"e": 6255,
"s": 6125,
"text": "Mode 1 − Clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1)."
},
{
"code": null,
"e": 6385,
"s": 6255,
"text": "Mode 2 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0)."
},
{
"code": null,
"e": 6515,
"s": 6385,
"text": "Mode 2 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0)."
},
{
"code": null,
"e": 6646,
"s": 6515,
"text": "Mode 3 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1)."
},
{
"code": null,
"e": 6777,
"s": 6646,
"text": "Mode 3 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1)."
},
{
"code": null,
"e": 6881,
"s": 6777,
"text": "SPI.attachInterrupt(handler) − Function to be called when a slave device receives data from the master."
},
{
"code": null,
"e": 6985,
"s": 6881,
"text": "SPI.attachInterrupt(handler) − Function to be called when a slave device receives data from the master."
},
{
"code": null,
"e": 7081,
"s": 6985,
"text": "Now, we will connect two Arduino UNO boards together; one as a master and the other as a slave."
},
{
"code": null,
"e": 7095,
"s": 7081,
"text": "(SS) : pin 10"
},
{
"code": null,
"e": 7111,
"s": 7095,
"text": "(MOSI) : pin 11"
},
{
"code": null,
"e": 7127,
"s": 7111,
"text": "(MISO) : pin 12"
},
{
"code": null,
"e": 7142,
"s": 7127,
"text": "(SCK) : pin 13"
},
{
"code": null,
"e": 7253,
"s": 7142,
"text": "The ground is common. Following is the diagrammatic representation of the connection between both the boards −"
},
{
"code": null,
"e": 7308,
"s": 7253,
"text": "Let us see examples of SPI as Master and SPI as Slave."
},
{
"code": null,
"e": 7824,
"s": 7308,
"text": "#include <SPI.h>\n\nvoid setup (void) {\n Serial.begin(115200); //set baud rate to 115200 for usart\n digitalWrite(SS, HIGH); // disable Slave Select\n SPI.begin ();\n SPI.setClockDivider(SPI_CLOCK_DIV8);//divide the clock by 8\n}\n\nvoid loop (void) {\n char c;\n digitalWrite(SS, LOW); // enable Slave Select\n // send test string\n for (const char * p = \"Hello, world!\\r\" ; c = *p; p++) {\n SPI.transfer (c);\n Serial.print(c);\n }\n digitalWrite(SS, HIGH); // disable Slave Select\n delay(2000);\n}"
},
{
"code": null,
"e": 8650,
"s": 7824,
"text": "#include <SPI.h>\nchar buff [50];\nvolatile byte indx;\nvolatile boolean process;\n\nvoid setup (void) {\n Serial.begin (115200);\n pinMode(MISO, OUTPUT); // have to send on master in so it set as output\n SPCR |= _BV(SPE); // turn on SPI in slave mode\n indx = 0; // buffer empty\n process = false;\n SPI.attachInterrupt(); // turn on interrupt\n}\nISR (SPI_STC_vect) // SPI interrupt routine { \n byte c = SPDR; // read byte from SPI Data Register\n if (indx < sizeof buff) {\n buff [indx++] = c; // save data in the next index in the array buff\n if (c == '\\r') //check for the end of the word\n process = true;\n }\n}\n\nvoid loop (void) {\n if (process) {\n process = false; //reset the process\n Serial.println (buff); //print the array on serial monitor\n indx= 0; //reset button to zero\n }\n}"
},
{
"code": null,
"e": 8685,
"s": 8650,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 8696,
"s": 8685,
"text": " Amit Rana"
},
{
"code": null,
"e": 8729,
"s": 8696,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 8740,
"s": 8729,
"text": " Amit Rana"
},
{
"code": null,
"e": 8773,
"s": 8740,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8786,
"s": 8773,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8821,
"s": 8786,
"text": "\n 19 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8834,
"s": 8821,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8866,
"s": 8834,
"text": "\n 11 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8879,
"s": 8866,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8910,
"s": 8879,
"text": "\n 9 Lectures \n 41 mins\n"
},
{
"code": null,
"e": 8923,
"s": 8910,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8930,
"s": 8923,
"text": " Print"
},
{
"code": null,
"e": 8941,
"s": 8930,
"text": " Add Notes"
}
] |
A Simple Neural Network. This is the simplest possible neural... | by Doug Wright | Towards Data Science | Though I recently completed Udacity’s Deep Learning NanoDegree program, I am fairly new to this subject. In an effort to further my studies, I am currently reading an excellent book on the subject, Andrew Trask’s Grokking Deep Learning. This blog post is directly inspired by this fantastic book.
So, what is a neural network?
Neural Networks are incredibly powerful parametric models that transform your input data into output data using a combination of matrices and differentiable functions. — Andrew Trask
In other words, a neural network is a way of modeling your input data so that math functions performed on this data produce meaningful results. Let’s dig in and build one to learn more.
def neural_network(input, weight): prediction = input * weight return prediction
This is the simplest possible neural network. We take an input (real world data) and a weight to multiply against the input, then we return the result. So for example, let’s say that Denmark’s soccer team scored 3 goals in their last game. Given a weight of 0.2, we can use our neural network to predict that Denmark has a 60% chance to win their next game.
$ neural_network(3, 0.2)$ => 0.6
But how do we find our weight?
With supervised deep learning, we can train our model with input data and actual results to determine a weight. For example, if we had the following historical data for Denmark’s soccer team.
GOALS | WIN/LOSS3 | 11 | 04 | 1
We can then tell our network to start with a random weight and compute the likelihood of winning. Differing the computed prediction with the actual win/loss number, we can modify our weight over and over again until we get a number that, when multiplied by our inputs (goals scored), gives us a number closest to the actual win/loss result.
So, if the random number at first was 0.5, our prediction would be
3 * 0.5 = 1.51 * 0.5 = 0.54 * 0.5 = 2
With this starting point, our network is 50% over estimating for the first game, 50% over for the second, and 100% over estimating for the last game. Now with this information, we can go back and modify our weight to reduce our error rate in predicting our outcome. This is the essence of linear regression, which I won’t discuss in detail in this article. But this should give you a sense of how we can determine weights with supervised learning, by reducing our error rate each time we modify our weights and compare our predictions with our outcomes.
Before I leave you scratching your head with how the above code can possibly be used to drive autonomous cars, translate language or win a Go game, let’s dive into a multiple input neural net.
What if we had more data than just number of goals scored to predict if Denmark’s soccer team will win their next game. Let’s say we knew the number of goals, their current win/loss ratio, and the number of fans they have.
Goals Scored | Win/Loss Ratio | No. Fans3 | 0.6 | 30,000
With more data, we can combine multiple inputs to compute a weighted sum for our prediction.
def neural_network(inputs, weights): output = 0 for i in range(len(inputs)): output += (inputs[i] * weights[i]) return output
Taking our 3 points of input data with the following weights, we can determine that Denmark is 78% likely to win their next game.
weights = [0.2, 0.3, 0]inputs = [ 3, 0.6, 30000]$ neural_network(inputs, weights)$ => 0.78
Notice that our corresponding weight for number of fans is zero. You can imagine that given a set of historical game data, number of fans may prove to have little outcome on the actual game, thus a computed weight would be close to zero.
Congratulations! You have just learned one of the essential building blocks of Deep Learning neural networks. We take data in and perform math functions (in our case, multiplication) on our data to determine an output. With larger data sets we can train our networks to compute more accurate weights. We can also use hidden layers to perform more functions before determining our outputs.
For more information, I highly recommend Andrew Trask’s Grokking Deep Learning and watching Siraj Raval’s YouTube channel. | [
{
"code": null,
"e": 469,
"s": 172,
"text": "Though I recently completed Udacity’s Deep Learning NanoDegree program, I am fairly new to this subject. In an effort to further my studies, I am currently reading an excellent book on the subject, Andrew Trask’s Grokking Deep Learning. This blog post is directly inspired by this fantastic book."
},
{
"code": null,
"e": 499,
"s": 469,
"text": "So, what is a neural network?"
},
{
"code": null,
"e": 682,
"s": 499,
"text": "Neural Networks are incredibly powerful parametric models that transform your input data into output data using a combination of matrices and differentiable functions. — Andrew Trask"
},
{
"code": null,
"e": 868,
"s": 682,
"text": "In other words, a neural network is a way of modeling your input data so that math functions performed on this data produce meaningful results. Let’s dig in and build one to learn more."
},
{
"code": null,
"e": 955,
"s": 868,
"text": "def neural_network(input, weight): prediction = input * weight return prediction"
},
{
"code": null,
"e": 1313,
"s": 955,
"text": "This is the simplest possible neural network. We take an input (real world data) and a weight to multiply against the input, then we return the result. So for example, let’s say that Denmark’s soccer team scored 3 goals in their last game. Given a weight of 0.2, we can use our neural network to predict that Denmark has a 60% chance to win their next game."
},
{
"code": null,
"e": 1346,
"s": 1313,
"text": "$ neural_network(3, 0.2)$ => 0.6"
},
{
"code": null,
"e": 1377,
"s": 1346,
"text": "But how do we find our weight?"
},
{
"code": null,
"e": 1569,
"s": 1377,
"text": "With supervised deep learning, we can train our model with input data and actual results to determine a weight. For example, if we had the following historical data for Denmark’s soccer team."
},
{
"code": null,
"e": 1621,
"s": 1569,
"text": "GOALS | WIN/LOSS3 | 11 | 04 | 1"
},
{
"code": null,
"e": 1962,
"s": 1621,
"text": "We can then tell our network to start with a random weight and compute the likelihood of winning. Differing the computed prediction with the actual win/loss number, we can modify our weight over and over again until we get a number that, when multiplied by our inputs (goals scored), gives us a number closest to the actual win/loss result."
},
{
"code": null,
"e": 2029,
"s": 1962,
"text": "So, if the random number at first was 0.5, our prediction would be"
},
{
"code": null,
"e": 2067,
"s": 2029,
"text": "3 * 0.5 = 1.51 * 0.5 = 0.54 * 0.5 = 2"
},
{
"code": null,
"e": 2621,
"s": 2067,
"text": "With this starting point, our network is 50% over estimating for the first game, 50% over for the second, and 100% over estimating for the last game. Now with this information, we can go back and modify our weight to reduce our error rate in predicting our outcome. This is the essence of linear regression, which I won’t discuss in detail in this article. But this should give you a sense of how we can determine weights with supervised learning, by reducing our error rate each time we modify our weights and compare our predictions with our outcomes."
},
{
"code": null,
"e": 2814,
"s": 2621,
"text": "Before I leave you scratching your head with how the above code can possibly be used to drive autonomous cars, translate language or win a Go game, let’s dive into a multiple input neural net."
},
{
"code": null,
"e": 3037,
"s": 2814,
"text": "What if we had more data than just number of goals scored to predict if Denmark’s soccer team will win their next game. Let’s say we knew the number of goals, their current win/loss ratio, and the number of fans they have."
},
{
"code": null,
"e": 3124,
"s": 3037,
"text": "Goals Scored | Win/Loss Ratio | No. Fans3 | 0.6 | 30,000"
},
{
"code": null,
"e": 3217,
"s": 3124,
"text": "With more data, we can combine multiple inputs to compute a weighted sum for our prediction."
},
{
"code": null,
"e": 3357,
"s": 3217,
"text": "def neural_network(inputs, weights): output = 0 for i in range(len(inputs)): output += (inputs[i] * weights[i]) return output"
},
{
"code": null,
"e": 3487,
"s": 3357,
"text": "Taking our 3 points of input data with the following weights, we can determine that Denmark is 78% likely to win their next game."
},
{
"code": null,
"e": 3580,
"s": 3487,
"text": "weights = [0.2, 0.3, 0]inputs = [ 3, 0.6, 30000]$ neural_network(inputs, weights)$ => 0.78"
},
{
"code": null,
"e": 3818,
"s": 3580,
"text": "Notice that our corresponding weight for number of fans is zero. You can imagine that given a set of historical game data, number of fans may prove to have little outcome on the actual game, thus a computed weight would be close to zero."
},
{
"code": null,
"e": 4207,
"s": 3818,
"text": "Congratulations! You have just learned one of the essential building blocks of Deep Learning neural networks. We take data in and perform math functions (in our case, multiplication) on our data to determine an output. With larger data sets we can train our networks to compute more accurate weights. We can also use hidden layers to perform more functions before determining our outputs."
}
] |
Java Stream findAny() with examples | The findAny() method of the Java Stream returns an Optional for some element of the stream or an empty Optional if the stream is empty. Here, Optional is a container object which may or may not contain a non-null value.
Following is an example to implement the findAny() method in Java −
Live Demo
import java.util.*;
public class Demo {
public static void main(String[] args){
List<Integer> list = Arrays.asList(10, 20, 30, 40, 50);
Optional<Integer> res = list.stream().findAny();
if (res.isPresent()) {
System.out.println(res.get());
} else {
System.out.println("None!");
}
}
}
10
Let us see another example with list of strings −
Live Demo
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<String> myList = Arrays.asList("Kevin", "Jofra","Tom", "Chris", "Liam");
Optional<String> res = myList.stream().findAny();
if (res.isPresent()) {
System.out.println(res.get());
} else {
System.out.println("None!");
}
}
}
Kevin | [
{
"code": null,
"e": 1282,
"s": 1062,
"text": "The findAny() method of the Java Stream returns an Optional for some element of the stream or an empty Optional if the stream is empty. Here, Optional is a container object which may or may not contain a non-null value."
},
{
"code": null,
"e": 1350,
"s": 1282,
"text": "Following is an example to implement the findAny() method in Java −"
},
{
"code": null,
"e": 1361,
"s": 1350,
"text": " Live Demo"
},
{
"code": null,
"e": 1698,
"s": 1361,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String[] args){\n List<Integer> list = Arrays.asList(10, 20, 30, 40, 50);\n Optional<Integer> res = list.stream().findAny();\n if (res.isPresent()) {\n System.out.println(res.get());\n } else {\n System.out.println(\"None!\");\n }\n }\n}"
},
{
"code": null,
"e": 1701,
"s": 1698,
"text": "10"
},
{
"code": null,
"e": 1751,
"s": 1701,
"text": "Let us see another example with list of strings −"
},
{
"code": null,
"e": 1762,
"s": 1751,
"text": " Live Demo"
},
{
"code": null,
"e": 2123,
"s": 1762,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String[] args) {\n List<String> myList = Arrays.asList(\"Kevin\", \"Jofra\",\"Tom\", \"Chris\", \"Liam\");\n Optional<String> res = myList.stream().findAny();\n if (res.isPresent()) {\n System.out.println(res.get());\n } else {\n System.out.println(\"None!\");\n }\n }\n}"
},
{
"code": null,
"e": 2129,
"s": 2123,
"text": "Kevin"
}
] |
How to strip down all the punctuation from a string in Python? | The fastest way to strip all punctuation from a string is to use str.translate(). You can use it as follows:
import string
s = "string. With. Punctuation?"
print s.translate(None, string.punctuation)
This will give us the output:
string With Punctuation
If you want a more readable solution, you can explicitly iterate over the set and ignore all punctuation in a loop as follows:
import string
s = "string. With. Punctuation?"
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
print s
This will give us the output:
string With Punctuation | [
{
"code": null,
"e": 1171,
"s": 1062,
"text": "The fastest way to strip all punctuation from a string is to use str.translate(). You can use it as follows:"
},
{
"code": null,
"e": 1262,
"s": 1171,
"text": "import string\ns = \"string. With. Punctuation?\"\nprint s.translate(None, string.punctuation)"
},
{
"code": null,
"e": 1292,
"s": 1262,
"text": "This will give us the output:"
},
{
"code": null,
"e": 1316,
"s": 1292,
"text": "string With Punctuation"
},
{
"code": null,
"e": 1443,
"s": 1316,
"text": "If you want a more readable solution, you can explicitly iterate over the set and ignore all punctuation in a loop as follows:"
},
{
"code": null,
"e": 1581,
"s": 1443,
"text": "import string\ns = \"string. With. Punctuation?\"\nexclude = set(string.punctuation)\ns = ''.join(ch for ch in s if ch not in exclude)\nprint s"
},
{
"code": null,
"e": 1611,
"s": 1581,
"text": "This will give us the output:"
},
{
"code": null,
"e": 1635,
"s": 1611,
"text": "string With Punctuation"
}
] |
Counting elements of an array using a recursive function in JS? | The recursive function calls itself with some base condition. Let’s say the following is our array
with marks −
var listOfMarks=[56,78,90,94,91,82,77];
Following is the code to get the count of array elements −
function countNumberOfElementsUsingRecursive(listOfMarks) {
if (listOfMarks.length == 0) {
return 0;
}
return 1 +
countNumberOfElementsUsingRecursive(listOfMarks.slice(1));
}
var listOfMarks=[56,78,90,94,91,82,77];
console.log("The array=");
console.log(listOfMarks);
var numberOfElements=countNumberOfElementsUsingRecursive(listOfMarks);
console.log("The Number of elements = "+numberOfElements);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo110.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo110.js
The array=[
56, 78, 90, 94,
91, 82, 77
]
The Number of elements = 7 | [
{
"code": null,
"e": 1174,
"s": 1062,
"text": "The recursive function calls itself with some base condition. Let’s say the following is our array\nwith marks −"
},
{
"code": null,
"e": 1214,
"s": 1174,
"text": "var listOfMarks=[56,78,90,94,91,82,77];"
},
{
"code": null,
"e": 1273,
"s": 1214,
"text": "Following is the code to get the count of array elements −"
},
{
"code": null,
"e": 1689,
"s": 1273,
"text": "function countNumberOfElementsUsingRecursive(listOfMarks) {\n if (listOfMarks.length == 0) {\n return 0;\n }\n return 1 +\n countNumberOfElementsUsingRecursive(listOfMarks.slice(1));\n}\nvar listOfMarks=[56,78,90,94,91,82,77];\nconsole.log(\"The array=\");\nconsole.log(listOfMarks);\nvar numberOfElements=countNumberOfElementsUsingRecursive(listOfMarks);\nconsole.log(\"The Number of elements = \"+numberOfElements);"
},
{
"code": null,
"e": 1755,
"s": 1689,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1773,
"s": 1755,
"text": "node fileName.js."
},
{
"code": null,
"e": 1807,
"s": 1773,
"text": "Here, my file name is demo110.js."
},
{
"code": null,
"e": 1848,
"s": 1807,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1972,
"s": 1848,
"text": "PS C:\\Users\\Amit\\JavaScript-code> node demo110.js\nThe array=[\n 56, 78, 90, 94,\n 91, 82, 77\n]\nThe Number of elements = 7"
}
] |
.NET Core - SDK | In this chapter, we will understand the upcoming features in .NET Core. We will start with the .NET command line tools by opening the following Url in browser https://github.com/dotnet/cli
To know more about the progress, you can download the latest version of .NET Core SDK by scrolling down and you will see the Installer and Binaries section.
You can see the latest version of preview tools for different operating systems, let us select the Installer as per your operating system.
We are working on preview 1 of .NET Core 2.0.
Let us now look at our current tooling by opening the command prompt and execute the following command.
dotnet --info
You will see information about the currently installed version of .NET Command Line Tools on your system as shown below.
You can see that currently we have preview 2 tooling. Let us now run the following command to see about the new command.
dotnet help new
For new command language of project, you can select like C# and F# and the type of project, etc.
Let us now see the changes in the latest version of .NET Core. Once the installer is downloaded, double-click on it to install it. Click on Install.
The following screenshot shows the installation process.
It will start the installation process. One the installation is finished, Close this dialog.
Open the command prompt and execute the following command.
dotnet --info
You will see information of currently installed version of .NET Command Line Tools on your system as shown below.
You can now see that we have preview1 tooling of .NET Core 2. Let us now run the following code in the command prompt to see about the new command in .NET Core 2 preview1.
dotnet help new
The command helps you download packages as well to the package cache.
The command opens the following webpage which contains information about the new command in .NET Core 2 preview1.
Let us scroll down, you can now see that we can create the .NET Core application with more templates.
We can now create mstest, web, mvc and webapi projects as well using the command line.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2575,
"s": 2386,
"text": "In this chapter, we will understand the upcoming features in .NET Core. We will start with the .NET command line tools by opening the following Url in browser https://github.com/dotnet/cli"
},
{
"code": null,
"e": 2732,
"s": 2575,
"text": "To know more about the progress, you can download the latest version of .NET Core SDK by scrolling down and you will see the Installer and Binaries section."
},
{
"code": null,
"e": 2871,
"s": 2732,
"text": "You can see the latest version of preview tools for different operating systems, let us select the Installer as per your operating system."
},
{
"code": null,
"e": 2917,
"s": 2871,
"text": "We are working on preview 1 of .NET Core 2.0."
},
{
"code": null,
"e": 3021,
"s": 2917,
"text": "Let us now look at our current tooling by opening the command prompt and execute the following command."
},
{
"code": null,
"e": 3037,
"s": 3021,
"text": "dotnet --info \n"
},
{
"code": null,
"e": 3158,
"s": 3037,
"text": "You will see information about the currently installed version of .NET Command Line Tools on your system as shown below."
},
{
"code": null,
"e": 3279,
"s": 3158,
"text": "You can see that currently we have preview 2 tooling. Let us now run the following command to see about the new command."
},
{
"code": null,
"e": 3296,
"s": 3279,
"text": "dotnet help new\n"
},
{
"code": null,
"e": 3393,
"s": 3296,
"text": "For new command language of project, you can select like C# and F# and the type of project, etc."
},
{
"code": null,
"e": 3542,
"s": 3393,
"text": "Let us now see the changes in the latest version of .NET Core. Once the installer is downloaded, double-click on it to install it. Click on Install."
},
{
"code": null,
"e": 3599,
"s": 3542,
"text": "The following screenshot shows the installation process."
},
{
"code": null,
"e": 3692,
"s": 3599,
"text": "It will start the installation process. One the installation is finished, Close this dialog."
},
{
"code": null,
"e": 3751,
"s": 3692,
"text": "Open the command prompt and execute the following command."
},
{
"code": null,
"e": 3766,
"s": 3751,
"text": "dotnet --info\n"
},
{
"code": null,
"e": 3880,
"s": 3766,
"text": "You will see information of currently installed version of .NET Command Line Tools on your system as shown below."
},
{
"code": null,
"e": 4052,
"s": 3880,
"text": "You can now see that we have preview1 tooling of .NET Core 2. Let us now run the following code in the command prompt to see about the new command in .NET Core 2 preview1."
},
{
"code": null,
"e": 4069,
"s": 4052,
"text": "dotnet help new\n"
},
{
"code": null,
"e": 4139,
"s": 4069,
"text": "The command helps you download packages as well to the package cache."
},
{
"code": null,
"e": 4253,
"s": 4139,
"text": "The command opens the following webpage which contains information about the new command in .NET Core 2 preview1."
},
{
"code": null,
"e": 4355,
"s": 4253,
"text": "Let us scroll down, you can now see that we can create the .NET Core application with more templates."
},
{
"code": null,
"e": 4442,
"s": 4355,
"text": "We can now create mstest, web, mvc and webapi projects as well using the command line."
},
{
"code": null,
"e": 4449,
"s": 4442,
"text": " Print"
},
{
"code": null,
"e": 4460,
"s": 4449,
"text": " Add Notes"
}
] |
C# | Get a collection of values in the StringDictionary - GeeksforGeeks | 01 Feb, 2019
StringDictionary.Values property is used to get a collection of values in the StringDictionary.
Syntax:
public virtual System.Collections.ICollection Values { get; }
Return Value: An ICollection that provides the values in the StringDictionary.
Example 1:
// C# code to get a collection// of values in the StringDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a StringDictionary named myDict StringDictionary myDict = new StringDictionary(); // Adding key and value into the StringDictionary myDict.Add("A", "Apple"); myDict.Add("B", "Banana"); myDict.Add("C", "Cat"); myDict.Add("D", "Dog"); // Getting a collection of values // in the StringDictionary foreach(string val in myDict.Values) { Console.WriteLine(val); } }}
Output:
Dog
Banana
Cat
Apple
Example 2:
// C# code to get a collection// of values in the StringDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a StringDictionary named myDict StringDictionary myDict = new StringDictionary(); // Adding key and value into the StringDictionary myDict.Add("3", "prime & odd"); myDict.Add("2", "prime & even"); myDict.Add("4", "non-prime & even"); myDict.Add("9", "non-prime & odd"); // Getting a collection of values // in the StringDictionary foreach(string val in myDict.Values) { Console.WriteLine(val); } }}
Output:
prime & even
prime & odd
non-prime & odd
non-prime & even
Note:
The order of the values in the ICollection is unspecified, but it is the same order as the associated keys in the ICollection returned by the Keys method.
The returned ICollection is not a static copy. Instead, the ICollection refers back to the values in the original StringDictionary. Therefore, changes to the StringDictionary continue to be reflected in the ICollection.
Retrieving the value of this property is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringdictionary.values?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Specialized-Namespace
CSharp-Specialized-StringDictionary
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C# | [
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24007,
"s": 23911,
"text": "StringDictionary.Values property is used to get a collection of values in the StringDictionary."
},
{
"code": null,
"e": 24015,
"s": 24007,
"text": "Syntax:"
},
{
"code": null,
"e": 24078,
"s": 24015,
"text": "public virtual System.Collections.ICollection Values { get; }\n"
},
{
"code": null,
"e": 24157,
"s": 24078,
"text": "Return Value: An ICollection that provides the values in the StringDictionary."
},
{
"code": null,
"e": 24168,
"s": 24157,
"text": "Example 1:"
},
{
"code": "// C# code to get a collection// of values in the StringDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a StringDictionary named myDict StringDictionary myDict = new StringDictionary(); // Adding key and value into the StringDictionary myDict.Add(\"A\", \"Apple\"); myDict.Add(\"B\", \"Banana\"); myDict.Add(\"C\", \"Cat\"); myDict.Add(\"D\", \"Dog\"); // Getting a collection of values // in the StringDictionary foreach(string val in myDict.Values) { Console.WriteLine(val); } }}",
"e": 24855,
"s": 24168,
"text": null
},
{
"code": null,
"e": 24863,
"s": 24855,
"text": "Output:"
},
{
"code": null,
"e": 24885,
"s": 24863,
"text": "Dog\nBanana\nCat\nApple\n"
},
{
"code": null,
"e": 24896,
"s": 24885,
"text": "Example 2:"
},
{
"code": "// C# code to get a collection// of values in the StringDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a StringDictionary named myDict StringDictionary myDict = new StringDictionary(); // Adding key and value into the StringDictionary myDict.Add(\"3\", \"prime & odd\"); myDict.Add(\"2\", \"prime & even\"); myDict.Add(\"4\", \"non-prime & even\"); myDict.Add(\"9\", \"non-prime & odd\"); // Getting a collection of values // in the StringDictionary foreach(string val in myDict.Values) { Console.WriteLine(val); } }}",
"e": 25620,
"s": 24896,
"text": null
},
{
"code": null,
"e": 25628,
"s": 25620,
"text": "Output:"
},
{
"code": null,
"e": 25687,
"s": 25628,
"text": "prime & even\nprime & odd\nnon-prime & odd\nnon-prime & even\n"
},
{
"code": null,
"e": 25693,
"s": 25687,
"text": "Note:"
},
{
"code": null,
"e": 25848,
"s": 25693,
"text": "The order of the values in the ICollection is unspecified, but it is the same order as the associated keys in the ICollection returned by the Keys method."
},
{
"code": null,
"e": 26068,
"s": 25848,
"text": "The returned ICollection is not a static copy. Instead, the ICollection refers back to the values in the original StringDictionary. Therefore, changes to the StringDictionary continue to be reflected in the ICollection."
},
{
"code": null,
"e": 26128,
"s": 26068,
"text": "Retrieving the value of this property is an O(1) operation."
},
{
"code": null,
"e": 26139,
"s": 26128,
"text": "Reference:"
},
{
"code": null,
"e": 26262,
"s": 26139,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringdictionary.values?view=netframework-4.7.2"
},
{
"code": null,
"e": 26291,
"s": 26262,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 26320,
"s": 26291,
"text": "CSharp-Specialized-Namespace"
},
{
"code": null,
"e": 26356,
"s": 26320,
"text": "CSharp-Specialized-StringDictionary"
},
{
"code": null,
"e": 26359,
"s": 26356,
"text": "C#"
},
{
"code": null,
"e": 26457,
"s": 26359,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26466,
"s": 26457,
"text": "Comments"
},
{
"code": null,
"e": 26479,
"s": 26466,
"text": "Old Comments"
},
{
"code": null,
"e": 26519,
"s": 26479,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26542,
"s": 26519,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26570,
"s": 26542,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 26592,
"s": 26570,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 26609,
"s": 26592,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 26649,
"s": 26609,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 26682,
"s": 26649,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 26725,
"s": 26682,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 26741,
"s": 26725,
"text": "C# | List Class"
}
] |
What are the packages in Python? | To understand packages, you also need to know about modules. Any Python file is a module, its name being the file's base name/module's __name__ property without the .py extension. A package is a collection of Python modules, i.e., a package is a directory of Python modules containing an additional __init__.py file. The __init__.py distinguishes a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file.
When you import a module or a package, the corresponding object created by Python is always of type module. This means that the distinction between module and package is just at the file system level. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules.
For example, in the DateTime module, there is a submodule called date. When you import DateTime, it won't be imported. You'll need to import it separately.
>>> import datetime
>>> date.today()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'date' is not defined
>>> from datetime import date
>>> date.today()
datetime.date(2017, 9, 1) | [
{
"code": null,
"e": 1609,
"s": 1062,
"text": "To understand packages, you also need to know about modules. Any Python file is a module, its name being the file's base name/module's __name__ property without the .py extension. A package is a collection of Python modules, i.e., a package is a directory of Python modules containing an additional __init__.py file. The __init__.py distinguishes a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file."
},
{
"code": null,
"e": 1976,
"s": 1609,
"text": "When you import a module or a package, the corresponding object created by Python is always of type module. This means that the distinction between module and package is just at the file system level. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules."
},
{
"code": null,
"e": 2132,
"s": 1976,
"text": "For example, in the DateTime module, there is a submodule called date. When you import DateTime, it won't be imported. You'll need to import it separately."
},
{
"code": null,
"e": 2353,
"s": 2132,
"text": ">>> import datetime\n>>> date.today()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'date' is not defined\n>>> from datetime import date\n>>> date.today()\ndatetime.date(2017, 9, 1)"
}
] |
How to modify properties of a nested object in JavaScript? | There are two methods to modify properties of nested objects. One is Dot method and the other is Bracket method. The functionality is same for both the methods, but the only difference is their notation.
lets' discuss them in detail.
In the following example initially the value of property country is England. But using Dot notation the value is changed to India.
Live Demo
<html>
<body>
<script>
var person;
var txt = '';
person = {
"name":"Ram",
"age":27,
"address": {
"houseno":123,
"streetname":"Baker street",
"country":"England"
}
}
document.write("Before change : " + " " + person.address.country);
person.address.country = "India";
document.write("</br>");
document.write("After change : " + " " + person.address.country);
</script>
</body>
</html>
Before change : England
After change : India
In the following example the value of property 'country' is changed from England to India using Bracket notation.
Live Demo
<html>
<body>
<script>
var person;
var txt = '';
person = {
"name":"Ram",
"age":27,
"address": {
"houseno":123,
"streetname":"Baker street",
"country":"England"
}
}
document.write("Before change : " + " " + person.address["country"]);
person.address.country = "India";
document.write("</br>");
document.write("After change : " + " " + person.address["country"]);
</script>
</body>
</html>
Before change : England
After change : India | [
{
"code": null,
"e": 1267,
"s": 1062,
"text": "There are two methods to modify properties of nested objects. One is Dot method and the other is Bracket method. The functionality is same for both the methods, but the only difference is their notation. "
},
{
"code": null,
"e": 1297,
"s": 1267,
"text": "lets' discuss them in detail."
},
{
"code": null,
"e": 1428,
"s": 1297,
"text": "In the following example initially the value of property country is England. But using Dot notation the value is changed to India."
},
{
"code": null,
"e": 1438,
"s": 1428,
"text": "Live Demo"
},
{
"code": null,
"e": 1896,
"s": 1438,
"text": "<html>\n<body>\n<script>\n var person;\n var txt = '';\n person = {\n \"name\":\"Ram\",\n \"age\":27,\n \"address\": {\n \"houseno\":123,\n \"streetname\":\"Baker street\",\n \"country\":\"England\"\n }\n }\n document.write(\"Before change : \" + \" \" + person.address.country);\n person.address.country = \"India\";\n document.write(\"</br>\");\n document.write(\"After change : \" + \" \" + person.address.country);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1941,
"s": 1896,
"text": "Before change : England\nAfter change : India"
},
{
"code": null,
"e": 2057,
"s": 1941,
"text": "In the following example the value of property 'country' is changed from England to India using Bracket notation. "
},
{
"code": null,
"e": 2067,
"s": 2057,
"text": "Live Demo"
},
{
"code": null,
"e": 2531,
"s": 2067,
"text": "<html>\n<body>\n<script>\n var person;\n var txt = '';\n person = {\n \"name\":\"Ram\",\n \"age\":27,\n \"address\": {\n \"houseno\":123,\n \"streetname\":\"Baker street\",\n \"country\":\"England\"\n }\n }\n document.write(\"Before change : \" + \" \" + person.address[\"country\"]);\n person.address.country = \"India\";\n document.write(\"</br>\");\n document.write(\"After change : \" + \" \" + person.address[\"country\"]);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2576,
"s": 2531,
"text": "Before change : England\nAfter change : India"
}
] |
Difference Between malloc() and calloc() with Examples - GeeksforGeeks | 21 Jan, 2022
Pre-requisite: Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()The functions malloc() and calloc() are library functions that allocate memory dynamically. Dynamic means the memory is allocated during runtime (execution of the program) from the heap segment.
malloc() allocates a memory block of given size (in bytes) and returns a pointer to the beginning of the block. malloc() doesn’t initialize the allocated memory. If you try to read from the allocated memory without first initializing it, then you will invoke undefined behavior, which will usually mean the values you read will be garbage.
calloc() allocates the memory and also initializes every byte in the allocated memory to 0. If you try to read the value of the allocated memory without initializing it, you’ll get 0 as it has already been initialized to 0 by calloc().
malloc() takes a single argument, which is the number of bytes to allocate.
Unlike malloc(), calloc() takes two arguments: 1) Number of blocks to be allocated. 2) Size of each block in bytes.
After successful allocation in malloc() and calloc(), a pointer to the block of memory is returned otherwise NULL is returned which indicates failure.
C
#include <stdio.h>#include <stdlib.h> int main(){ // Both of these allocate the same number of bytes, // which is the amount of bytes that is required to // store 5 int values. // The memory allocated by calloc will be // zero-initialized, but the memory allocated with // malloc will be uninitialized so reading it would be // undefined behavior. int* allocated_with_malloc = malloc(5 * sizeof(int)); int* allocated_with_calloc = calloc(5, sizeof(int)); // As you can see, all of the values are initialized to // zero. printf("Values of allocated_with_calloc: "); for (size_t i = 0; i < 5; ++i) { printf("%d ", allocated_with_calloc[i]); } putchar('\n'); // This malloc requests 1 terabyte of dynamic memory, // which is unavailable in this case, and so the // allocation fails and returns NULL. int* failed_malloc = malloc(1000000000000); if (failed_malloc == NULL) { printf("The allocation failed, the value of " "failed_malloc is: %p", (void*)failed_malloc); } // Remember to always free dynamically allocated memory. free(allocated_with_malloc); free(allocated_with_calloc);}
Values of allocated_with_calloc: 0 0 0 0 0
The allocation failed, the value of failed_malloc is: (nil)
chakradharkandula
shubham_singh
Navfal
HarshitHiremath
lennymclennington
C-Dynamic Memory Allocation
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Command line arguments in C/C++
fork() in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
Exception Handling in C++
Function Pointer in C
Structures in C
Substring in C++
'this' pointer in C++
std::string class in C++ | [
{
"code": null,
"e": 24356,
"s": 24328,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 24643,
"s": 24356,
"text": "Pre-requisite: Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()The functions malloc() and calloc() are library functions that allocate memory dynamically. Dynamic means the memory is allocated during runtime (execution of the program) from the heap segment."
},
{
"code": null,
"e": 24983,
"s": 24643,
"text": "malloc() allocates a memory block of given size (in bytes) and returns a pointer to the beginning of the block. malloc() doesn’t initialize the allocated memory. If you try to read from the allocated memory without first initializing it, then you will invoke undefined behavior, which will usually mean the values you read will be garbage."
},
{
"code": null,
"e": 25219,
"s": 24983,
"text": "calloc() allocates the memory and also initializes every byte in the allocated memory to 0. If you try to read the value of the allocated memory without initializing it, you’ll get 0 as it has already been initialized to 0 by calloc()."
},
{
"code": null,
"e": 25295,
"s": 25219,
"text": "malloc() takes a single argument, which is the number of bytes to allocate."
},
{
"code": null,
"e": 25411,
"s": 25295,
"text": "Unlike malloc(), calloc() takes two arguments: 1) Number of blocks to be allocated. 2) Size of each block in bytes."
},
{
"code": null,
"e": 25563,
"s": 25411,
"text": "After successful allocation in malloc() and calloc(), a pointer to the block of memory is returned otherwise NULL is returned which indicates failure. "
},
{
"code": null,
"e": 25565,
"s": 25563,
"text": "C"
},
{
"code": "#include <stdio.h>#include <stdlib.h> int main(){ // Both of these allocate the same number of bytes, // which is the amount of bytes that is required to // store 5 int values. // The memory allocated by calloc will be // zero-initialized, but the memory allocated with // malloc will be uninitialized so reading it would be // undefined behavior. int* allocated_with_malloc = malloc(5 * sizeof(int)); int* allocated_with_calloc = calloc(5, sizeof(int)); // As you can see, all of the values are initialized to // zero. printf(\"Values of allocated_with_calloc: \"); for (size_t i = 0; i < 5; ++i) { printf(\"%d \", allocated_with_calloc[i]); } putchar('\\n'); // This malloc requests 1 terabyte of dynamic memory, // which is unavailable in this case, and so the // allocation fails and returns NULL. int* failed_malloc = malloc(1000000000000); if (failed_malloc == NULL) { printf(\"The allocation failed, the value of \" \"failed_malloc is: %p\", (void*)failed_malloc); } // Remember to always free dynamically allocated memory. free(allocated_with_malloc); free(allocated_with_calloc);}",
"e": 26766,
"s": 25565,
"text": null
},
{
"code": null,
"e": 26870,
"s": 26766,
"text": "Values of allocated_with_calloc: 0 0 0 0 0 \nThe allocation failed, the value of failed_malloc is: (nil)"
},
{
"code": null,
"e": 26888,
"s": 26870,
"text": "chakradharkandula"
},
{
"code": null,
"e": 26902,
"s": 26888,
"text": "shubham_singh"
},
{
"code": null,
"e": 26909,
"s": 26902,
"text": "Navfal"
},
{
"code": null,
"e": 26925,
"s": 26909,
"text": "HarshitHiremath"
},
{
"code": null,
"e": 26943,
"s": 26925,
"text": "lennymclennington"
},
{
"code": null,
"e": 26971,
"s": 26943,
"text": "C-Dynamic Memory Allocation"
},
{
"code": null,
"e": 26982,
"s": 26971,
"text": "C Language"
},
{
"code": null,
"e": 27080,
"s": 26982,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27089,
"s": 27080,
"text": "Comments"
},
{
"code": null,
"e": 27102,
"s": 27089,
"text": "Old Comments"
},
{
"code": null,
"e": 27134,
"s": 27102,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 27146,
"s": 27134,
"text": "fork() in C"
},
{
"code": null,
"e": 27193,
"s": 27146,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 27231,
"s": 27193,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27257,
"s": 27231,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 27279,
"s": 27257,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27295,
"s": 27279,
"text": "Structures in C"
},
{
"code": null,
"e": 27312,
"s": 27295,
"text": "Substring in C++"
},
{
"code": null,
"e": 27334,
"s": 27312,
"text": "'this' pointer in C++"
}
] |
Double the first element and move zero to end - GeeksforGeeks | 28 Jan, 2022
For a given array of n integers and assume that ‘0’ is an invalid number and all others as a valid number. Convert the array in such a way that if both current and next element is valid and both have same value then double current value and replace the next number with 0. After the modification, rearrange the array such that all 0’s shifted to the end. Examples:
Input : arr[] = {2, 2, 0, 4, 0, 8}
Output : 4 4 8 0 0 0
Input : arr[] = {0, 2, 2, 2, 0, 6, 6, 0, 0, 8}
Output : 4 2 12 8 0 0 0 0 0 0
Source: Microsoft IDC Interview Experience | Set 150.
Approach: First modify the array as mentioned, i.e., if the next valid number is the same as the current number, double its value and replace the next number with 0. Algorithm for Modification:
1. if n == 1
2. return
3. for i = 0 to n-2
4. if (arr[i] != 0) && (arr[i] == arr[i+1])
5. arr[i] = 2 * arr[i]
6. arr[i+1] = 0
7. i++
After modifying the array, Move all zeroes to the end of the array.
C++
Java
Python3
C#
Javascript
// C++ implementation to rearrange the array// elements after modification#include <bits/stdc++.h> using namespace std; // function which pushes all zeros to end of// an array.void pushZerosToEnd(int arr[], int n){ // Count of non-zero elements int count = 0; // Traverse the array. If element encountered // is non-zero, then replace the element at // index 'count' with this element for (int i = 0; i < n; i++) if (arr[i] != 0) // here count is incremented arr[count++] = arr[i]; // Now all non-zero elements have been shifted // to front and 'count' is set as index of // first 0. Make all elements 0 from count // to end. while (count < n) arr[count++] = 0;} // function to rearrange the array elements// after modificationvoid modifyAndRearrangeArr(int arr[], int n){ // if 'arr[]' contains a single element // only if (n == 1) return; // traverse the array for (int i = 0; i < n - 1; i++) { // if true, perform the required modification if ((arr[i] != 0) && (arr[i] == arr[i + 1])) { // double current index value arr[i] = 2 * arr[i]; // put 0 in the next index arr[i + 1] = 0; // increment by 1 so as to move two // indexes ahead during loop iteration i++; } } // push all the zeros at the end of 'arr[]' pushZerosToEnd(arr, n);} // function to print the array elementsvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Driver program to test aboveint main(){ int arr[] = { 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Original array: "; printArray(arr, n); modifyAndRearrangeArr(arr, n); cout << "\nModified array: "; printArray(arr, n); return 0;}
// Java implementation to rearrange the// array elements after modificationclass GFG { // function which pushes all // zeros to end of an array. static void pushZerosToEnd(int arr[], int n) { // Count of non-zero elements int count = 0; // Traverse the array. If element // encountered is non-zero, then // replace the element at index // 'count' with this element for (int i = 0; i < n; i++) if (arr[i] != 0) // here count is incremented arr[count++] = arr[i]; // Now all non-zero elements // have been shifted to front and // 'count' is set as index of first 0. // Make all elements 0 from count to end. while (count < n) arr[count++] = 0; } // function to rearrange the array // elements after modification static void modifyAndRearrangeArr(int arr[], int n) { // if 'arr[]' contains a single element // only if (n == 1) return; // traverse the array for (int i = 0; i < n - 1; i++) { // if true, perform the required modification if ((arr[i] != 0) && (arr[i] == arr[i + 1])) { // double current index value arr[i] = 2 * arr[i]; // put 0 in the next index arr[i + 1] = 0; // increment by 1 so as to move two // indexes ahead during loop iteration i++; } } // push all the zeros at // the end of 'arr[]' pushZerosToEnd(arr, n); } // function to print the array elements static void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); System.out.println(); } // Driver program to test above public static void main(String[] args) { int arr[] = { 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 }; int n = arr.length; System.out.print("Original array: "); printArray(arr, n); modifyAndRearrangeArr(arr, n); System.out.print("Modified array: "); printArray(arr, n); }} // This code is contributed // by prerna saini
# Python3 implementation to rearrange# the array elements after modification # function which pushes all zeros# to end of an array.def pushZerosToEnd(arr, n): # Count of non-zero elements count = 0 # Traverse the array. If element # encountered is non-zero, then # replace the element at index # 'count' with this element for i in range(0, n): if arr[i] != 0: # here count is incremented arr[count] = arr[i] count+=1 # Now all non-zero elements have been # shifted to front and 'count' is set # as index of first 0. Make all # elements 0 from count to end. while (count < n): arr[count] = 0 count+=1 # function to rearrange the array# elements after modificationdef modifyAndRearrangeArr(ar, n): # if 'arr[]' contains a single # element only if n == 1: return # traverse the array for i in range(0, n - 1): # if true, perform the required modification if (arr[i] != 0) and (arr[i] == arr[i + 1]): # double current index value arr[i] = 2 * arr[i] # put 0 in the next index arr[i + 1] = 0 # increment by 1 so as to move two # indexes ahead during loop iteration i+=1 # push all the zeros at the end of 'arr[]' pushZerosToEnd(arr, n) # function to print the array elementsdef printArray(arr, n): for i in range(0, n): print(arr[i],end=" ") # Driver program to test abovearr = [ 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 ]n = len(arr) print("Original array:",end=" ")printArray(arr, n) modifyAndRearrangeArr(arr, n) print("\nModified array:",end=" ")printArray(arr, n) # This code is contributed by Smitha Dinesh Semwal
// C# implementation to rearrange the// array elements after modificationusing System; class GFG { // function which pushes all // zeros to end of an array. static void pushZerosToEnd(int[] arr, int n) { // Count of non-zero elements int count = 0; // Traverse the array. If element // encountered is non-zero, then // replace the element at index // 'count' with this element for (int i = 0; i < n; i++) if (arr[i] != 0) // here count is incremented arr[count++] = arr[i]; // Now all non-zero elements // have been shifted to front and // 'count' is set as index of first 0. // Make all elements 0 from count to end. while (count < n) arr[count++] = 0; } // function to rearrange the array // elements after modification static void modifyAndRearrangeArr(int[] arr, int n) { // if 'arr[]' contains a single element // only if (n == 1) return; // traverse the array for (int i = 0; i < n - 1; i++) { // if true, perform the required modification if ((arr[i] != 0) && (arr[i] == arr[i + 1])) { // double current index value arr[i] = 2 * arr[i]; // put 0 in the next index arr[i + 1] = 0; // increment by 1 so as to move two // indexes ahead during loop iteration i++; } } // push all the zeros at // the end of 'arr[]' pushZerosToEnd(arr, n); } // function to print the array elements static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); Console.WriteLine(); } // Driver program to test above public static void Main() { int[] arr = { 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 }; int n = arr.Length; Console.Write("Original array: "); printArray(arr, n); modifyAndRearrangeArr(arr, n); Console.Write("Modified array: "); printArray(arr, n); }} // This code is contributed by Sam007
<script> // JavaScript implementation to rearrange the array // elements after modification // function which pushes all zeros to end of // an array. function pushZerosToEnd(arr, n) { // Count of non-zero elements var count = 0; // Traverse the array. If element encountered // is non-zero, then replace the element at // index 'count' with this element for (var i = 0; i < n; i++) if (arr[i] != 0) // here count is incremented arr[count++] = arr[i]; // Now all non-zero elements have been shifted // to front and 'count' is set as index of // first 0. Make all elements 0 from count // to end. while (count < n) arr[count++] = 0; } // function to rearrange the array elements // after modification function modifyAndRearrangeArr(arr, n) { // if 'arr[]' contains a single element // only if (n == 1) return; // traverse the array for (var i = 0; i < n - 1; i++) { // if true, perform the required modification if (arr[i] != 0 && arr[i] == arr[i + 1]) { // double current index value arr[i] = 2 * arr[i]; // put 0 in the next index arr[i + 1] = 0; // increment by 1 so as to move two // indexes ahead during loop iteration i++; } } // push all the zeros at the end of 'arr[]' pushZerosToEnd(arr, n); } // function to print the array elements function printArray(arr, n) { for (var i = 0; i < n; i++) document.write(arr[i] + " "); } // Driver program to test above var arr = [0, 2, 2, 2, 0, 6, 6, 0, 0, 8]; var n = arr.length; document.write("Original array: "); printArray(arr, n); modifyAndRearrangeArr(arr, n); document.write("<br>"); document.write("Modified array: "); printArray(arr, n); // This code is contributed by rdtank. </script>
Output:
Original array: 0 2 2 2 0 6 6 0 0 8
Modified array: 4 2 12 8 0 0 0 0 0 0
Time Complexity: O(n).
Approach with efficient zero shiftings:
Although the above solution is efficient, we can further optimise it in shifting zero algorithms by reducing the number of operations.
In the above shifting algorithms, we scan some elements twice when we set the count index to last index element to zero.
Efficient Zero Shifting Algorithms:
int lastSeenPositiveIndex = 0;
for( index = 0; index < n; index++)
{
if(array[index] != 0)
{
swap(array[index], array[lastSeenPositiveIndex]);
lastSeenPositiveIndex++;
}
}
C++
Java
Python3
C#
Javascript
// Utility Function For Swapping Two Element Of An Arrayvoid swap(int& a, int& b) { a = b + a - (b = a); } // shift all zero to left side of an arrayvoid shiftAllZeroToLeft(int array[], int n){ // Maintain last index with positive value int lastSeenNonZero = 0; for (index = 0; index < n; index++) { // If Element is non-zero if (array[index] != 0) { // swap current index, with lastSeen non-zero swap(array[index], array[lastSeenNonZero]); // next element will be last seen non-zero lastSeenNonZero++; } }} // This snippet is contributed By: Faizanur Rahman
class GFG { // Function For Swapping Two Element Of An Array public static void swap(int[] A, int i, int j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; } // shift all zero to left side of an array static void shiftAllZeroToLeft(int array[], int n) { // Maintain last index with positive value int lastSeenNonZero = 0; for (int index = 0; index < n; index++) { // If Element is non-zero if (array[index] != 0) { // swap current index, with lastSeen // non-zero swap(array, array[index], array[lastSeenNonZero]); // next element will be last seen non-zero lastSeenNonZero++; } } }} // This code is contributed By sam_2200
# Maintain last index with positive valuedef shiftAllZeroToLeft(arr, n): lastSeenNonZero = 0 for index in range(0, n): # If Element is non-zero if (array[index] != 0): # swap current index, with lastSeen # non-zero array[index], array[lastSeenNonZero] = array[lastSeenNonZero], array[index] # next element will be last seen non-zero lastSeenNonZero++ # This code is contributed By sam_2200
using System;class GFG{ // Function For Swapping Two Element Of An Array public static void swap(int[] A, int i, int j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; } // shift all zero to left side of an array static void shiftAllZeroToLeft(int[] array, int n) { // Maintain last index with positive value int lastSeenNonZero = 0; for (int index = 0; index < n; index++) { // If Element is non-zero if (array[index] != 0) { // swap current index, with lastSeen // non-zero swap(array, array[index], array[lastSeenNonZero]); // next element will be last seen non-zero lastSeenNonZero++; } } }} // This code is contributed By Saurabh Jaiswal
<script> // Function For Swapping Two Element Of An Array function swap(A,i,j) { let temp = A[i]; A[i] = A[j]; A[j] = temp; } // shift all zero to left side of an array function shiftAllZeroToLeft(array,n) { // Maintain last index with positive value let lastSeenNonZero = 0; for (let index = 0; index < n; index++) { // If Element is non-zero if (array[index] != 0) { // swap current index, with lastSeen // non-zero swap(array, array[index], array[lastSeenNonZero]); // next element will be last seen non-zero lastSeenNonZero++; } } }} // This code is contributed by sravan kumar Gottumukkala </script>
sagarika3kundu
faizanurrahman
sam_2200
rdtank
sravankumar8128
guneshshanbhag
_saurabh_jaiswal
rkbhola5
array-rearrange
Microsoft
Zoho
Arrays
Zoho
Microsoft
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Linked List vs Array
Python | Using 2D arrays/lists the right way
Given an array of size n and a number k, find all elements that appear more than n/k times
Queue | Set 1 (Introduction and Array Implementation)
Subset Sum Problem | DP-25
K'th Smallest/Largest Element in Unsorted Array | Set 1
Find the Missing Number
Array of Strings in C++ (5 Different Ways to Create)
Next Greater Element | [
{
"code": null,
"e": 25125,
"s": 25097,
"text": "\n28 Jan, 2022"
},
{
"code": null,
"e": 25491,
"s": 25125,
"text": "For a given array of n integers and assume that ‘0’ is an invalid number and all others as a valid number. Convert the array in such a way that if both current and next element is valid and both have same value then double current value and replace the next number with 0. After the modification, rearrange the array such that all 0’s shifted to the end. Examples: "
},
{
"code": null,
"e": 25626,
"s": 25491,
"text": "Input : arr[] = {2, 2, 0, 4, 0, 8}\nOutput : 4 4 8 0 0 0\n\nInput : arr[] = {0, 2, 2, 2, 0, 6, 6, 0, 0, 8}\nOutput : 4 2 12 8 0 0 0 0 0 0"
},
{
"code": null,
"e": 25680,
"s": 25626,
"text": "Source: Microsoft IDC Interview Experience | Set 150."
},
{
"code": null,
"e": 25876,
"s": 25680,
"text": "Approach: First modify the array as mentioned, i.e., if the next valid number is the same as the current number, double its value and replace the next number with 0. Algorithm for Modification: "
},
{
"code": null,
"e": 26037,
"s": 25876,
"text": "1. if n == 1\n2. return\n3. for i = 0 to n-2\n4. if (arr[i] != 0) && (arr[i] == arr[i+1])\n5. arr[i] = 2 * arr[i]\n6. arr[i+1] = 0\n7. i++"
},
{
"code": null,
"e": 26105,
"s": 26037,
"text": "After modifying the array, Move all zeroes to the end of the array."
},
{
"code": null,
"e": 26109,
"s": 26105,
"text": "C++"
},
{
"code": null,
"e": 26114,
"s": 26109,
"text": "Java"
},
{
"code": null,
"e": 26122,
"s": 26114,
"text": "Python3"
},
{
"code": null,
"e": 26125,
"s": 26122,
"text": "C#"
},
{
"code": null,
"e": 26136,
"s": 26125,
"text": "Javascript"
},
{
"code": "// C++ implementation to rearrange the array// elements after modification#include <bits/stdc++.h> using namespace std; // function which pushes all zeros to end of// an array.void pushZerosToEnd(int arr[], int n){ // Count of non-zero elements int count = 0; // Traverse the array. If element encountered // is non-zero, then replace the element at // index 'count' with this element for (int i = 0; i < n; i++) if (arr[i] != 0) // here count is incremented arr[count++] = arr[i]; // Now all non-zero elements have been shifted // to front and 'count' is set as index of // first 0. Make all elements 0 from count // to end. while (count < n) arr[count++] = 0;} // function to rearrange the array elements// after modificationvoid modifyAndRearrangeArr(int arr[], int n){ // if 'arr[]' contains a single element // only if (n == 1) return; // traverse the array for (int i = 0; i < n - 1; i++) { // if true, perform the required modification if ((arr[i] != 0) && (arr[i] == arr[i + 1])) { // double current index value arr[i] = 2 * arr[i]; // put 0 in the next index arr[i + 1] = 0; // increment by 1 so as to move two // indexes ahead during loop iteration i++; } } // push all the zeros at the end of 'arr[]' pushZerosToEnd(arr, n);} // function to print the array elementsvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Driver program to test aboveint main(){ int arr[] = { 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Original array: \"; printArray(arr, n); modifyAndRearrangeArr(arr, n); cout << \"\\nModified array: \"; printArray(arr, n); return 0;}",
"e": 28011,
"s": 26136,
"text": null
},
{
"code": "// Java implementation to rearrange the// array elements after modificationclass GFG { // function which pushes all // zeros to end of an array. static void pushZerosToEnd(int arr[], int n) { // Count of non-zero elements int count = 0; // Traverse the array. If element // encountered is non-zero, then // replace the element at index // 'count' with this element for (int i = 0; i < n; i++) if (arr[i] != 0) // here count is incremented arr[count++] = arr[i]; // Now all non-zero elements // have been shifted to front and // 'count' is set as index of first 0. // Make all elements 0 from count to end. while (count < n) arr[count++] = 0; } // function to rearrange the array // elements after modification static void modifyAndRearrangeArr(int arr[], int n) { // if 'arr[]' contains a single element // only if (n == 1) return; // traverse the array for (int i = 0; i < n - 1; i++) { // if true, perform the required modification if ((arr[i] != 0) && (arr[i] == arr[i + 1])) { // double current index value arr[i] = 2 * arr[i]; // put 0 in the next index arr[i + 1] = 0; // increment by 1 so as to move two // indexes ahead during loop iteration i++; } } // push all the zeros at // the end of 'arr[]' pushZerosToEnd(arr, n); } // function to print the array elements static void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver program to test above public static void main(String[] args) { int arr[] = { 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 }; int n = arr.length; System.out.print(\"Original array: \"); printArray(arr, n); modifyAndRearrangeArr(arr, n); System.out.print(\"Modified array: \"); printArray(arr, n); }} // This code is contributed // by prerna saini",
"e": 30250,
"s": 28011,
"text": null
},
{
"code": "# Python3 implementation to rearrange# the array elements after modification # function which pushes all zeros# to end of an array.def pushZerosToEnd(arr, n): # Count of non-zero elements count = 0 # Traverse the array. If element # encountered is non-zero, then # replace the element at index # 'count' with this element for i in range(0, n): if arr[i] != 0: # here count is incremented arr[count] = arr[i] count+=1 # Now all non-zero elements have been # shifted to front and 'count' is set # as index of first 0. Make all # elements 0 from count to end. while (count < n): arr[count] = 0 count+=1 # function to rearrange the array# elements after modificationdef modifyAndRearrangeArr(ar, n): # if 'arr[]' contains a single # element only if n == 1: return # traverse the array for i in range(0, n - 1): # if true, perform the required modification if (arr[i] != 0) and (arr[i] == arr[i + 1]): # double current index value arr[i] = 2 * arr[i] # put 0 in the next index arr[i + 1] = 0 # increment by 1 so as to move two # indexes ahead during loop iteration i+=1 # push all the zeros at the end of 'arr[]' pushZerosToEnd(arr, n) # function to print the array elementsdef printArray(arr, n): for i in range(0, n): print(arr[i],end=\" \") # Driver program to test abovearr = [ 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 ]n = len(arr) print(\"Original array:\",end=\" \")printArray(arr, n) modifyAndRearrangeArr(arr, n) print(\"\\nModified array:\",end=\" \")printArray(arr, n) # This code is contributed by Smitha Dinesh Semwal",
"e": 31993,
"s": 30250,
"text": null
},
{
"code": "// C# implementation to rearrange the// array elements after modificationusing System; class GFG { // function which pushes all // zeros to end of an array. static void pushZerosToEnd(int[] arr, int n) { // Count of non-zero elements int count = 0; // Traverse the array. If element // encountered is non-zero, then // replace the element at index // 'count' with this element for (int i = 0; i < n; i++) if (arr[i] != 0) // here count is incremented arr[count++] = arr[i]; // Now all non-zero elements // have been shifted to front and // 'count' is set as index of first 0. // Make all elements 0 from count to end. while (count < n) arr[count++] = 0; } // function to rearrange the array // elements after modification static void modifyAndRearrangeArr(int[] arr, int n) { // if 'arr[]' contains a single element // only if (n == 1) return; // traverse the array for (int i = 0; i < n - 1; i++) { // if true, perform the required modification if ((arr[i] != 0) && (arr[i] == arr[i + 1])) { // double current index value arr[i] = 2 * arr[i]; // put 0 in the next index arr[i + 1] = 0; // increment by 1 so as to move two // indexes ahead during loop iteration i++; } } // push all the zeros at // the end of 'arr[]' pushZerosToEnd(arr, n); } // function to print the array elements static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); Console.WriteLine(); } // Driver program to test above public static void Main() { int[] arr = { 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 }; int n = arr.Length; Console.Write(\"Original array: \"); printArray(arr, n); modifyAndRearrangeArr(arr, n); Console.Write(\"Modified array: \"); printArray(arr, n); }} // This code is contributed by Sam007",
"e": 34200,
"s": 31993,
"text": null
},
{
"code": "<script> // JavaScript implementation to rearrange the array // elements after modification // function which pushes all zeros to end of // an array. function pushZerosToEnd(arr, n) { // Count of non-zero elements var count = 0; // Traverse the array. If element encountered // is non-zero, then replace the element at // index 'count' with this element for (var i = 0; i < n; i++) if (arr[i] != 0) // here count is incremented arr[count++] = arr[i]; // Now all non-zero elements have been shifted // to front and 'count' is set as index of // first 0. Make all elements 0 from count // to end. while (count < n) arr[count++] = 0; } // function to rearrange the array elements // after modification function modifyAndRearrangeArr(arr, n) { // if 'arr[]' contains a single element // only if (n == 1) return; // traverse the array for (var i = 0; i < n - 1; i++) { // if true, perform the required modification if (arr[i] != 0 && arr[i] == arr[i + 1]) { // double current index value arr[i] = 2 * arr[i]; // put 0 in the next index arr[i + 1] = 0; // increment by 1 so as to move two // indexes ahead during loop iteration i++; } } // push all the zeros at the end of 'arr[]' pushZerosToEnd(arr, n); } // function to print the array elements function printArray(arr, n) { for (var i = 0; i < n; i++) document.write(arr[i] + \" \"); } // Driver program to test above var arr = [0, 2, 2, 2, 0, 6, 6, 0, 0, 8]; var n = arr.length; document.write(\"Original array: \"); printArray(arr, n); modifyAndRearrangeArr(arr, n); document.write(\"<br>\"); document.write(\"Modified array: \"); printArray(arr, n); // This code is contributed by rdtank. </script>",
"e": 36291,
"s": 34200,
"text": null
},
{
"code": null,
"e": 36300,
"s": 36291,
"text": "Output: "
},
{
"code": null,
"e": 36373,
"s": 36300,
"text": "Original array: 0 2 2 2 0 6 6 0 0 8\nModified array: 4 2 12 8 0 0 0 0 0 0"
},
{
"code": null,
"e": 36397,
"s": 36373,
"text": "Time Complexity: O(n). "
},
{
"code": null,
"e": 36437,
"s": 36397,
"text": "Approach with efficient zero shiftings:"
},
{
"code": null,
"e": 36572,
"s": 36437,
"text": "Although the above solution is efficient, we can further optimise it in shifting zero algorithms by reducing the number of operations."
},
{
"code": null,
"e": 36693,
"s": 36572,
"text": "In the above shifting algorithms, we scan some elements twice when we set the count index to last index element to zero."
},
{
"code": null,
"e": 36729,
"s": 36693,
"text": "Efficient Zero Shifting Algorithms:"
},
{
"code": null,
"e": 36929,
"s": 36729,
"text": "int lastSeenPositiveIndex = 0;\nfor( index = 0; index < n; index++)\n{\n if(array[index] != 0)\n {\n swap(array[index], array[lastSeenPositiveIndex]);\n lastSeenPositiveIndex++;\n }\n}"
},
{
"code": null,
"e": 36933,
"s": 36929,
"text": "C++"
},
{
"code": null,
"e": 36938,
"s": 36933,
"text": "Java"
},
{
"code": null,
"e": 36946,
"s": 36938,
"text": "Python3"
},
{
"code": null,
"e": 36949,
"s": 36946,
"text": "C#"
},
{
"code": null,
"e": 36960,
"s": 36949,
"text": "Javascript"
},
{
"code": "// Utility Function For Swapping Two Element Of An Arrayvoid swap(int& a, int& b) { a = b + a - (b = a); } // shift all zero to left side of an arrayvoid shiftAllZeroToLeft(int array[], int n){ // Maintain last index with positive value int lastSeenNonZero = 0; for (index = 0; index < n; index++) { // If Element is non-zero if (array[index] != 0) { // swap current index, with lastSeen non-zero swap(array[index], array[lastSeenNonZero]); // next element will be last seen non-zero lastSeenNonZero++; } }} // This snippet is contributed By: Faizanur Rahman",
"e": 37608,
"s": 36960,
"text": null
},
{
"code": "class GFG { // Function For Swapping Two Element Of An Array public static void swap(int[] A, int i, int j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; } // shift all zero to left side of an array static void shiftAllZeroToLeft(int array[], int n) { // Maintain last index with positive value int lastSeenNonZero = 0; for (int index = 0; index < n; index++) { // If Element is non-zero if (array[index] != 0) { // swap current index, with lastSeen // non-zero swap(array, array[index], array[lastSeenNonZero]); // next element will be last seen non-zero lastSeenNonZero++; } } }} // This code is contributed By sam_2200",
"e": 38433,
"s": 37608,
"text": null
},
{
"code": "# Maintain last index with positive valuedef shiftAllZeroToLeft(arr, n): lastSeenNonZero = 0 for index in range(0, n): # If Element is non-zero if (array[index] != 0): # swap current index, with lastSeen # non-zero array[index], array[lastSeenNonZero] = array[lastSeenNonZero], array[index] # next element will be last seen non-zero lastSeenNonZero++ # This code is contributed By sam_2200",
"e": 38941,
"s": 38433,
"text": null
},
{
"code": "using System;class GFG{ // Function For Swapping Two Element Of An Array public static void swap(int[] A, int i, int j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; } // shift all zero to left side of an array static void shiftAllZeroToLeft(int[] array, int n) { // Maintain last index with positive value int lastSeenNonZero = 0; for (int index = 0; index < n; index++) { // If Element is non-zero if (array[index] != 0) { // swap current index, with lastSeen // non-zero swap(array, array[index], array[lastSeenNonZero]); // next element will be last seen non-zero lastSeenNonZero++; } } }} // This code is contributed By Saurabh Jaiswal",
"e": 39839,
"s": 38941,
"text": null
},
{
"code": "<script> // Function For Swapping Two Element Of An Array function swap(A,i,j) { let temp = A[i]; A[i] = A[j]; A[j] = temp; } // shift all zero to left side of an array function shiftAllZeroToLeft(array,n) { // Maintain last index with positive value let lastSeenNonZero = 0; for (let index = 0; index < n; index++) { // If Element is non-zero if (array[index] != 0) { // swap current index, with lastSeen // non-zero swap(array, array[index], array[lastSeenNonZero]); // next element will be last seen non-zero lastSeenNonZero++; } } }} // This code is contributed by sravan kumar Gottumukkala </script>",
"e": 40648,
"s": 39839,
"text": null
},
{
"code": null,
"e": 40663,
"s": 40648,
"text": "sagarika3kundu"
},
{
"code": null,
"e": 40678,
"s": 40663,
"text": "faizanurrahman"
},
{
"code": null,
"e": 40687,
"s": 40678,
"text": "sam_2200"
},
{
"code": null,
"e": 40694,
"s": 40687,
"text": "rdtank"
},
{
"code": null,
"e": 40710,
"s": 40694,
"text": "sravankumar8128"
},
{
"code": null,
"e": 40725,
"s": 40710,
"text": "guneshshanbhag"
},
{
"code": null,
"e": 40742,
"s": 40725,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 40751,
"s": 40742,
"text": "rkbhola5"
},
{
"code": null,
"e": 40767,
"s": 40751,
"text": "array-rearrange"
},
{
"code": null,
"e": 40777,
"s": 40767,
"text": "Microsoft"
},
{
"code": null,
"e": 40782,
"s": 40777,
"text": "Zoho"
},
{
"code": null,
"e": 40789,
"s": 40782,
"text": "Arrays"
},
{
"code": null,
"e": 40794,
"s": 40789,
"text": "Zoho"
},
{
"code": null,
"e": 40804,
"s": 40794,
"text": "Microsoft"
},
{
"code": null,
"e": 40811,
"s": 40804,
"text": "Arrays"
},
{
"code": null,
"e": 40909,
"s": 40811,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40918,
"s": 40909,
"text": "Comments"
},
{
"code": null,
"e": 40931,
"s": 40918,
"text": "Old Comments"
},
{
"code": null,
"e": 40954,
"s": 40931,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 40975,
"s": 40954,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 41020,
"s": 40975,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 41111,
"s": 41020,
"text": "Given an array of size n and a number k, find all elements that appear more than n/k times"
},
{
"code": null,
"e": 41165,
"s": 41111,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 41192,
"s": 41165,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 41248,
"s": 41192,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 41272,
"s": 41248,
"text": "Find the Missing Number"
},
{
"code": null,
"e": 41325,
"s": 41272,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
] |
SciPy Constants | As SciPy is more focused on scientific implementations, it provides many built-in scientific constants.
These constants can be helpful when you are working with Data Science.
PI is an example of a scientific constant.
Print the constant value of PI:
A list of all units under the constants module can be seen using the dir()
function.
List all constants:
The units are placed under these categories:
Metric
Binary
Mass
Angle
Time
Length
Pressure
Volume
Speed
Temperature
Energy
Power
Force
Return the specified unit in meter (e.g. centi
returns 0.01)
Return the specified unit in bytes (e.g. kibi
returns 1024)
Return the specified unit in kg (e.g. gram
returns 0.001)
Return the specified unit in radians (e.g. degree returns 0.017453292519943295)
Return the specified unit in seconds (e.g. hour returns 3600.0)
Return the specified unit in meters (e.g. nautical_mile returns 1852.0)
Return the specified unit in pascals (e.g. psi returns 6894.757293168361)
Return the specified unit in square meters(e.g. hectare returns 10000.0)
Return the specified unit in cubic meters (e.g.
liter returns 0.001)
Return the specified unit in meters per second (e.g.
speed_of_sound returns 340.5)
Return the specified unit in Kelvin (e.g. zero_Celsius returns 273.15)
Return the specified unit in joules (e.g.
calorie returns 4.184)
Return the specified unit in watts (e.g. horsepower returns 745.6998715822701)
Return the specified unit in newton (e.g.
kilogram_force returns 9.80665)
Insert the correct syntax for printing the kilometer unit (in meters):
print(constants.)
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 104,
"s": 0,
"text": "As SciPy is more focused on scientific implementations, it provides many built-in scientific constants."
},
{
"code": null,
"e": 175,
"s": 104,
"text": "These constants can be helpful when you are working with Data Science."
},
{
"code": null,
"e": 218,
"s": 175,
"text": "PI is an example of a scientific constant."
},
{
"code": null,
"e": 250,
"s": 218,
"text": "Print the constant value of PI:"
},
{
"code": null,
"e": 335,
"s": 250,
"text": "A list of all units under the constants module can be seen using the dir()\nfunction."
},
{
"code": null,
"e": 355,
"s": 335,
"text": "List all constants:"
},
{
"code": null,
"e": 400,
"s": 355,
"text": "The units are placed under these categories:"
},
{
"code": null,
"e": 407,
"s": 400,
"text": "Metric"
},
{
"code": null,
"e": 414,
"s": 407,
"text": "Binary"
},
{
"code": null,
"e": 419,
"s": 414,
"text": "Mass"
},
{
"code": null,
"e": 425,
"s": 419,
"text": "Angle"
},
{
"code": null,
"e": 430,
"s": 425,
"text": "Time"
},
{
"code": null,
"e": 437,
"s": 430,
"text": "Length"
},
{
"code": null,
"e": 446,
"s": 437,
"text": "Pressure"
},
{
"code": null,
"e": 453,
"s": 446,
"text": "Volume"
},
{
"code": null,
"e": 459,
"s": 453,
"text": "Speed"
},
{
"code": null,
"e": 471,
"s": 459,
"text": "Temperature"
},
{
"code": null,
"e": 478,
"s": 471,
"text": "Energy"
},
{
"code": null,
"e": 484,
"s": 478,
"text": "Power"
},
{
"code": null,
"e": 490,
"s": 484,
"text": "Force"
},
{
"code": null,
"e": 554,
"s": 490,
"text": "Return the specified unit in meter (e.g. centi \n returns 0.01)"
},
{
"code": null,
"e": 617,
"s": 554,
"text": "Return the specified unit in bytes (e.g. kibi \n returns 1024)"
},
{
"code": null,
"e": 678,
"s": 617,
"text": "Return the specified unit in kg (e.g. gram \n returns 0.001)"
},
{
"code": null,
"e": 758,
"s": 678,
"text": "Return the specified unit in radians (e.g. degree returns 0.017453292519943295)"
},
{
"code": null,
"e": 822,
"s": 758,
"text": "Return the specified unit in seconds (e.g. hour returns 3600.0)"
},
{
"code": null,
"e": 894,
"s": 822,
"text": "Return the specified unit in meters (e.g. nautical_mile returns 1852.0)"
},
{
"code": null,
"e": 968,
"s": 894,
"text": "Return the specified unit in pascals (e.g. psi returns 6894.757293168361)"
},
{
"code": null,
"e": 1041,
"s": 968,
"text": "Return the specified unit in square meters(e.g. hectare returns 10000.0)"
},
{
"code": null,
"e": 1111,
"s": 1041,
"text": "Return the specified unit in cubic meters (e.g. \nliter returns 0.001)"
},
{
"code": null,
"e": 1195,
"s": 1111,
"text": "Return the specified unit in meters per second (e.g. \nspeed_of_sound returns 340.5)"
},
{
"code": null,
"e": 1266,
"s": 1195,
"text": "Return the specified unit in Kelvin (e.g. zero_Celsius returns 273.15)"
},
{
"code": null,
"e": 1332,
"s": 1266,
"text": "Return the specified unit in joules (e.g. \ncalorie returns 4.184)"
},
{
"code": null,
"e": 1411,
"s": 1332,
"text": "Return the specified unit in watts (e.g. horsepower returns 745.6998715822701)"
},
{
"code": null,
"e": 1486,
"s": 1411,
"text": "Return the specified unit in newton (e.g. \nkilogram_force returns 9.80665)"
},
{
"code": null,
"e": 1557,
"s": 1486,
"text": "Insert the correct syntax for printing the kilometer unit (in meters):"
},
{
"code": null,
"e": 1576,
"s": 1557,
"text": "print(constants.)\n"
},
{
"code": null,
"e": 1595,
"s": 1576,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1628,
"s": 1595,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1670,
"s": 1628,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1777,
"s": 1670,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1796,
"s": 1777,
"text": "[email protected]"
}
] |
How to remove a SubList from an ArrayList in Java? | The subList() method of the List interface accepts two integer values representing indexes of the elements and, returns a view of the of the current List object removing the elements between the specified indices.
The clear() method of List interface removes all the elements from the current List object.
Therefore, to remove a specific sub list of an array list you just need to call these two methods on your list object by specifying the boundaries of the sub list you need to remove as −
obj.subList().clear();
Live Demo
import java.util.ArrayList;
public class RemovingSubList {
public static void main(String[] args){
//Instantiating an ArrayList object
ArrayList<String> list = new ArrayList<String>();
list.add("JavaFX");
list.add("Java");
list.add("WebGL");
list.add("OpenCV");
list.add("OpenNLP");
list.add("JOGL");
list.add("Hadoop");
list.add("HBase");
list.add("Flume");
list.add("Mahout");
list.add("Impala");
System.out.println("Contents of the Array List: \n"+list);
//Removing the sub list
list.subList(4, 9).clear();
System.out.println("Contents of the Array List after removing the sub list: \n"+list);
}
}
Contents of the Array List:
[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
Contents of the Array List after removing the sub list:
[JavaFX, Java, WebGL, OpenCV, Mahout, Impala]
The removeRange() method of the AbstractList class method accepts two integer values representing indexes of the elements of the current ArrayList and removes them.
But this is a protected method and to use this you need to
Inherit the ArrayList class (from your class) using the extends keyword.
Inherit the ArrayList class (from your class) using the extends keyword.
Instantiate your class.
Instantiate your class.
Add elements to the obtained object.
Add elements to the obtained object.
Then, remove the desired subList using the removeRange() method.
Then, remove the desired subList using the removeRange() method.
Live Demo
import java.util.ArrayList;
public class RemovingSubList extends ArrayList<String>{
public static void main(String[] args){
RemovingSubList list = new RemovingSubList();
//Instantiating an ArrayList object
list.add("JavaFX");
list.add("Java");
list.add("WebGL");
list.add("OpenCV");
list.add("OpenNLP");
list.add("JOGL");
list.add("Hadoop");
list.add("HBase");
list.add("Flume");
list.add("Mahout");
list.add("Impala");
System.out.println("Contents of the Array List: \n"+list);
//Removing the sub list
list.removeRange(4, 9);
System.out.println("Contents of the Array List after removing the sub list: \n"+list);
}
}
Contents of the Array List:
[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
Contents of the Array List after removing the sub list:
[JavaFX, Java, WebGL, OpenCV, Mahout, Impala] | [
{
"code": null,
"e": 1276,
"s": 1062,
"text": "The subList() method of the List interface accepts two integer values representing indexes of the elements and, returns a view of the of the current List object removing the elements between the specified indices."
},
{
"code": null,
"e": 1368,
"s": 1276,
"text": "The clear() method of List interface removes all the elements from the current List object."
},
{
"code": null,
"e": 1555,
"s": 1368,
"text": "Therefore, to remove a specific sub list of an array list you just need to call these two methods on your list object by specifying the boundaries of the sub list you need to remove as −"
},
{
"code": null,
"e": 1578,
"s": 1555,
"text": "obj.subList().clear();"
},
{
"code": null,
"e": 1589,
"s": 1578,
"text": " Live Demo"
},
{
"code": null,
"e": 2298,
"s": 1589,
"text": "import java.util.ArrayList;\npublic class RemovingSubList {\n public static void main(String[] args){\n //Instantiating an ArrayList object\n ArrayList<String> list = new ArrayList<String>();\n list.add(\"JavaFX\");\n list.add(\"Java\");\n list.add(\"WebGL\");\n list.add(\"OpenCV\");\n list.add(\"OpenNLP\");\n list.add(\"JOGL\");\n list.add(\"Hadoop\");\n list.add(\"HBase\");\n list.add(\"Flume\");\n list.add(\"Mahout\");\n list.add(\"Impala\");\n System.out.println(\"Contents of the Array List: \\n\"+list);\n //Removing the sub list\n list.subList(4, 9).clear();\n System.out.println(\"Contents of the Array List after removing the sub list: \\n\"+list);\n }\n}"
},
{
"code": null,
"e": 2511,
"s": 2298,
"text": "Contents of the Array List:\n[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]\nContents of the Array List after removing the sub list:\n[JavaFX, Java, WebGL, OpenCV, Mahout, Impala]"
},
{
"code": null,
"e": 2676,
"s": 2511,
"text": "The removeRange() method of the AbstractList class method accepts two integer values representing indexes of the elements of the current ArrayList and removes them."
},
{
"code": null,
"e": 2735,
"s": 2676,
"text": "But this is a protected method and to use this you need to"
},
{
"code": null,
"e": 2808,
"s": 2735,
"text": "Inherit the ArrayList class (from your class) using the extends keyword."
},
{
"code": null,
"e": 2881,
"s": 2808,
"text": "Inherit the ArrayList class (from your class) using the extends keyword."
},
{
"code": null,
"e": 2905,
"s": 2881,
"text": "Instantiate your class."
},
{
"code": null,
"e": 2929,
"s": 2905,
"text": "Instantiate your class."
},
{
"code": null,
"e": 2966,
"s": 2929,
"text": "Add elements to the obtained object."
},
{
"code": null,
"e": 3003,
"s": 2966,
"text": "Add elements to the obtained object."
},
{
"code": null,
"e": 3068,
"s": 3003,
"text": "Then, remove the desired subList using the removeRange() method."
},
{
"code": null,
"e": 3133,
"s": 3068,
"text": "Then, remove the desired subList using the removeRange() method."
},
{
"code": null,
"e": 3144,
"s": 3133,
"text": " Live Demo"
},
{
"code": null,
"e": 3870,
"s": 3144,
"text": "import java.util.ArrayList;\npublic class RemovingSubList extends ArrayList<String>{\n public static void main(String[] args){\n RemovingSubList list = new RemovingSubList();\n //Instantiating an ArrayList object\n list.add(\"JavaFX\");\n list.add(\"Java\");\n list.add(\"WebGL\");\n list.add(\"OpenCV\");\n list.add(\"OpenNLP\");\n list.add(\"JOGL\");\n list.add(\"Hadoop\");\n list.add(\"HBase\");\n list.add(\"Flume\");\n list.add(\"Mahout\");\n list.add(\"Impala\");\n System.out.println(\"Contents of the Array List: \\n\"+list);\n //Removing the sub list\n list.removeRange(4, 9);\n System.out.println(\"Contents of the Array List after removing the sub list: \\n\"+list);\n }\n}"
},
{
"code": null,
"e": 4083,
"s": 3870,
"text": "Contents of the Array List:\n[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]\nContents of the Array List after removing the sub list:\n[JavaFX, Java, WebGL, OpenCV, Mahout, Impala]"
}
] |
Modular Exponentiation (Power in Modular Arithmetic) in java | The java.math.BigInteger.modPow(BigInteger exponent, BigInteger m) returns a BigInteger whose value is (this<sup>exponent</sup> mod m). Unlike pow, this method permits negative exponents. You can calculate the modular Exponentiation using this method.
Live Demo
import java.math.*;
public class BigIntegerDemo {
public static void main(String[] args) {
// create 3 BigInteger objects
BigInteger bi1, bi2, bi3;
// create a BigInteger exponent
BigInteger exponent = new BigInteger("2");
bi1 = new BigInteger("7");
bi2 = new BigInteger("20");
// perform modPow operation on bi1 using bi2 and exp
bi3 = bi1.modPow(exponent, bi2);
String str = bi1 + "^" +exponent+ " mod " + bi2 + " is " +bi3;
// print bi3 value
System.out.println( str );
}
}
7^2 mod 20 is 9 | [
{
"code": null,
"e": 1314,
"s": 1062,
"text": "The java.math.BigInteger.modPow(BigInteger exponent, BigInteger m) returns a BigInteger whose value is (this<sup>exponent</sup> mod m). Unlike pow, this method permits negative exponents. You can calculate the modular Exponentiation using this method."
},
{
"code": null,
"e": 1324,
"s": 1314,
"text": "Live Demo"
},
{
"code": null,
"e": 1892,
"s": 1324,
"text": "import java.math.*;\n\npublic class BigIntegerDemo {\n public static void main(String[] args) {\n // create 3 BigInteger objects\n BigInteger bi1, bi2, bi3;\n \n // create a BigInteger exponent\n BigInteger exponent = new BigInteger(\"2\");\n bi1 = new BigInteger(\"7\");\n bi2 = new BigInteger(\"20\");\n \n // perform modPow operation on bi1 using bi2 and exp\n bi3 = bi1.modPow(exponent, bi2);\n String str = bi1 + \"^\" +exponent+ \" mod \" + bi2 + \" is \" +bi3;\n \n // print bi3 value\n System.out.println( str );\n }\n}"
},
{
"code": null,
"e": 1908,
"s": 1892,
"text": "7^2 mod 20 is 9"
}
] |
Subsets and Splits