title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
SQLite - UNION Clause | SQLite UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows.
To use UNION, each SELECT must have the same number of columns selected, the same number of column expressions, the same data type, and have them in the same order, but they do not have to be of the same length.
Following is the basic syntax of UNION.
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here the given condition could be any given expression based on your requirement.
Consider the following two tables, (a) COMPANY table as follows −
sqlite> select * from COMPANY;
ID NAME AGE ADDRESS SALARY
---------- -------------------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
(b) Another table is DEPARTMENT as follows −
ID DEPT EMP_ID
---------- -------------------- ----------
1 IT Billing 1
2 Engineering 2
3 Finance 7
4 Engineering 3
5 Finance 4
6 Engineering 5
7 Finance 6
Now let us join these two tables using SELECT statement along with UNION clause as follows −
sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
This will produce the following result.
EMP_ID NAME DEPT
---------- -------------------- ----------
1 Paul IT Billing
2 Allen Engineering
3 Teddy Engineering
4 Mark Finance
5 David Engineering
6 Kim Finance
7 James Finance
The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows.
The same rules that apply to UNION apply to the UNION ALL operator as well.
Following is the basic syntax of UNION ALL.
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION ALL
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here the given condition could be any given expression based on your requirement.
Now, let us join the above-mentioned two tables in our SELECT statement as follows −
sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION ALL
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
This will produce the following result.
EMP_ID NAME DEPT
---------- -------------------- ----------
1 Paul IT Billing
2 Allen Engineering
3 Teddy Engineering
4 Mark Finance
5 David Engineering
6 Kim Finance
7 James Finance
1 Paul IT Billing
2 Allen Engineering
3 Teddy Engineering
4 Mark Finance
5 David Engineering
6 Kim Finance
7 James Finance
25 Lectures
4.5 hours
Sandip Bhattacharya
17 Lectures
1 hours
Laurence Svekis
5 Lectures
51 mins
Vinay Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2769,
"s": 2638,
"text": "SQLite UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows."
},
{
"code": null,
"e": 2981,
"s": 2769,
"text": "To use UNION, each SELECT must have the same number of columns selected, the same number of column expressions, the same data type, and have them in the same order, but they do not have to be of the same length."
},
{
"code": null,
"e": 3021,
"s": 2981,
"text": "Following is the basic syntax of UNION."
},
{
"code": null,
"e": 3170,
"s": 3021,
"text": "SELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n\nUNION\n\nSELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n"
},
{
"code": null,
"e": 3252,
"s": 3170,
"text": "Here the given condition could be any given expression based on your requirement."
},
{
"code": null,
"e": 3318,
"s": 3252,
"text": "Consider the following two tables, (a) COMPANY table as follows −"
},
{
"code": null,
"e": 3945,
"s": 3318,
"text": "sqlite> select * from COMPANY;\nID NAME AGE ADDRESS SALARY\n---------- -------------------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 3990,
"s": 3945,
"text": "(b) Another table is DEPARTMENT as follows −"
},
{
"code": null,
"e": 4328,
"s": 3990,
"text": "ID DEPT EMP_ID\n---------- -------------------- ----------\n1 IT Billing 1\n2 Engineering 2\n3 Finance 7\n4 Engineering 3\n5 Finance 4\n6 Engineering 5\n7 Finance 6"
},
{
"code": null,
"e": 4421,
"s": 4328,
"text": "Now let us join these two tables using SELECT statement along with UNION clause as follows −"
},
{
"code": null,
"e": 4688,
"s": 4421,
"text": "sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID\n \n UNION\n \n SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID;"
},
{
"code": null,
"e": 4728,
"s": 4688,
"text": "This will produce the following result."
},
{
"code": null,
"e": 5122,
"s": 4728,
"text": "EMP_ID NAME DEPT\n---------- -------------------- ----------\n1 Paul IT Billing\n2 Allen Engineering\n3 Teddy Engineering\n4 Mark Finance\n5 David Engineering\n6 Kim Finance\n7 James Finance\n"
},
{
"code": null,
"e": 5227,
"s": 5122,
"text": "The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows."
},
{
"code": null,
"e": 5303,
"s": 5227,
"text": "The same rules that apply to UNION apply to the UNION ALL operator as well."
},
{
"code": null,
"e": 5347,
"s": 5303,
"text": "Following is the basic syntax of UNION ALL."
},
{
"code": null,
"e": 5500,
"s": 5347,
"text": "SELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n\nUNION ALL\n\nSELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n"
},
{
"code": null,
"e": 5582,
"s": 5500,
"text": "Here the given condition could be any given expression based on your requirement."
},
{
"code": null,
"e": 5667,
"s": 5582,
"text": "Now, let us join the above-mentioned two tables in our SELECT statement as follows −"
},
{
"code": null,
"e": 5929,
"s": 5667,
"text": "sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID\n \n UNION ALL\n\n SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID;"
},
{
"code": null,
"e": 5969,
"s": 5929,
"text": "This will produce the following result."
},
{
"code": null,
"e": 6672,
"s": 5969,
"text": "EMP_ID NAME DEPT\n---------- -------------------- ----------\n1 Paul IT Billing\n2 Allen Engineering\n3 Teddy Engineering\n4 Mark Finance\n5 David Engineering\n6 Kim Finance\n7 James Finance\n1 Paul IT Billing\n2 Allen Engineering\n3 Teddy Engineering\n4 Mark Finance\n5 David Engineering\n6 Kim Finance\n7 James Finance\n"
},
{
"code": null,
"e": 6707,
"s": 6672,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6728,
"s": 6707,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 6761,
"s": 6728,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6778,
"s": 6761,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 6809,
"s": 6778,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 6822,
"s": 6809,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 6829,
"s": 6822,
"text": " Print"
},
{
"code": null,
"e": 6840,
"s": 6829,
"text": " Add Notes"
}
]
|
DB2 - Storagegroups | This chapter describes the Database Storagegroups.
A set of Storage paths to store database table or objects, is a storage group. You can assign the tablespaces to the storage group. When you create a database, all the tablespaces take default storagegorup. The default storage group for a database is ‘IBMSTOGROUP’. When you create a new database, the default storage group is active, if you pass the “AUTOMATIC STOGROUP NO” parameter at the end of “CREATE DATABASE” command. The database does not have any default storage groups.
You can list all the storagegroups in the database.
Syntax: [To see the list of available storagegroups in current database]
db2 select * from syscat.stogroups
Example: [To see the list of available storagegorups in current database]
db2 select * from syscat.stogroups
Here is a syntax to create a storagegroup in the database:
Syntax: [To create a new stogroup. The ‘stogropu_name’ indicates name of new storage group and ‘path’ indicates the location where data (tables) are stored]
db2 create stogroup on ‘path’
Example: [To create a new stogroup ‘stg1’ on the path ‘data1’ folder]
db2 create stogroup stg1 on ‘/data1’
Output:
DB20000I The SQL command completed succesfully
Here is how you can create a tablespace with storegroup:
Syntax: [To create a new tablespace using existed storage group]
db2 create tablespace <tablespace_name> using stogroup <stogroup_name>
Example: [To create a new tablespace named ‘ts1’ using existed storage group ‘stg1’]
db2 create tablespace ts1 using stogroup stg1
Output:
DB20000I The SQL command completed succesfully
You can alter the location of a storegroup by using following syntax:
Syntax: [To shift a storage group from old location to new location]
db2 alter stogroup add ‘location’, ‘location’
Example: [To modify location path from old location to new location for storage group named ‘sg1’]
db2 alter stogroup sg1 add ‘/path/data3’, ‘/path/data4’
Before dropping folder path of storagegroup, you can add new location for the storagegroup by using alter command.
Syntax: [To drop old path from storage group location]
db2 alter stogroup drop ‘/path’
Example: [To drop storage group location from ‘stg1’]
db2 alter stogroup stg1 drop ‘/path/data1’
Rebalancing the tablespace is required when we create a new folder for storagegroup or tablespaces while the transactions are conducted on the database and the tablespace becomes full. Rebalancing updates database configuration files with new storagegroup.
Syntax: [To rebalance the tablespace from old storage group path to new storage group]
db2 alter tablspace <ts_name> rebalance
Example: [To rebalance]
db2 alter tablespace ts1 rebalance
Syntax: [To modify the name of existing storage name]
db2 rename stogroup <old_stg_name> to <new_stg_name>
Example: [To modify the name of storage group from ‘sg1’ to new name ‘sgroup1’]
db2 rename stogroup sg1 to sgroup1
Step 1: Before dropping any storagegroup, you can assign some different storagegroup for tablespaces.
Syntax: [To assign another storagegroup for table space.]
db2 alter tablspace <ts_name> using stogroup <another sto_group_name>
Example: [To change from one old stogroup to new stogroup named ‘sg2’ for tablespace ‘ts1’]
db2 alter tablespace ts1 using stogroup sg2
Step 2:
Syntax: [To drop the existing stogroup]
db2 drop stogorup <stogroup_name>
Example: [To drop stogroup ‘stg1’ from database]
db2 drop stogroup stg1
10 Lectures
1.5 hours
Nishant Malik
41 Lectures
8.5 hours
Parth Panjabi
53 Lectures
11.5 hours
Parth Panjabi
33 Lectures
7 hours
Parth Panjabi
44 Lectures
3 hours
Arnab Chakraborty
178 Lectures
14.5 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1979,
"s": 1928,
"text": "This chapter describes the Database Storagegroups."
},
{
"code": null,
"e": 2461,
"s": 1979,
"text": "A set of Storage paths to store database table or objects, is a storage group. You can assign the tablespaces to the storage group. When you create a database, all the tablespaces take default storagegorup. The default storage group for a database is ‘IBMSTOGROUP’. When you create a new database, the default storage group is active, if you pass the “AUTOMATIC STOGROUP NO” parameter at the end of “CREATE DATABASE” command. The database does not have any default storage groups."
},
{
"code": null,
"e": 2513,
"s": 2461,
"text": "You can list all the storagegroups in the database."
},
{
"code": null,
"e": 2586,
"s": 2513,
"text": "Syntax: [To see the list of available storagegroups in current database]"
},
{
"code": null,
"e": 2621,
"s": 2586,
"text": "db2 select * from syscat.stogroups"
},
{
"code": null,
"e": 2695,
"s": 2621,
"text": "Example: [To see the list of available storagegorups in current database]"
},
{
"code": null,
"e": 2730,
"s": 2695,
"text": "db2 select * from syscat.stogroups"
},
{
"code": null,
"e": 2789,
"s": 2730,
"text": "Here is a syntax to create a storagegroup in the database:"
},
{
"code": null,
"e": 2946,
"s": 2789,
"text": "Syntax: [To create a new stogroup. The ‘stogropu_name’ indicates name of new storage group and ‘path’ indicates the location where data (tables) are stored]"
},
{
"code": null,
"e": 2977,
"s": 2946,
"text": "db2 create stogroup on ‘path’"
},
{
"code": null,
"e": 3047,
"s": 2977,
"text": "Example: [To create a new stogroup ‘stg1’ on the path ‘data1’ folder]"
},
{
"code": null,
"e": 3084,
"s": 3047,
"text": "db2 create stogroup stg1 on ‘/data1’"
},
{
"code": null,
"e": 3092,
"s": 3084,
"text": "Output:"
},
{
"code": null,
"e": 3140,
"s": 3092,
"text": "DB20000I The SQL command completed succesfully "
},
{
"code": null,
"e": 3197,
"s": 3140,
"text": "Here is how you can create a tablespace with storegroup:"
},
{
"code": null,
"e": 3262,
"s": 3197,
"text": "Syntax: [To create a new tablespace using existed storage group]"
},
{
"code": null,
"e": 3335,
"s": 3262,
"text": "db2 create tablespace <tablespace_name> using stogroup <stogroup_name> "
},
{
"code": null,
"e": 3420,
"s": 3335,
"text": "Example: [To create a new tablespace named ‘ts1’ using existed storage group ‘stg1’]"
},
{
"code": null,
"e": 3467,
"s": 3420,
"text": "db2 create tablespace ts1 using stogroup stg1 "
},
{
"code": null,
"e": 3475,
"s": 3467,
"text": "Output:"
},
{
"code": null,
"e": 3523,
"s": 3475,
"text": "DB20000I The SQL command completed succesfully "
},
{
"code": null,
"e": 3593,
"s": 3523,
"text": "You can alter the location of a storegroup by using following syntax:"
},
{
"code": null,
"e": 3662,
"s": 3593,
"text": "Syntax: [To shift a storage group from old location to new location]"
},
{
"code": null,
"e": 3710,
"s": 3662,
"text": "db2 alter stogroup add ‘location’, ‘location’ "
},
{
"code": null,
"e": 3809,
"s": 3710,
"text": "Example: [To modify location path from old location to new location for storage group named ‘sg1’]"
},
{
"code": null,
"e": 3866,
"s": 3809,
"text": "db2 alter stogroup sg1 add ‘/path/data3’, ‘/path/data4’ "
},
{
"code": null,
"e": 3981,
"s": 3866,
"text": "Before dropping folder path of storagegroup, you can add new location for the storagegroup by using alter command."
},
{
"code": null,
"e": 4036,
"s": 3981,
"text": "Syntax: [To drop old path from storage group location]"
},
{
"code": null,
"e": 4070,
"s": 4036,
"text": "db2 alter stogroup drop ‘/path’ "
},
{
"code": null,
"e": 4124,
"s": 4070,
"text": "Example: [To drop storage group location from ‘stg1’]"
},
{
"code": null,
"e": 4169,
"s": 4124,
"text": "db2 alter stogroup stg1 drop ‘/path/data1’ "
},
{
"code": null,
"e": 4426,
"s": 4169,
"text": "Rebalancing the tablespace is required when we create a new folder for storagegroup or tablespaces while the transactions are conducted on the database and the tablespace becomes full. Rebalancing updates database configuration files with new storagegroup."
},
{
"code": null,
"e": 4513,
"s": 4426,
"text": "Syntax: [To rebalance the tablespace from old storage group path to new storage group]"
},
{
"code": null,
"e": 4556,
"s": 4513,
"text": "db2 alter tablspace <ts_name> rebalance "
},
{
"code": null,
"e": 4580,
"s": 4556,
"text": "Example: [To rebalance]"
},
{
"code": null,
"e": 4618,
"s": 4580,
"text": "db2 alter tablespace ts1 rebalance "
},
{
"code": null,
"e": 4672,
"s": 4618,
"text": "Syntax: [To modify the name of existing storage name]"
},
{
"code": null,
"e": 4728,
"s": 4672,
"text": "db2 rename stogroup <old_stg_name> to <new_stg_name> "
},
{
"code": null,
"e": 4808,
"s": 4728,
"text": "Example: [To modify the name of storage group from ‘sg1’ to new name ‘sgroup1’]"
},
{
"code": null,
"e": 4846,
"s": 4808,
"text": "db2 rename stogroup sg1 to sgroup1 "
},
{
"code": null,
"e": 4948,
"s": 4846,
"text": "Step 1: Before dropping any storagegroup, you can assign some different storagegroup for tablespaces."
},
{
"code": null,
"e": 5006,
"s": 4948,
"text": "Syntax: [To assign another storagegroup for table space.]"
},
{
"code": null,
"e": 5080,
"s": 5006,
"text": "db2 alter tablspace <ts_name> using stogroup <another sto_group_name> "
},
{
"code": null,
"e": 5172,
"s": 5080,
"text": "Example: [To change from one old stogroup to new stogroup named ‘sg2’ for tablespace ‘ts1’]"
},
{
"code": null,
"e": 5219,
"s": 5172,
"text": "db2 alter tablespace ts1 using stogroup sg2 "
},
{
"code": null,
"e": 5227,
"s": 5219,
"text": "Step 2:"
},
{
"code": null,
"e": 5267,
"s": 5227,
"text": "Syntax: [To drop the existing stogroup]"
},
{
"code": null,
"e": 5304,
"s": 5267,
"text": "db2 drop stogorup <stogroup_name> "
},
{
"code": null,
"e": 5353,
"s": 5304,
"text": "Example: [To drop stogroup ‘stg1’ from database]"
},
{
"code": null,
"e": 5378,
"s": 5353,
"text": "db2 drop stogroup stg1 "
},
{
"code": null,
"e": 5413,
"s": 5378,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5428,
"s": 5413,
"text": " Nishant Malik"
},
{
"code": null,
"e": 5463,
"s": 5428,
"text": "\n 41 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5478,
"s": 5463,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 5514,
"s": 5478,
"text": "\n 53 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 5529,
"s": 5514,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 5562,
"s": 5529,
"text": "\n 33 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5577,
"s": 5562,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 5610,
"s": 5577,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5629,
"s": 5610,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5666,
"s": 5629,
"text": "\n 178 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 5685,
"s": 5666,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5692,
"s": 5685,
"text": " Print"
},
{
"code": null,
"e": 5703,
"s": 5692,
"text": " Add Notes"
}
]
|
Cost Accounting - Marginal Costing | Marginal cost is the change in the total cost when the quantity produced is incremented by one. That is, it is the cost of producing one more unit of a good. For example, let us suppose:
Variable cost per unit = Rs 25
Fixed cost = Rs 1,00,000
Cost of 10,000 units = 25 × 10,000 = Rs 2,50,000
Total Cost of 10,000 units = Fixed Cost + Variable Cost
= 1,00,000 + 2,50,000
= Rs 3,50,000
Total cost of 10,001 units = 1,00,000 + 2,50,025
= Rs 3,50,025
Marginal Cost = 3,50,025 – 3,50,000
= Rs 25
Let us see why marginal costing is required:
Variable cost per unit remains constant; any increase or decrease in production changes the total cost of output.
Variable cost per unit remains constant; any increase or decrease in production changes the total cost of output.
Total fixed cost remains unchanged up to a certain level of production and does not vary with increase or decrease in production. It means the fixed cost remains constant in terms of total cost.
Total fixed cost remains unchanged up to a certain level of production and does not vary with increase or decrease in production. It means the fixed cost remains constant in terms of total cost.
Fixed expenses exclude from the total cost in marginal costing technique and provide us the same cost per unit up to a certain level of production.
Fixed expenses exclude from the total cost in marginal costing technique and provide us the same cost per unit up to a certain level of production.
Features of marginal costing are as follows:
Marginal costing is used to know the impact of variable cost on the volume of production or output.
Marginal costing is used to know the impact of variable cost on the volume of production or output.
Break-even analysis is an integral and important part of marginal costing.
Break-even analysis is an integral and important part of marginal costing.
Contribution of each product or department is a foundation to know the profitability of the product or department.
Contribution of each product or department is a foundation to know the profitability of the product or department.
Addition of variable cost and profit to contribution is equal to selling price.
Addition of variable cost and profit to contribution is equal to selling price.
Marginal costing is the base of valuation of stock of finished product and work in progress.
Marginal costing is the base of valuation of stock of finished product and work in progress.
Fixed cost is recovered from contribution and variable cost is charged to production.
Fixed cost is recovered from contribution and variable cost is charged to production.
Costs are classified on the basis of fixed and variable costs only. Semi-fixed prices are also converted either as fixed cost or as variable cost.
Costs are classified on the basis of fixed and variable costs only. Semi-fixed prices are also converted either as fixed cost or as variable cost.
‘Contribution’ is a fund that is equal to the selling price of a product less marginal cost. Contribution may be described as follows:
Contribution = Selling Price – Marginal Cost
Contribution = Fixed Expenses + Profit
Contribution – Fixed Expenses = Profit
Income Statement
For the year ended 31-03-2014
The advantages of marginal costing are as follows:
Easy to operate and simple to understand.
Easy to operate and simple to understand.
Marginal costing is useful in profit planning; it is helpful to determine profitability at different level of production and sale.
Marginal costing is useful in profit planning; it is helpful to determine profitability at different level of production and sale.
It is useful in decision making about fixation of selling price, export decision and make or buy decision.
It is useful in decision making about fixation of selling price, export decision and make or buy decision.
Break even analysis and P/V ratio are useful techniques of marginal costing.
Break even analysis and P/V ratio are useful techniques of marginal costing.
Evaluation of different departments is possible through marginal costing.
Evaluation of different departments is possible through marginal costing.
By avoiding arbitrary allocation of fixed cost, it provides control over variable cost.
By avoiding arbitrary allocation of fixed cost, it provides control over variable cost.
Fixed overhead recovery rate is easy.
Fixed overhead recovery rate is easy.
Under marginal costing, valuation of inventory done at marginal cost. Therefore, it is not possible to carry forward illogical fixed overheads from one accounting period to the next period.
Under marginal costing, valuation of inventory done at marginal cost. Therefore, it is not possible to carry forward illogical fixed overheads from one accounting period to the next period.
Since fixed cost is not controllable in short period, it helps to concentrate in control over variable cost.
Since fixed cost is not controllable in short period, it helps to concentrate in control over variable cost.
13 Lectures
2 hours
Manish Gupta
8 Lectures
1 hours
Blair Cook
15 Lectures
59 mins
Prashant Panchal
26 Lectures
2.5 hours
Ross Maynard
12 Lectures
1.5 hours
Dr. John McLellan
5 Lectures
50 mins
Dr. John McLellan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2826,
"s": 2639,
"text": "Marginal cost is the change in the total cost when the quantity produced is incremented by one. That is, it is the cost of producing one more unit of a good. For example, let us suppose:"
},
{
"code": null,
"e": 3278,
"s": 2826,
"text": "Variable cost per unit = Rs 25\nFixed cost = Rs 1,00,000\nCost of 10,000 units = 25 × 10,000 = Rs 2,50,000\nTotal Cost of 10,000 units = Fixed Cost + Variable Cost\n = 1,00,000 + 2,50,000\n = Rs 3,50,000\nTotal cost of 10,001 units = 1,00,000 + 2,50,025\n = Rs 3,50,025\nMarginal Cost = 3,50,025 – 3,50,000\n = Rs 25\n"
},
{
"code": null,
"e": 3323,
"s": 3278,
"text": "Let us see why marginal costing is required:"
},
{
"code": null,
"e": 3437,
"s": 3323,
"text": "Variable cost per unit remains constant; any increase or decrease in production changes the total cost of output."
},
{
"code": null,
"e": 3551,
"s": 3437,
"text": "Variable cost per unit remains constant; any increase or decrease in production changes the total cost of output."
},
{
"code": null,
"e": 3746,
"s": 3551,
"text": "Total fixed cost remains unchanged up to a certain level of production and does not vary with increase or decrease in production. It means the fixed cost remains constant in terms of total cost."
},
{
"code": null,
"e": 3941,
"s": 3746,
"text": "Total fixed cost remains unchanged up to a certain level of production and does not vary with increase or decrease in production. It means the fixed cost remains constant in terms of total cost."
},
{
"code": null,
"e": 4089,
"s": 3941,
"text": "Fixed expenses exclude from the total cost in marginal costing technique and provide us the same cost per unit up to a certain level of production."
},
{
"code": null,
"e": 4237,
"s": 4089,
"text": "Fixed expenses exclude from the total cost in marginal costing technique and provide us the same cost per unit up to a certain level of production."
},
{
"code": null,
"e": 4282,
"s": 4237,
"text": "Features of marginal costing are as follows:"
},
{
"code": null,
"e": 4382,
"s": 4282,
"text": "Marginal costing is used to know the impact of variable cost on the volume of production or output."
},
{
"code": null,
"e": 4482,
"s": 4382,
"text": "Marginal costing is used to know the impact of variable cost on the volume of production or output."
},
{
"code": null,
"e": 4557,
"s": 4482,
"text": "Break-even analysis is an integral and important part of marginal costing."
},
{
"code": null,
"e": 4632,
"s": 4557,
"text": "Break-even analysis is an integral and important part of marginal costing."
},
{
"code": null,
"e": 4747,
"s": 4632,
"text": "Contribution of each product or department is a foundation to know the profitability of the product or department."
},
{
"code": null,
"e": 4862,
"s": 4747,
"text": "Contribution of each product or department is a foundation to know the profitability of the product or department."
},
{
"code": null,
"e": 4942,
"s": 4862,
"text": "Addition of variable cost and profit to contribution is equal to selling price."
},
{
"code": null,
"e": 5022,
"s": 4942,
"text": "Addition of variable cost and profit to contribution is equal to selling price."
},
{
"code": null,
"e": 5115,
"s": 5022,
"text": "Marginal costing is the base of valuation of stock of finished product and work in progress."
},
{
"code": null,
"e": 5208,
"s": 5115,
"text": "Marginal costing is the base of valuation of stock of finished product and work in progress."
},
{
"code": null,
"e": 5294,
"s": 5208,
"text": "Fixed cost is recovered from contribution and variable cost is charged to production."
},
{
"code": null,
"e": 5380,
"s": 5294,
"text": "Fixed cost is recovered from contribution and variable cost is charged to production."
},
{
"code": null,
"e": 5527,
"s": 5380,
"text": "Costs are classified on the basis of fixed and variable costs only. Semi-fixed prices are also converted either as fixed cost or as variable cost."
},
{
"code": null,
"e": 5674,
"s": 5527,
"text": "Costs are classified on the basis of fixed and variable costs only. Semi-fixed prices are also converted either as fixed cost or as variable cost."
},
{
"code": null,
"e": 5809,
"s": 5674,
"text": "‘Contribution’ is a fund that is equal to the selling price of a product less marginal cost. Contribution may be described as follows:"
},
{
"code": null,
"e": 5967,
"s": 5809,
"text": "Contribution = Selling Price – Marginal Cost\nContribution = Fixed Expenses + Profit\nContribution – Fixed Expenses = Profit\n"
},
{
"code": null,
"e": 5984,
"s": 5967,
"text": "Income Statement"
},
{
"code": null,
"e": 6014,
"s": 5984,
"text": "For the year ended 31-03-2014"
},
{
"code": null,
"e": 6065,
"s": 6014,
"text": "The advantages of marginal costing are as follows:"
},
{
"code": null,
"e": 6107,
"s": 6065,
"text": "Easy to operate and simple to understand."
},
{
"code": null,
"e": 6149,
"s": 6107,
"text": "Easy to operate and simple to understand."
},
{
"code": null,
"e": 6280,
"s": 6149,
"text": "Marginal costing is useful in profit planning; it is helpful to determine profitability at different level of production and sale."
},
{
"code": null,
"e": 6411,
"s": 6280,
"text": "Marginal costing is useful in profit planning; it is helpful to determine profitability at different level of production and sale."
},
{
"code": null,
"e": 6518,
"s": 6411,
"text": "It is useful in decision making about fixation of selling price, export decision and make or buy decision."
},
{
"code": null,
"e": 6625,
"s": 6518,
"text": "It is useful in decision making about fixation of selling price, export decision and make or buy decision."
},
{
"code": null,
"e": 6702,
"s": 6625,
"text": "Break even analysis and P/V ratio are useful techniques of marginal costing."
},
{
"code": null,
"e": 6779,
"s": 6702,
"text": "Break even analysis and P/V ratio are useful techniques of marginal costing."
},
{
"code": null,
"e": 6853,
"s": 6779,
"text": "Evaluation of different departments is possible through marginal costing."
},
{
"code": null,
"e": 6927,
"s": 6853,
"text": "Evaluation of different departments is possible through marginal costing."
},
{
"code": null,
"e": 7015,
"s": 6927,
"text": "By avoiding arbitrary allocation of fixed cost, it provides control over variable cost."
},
{
"code": null,
"e": 7103,
"s": 7015,
"text": "By avoiding arbitrary allocation of fixed cost, it provides control over variable cost."
},
{
"code": null,
"e": 7141,
"s": 7103,
"text": "Fixed overhead recovery rate is easy."
},
{
"code": null,
"e": 7179,
"s": 7141,
"text": "Fixed overhead recovery rate is easy."
},
{
"code": null,
"e": 7369,
"s": 7179,
"text": "Under marginal costing, valuation of inventory done at marginal cost. Therefore, it is not possible to carry forward illogical fixed overheads from one accounting period to the next period."
},
{
"code": null,
"e": 7559,
"s": 7369,
"text": "Under marginal costing, valuation of inventory done at marginal cost. Therefore, it is not possible to carry forward illogical fixed overheads from one accounting period to the next period."
},
{
"code": null,
"e": 7668,
"s": 7559,
"text": "Since fixed cost is not controllable in short period, it helps to concentrate in control over variable cost."
},
{
"code": null,
"e": 7777,
"s": 7668,
"text": "Since fixed cost is not controllable in short period, it helps to concentrate in control over variable cost."
},
{
"code": null,
"e": 7810,
"s": 7777,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7824,
"s": 7810,
"text": " Manish Gupta"
},
{
"code": null,
"e": 7856,
"s": 7824,
"text": "\n 8 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7868,
"s": 7856,
"text": " Blair Cook"
},
{
"code": null,
"e": 7900,
"s": 7868,
"text": "\n 15 Lectures \n 59 mins\n"
},
{
"code": null,
"e": 7918,
"s": 7900,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 7953,
"s": 7918,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7967,
"s": 7953,
"text": " Ross Maynard"
},
{
"code": null,
"e": 8002,
"s": 7967,
"text": "\n 12 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8021,
"s": 8002,
"text": " Dr. John McLellan"
},
{
"code": null,
"e": 8052,
"s": 8021,
"text": "\n 5 Lectures \n 50 mins\n"
},
{
"code": null,
"e": 8071,
"s": 8052,
"text": " Dr. John McLellan"
},
{
"code": null,
"e": 8078,
"s": 8071,
"text": " Print"
},
{
"code": null,
"e": 8089,
"s": 8078,
"text": " Add Notes"
}
]
|
How to Create a Beautify Combo Chart in Python Plotly | by Di(Candice) Han | Towards Data Science | Nobody would deny that line and bar combo chart is one of the most widely used combo charts. In Excel, there is a build-in feature of Combo chart. It is also one of the most popular charts to analyze financial data.
In this tutorial, we are going to build a customized combo plot using plotly. The finished combo chart will look like this.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport plotly.graph_objects as go%matplotlib inline
Amazon_Financials ={'Year': [2009, 2010,2011,2012,2013,2014,2015,2016,2017,2018,2019], 'Revenue($M)': [24509, 34204,48077,61093,74452,88988,107006,135987,177866,232887,280522], 'Profit($M)':[5531,7643,10789,15122,20271,26236,35355,47722,65932,93731,114986]}df = pd.DataFrame(data=Amazon_Financials)
The dataset is very simple. It contains the revenue and profit data of Amazon.com, Inc between 2009 and 2020.
fig = go.Figure()fig.add_trace( go.Scatter( x=df['Year'], y=df['Revenue($M)'], name="Revenue" ))fig.add_trace( go.Bar( x=df['Year'], y=df['Profit($M)'], name="Profit" ))fig.show()
It can be clearly seen that the font of the axis labels on the horizontal and vertical coordinates is a little bit small, It is hard to read. The label of x-axis is not completely shown. And the scale line is not very helpful in pinpointing the real number for each bar. The first step is to enlarge the font of the axis labels and remove the scale line. There is no title for the legend or for the chart. Titles need to be added to provide information to the end users about what is the topic of the chart.
fig = go.Figure()fig.add_trace( go.Scatter( x=df['Year'], y=df['Revenue($M)'], name="Revenue" ))fig.add_trace( go.Bar( x=df['Year'], y=df['Profit($M)'], name="Profit", text = df['Profit($M)'], textposition='outside', textfont=dict( size=13, color='#1f77b4') ))fig.update_traces(texttemplate='%{text:.2s}')fig.update_layout(legend_title_text='Financials', title_text='2009-2019 Financial Report')fig.show()
In this example, the color of the line will become ‘firebrick’. You can use Hex Color Codes or RBG as well. The bars will become light blue color surrounded by lines to enhance the visibility of bars. I also made the bars a little bit transparent. The background color is changed to light grey. X-axis and y-axis are labeled to avoid any confusion.
import plotly.graph_objects as gofig = go.Figure()fig.add_trace( go.Scatter( x=df['Year'], y=df['Revenue($M)'], name="Revenue", mode='lines+markers', # mode = 'lines', if you don't want the markers marker={'size':9}, line = dict(color='firebrick', width=3) ))fig.add_trace( go.Bar( x=df['Year'], y=df['Profit($M)'], name="Profit", text = df['Profit($M)'], textposition='outside', textfont=dict( size=13, color='#1f77b4'), marker_color='rgb(158,202,225)', marker_line_color='rgb(17, 69, 126)', marker_line_width=2, opacity=0.7 ))# strip down the rest of the plotfig.update_layout( showlegend=True, plot_bgcolor="rgb(240,240,240)", margin=dict(t=50,l=10,b=10,r=10), title_text='2009-2019 Financial Report', legend_title_text='Financials', xaxis_tickfont_size=14, yaxis=dict( title='USD (millions)', titlefont_size=16, tickfont_size=14, ), legend=dict( x=0.01, y=0.99, bgcolor='rgba(255, 255, 255, 0)', bordercolor='rgba(255, 255, 255, 0)' ), bargap=0.15)fig.update_traces(texttemplate='%{text:.2s}')fig.show()
There are still some small adjustments required to make the chart more informative and less confusing.
•The x-axis doesn’t have all years
•Fonts of both axes are very small
•Title of the chart should be centered
fig = go.Figure()fig.add_trace( go.Scatter( x=df[‘Year’], y=df[‘Revenue($M)’], name=”Revenue”, mode=’lines+markers’, # mode = ‘lines’ marker={‘size’:9}, line = dict(color=’firebrick’, width=3) ))fig.add_trace( go.Bar( x=df[‘Year’], y=df[‘Profit($M)’], name=”Profit”, text = df[‘Profit($M)’], textposition=’outside’, textfont=dict( size=13, color=’#1f77b4'), marker_color=’rgb(158,202,225)’, marker_line_color=’rgb(17, 69, 126)’, marker_line_width=2, opacity=0.7 ))# strip down the rest of the plotfig.update_layout( showlegend=True, plot_bgcolor=”rgb(240,240,240)”, margin=dict(t=50,l=10,b=10,r=10), title_text=’2009–2019 Financial Report’, title_font_family=”Times New Roman”, legend_title_text=’Financials’, title_font_size = 25, title_font_color=”darkblue”, title_x=0.5, xaxis=dict( tickfont_size=14, tickangle = 270, showgrid = True, zeroline = True, showline = True, showticklabels = True, dtick=1 ), yaxis=dict( title=’USD (millions)’, titlefont_size=16, tickfont_size=14 ), legend=dict( x=0.01, y=0.99, bgcolor=’rgba(255, 255, 255, 0)’, bordercolor=’rgba(255, 255, 255, 0)’ ), bargap=0.15)fig.update_traces(texttemplate=’%{text:.2s}’)fig.show()
Now this chart looks much better than the preliminary version. We can further beautify the chart by introducing more customization.
We can change the shape, color of markers, and also the color of those bars to make the chart more impressive.
import plotly.graph_objects as gofig = go.Figure()fig.add_trace( go.Scatter( x=df['Year'], y=df['Revenue($M)'], name="Revenue", mode='lines+markers', # mode = 'lines' marker= dict(size=9, symbol = 'diamond', color ='RGB(251, 177, 36)', line_width = 2 ), line = dict(color='firebrick', width=3) ))fig.add_trace( go.Bar( x=df['Year'], y=df['Profit($M)'], name="Profit", text = df['Profit($M)'], textposition='outside', textfont=dict( size=13, color='#1f77b4'), marker_color=["#f3e5f5", '#e1bee7', '#ce93d8', '#ba68c8','#ab47bc', '#9c27b0','#8e24aa','#7b1fa2','#6a1b9a','#4a148c','#3c0a99'], marker_line_color='rgb(17, 69, 126)', marker_line_width=1, opacity=0.7 ))# strip down the rest of the plotfig.update_layout( showlegend=True, plot_bgcolor="rgb(240,240,240)", margin=dict(t=50,l=10,b=10,r=10), title_text='2009-2019 Financial Report', title_font_family="Times New Roman", title_font_size = 25, title_font_color="darkblue", title_x=0.5, xaxis=dict( tickfont_size=14, tickangle = 270, showgrid = True, zeroline = True, showline = True, showticklabels = True, dtick=1 ), yaxis=dict( title='USD (millions)', titlefont_size=16, tickfont_size=14 ), legend=dict( x=0.01, y=0.99, bgcolor='rgba(255, 255, 255, 0)', bordercolor='rgba(255, 255, 255, 0)' ), bargap=0.15)fig.update_traces(texttemplate='%{text:.2s}')fig.show()
If you want to use one of the variable/feature to define the color of the bars, simple replace
fig.add_trace( go.Bar( x=df['Year'], y=df['Profit($M)'], name="Profit", text = df['Profit($M)'], textposition='outside', textfont=dict( size=13, color='#1f77b4'), marker_color=["#f3e5f5", '#e1bee7', '#ce93d8', '#ba68c8','#ab47bc', '#9c27b0','#8e24aa','#7b1fa2','#6a1b9a','#4a148c','#3c0a99'], marker_line_color='rgb(17, 69, 126)', marker_line_width=1, opacity=0.7 ))
with
fig.add_trace( go.Bar( x=df['Year'], y=df['Profit($M)'], name="Profit", text = df['Profit($M)'], textposition='outside', textfont=dict( size=13, color='#1f77b4'), marker_color=df['Profit($M)'], marker_line_color='rgb(17, 69, 126)', marker_line_width=2, opacity=0.7 ))
Then you will get a combo chart like this,
At the very end, let us take a final look at the Before and After charts.
The beautified chart is much more clear and and can more information to the audience. Labels and title are also informative. Grid lines is helpful in pinpointing the actual numbers of each bars. | [
{
"code": null,
"e": 388,
"s": 172,
"text": "Nobody would deny that line and bar combo chart is one of the most widely used combo charts. In Excel, there is a build-in feature of Combo chart. It is also one of the most popular charts to analyze financial data."
},
{
"code": null,
"e": 512,
"s": 388,
"text": "In this tutorial, we are going to build a customized combo plot using plotly. The finished combo chart will look like this."
},
{
"code": null,
"e": 632,
"s": 512,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport plotly.graph_objects as go%matplotlib inline"
},
{
"code": null,
"e": 969,
"s": 632,
"text": "Amazon_Financials ={'Year': [2009, 2010,2011,2012,2013,2014,2015,2016,2017,2018,2019], 'Revenue($M)': [24509, 34204,48077,61093,74452,88988,107006,135987,177866,232887,280522], 'Profit($M)':[5531,7643,10789,15122,20271,26236,35355,47722,65932,93731,114986]}df = pd.DataFrame(data=Amazon_Financials)"
},
{
"code": null,
"e": 1079,
"s": 969,
"text": "The dataset is very simple. It contains the revenue and profit data of Amazon.com, Inc between 2009 and 2020."
},
{
"code": null,
"e": 1313,
"s": 1079,
"text": "fig = go.Figure()fig.add_trace( go.Scatter( x=df['Year'], y=df['Revenue($M)'], name=\"Revenue\" ))fig.add_trace( go.Bar( x=df['Year'], y=df['Profit($M)'], name=\"Profit\" ))fig.show()"
},
{
"code": null,
"e": 1821,
"s": 1313,
"text": "It can be clearly seen that the font of the axis labels on the horizontal and vertical coordinates is a little bit small, It is hard to read. The label of x-axis is not completely shown. And the scale line is not very helpful in pinpointing the real number for each bar. The first step is to enlarge the font of the axis labels and remove the scale line. There is no title for the legend or for the chart. Titles need to be added to provide information to the end users about what is the topic of the chart."
},
{
"code": null,
"e": 2332,
"s": 1821,
"text": "fig = go.Figure()fig.add_trace( go.Scatter( x=df['Year'], y=df['Revenue($M)'], name=\"Revenue\" ))fig.add_trace( go.Bar( x=df['Year'], y=df['Profit($M)'], name=\"Profit\", text = df['Profit($M)'], textposition='outside', textfont=dict( size=13, color='#1f77b4') ))fig.update_traces(texttemplate='%{text:.2s}')fig.update_layout(legend_title_text='Financials', title_text='2009-2019 Financial Report')fig.show()"
},
{
"code": null,
"e": 2681,
"s": 2332,
"text": "In this example, the color of the line will become ‘firebrick’. You can use Hex Color Codes or RBG as well. The bars will become light blue color surrounded by lines to enhance the visibility of bars. I also made the bars a little bit transparent. The background color is changed to light grey. X-axis and y-axis are labeled to avoid any confusion."
},
{
"code": null,
"e": 3919,
"s": 2681,
"text": "import plotly.graph_objects as gofig = go.Figure()fig.add_trace( go.Scatter( x=df['Year'], y=df['Revenue($M)'], name=\"Revenue\", mode='lines+markers', # mode = 'lines', if you don't want the markers marker={'size':9}, line = dict(color='firebrick', width=3) ))fig.add_trace( go.Bar( x=df['Year'], y=df['Profit($M)'], name=\"Profit\", text = df['Profit($M)'], textposition='outside', textfont=dict( size=13, color='#1f77b4'), marker_color='rgb(158,202,225)', marker_line_color='rgb(17, 69, 126)', marker_line_width=2, opacity=0.7 ))# strip down the rest of the plotfig.update_layout( showlegend=True, plot_bgcolor=\"rgb(240,240,240)\", margin=dict(t=50,l=10,b=10,r=10), title_text='2009-2019 Financial Report', legend_title_text='Financials', xaxis_tickfont_size=14, yaxis=dict( title='USD (millions)', titlefont_size=16, tickfont_size=14, ), legend=dict( x=0.01, y=0.99, bgcolor='rgba(255, 255, 255, 0)', bordercolor='rgba(255, 255, 255, 0)' ), bargap=0.15)fig.update_traces(texttemplate='%{text:.2s}')fig.show()"
},
{
"code": null,
"e": 4022,
"s": 3919,
"text": "There are still some small adjustments required to make the chart more informative and less confusing."
},
{
"code": null,
"e": 4057,
"s": 4022,
"text": "•The x-axis doesn’t have all years"
},
{
"code": null,
"e": 4092,
"s": 4057,
"text": "•Fonts of both axes are very small"
},
{
"code": null,
"e": 4131,
"s": 4092,
"text": "•Title of the chart should be centered"
},
{
"code": null,
"e": 5285,
"s": 4131,
"text": "fig = go.Figure()fig.add_trace( go.Scatter( x=df[‘Year’], y=df[‘Revenue($M)’], name=”Revenue”, mode=’lines+markers’, # mode = ‘lines’ marker={‘size’:9}, line = dict(color=’firebrick’, width=3) ))fig.add_trace( go.Bar( x=df[‘Year’], y=df[‘Profit($M)’], name=”Profit”, text = df[‘Profit($M)’], textposition=’outside’, textfont=dict( size=13, color=’#1f77b4'), marker_color=’rgb(158,202,225)’, marker_line_color=’rgb(17, 69, 126)’, marker_line_width=2, opacity=0.7 ))# strip down the rest of the plotfig.update_layout( showlegend=True, plot_bgcolor=”rgb(240,240,240)”, margin=dict(t=50,l=10,b=10,r=10), title_text=’2009–2019 Financial Report’, title_font_family=”Times New Roman”, legend_title_text=’Financials’, title_font_size = 25, title_font_color=”darkblue”, title_x=0.5, xaxis=dict( tickfont_size=14, tickangle = 270, showgrid = True, zeroline = True, showline = True, showticklabels = True, dtick=1 ), yaxis=dict( title=’USD (millions)’, titlefont_size=16, tickfont_size=14 ), legend=dict( x=0.01, y=0.99, bgcolor=’rgba(255, 255, 255, 0)’, bordercolor=’rgba(255, 255, 255, 0)’ ), bargap=0.15)fig.update_traces(texttemplate=’%{text:.2s}’)fig.show()"
},
{
"code": null,
"e": 5417,
"s": 5285,
"text": "Now this chart looks much better than the preliminary version. We can further beautify the chart by introducing more customization."
},
{
"code": null,
"e": 5528,
"s": 5417,
"text": "We can change the shape, color of markers, and also the color of those bars to make the chart more impressive."
},
{
"code": null,
"e": 7240,
"s": 5528,
"text": "import plotly.graph_objects as gofig = go.Figure()fig.add_trace( go.Scatter( x=df['Year'], y=df['Revenue($M)'], name=\"Revenue\", mode='lines+markers', # mode = 'lines' marker= dict(size=9, symbol = 'diamond', color ='RGB(251, 177, 36)', line_width = 2 ), line = dict(color='firebrick', width=3) ))fig.add_trace( go.Bar( x=df['Year'], y=df['Profit($M)'], name=\"Profit\", text = df['Profit($M)'], textposition='outside', textfont=dict( size=13, color='#1f77b4'), marker_color=[\"#f3e5f5\", '#e1bee7', '#ce93d8', '#ba68c8','#ab47bc', '#9c27b0','#8e24aa','#7b1fa2','#6a1b9a','#4a148c','#3c0a99'], marker_line_color='rgb(17, 69, 126)', marker_line_width=1, opacity=0.7 ))# strip down the rest of the plotfig.update_layout( showlegend=True, plot_bgcolor=\"rgb(240,240,240)\", margin=dict(t=50,l=10,b=10,r=10), title_text='2009-2019 Financial Report', title_font_family=\"Times New Roman\", title_font_size = 25, title_font_color=\"darkblue\", title_x=0.5, xaxis=dict( tickfont_size=14, tickangle = 270, showgrid = True, zeroline = True, showline = True, showticklabels = True, dtick=1 ), yaxis=dict( title='USD (millions)', titlefont_size=16, tickfont_size=14 ), legend=dict( x=0.01, y=0.99, bgcolor='rgba(255, 255, 255, 0)', bordercolor='rgba(255, 255, 255, 0)' ), bargap=0.15)fig.update_traces(texttemplate='%{text:.2s}')fig.show()"
},
{
"code": null,
"e": 7335,
"s": 7240,
"text": "If you want to use one of the variable/feature to define the color of the bars, simple replace"
},
{
"code": null,
"e": 7819,
"s": 7335,
"text": "fig.add_trace( go.Bar( x=df['Year'], y=df['Profit($M)'], name=\"Profit\", text = df['Profit($M)'], textposition='outside', textfont=dict( size=13, color='#1f77b4'), marker_color=[\"#f3e5f5\", '#e1bee7', '#ce93d8', '#ba68c8','#ab47bc', '#9c27b0','#8e24aa','#7b1fa2','#6a1b9a','#4a148c','#3c0a99'], marker_line_color='rgb(17, 69, 126)', marker_line_width=1, opacity=0.7 ))"
},
{
"code": null,
"e": 7824,
"s": 7819,
"text": "with"
},
{
"code": null,
"e": 8190,
"s": 7824,
"text": "fig.add_trace( go.Bar( x=df['Year'], y=df['Profit($M)'], name=\"Profit\", text = df['Profit($M)'], textposition='outside', textfont=dict( size=13, color='#1f77b4'), marker_color=df['Profit($M)'], marker_line_color='rgb(17, 69, 126)', marker_line_width=2, opacity=0.7 ))"
},
{
"code": null,
"e": 8233,
"s": 8190,
"text": "Then you will get a combo chart like this,"
},
{
"code": null,
"e": 8307,
"s": 8233,
"text": "At the very end, let us take a final look at the Before and After charts."
}
]
|
An Intuitive Explanation of Policy Gradient | by Adrien Lucas Ecoffet | Towards Data Science | This is part 1 of a series of tutorials which I expect to have 2 or 3 parts. The next part will be on A2C and, time providing, I hope to complete a part on various forms of off-policy policy gradients.
The notebooks for these posts can be found in this git repo.
Some of today’s most successful reinforcement learning algorithms, from A3C to TRPO to PPO belong to the policy gradient family of algorithm, and often more specifically to the actor-critic family. Clearly as an RL enthusiast, you owe it to yourself to have a good understanding of the policy gradient method, which is why so many tutorials out there attempt to describe them.
Yet, if you’ve ever tried to follow one of these tutorials, you were probably faced with an equation along the following lines:
or perhaps the related update rule:
or perhaps even the loss function:
Most likely this was accompanied by a very handwavy explanation, a ton of complicated math, or no explanation at all.
Indeed, some of my favorite tutorials on Reinforcement Learning are guilty of this. Jaromiru’s Let’s make an A3C states:
The second term inside the expectation, ∇θlogπ(a|s), tells us a direction in which logged probability of taking action a in state s rises. Simply said, how to make this action in this context more probable.
While Arthur Juliani states in Simple Reinforcement Learning with Tensorflow:
Intuitively, this loss function allows us to increase the weight for actions that yielded a positive reward, and decrease them for actions that yielded a negative reward.
Both of these explanations are unsatisfactory. Specifically, they completely fail to explain the presence of the mysterious log function in these formulas. If you only remembered their intuitive explanations, you would not be able to write down the loss function yourself. This is not OK.
Amazingly, there actually is a perfectly intuitive explanation of this formula! However, as far as I know the only clear statement of this intuition is hidden in Chapter 13, section 3 of Sutton & Barto’s Reinforcement Learning: An Introduction.
Once I describe it to you in painstaking details, you will be able to account for the presence of the log function and you should be able to write down the formula from first principles. Indeed, you will also be able to come up with your own variants policy gradient!
In this post, I will assume that you already have some basic notions of Reinforcement Learning, and in particular that you are familiar with Q-Learning and, ideally, DQNs.
If you aren’t yet familiar with Q-Learning, I suggest you read at least the introduction of one of the many great DQN tutorials out there. Some suggestions:
Beat Atari with Deep Reinforcement Learning by yours truly
Let’s Make a DQN by Jaromiru
Simple Reinforcement Learning with Tensorflow by Arthur Juliani
Before going any further, let’s learn about some of the advantages of policy gradient methods over Q-Learning, as extra motivation to try to genuinely understand policy gradient:
The policy implied by Q-Learning is deterministic. This means that Q-Learning can’t learn stochastic policies, which can be useful in some environments. It also means that we need to create our own exploration strategy since following the policy will not perform any exploration. We usually do this with ε-greedy exploration, which can be quite inefficient.
There is no straightforward way to handle continuous actions in Q-Learning. In policy gradient, handling continous actions is relatively easy.
As its name implies, in policy gradient we are following gradients with respect to the policy itself, which means we are constantly improving the policy. By contrast, in Q-Learning we are improving our estimates of the values of different actions, which only implicitely improves the policy. You would think that improving the policy directly would be more efficient, and indeed it very often is.
In general, policy gradient methods have very often beaten value-based methods such as DQNs on modern tasks such as playing Atari games.
Although this article aims to provide intuition on policy gradients and thus aims to not be too mathematical, our goal is still to explain an equation, and so we need to use some mathematical notation, which I will introduce as needed throughout the article. Let’s start with our first fundamental pieces of notation:
The letter π will symbolize a policy. Let’s call πθ(a|s) the probability of taking action a in state s. θ represents the parameters of our policy (the weights of our neural network).
Our goal is to update θ to values that make πθ the optimal policy. Because θ will change, we will use the notation θt to denote θ at iteration t. We want to find out the update rule that takes use from θt to θt+1 in a way that we eventually reach the optimal policy.
Typically, for a discrete action space, πθ would be a neural network with a softmax output unit, so that the output can be thought of as the probability of taking each action.
Clearly, if action a∗ is the optimal action, we want πθ(a∗|s) to be as close to 1 as possible.
For this we can simply perform gradient ascent on πθ(a∗|s), so at each iteration we update θ in the following way:
We can view the gradient ∇πθt(a∗|s) as being “the direction in which to move θt so as to increase the value of πθt(a∗|s) the fastest”. Note that we are indeed using gradient ascent since we want to increase a value, not decrease it as is usual in deep learning.
Thus one way to view this update is that we keep “pushing” towards more of action a* in our policy, which is indeed what we want.
In the example below, we know that the first action is the best action, so we run gradient ascent on it. For this running example we will assume a single state s so that the evolution of the policy is easier to plot. We will generalize to multiple states later in this series when we introduce A2C.
The gif above shows the result of our algorithm. The height of each bar is the probability of taking each action as our algorithm runs, and the arrow shows the gradient that we are following each iteration. In this case, we are only applying the gradient on the first action, which happens to have the largest value (10), which is why it is the only one that increases at the expense of others.
Of course, in practice, we won’t know which action is best... After all that’s what we’re trying to figure out in the first place!
To get back to the metaphor of “pushing”, if we don’t know which action is optimal, we might “push” on suboptimal actions and our policy will never converge.
One solution would be to “push” on actions in a way that is proportional to our guess of the value of these actions. These guesses can be highly approximate, but as long as they are somewhat grounded in reality, more overall pushing will happen on the optimal action a∗. This way it is guaranteed that eventually our policy will converge to a∗=1!
We will call our guess of the value of action a in state s Q̂ (s,a). Indeed, this is very similar to the Q function that we know from Q-Learning, though there is a subtle and important difference that will make it easier to learn and that we will learn about later. For now, let’s just assume that this Q function is a given.
We get the following gradient ascent update, that we can now apply to each action in turn instead of just to the optimal action:
Let’s weigh our updates to the simulated policy gradient using a noisy version of the Q values of the different actions (10 for action a, 5 for action b, 2.5 for action c), and this time, we will randomly update each of the different possible actions, since we assume that we don’t know which one is best. As we see, the first action does still end up winning, even though our estimates of the values (as shown by the lengths of the arrows) varies significantly across iterations.
Of course, in practice, our agent is not going to choose actions uniformly at random, which is what we implicitly assumed so far. Rather, we are going to follow the very policy πθ that we are trying to train! This is called training on-policy. There are two reasons why we might want to train on-policy:
We accumulate more rewards even as we train, which is something we might value in some contexts.
It allows us to explore more promising areas of the state space by not exploring purely randomly but rather closer to our current guess of the optimal actions.
This creates a problem with our current training algorithm, however: although we are going to “push” stronger on the actions that have a better value, we are also going to “push” more often on whichever actions happen to have higher values of πθ to begin with (which could happen due to chance or bad initialization)! These actions might end up winning the race to the top in spite of being bad.
Let’s illustrate this phenomenon by using the same update rule but sampling actions according to their probability instead of uniformly:
Here we can see that the third action, in spite of having a lower value than the other two, ends up winning because it starts out initialized much higher.
This means that we need to compensate for the fact that more probable actions are going to be taken more often. How do we do this? Simple: we divide our update by the probability of the action. This way, if an action is 4x more likely to be taken than another, we will have 4x more gradient updates to it but each will be 4x smaller.
This gives us the following update rule:
Let’s try it:
We now see that even though action 3 starts out with a significant advantage, action 1 eventually wins out because its updates are much larger when its probability is small. Exactly the behavior that we wanted!
And we are now done explaining the intuition behind policy gradient! All the rest of this post is simply filling out some details. This is a significant accomplishment and you should feel proud of yourself for understanding this far!
“But, wait a minute”, you say, “I thought you would tell us how to understand the mysterious update rule
but our update rule looks completely different!”
Ah yes, indeed our update rule looks different, but it is in fact essentially the same! As a reminder, the key point in our rule is
while the rule we are trying to explain contains
The next section will explain the difference between  and Q̂, but suffice it to say for now that both work perfectly fine, but that using  is just an optimization.
The only difference remaining is thus between
and
In fact, these two expressions are equivalent! This is due to the chain rule and the fact that the derivative of log x is 1/x, as you might know from calculus. So we have in general:
So now you know the origin of the mysterious log function in the policy gradient update! So why do people use the form using the log function instead of the more intuitive one which divides by π(s|a)? I can see two reasons for this:
It obfuscates the intuition behind policy gradient, thus making you seem more impressive for understanding it.It makes it possible to express the update as a loss function when doing gradient descent, as in the equation L=−Â (s,a)logπθ(s|a) we saw at the beginning (bringing Â(s,a)inside the loss function is fine since it is a constant with respect to θ). This way you can use your favorite deep learning library to train your policy (which we will see how to do soon!).
It obfuscates the intuition behind policy gradient, thus making you seem more impressive for understanding it.
It makes it possible to express the update as a loss function when doing gradient descent, as in the equation L=−Â (s,a)logπθ(s|a) we saw at the beginning (bringing Â(s,a)inside the loss function is fine since it is a constant with respect to θ). This way you can use your favorite deep learning library to train your policy (which we will see how to do soon!).
At this point you now understand the basic form of the REINFORCE algorithm, which, as I am sure you expect, stands for “REward Increment = Nonnegative Factor × Offset Reinforcement × Characteristic Eligibility”... (yes I am serious, see the original paper). REINFORCE is the fundamental policy gradient algorithm on which nearly all the advanced policy gradient algorithms you might have heard of are based.
Now the final thing left to explain, as promised, is the difference between Q̂ and Â. You should already be familiar with Q from Q-Learning: Q(s,a) is the value (cumulative discounted reward, to be exact) obtained by taking action a in state s, and then following our policy π thereafter.
Note that it may be the case that following any action will give us a cumulative reward of, say, at least 100, but that some actions will be better than others, so that Q might be equal to, say, 101 for action a, 102 for action b and 100 for action c. As you can guess, this means that almost all of the weight of our update will tell us nothing about whether the current action is better, which is problematic.
You may also be familiar with the V(s) function, which simply gives us the value of following the policy starting in state s and all the way after that. In the example above, V(s) will be larger than 100 since all the Q(s, a) are larger than 100.
By subtracting V(s) from Q(s, a), we get the advantage function A(s, a). This function tells us how much better or worse taking action a in state is is compared to acting according to the policy. In the example above, it will subtract the extra 100 from the Q values of all the action, providing more signal to noise ratio.
In this tutorial I always wrote Q̂ or Â, with a “hat” on top of Q and A to emphasize that we are not using the “real” Q or A but rather an estimate of them. How to get those estimates will be the subject of the next post in the series.
As it turns out, REINFORCE will still work perfectly fine if we subtract any function from Q̂(s,a) as long as that function does not depend on the action. This makes sense based on our previous intuition of course, since the only thing that matters is that we “push” harder on the actions that have a higher Q value, and subtracting any value that doesn’t depend on the action will preserve the ranking of how hard we push on the various actions.
This means that using the  function instead of the Q̂ function is perfectly allowable. In fact, it is widely recommended for the reasons described above and also because it is supposed to reduce the variance of the gradient updates. Note that  is not known for sure to be the best function to use instead of Q̂, but in practice it generally works quite well.
Let’s see what using  does in our simulation:
Output:
Running using A functionDone in 48 iterationsVariance of A gradients: 31.384320255389287Running using Q functionDone in 30 iterationsVariance of Q gradients: 31.813126235495847
Unfortunately, the impact is not dramatic here: the variance does end up slightly lower, but the time to converge is longer. That said, I am comparing the same learning rate between the two, and using the advantage function should let you use a higher learning rate without diverging. Further, this is a toy example and the benefits of using the advantage function has been widely attested in practice on larger problems. Sadly, this is the one instance in this tutorial in which you’ll have to take my word for it that something works well.
You now have a full intuitive understanding of basic policy gradients. However, you might be wondering how to use these in practice: how do you represent a policy with a neural network? How do you get your  estimate in the first place? What other tricks are used in practice to make this work?
We will learn about all of this soon in part 2, which will explain the A2C algorithm. | [
{
"code": null,
"e": 373,
"s": 171,
"text": "This is part 1 of a series of tutorials which I expect to have 2 or 3 parts. The next part will be on A2C and, time providing, I hope to complete a part on various forms of off-policy policy gradients."
},
{
"code": null,
"e": 434,
"s": 373,
"text": "The notebooks for these posts can be found in this git repo."
},
{
"code": null,
"e": 811,
"s": 434,
"text": "Some of today’s most successful reinforcement learning algorithms, from A3C to TRPO to PPO belong to the policy gradient family of algorithm, and often more specifically to the actor-critic family. Clearly as an RL enthusiast, you owe it to yourself to have a good understanding of the policy gradient method, which is why so many tutorials out there attempt to describe them."
},
{
"code": null,
"e": 939,
"s": 811,
"text": "Yet, if you’ve ever tried to follow one of these tutorials, you were probably faced with an equation along the following lines:"
},
{
"code": null,
"e": 975,
"s": 939,
"text": "or perhaps the related update rule:"
},
{
"code": null,
"e": 1010,
"s": 975,
"text": "or perhaps even the loss function:"
},
{
"code": null,
"e": 1128,
"s": 1010,
"text": "Most likely this was accompanied by a very handwavy explanation, a ton of complicated math, or no explanation at all."
},
{
"code": null,
"e": 1249,
"s": 1128,
"text": "Indeed, some of my favorite tutorials on Reinforcement Learning are guilty of this. Jaromiru’s Let’s make an A3C states:"
},
{
"code": null,
"e": 1456,
"s": 1249,
"text": "The second term inside the expectation, ∇θlogπ(a|s), tells us a direction in which logged probability of taking action a in state s rises. Simply said, how to make this action in this context more probable."
},
{
"code": null,
"e": 1534,
"s": 1456,
"text": "While Arthur Juliani states in Simple Reinforcement Learning with Tensorflow:"
},
{
"code": null,
"e": 1705,
"s": 1534,
"text": "Intuitively, this loss function allows us to increase the weight for actions that yielded a positive reward, and decrease them for actions that yielded a negative reward."
},
{
"code": null,
"e": 1994,
"s": 1705,
"text": "Both of these explanations are unsatisfactory. Specifically, they completely fail to explain the presence of the mysterious log function in these formulas. If you only remembered their intuitive explanations, you would not be able to write down the loss function yourself. This is not OK."
},
{
"code": null,
"e": 2239,
"s": 1994,
"text": "Amazingly, there actually is a perfectly intuitive explanation of this formula! However, as far as I know the only clear statement of this intuition is hidden in Chapter 13, section 3 of Sutton & Barto’s Reinforcement Learning: An Introduction."
},
{
"code": null,
"e": 2507,
"s": 2239,
"text": "Once I describe it to you in painstaking details, you will be able to account for the presence of the log function and you should be able to write down the formula from first principles. Indeed, you will also be able to come up with your own variants policy gradient!"
},
{
"code": null,
"e": 2679,
"s": 2507,
"text": "In this post, I will assume that you already have some basic notions of Reinforcement Learning, and in particular that you are familiar with Q-Learning and, ideally, DQNs."
},
{
"code": null,
"e": 2836,
"s": 2679,
"text": "If you aren’t yet familiar with Q-Learning, I suggest you read at least the introduction of one of the many great DQN tutorials out there. Some suggestions:"
},
{
"code": null,
"e": 2895,
"s": 2836,
"text": "Beat Atari with Deep Reinforcement Learning by yours truly"
},
{
"code": null,
"e": 2924,
"s": 2895,
"text": "Let’s Make a DQN by Jaromiru"
},
{
"code": null,
"e": 2988,
"s": 2924,
"text": "Simple Reinforcement Learning with Tensorflow by Arthur Juliani"
},
{
"code": null,
"e": 3167,
"s": 2988,
"text": "Before going any further, let’s learn about some of the advantages of policy gradient methods over Q-Learning, as extra motivation to try to genuinely understand policy gradient:"
},
{
"code": null,
"e": 3525,
"s": 3167,
"text": "The policy implied by Q-Learning is deterministic. This means that Q-Learning can’t learn stochastic policies, which can be useful in some environments. It also means that we need to create our own exploration strategy since following the policy will not perform any exploration. We usually do this with ε-greedy exploration, which can be quite inefficient."
},
{
"code": null,
"e": 3668,
"s": 3525,
"text": "There is no straightforward way to handle continuous actions in Q-Learning. In policy gradient, handling continous actions is relatively easy."
},
{
"code": null,
"e": 4065,
"s": 3668,
"text": "As its name implies, in policy gradient we are following gradients with respect to the policy itself, which means we are constantly improving the policy. By contrast, in Q-Learning we are improving our estimates of the values of different actions, which only implicitely improves the policy. You would think that improving the policy directly would be more efficient, and indeed it very often is."
},
{
"code": null,
"e": 4202,
"s": 4065,
"text": "In general, policy gradient methods have very often beaten value-based methods such as DQNs on modern tasks such as playing Atari games."
},
{
"code": null,
"e": 4520,
"s": 4202,
"text": "Although this article aims to provide intuition on policy gradients and thus aims to not be too mathematical, our goal is still to explain an equation, and so we need to use some mathematical notation, which I will introduce as needed throughout the article. Let’s start with our first fundamental pieces of notation:"
},
{
"code": null,
"e": 4703,
"s": 4520,
"text": "The letter π will symbolize a policy. Let’s call πθ(a|s) the probability of taking action a in state s. θ represents the parameters of our policy (the weights of our neural network)."
},
{
"code": null,
"e": 4970,
"s": 4703,
"text": "Our goal is to update θ to values that make πθ the optimal policy. Because θ will change, we will use the notation θt to denote θ at iteration t. We want to find out the update rule that takes use from θt to θt+1 in a way that we eventually reach the optimal policy."
},
{
"code": null,
"e": 5146,
"s": 4970,
"text": "Typically, for a discrete action space, πθ would be a neural network with a softmax output unit, so that the output can be thought of as the probability of taking each action."
},
{
"code": null,
"e": 5241,
"s": 5146,
"text": "Clearly, if action a∗ is the optimal action, we want πθ(a∗|s) to be as close to 1 as possible."
},
{
"code": null,
"e": 5356,
"s": 5241,
"text": "For this we can simply perform gradient ascent on πθ(a∗|s), so at each iteration we update θ in the following way:"
},
{
"code": null,
"e": 5618,
"s": 5356,
"text": "We can view the gradient ∇πθt(a∗|s) as being “the direction in which to move θt so as to increase the value of πθt(a∗|s) the fastest”. Note that we are indeed using gradient ascent since we want to increase a value, not decrease it as is usual in deep learning."
},
{
"code": null,
"e": 5748,
"s": 5618,
"text": "Thus one way to view this update is that we keep “pushing” towards more of action a* in our policy, which is indeed what we want."
},
{
"code": null,
"e": 6047,
"s": 5748,
"text": "In the example below, we know that the first action is the best action, so we run gradient ascent on it. For this running example we will assume a single state s so that the evolution of the policy is easier to plot. We will generalize to multiple states later in this series when we introduce A2C."
},
{
"code": null,
"e": 6442,
"s": 6047,
"text": "The gif above shows the result of our algorithm. The height of each bar is the probability of taking each action as our algorithm runs, and the arrow shows the gradient that we are following each iteration. In this case, we are only applying the gradient on the first action, which happens to have the largest value (10), which is why it is the only one that increases at the expense of others."
},
{
"code": null,
"e": 6573,
"s": 6442,
"text": "Of course, in practice, we won’t know which action is best... After all that’s what we’re trying to figure out in the first place!"
},
{
"code": null,
"e": 6731,
"s": 6573,
"text": "To get back to the metaphor of “pushing”, if we don’t know which action is optimal, we might “push” on suboptimal actions and our policy will never converge."
},
{
"code": null,
"e": 7078,
"s": 6731,
"text": "One solution would be to “push” on actions in a way that is proportional to our guess of the value of these actions. These guesses can be highly approximate, but as long as they are somewhat grounded in reality, more overall pushing will happen on the optimal action a∗. This way it is guaranteed that eventually our policy will converge to a∗=1!"
},
{
"code": null,
"e": 7404,
"s": 7078,
"text": "We will call our guess of the value of action a in state s Q̂ (s,a). Indeed, this is very similar to the Q function that we know from Q-Learning, though there is a subtle and important difference that will make it easier to learn and that we will learn about later. For now, let’s just assume that this Q function is a given."
},
{
"code": null,
"e": 7533,
"s": 7404,
"text": "We get the following gradient ascent update, that we can now apply to each action in turn instead of just to the optimal action:"
},
{
"code": null,
"e": 8014,
"s": 7533,
"text": "Let’s weigh our updates to the simulated policy gradient using a noisy version of the Q values of the different actions (10 for action a, 5 for action b, 2.5 for action c), and this time, we will randomly update each of the different possible actions, since we assume that we don’t know which one is best. As we see, the first action does still end up winning, even though our estimates of the values (as shown by the lengths of the arrows) varies significantly across iterations."
},
{
"code": null,
"e": 8318,
"s": 8014,
"text": "Of course, in practice, our agent is not going to choose actions uniformly at random, which is what we implicitly assumed so far. Rather, we are going to follow the very policy πθ that we are trying to train! This is called training on-policy. There are two reasons why we might want to train on-policy:"
},
{
"code": null,
"e": 8415,
"s": 8318,
"text": "We accumulate more rewards even as we train, which is something we might value in some contexts."
},
{
"code": null,
"e": 8575,
"s": 8415,
"text": "It allows us to explore more promising areas of the state space by not exploring purely randomly but rather closer to our current guess of the optimal actions."
},
{
"code": null,
"e": 8971,
"s": 8575,
"text": "This creates a problem with our current training algorithm, however: although we are going to “push” stronger on the actions that have a better value, we are also going to “push” more often on whichever actions happen to have higher values of πθ to begin with (which could happen due to chance or bad initialization)! These actions might end up winning the race to the top in spite of being bad."
},
{
"code": null,
"e": 9108,
"s": 8971,
"text": "Let’s illustrate this phenomenon by using the same update rule but sampling actions according to their probability instead of uniformly:"
},
{
"code": null,
"e": 9263,
"s": 9108,
"text": "Here we can see that the third action, in spite of having a lower value than the other two, ends up winning because it starts out initialized much higher."
},
{
"code": null,
"e": 9597,
"s": 9263,
"text": "This means that we need to compensate for the fact that more probable actions are going to be taken more often. How do we do this? Simple: we divide our update by the probability of the action. This way, if an action is 4x more likely to be taken than another, we will have 4x more gradient updates to it but each will be 4x smaller."
},
{
"code": null,
"e": 9638,
"s": 9597,
"text": "This gives us the following update rule:"
},
{
"code": null,
"e": 9652,
"s": 9638,
"text": "Let’s try it:"
},
{
"code": null,
"e": 9863,
"s": 9652,
"text": "We now see that even though action 3 starts out with a significant advantage, action 1 eventually wins out because its updates are much larger when its probability is small. Exactly the behavior that we wanted!"
},
{
"code": null,
"e": 10097,
"s": 9863,
"text": "And we are now done explaining the intuition behind policy gradient! All the rest of this post is simply filling out some details. This is a significant accomplishment and you should feel proud of yourself for understanding this far!"
},
{
"code": null,
"e": 10202,
"s": 10097,
"text": "“But, wait a minute”, you say, “I thought you would tell us how to understand the mysterious update rule"
},
{
"code": null,
"e": 10251,
"s": 10202,
"text": "but our update rule looks completely different!”"
},
{
"code": null,
"e": 10383,
"s": 10251,
"text": "Ah yes, indeed our update rule looks different, but it is in fact essentially the same! As a reminder, the key point in our rule is"
},
{
"code": null,
"e": 10432,
"s": 10383,
"text": "while the rule we are trying to explain contains"
},
{
"code": null,
"e": 10600,
"s": 10432,
"text": "The next section will explain the difference between  and Q̂, but suffice it to say for now that both work perfectly fine, but that using  is just an optimization."
},
{
"code": null,
"e": 10646,
"s": 10600,
"text": "The only difference remaining is thus between"
},
{
"code": null,
"e": 10650,
"s": 10646,
"text": "and"
},
{
"code": null,
"e": 10833,
"s": 10650,
"text": "In fact, these two expressions are equivalent! This is due to the chain rule and the fact that the derivative of log x is 1/x, as you might know from calculus. So we have in general:"
},
{
"code": null,
"e": 11066,
"s": 10833,
"text": "So now you know the origin of the mysterious log function in the policy gradient update! So why do people use the form using the log function instead of the more intuitive one which divides by π(s|a)? I can see two reasons for this:"
},
{
"code": null,
"e": 11540,
"s": 11066,
"text": "It obfuscates the intuition behind policy gradient, thus making you seem more impressive for understanding it.It makes it possible to express the update as a loss function when doing gradient descent, as in the equation L=−Â (s,a)logπθ(s|a) we saw at the beginning (bringing Â(s,a)inside the loss function is fine since it is a constant with respect to θ). This way you can use your favorite deep learning library to train your policy (which we will see how to do soon!)."
},
{
"code": null,
"e": 11651,
"s": 11540,
"text": "It obfuscates the intuition behind policy gradient, thus making you seem more impressive for understanding it."
},
{
"code": null,
"e": 12015,
"s": 11651,
"text": "It makes it possible to express the update as a loss function when doing gradient descent, as in the equation L=−Â (s,a)logπθ(s|a) we saw at the beginning (bringing Â(s,a)inside the loss function is fine since it is a constant with respect to θ). This way you can use your favorite deep learning library to train your policy (which we will see how to do soon!)."
},
{
"code": null,
"e": 12423,
"s": 12015,
"text": "At this point you now understand the basic form of the REINFORCE algorithm, which, as I am sure you expect, stands for “REward Increment = Nonnegative Factor × Offset Reinforcement × Characteristic Eligibility”... (yes I am serious, see the original paper). REINFORCE is the fundamental policy gradient algorithm on which nearly all the advanced policy gradient algorithms you might have heard of are based."
},
{
"code": null,
"e": 12713,
"s": 12423,
"text": "Now the final thing left to explain, as promised, is the difference between Q̂ and Â. You should already be familiar with Q from Q-Learning: Q(s,a) is the value (cumulative discounted reward, to be exact) obtained by taking action a in state s, and then following our policy π thereafter."
},
{
"code": null,
"e": 13125,
"s": 12713,
"text": "Note that it may be the case that following any action will give us a cumulative reward of, say, at least 100, but that some actions will be better than others, so that Q might be equal to, say, 101 for action a, 102 for action b and 100 for action c. As you can guess, this means that almost all of the weight of our update will tell us nothing about whether the current action is better, which is problematic."
},
{
"code": null,
"e": 13372,
"s": 13125,
"text": "You may also be familiar with the V(s) function, which simply gives us the value of following the policy starting in state s and all the way after that. In the example above, V(s) will be larger than 100 since all the Q(s, a) are larger than 100."
},
{
"code": null,
"e": 13696,
"s": 13372,
"text": "By subtracting V(s) from Q(s, a), we get the advantage function A(s, a). This function tells us how much better or worse taking action a in state is is compared to acting according to the policy. In the example above, it will subtract the extra 100 from the Q values of all the action, providing more signal to noise ratio."
},
{
"code": null,
"e": 13933,
"s": 13696,
"text": "In this tutorial I always wrote Q̂ or Â, with a “hat” on top of Q and A to emphasize that we are not using the “real” Q or A but rather an estimate of them. How to get those estimates will be the subject of the next post in the series."
},
{
"code": null,
"e": 14380,
"s": 13933,
"text": "As it turns out, REINFORCE will still work perfectly fine if we subtract any function from Q̂(s,a) as long as that function does not depend on the action. This makes sense based on our previous intuition of course, since the only thing that matters is that we “push” harder on the actions that have a higher Q value, and subtracting any value that doesn’t depend on the action will preserve the ranking of how hard we push on the various actions."
},
{
"code": null,
"e": 14743,
"s": 14380,
"text": "This means that using the  function instead of the Q̂ function is perfectly allowable. In fact, it is widely recommended for the reasons described above and also because it is supposed to reduce the variance of the gradient updates. Note that  is not known for sure to be the best function to use instead of Q̂, but in practice it generally works quite well."
},
{
"code": null,
"e": 14791,
"s": 14743,
"text": "Let’s see what using  does in our simulation:"
},
{
"code": null,
"e": 14799,
"s": 14791,
"text": "Output:"
},
{
"code": null,
"e": 14976,
"s": 14799,
"text": "Running using A functionDone in 48 iterationsVariance of A gradients: 31.384320255389287Running using Q functionDone in 30 iterationsVariance of Q gradients: 31.813126235495847"
},
{
"code": null,
"e": 15518,
"s": 14976,
"text": "Unfortunately, the impact is not dramatic here: the variance does end up slightly lower, but the time to converge is longer. That said, I am comparing the same learning rate between the two, and using the advantage function should let you use a higher learning rate without diverging. Further, this is a toy example and the benefits of using the advantage function has been widely attested in practice on larger problems. Sadly, this is the one instance in this tutorial in which you’ll have to take my word for it that something works well."
},
{
"code": null,
"e": 15814,
"s": 15518,
"text": "You now have a full intuitive understanding of basic policy gradients. However, you might be wondering how to use these in practice: how do you represent a policy with a neural network? How do you get your  estimate in the first place? What other tricks are used in practice to make this work?"
}
]
|
Plotting Histogram in Python using Matplotlib - GeeksforGeeks | 29 Jul, 2021
A histogram is basically used to represent data provided in a form of some groups.It is accurate method for the graphical representation of numerical data distribution.It is a type of bar plot where X-axis represents the bin ranges while Y-axis gives information about frequency.
To create a histogram the first step is to create bin of the ranges, then distribute the whole range of the values into a series of intervals, and count the values which fall into each of the intervals.Bins are clearly identified as consecutive, non-overlapping intervals of variables.The matplotlib.pyplot.hist() function is used to compute and create histogram of x.
The following table shows the parameters accepted by matplotlib.pyplot.hist() function :
Let’s create a basic histogram of some random values. Below code creates a simple histogram of some random values:
Python3
from matplotlib import pyplot as pltimport numpy as np # Creating dataseta = np.array([22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27]) # Creating histogramfig, ax = plt.subplots(figsize =(10, 7))ax.hist(a, bins = [0, 25, 50, 75, 100]) # Show plotplt.show()
Output :
Matplotlib provides a range of different methods to customize histogram. matplotlib.pyplot.hist() function itself provides many attributes with the help of which we can modify a histogram.The hist() function provide a patches object which gives access to the properties of the created objects, using this we can modify the plot according to our will.
Example 1:
Python3
import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatter # Creating datasetnp.random.seed(23685752)N_points = 10000n_bins = 20 # Creating distributionx = np.random.randn(N_points)y = .8 ** x + np.random.randn(10000) + 25 # Creating histogramfig, axs = plt.subplots(1, 1, figsize =(10, 7), tight_layout = True) axs.hist(x, bins = n_bins) # Show plotplt.show()
Output :
Example 2: The code below modifies the above histogram for a better view and accurate readings.
Python3
import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatter # Creating datasetnp.random.seed(23685752)N_points = 10000n_bins = 20 # Creating distributionx = np.random.randn(N_points)y = .8 ** x + np.random.randn(10000) + 25legend = ['distribution'] # Creating histogramfig, axs = plt.subplots(1, 1, figsize =(10, 7), tight_layout = True) # Remove axes splinesfor s in ['top', 'bottom', 'left', 'right']: axs.spines[s].set_visible(False) # Remove x, y ticksaxs.xaxis.set_ticks_position('none')axs.yaxis.set_ticks_position('none') # Add padding between axes and labelsaxs.xaxis.set_tick_params(pad = 5)axs.yaxis.set_tick_params(pad = 10) # Add x, y gridlinesaxs.grid(b = True, color ='grey', linestyle ='-.', linewidth = 0.5, alpha = 0.6) # Add Text watermarkfig.text(0.9, 0.15, 'Jeeteshgavande30', fontsize = 12, color ='red', ha ='right', va ='bottom', alpha = 0.7) # Creating histogramN, bins, patches = axs.hist(x, bins = n_bins) # Setting colorfracs = ((N**(1 / 5)) / N.max())norm = colors.Normalize(fracs.min(), fracs.max()) for thisfrac, thispatch in zip(fracs, patches): color = plt.cm.viridis(norm(thisfrac)) thispatch.set_facecolor(color) # Adding extra features plt.xlabel("X-axis")plt.ylabel("y-axis")plt.legend(legend)plt.title('Customized histogram') # Show plotplt.show()
Output :
simmytarika5
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python | [
{
"code": null,
"e": 30326,
"s": 30298,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 30606,
"s": 30326,
"text": "A histogram is basically used to represent data provided in a form of some groups.It is accurate method for the graphical representation of numerical data distribution.It is a type of bar plot where X-axis represents the bin ranges while Y-axis gives information about frequency."
},
{
"code": null,
"e": 30976,
"s": 30606,
"text": "To create a histogram the first step is to create bin of the ranges, then distribute the whole range of the values into a series of intervals, and count the values which fall into each of the intervals.Bins are clearly identified as consecutive, non-overlapping intervals of variables.The matplotlib.pyplot.hist() function is used to compute and create histogram of x. "
},
{
"code": null,
"e": 31066,
"s": 30976,
"text": "The following table shows the parameters accepted by matplotlib.pyplot.hist() function : "
},
{
"code": null,
"e": 31183,
"s": 31066,
"text": "Let’s create a basic histogram of some random values. Below code creates a simple histogram of some random values: "
},
{
"code": null,
"e": 31191,
"s": 31183,
"text": "Python3"
},
{
"code": "from matplotlib import pyplot as pltimport numpy as np # Creating dataseta = np.array([22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27]) # Creating histogramfig, ax = plt.subplots(figsize =(10, 7))ax.hist(a, bins = [0, 25, 50, 75, 100]) # Show plotplt.show()",
"e": 31499,
"s": 31191,
"text": null
},
{
"code": null,
"e": 31509,
"s": 31499,
"text": "Output : "
},
{
"code": null,
"e": 31860,
"s": 31509,
"text": "Matplotlib provides a range of different methods to customize histogram. matplotlib.pyplot.hist() function itself provides many attributes with the help of which we can modify a histogram.The hist() function provide a patches object which gives access to the properties of the created objects, using this we can modify the plot according to our will."
},
{
"code": null,
"e": 31873,
"s": 31860,
"text": "Example 1: "
},
{
"code": null,
"e": 31881,
"s": 31873,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatter # Creating datasetnp.random.seed(23685752)N_points = 10000n_bins = 20 # Creating distributionx = np.random.randn(N_points)y = .8 ** x + np.random.randn(10000) + 25 # Creating histogramfig, axs = plt.subplots(1, 1, figsize =(10, 7), tight_layout = True) axs.hist(x, bins = n_bins) # Show plotplt.show()",
"e": 32354,
"s": 31881,
"text": null
},
{
"code": null,
"e": 32364,
"s": 32354,
"text": "Output : "
},
{
"code": null,
"e": 32461,
"s": 32364,
"text": "Example 2: The code below modifies the above histogram for a better view and accurate readings. "
},
{
"code": null,
"e": 32469,
"s": 32461,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatter # Creating datasetnp.random.seed(23685752)N_points = 10000n_bins = 20 # Creating distributionx = np.random.randn(N_points)y = .8 ** x + np.random.randn(10000) + 25legend = ['distribution'] # Creating histogramfig, axs = plt.subplots(1, 1, figsize =(10, 7), tight_layout = True) # Remove axes splinesfor s in ['top', 'bottom', 'left', 'right']: axs.spines[s].set_visible(False) # Remove x, y ticksaxs.xaxis.set_ticks_position('none')axs.yaxis.set_ticks_position('none') # Add padding between axes and labelsaxs.xaxis.set_tick_params(pad = 5)axs.yaxis.set_tick_params(pad = 10) # Add x, y gridlinesaxs.grid(b = True, color ='grey', linestyle ='-.', linewidth = 0.5, alpha = 0.6) # Add Text watermarkfig.text(0.9, 0.15, 'Jeeteshgavande30', fontsize = 12, color ='red', ha ='right', va ='bottom', alpha = 0.7) # Creating histogramN, bins, patches = axs.hist(x, bins = n_bins) # Setting colorfracs = ((N**(1 / 5)) / N.max())norm = colors.Normalize(fracs.min(), fracs.max()) for thisfrac, thispatch in zip(fracs, patches): color = plt.cm.viridis(norm(thisfrac)) thispatch.set_facecolor(color) # Adding extra features plt.xlabel(\"X-axis\")plt.ylabel(\"y-axis\")plt.legend(legend)plt.title('Customized histogram') # Show plotplt.show()",
"e": 33934,
"s": 32469,
"text": null
},
{
"code": null,
"e": 33944,
"s": 33934,
"text": "Output : "
},
{
"code": null,
"e": 33959,
"s": 33946,
"text": "simmytarika5"
},
{
"code": null,
"e": 33983,
"s": 33959,
"text": "Matplotlib Pyplot-class"
},
{
"code": null,
"e": 34001,
"s": 33983,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 34008,
"s": 34001,
"text": "Python"
},
{
"code": null,
"e": 34106,
"s": 34008,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34134,
"s": 34106,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 34184,
"s": 34134,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 34206,
"s": 34184,
"text": "Python map() function"
},
{
"code": null,
"e": 34250,
"s": 34206,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 34268,
"s": 34250,
"text": "Python Dictionary"
},
{
"code": null,
"e": 34291,
"s": 34268,
"text": "Taking input in Python"
},
{
"code": null,
"e": 34326,
"s": 34291,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 34348,
"s": 34326,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 34380,
"s": 34348,
"text": "How to Install PIP on Windows ?"
}
]
|
ASP.NET MVC - Model Binding | ASP.NET MVC model binding allows you to map HTTP request data with a model. It is the process of creating .NET objects using the data sent by the browser in an HTTP request. The ASP.NET Web Forms developers who are new to ASP.Net MVC are mostly confused how the values from View get converted to the Model class when it reaches the Action method of the Controller class, so this conversion is done by the Model binder.
Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene.
Let’s take a look at a simple example in which we add a ‘Create View’ in our project from the last chapter and we will see how we get these values from the View to the EmployeeController action method.
Following is the Create Action method for POST.
// POST: Employee/Create
[HttpPost]
public ActionResult Create(FormCollection collection){
try{
// TODO: Add insert logic here
return RedirectToAction("Index");
}catch{
return View();
}
}
Right-click on the Create Action method and select Add View...
It will display the Add View dialog.
As you can see in the above screenshot, the default name is already mentioned. Now select Create from the Template dropdown and Employee from the Model class dropdown.
You will see the default code in the Create.cshtml view.
@model MVCSimpleApp.Models.Employee
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>Create</title>
</head>
<body>
@using (Html.BeginForm()){
@Html.AntiForgeryToken()
<div class = "form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<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 = "Create" class = "btn btn-default"/>
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
When the user enters values on Create View then it is available in FormCollection as well as Request.Form. We can use any of these values to populate the employee info from the view.
Let’s use the following code to create the Employee using FormCollection.
// POST: Employee/Create
[HttpPost]
public ActionResult Create(FormCollection collection){
try {
Employee emp = new Employee();
emp.Name = collection["Name"];
DateTime jDate;
DateTime.TryParse(collection["DOB"], out jDate);
emp.JoiningDate = jDate;
string age = collection["Age"];
emp.Age = Int32.Parse(age);
empList.Add(emp);
return RedirectToAction("Index");
}catch {
return View();
}
}
Run this application and request for this URL http://localhost:63004/Employee/. You will receive the following output.
Click the ‘Create New’ link on top of the page and it will go to the following view.
Let’s enter data for another employee you want to add.
Click on the create button and you will see that the new employee is added in your list.
In the above example, we are getting all the posted values from the HTML view and then mapping these values to the Employee properties and assigning them one by one.
In this case, we will also be doing the type casting wherever the posted values are not of the same format as of the Model property.
This is also known as manual binding and this type of implementation might not be that bad for simple and small data model. However, if you have huge data models and need a lot of type casting then we can utilize the power and ease-of-use of ASP.NET MVC Model binding.
Let’s take a look at the same example we did for Model binding.
We need to change the parameter of Create Method to accept the Employee Model object rather than FormCollection as shown in the following code.
// POST: Employee/Create
[HttpPost]
public ActionResult Create(Employee emp){
try{
empList.Add(emp);
return RedirectToAction("Index");
}catch{
return View();
}
}
Now the magic of Model Binding depends on the id of HTML variables that are supplying the values.
For our Employee Model, the id of the HTML input fields should be the same as the Property names of the Employee Model and you can see that Visual Studio is using the same property names of the model while creating a view.
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
The mapping will be based on the Property name by default. This is where we will find HTML helper methods very helpful because these helper methods will generate the HTML, which will have proper Names for the Model Binding to work.
Run this application and request for the URL http://localhost:63004/Employee/. You will see the following output.
Let’s click on the Create New link on the top of the page and it will go to the following view.
Let’s enter data for another employee that we want to add.
Now click the create button and you will see that the new employee is added to your list using the ASP.Net MVC model binding.
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": 2688,
"s": 2269,
"text": "ASP.NET MVC model binding allows you to map HTTP request data with a model. It is the process of creating .NET objects using the data sent by the browser in an HTTP request. The ASP.NET Web Forms developers who are new to ASP.Net MVC are mostly confused how the values from View get converted to the Model class when it reaches the Action method of the Controller class, so this conversion is done by the Model binder."
},
{
"code": null,
"e": 2997,
"s": 2688,
"text": "Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene."
},
{
"code": null,
"e": 3199,
"s": 2997,
"text": "Let’s take a look at a simple example in which we add a ‘Create View’ in our project from the last chapter and we will see how we get these values from the View to the EmployeeController action method."
},
{
"code": null,
"e": 3247,
"s": 3199,
"text": "Following is the Create Action method for POST."
},
{
"code": null,
"e": 3462,
"s": 3247,
"text": "// POST: Employee/Create\n[HttpPost]\npublic ActionResult Create(FormCollection collection){\n try{\n // TODO: Add insert logic here\n return RedirectToAction(\"Index\");\n }catch{\n return View();\n }\n}"
},
{
"code": null,
"e": 3525,
"s": 3462,
"text": "Right-click on the Create Action method and select Add View..."
},
{
"code": null,
"e": 3562,
"s": 3525,
"text": "It will display the Add View dialog."
},
{
"code": null,
"e": 3730,
"s": 3562,
"text": "As you can see in the above screenshot, the default name is already mentioned. Now select Create from the Template dropdown and Employee from the Model class dropdown."
},
{
"code": null,
"e": 3787,
"s": 3730,
"text": "You will see the default code in the Create.cshtml view."
},
{
"code": null,
"e": 6159,
"s": 3787,
"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>Create</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(true, \"\", new { @class = \"text-danger\" })\n\t\t\t\t\n <div class = \"form-group\">\n @Html.LabelFor(model => model.Name, htmlAttributes:\n new{ @class = \"control-label col-md-2\" })\n\t\t\t\t\t\t\n <div class = \"col-md-10\">\n @Html.EditorFor(model => model.Name, new{ htmlAttributes =\n new { @class = \"form-control\" } })\n\t\t\t\t\t\t\t\n @Html.ValidationMessageFor(model => model.Name, \"\",\n new{ @class = \"text-danger\" })\n </div>\n </div>\n\t\t\t\t\n <div class = \"form-group\">\n @Html.LabelFor(model => model.JoiningDate, htmlAttributes:\n new{ @class = \"control-label col-md-2\" })\n\t\t\t\t\t\t\n <div class = \"col-md-10\">\n @Html.EditorFor(model => model.JoiningDate, new{ htmlAttributes =\n new { @class = \"form-control\" } })\n\t\t\t\t\t\t\t\n @Html.ValidationMessageFor(model => model.JoiningDate, \"\",\n new { @class = \"text-danger\" })\n </div>\n </div>\n\t\t\t\t\n <div class = \"form-group\">\n @Html.LabelFor(model => model.Age, htmlAttributes:\n new { @class = \"control-label col-md-2\" })\n\t\t\t\t\t\t\n <div class = \"col-md-10\">\n @Html.EditorFor(model => model.Age, new { htmlAttributes =\n new { @class = \"form-control\" } })\n\t\t\t\t\t\t\t\n @Html.ValidationMessageFor(model => model.Age, \"\", new{ @class = \"text-danger\" })\n </div>\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 = \"Create\" 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": 6342,
"s": 6159,
"text": "When the user enters values on Create View then it is available in FormCollection as well as Request.Form. We can use any of these values to populate the employee info from the view."
},
{
"code": null,
"e": 6416,
"s": 6342,
"text": "Let’s use the following code to create the Employee using FormCollection."
},
{
"code": null,
"e": 6874,
"s": 6416,
"text": "// POST: Employee/Create\n[HttpPost]\npublic ActionResult Create(FormCollection collection){\n try {\n Employee emp = new Employee();\n emp.Name = collection[\"Name\"];\n DateTime jDate;\n DateTime.TryParse(collection[\"DOB\"], out jDate);\n emp.JoiningDate = jDate;\n string age = collection[\"Age\"];\n emp.Age = Int32.Parse(age);\n empList.Add(emp);\n return RedirectToAction(\"Index\");\n }catch {\n return View();\n }\n}"
},
{
"code": null,
"e": 6993,
"s": 6874,
"text": "Run this application and request for this URL http://localhost:63004/Employee/. You will receive the following output."
},
{
"code": null,
"e": 7078,
"s": 6993,
"text": "Click the ‘Create New’ link on top of the page and it will go to the following view."
},
{
"code": null,
"e": 7133,
"s": 7078,
"text": "Let’s enter data for another employee you want to add."
},
{
"code": null,
"e": 7222,
"s": 7133,
"text": "Click on the create button and you will see that the new employee is added in your list."
},
{
"code": null,
"e": 7388,
"s": 7222,
"text": "In the above example, we are getting all the posted values from the HTML view and then mapping these values to the Employee properties and assigning them one by one."
},
{
"code": null,
"e": 7521,
"s": 7388,
"text": "In this case, we will also be doing the type casting wherever the posted values are not of the same format as of the Model property."
},
{
"code": null,
"e": 7790,
"s": 7521,
"text": "This is also known as manual binding and this type of implementation might not be that bad for simple and small data model. However, if you have huge data models and need a lot of type casting then we can utilize the power and ease-of-use of ASP.NET MVC Model binding."
},
{
"code": null,
"e": 7854,
"s": 7790,
"text": "Let’s take a look at the same example we did for Model binding."
},
{
"code": null,
"e": 7998,
"s": 7854,
"text": "We need to change the parameter of Create Method to accept the Employee Model object rather than FormCollection as shown in the following code."
},
{
"code": null,
"e": 8187,
"s": 7998,
"text": "// POST: Employee/Create\n[HttpPost]\npublic ActionResult Create(Employee emp){\n try{\n empList.Add(emp);\n return RedirectToAction(\"Index\");\n }catch{\n return View();\n }\n}"
},
{
"code": null,
"e": 8285,
"s": 8187,
"text": "Now the magic of Model Binding depends on the id of HTML variables that are supplying the values."
},
{
"code": null,
"e": 8508,
"s": 8285,
"text": "For our Employee Model, the id of the HTML input fields should be the same as the Property names of the Employee Model and you can see that Visual Studio is using the same property names of the model while creating a view."
},
{
"code": null,
"e": 8604,
"s": 8508,
"text": "@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = \"form-control\" } })\n"
},
{
"code": null,
"e": 8836,
"s": 8604,
"text": "The mapping will be based on the Property name by default. This is where we will find HTML helper methods very helpful because these helper methods will generate the HTML, which will have proper Names for the Model Binding to work."
},
{
"code": null,
"e": 8950,
"s": 8836,
"text": "Run this application and request for the URL http://localhost:63004/Employee/. You will see the following output."
},
{
"code": null,
"e": 9046,
"s": 8950,
"text": "Let’s click on the Create New link on the top of the page and it will go to the following view."
},
{
"code": null,
"e": 9105,
"s": 9046,
"text": "Let’s enter data for another employee that we want to add."
},
{
"code": null,
"e": 9231,
"s": 9105,
"text": "Now click the create button and you will see that the new employee is added to your list using the ASP.Net MVC model binding."
},
{
"code": null,
"e": 9266,
"s": 9231,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9280,
"s": 9266,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9315,
"s": 9280,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9338,
"s": 9315,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 9372,
"s": 9338,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 9392,
"s": 9372,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 9427,
"s": 9392,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9444,
"s": 9427,
"text": " University Code"
},
{
"code": null,
"e": 9479,
"s": 9444,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9496,
"s": 9479,
"text": " University Code"
},
{
"code": null,
"e": 9530,
"s": 9496,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 9545,
"s": 9530,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 9552,
"s": 9545,
"text": " Print"
},
{
"code": null,
"e": 9563,
"s": 9552,
"text": " Add Notes"
}
]
|
C++ Array Library - data() Function | The C++ function std::array::data() return a pointer pointing to the first element of the array container. As array stores all elements in contigious memory location we can use this poiter to perform all valid operations on array.
Following is the declaration for std::array::data() function form std::array header.
value_type *data() noexcept;
const value_type *data() const noexcept;
None
Returns a pointer to the first element of the array. If array object is const-qualified this method returns const object otherwise it returns non-const object.
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::array::data() function.
#include <iostream>
#include <array>
using namespace std;
int main(void) {
array<char, 128> s = {"C++ standard library from tutorialspoint.com"};
char *p, *q;
/* pointer to the first element of character array. */
p = s.data();
/* print string contents */
cout << p << endl;
q = p;
/* print string using pointer arithmatic */
while (*q) {
cout << *q;
++q;
}
cout << endl;
return 0;
}
Let us compile and run the above program, this will produce the following result −
C++ standard library from tutorialspoint.com
C++ standard library from tutorialspoint.com
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2834,
"s": 2603,
"text": "The C++ function std::array::data() return a pointer pointing to the first element of the array container. As array stores all elements in contigious memory location we can use this poiter to perform all valid operations on array."
},
{
"code": null,
"e": 2919,
"s": 2834,
"text": "Following is the declaration for std::array::data() function form std::array header."
},
{
"code": null,
"e": 2989,
"s": 2919,
"text": "value_type *data() noexcept;\nconst value_type *data() const noexcept;"
},
{
"code": null,
"e": 2994,
"s": 2989,
"text": "None"
},
{
"code": null,
"e": 3154,
"s": 2994,
"text": "Returns a pointer to the first element of the array. If array object is const-qualified this method returns const object otherwise it returns non-const object."
},
{
"code": null,
"e": 3199,
"s": 3154,
"text": "This member function never throws exception."
},
{
"code": null,
"e": 3218,
"s": 3199,
"text": "Constant i.e. O(1)"
},
{
"code": null,
"e": 3288,
"s": 3218,
"text": "The following example shows the usage of std::array::data() function."
},
{
"code": null,
"e": 3729,
"s": 3288,
"text": "#include <iostream>\n#include <array>\n\nusing namespace std;\n\nint main(void) {\n\n array<char, 128> s = {\"C++ standard library from tutorialspoint.com\"};\n char *p, *q;\n\n /* pointer to the first element of character array. */\n p = s.data();\n\n /* print string contents */\n cout << p << endl;\n\n q = p;\n\n /* print string using pointer arithmatic */\n while (*q) {\n cout << *q;\n ++q;\n }\n\n cout << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 3812,
"s": 3729,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3903,
"s": 3812,
"text": "C++ standard library from tutorialspoint.com\nC++ standard library from tutorialspoint.com\n"
},
{
"code": null,
"e": 3910,
"s": 3903,
"text": " Print"
},
{
"code": null,
"e": 3921,
"s": 3910,
"text": " Add Notes"
}
]
|
LeafletJS - Controls | Leaflet provides various controls such as zoom, attribution, scale, etc., where −
Zoom − By default, this control exists at the top left corner of the map. It has two buttons "+" and "–", using which you can zoom-in or zoom-out the map. You can remove the default zoom control by setting the zoomControl option of the map options to false.
Zoom − By default, this control exists at the top left corner of the map. It has two buttons "+" and "–", using which you can zoom-in or zoom-out the map. You can remove the default zoom control by setting the zoomControl option of the map options to false.
Attribution − By default, this control exists at the bottom right corner of the map. It displays the attribution data in a small textbox. By default, it displays the text. You can remove the default attribution control by setting the attributionControl option of the map options to false.
Attribution − By default, this control exists at the bottom right corner of the map. It displays the attribution data in a small textbox. By default, it displays the text. You can remove the default attribution control by setting the attributionControl option of the map options to false.
Scale − By default, this control exists at the bottom left corner of the map. It displays the current center of the screen.
Scale − By default, this control exists at the bottom left corner of the map. It displays the current center of the screen.
In this chapter, we will explain how you can create and add all these three controls to your map using Leaflet JavaScript library.
To add a zoom control of your own to the map using Leaflet JavaScript library, follow the steps given below −
Step 1 − Create a Map object by passing a element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Create the zoomOptions variable and define your own text values for the zoom-in and zoom-out options, instead of the default ones (+ and -).
Then, create the zoom control by passing the zoomOptions variable to L.control.zoom() as shown below.
// zoom control options
var zoomOptions = {
zoomInText: '1',
zoomOutText: '0',
};
// Creating zoom control
var zoom = L.control.zoom(zoomOptions);
Step 5 − Add the zoom control object created in the previous step to the map using the addTo() method.
// Adding zoom control to the map
zoom.addTo(map);
Following is the code to add your own zoom control to your map, instead of the default one. Here, on pressing 1, the map zooms in, and on pressing 0, the map zooms out.
<!DOCTYPE html>
<html>
<head>
<title>Zoom Example</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width:900px; height:580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [17.385044, 78.486671],
zoom: 10,
zoomControl: false
}
var map = new L.map('map', mapOptions); // Creating a map object
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
map.addLayer(layer); // Adding layer to the map
// zoom control options
var zoomOptions = {
zoomInText: '1',
zoomOutText: '0',
};
var zoom = L.control.zoom(zoomOptions); // Creating zoom control
zoom.addTo(map); // Adding zoom control to the map
</script>
</body>
</html>
It generates the following output −
To add an attribution of your own to the map using Leaflet JavaScript library, follow the steps given below −
Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Create the attrOptions variable and define your own prefix value instead of the default one (leaflet).
Then, create the attribution control by passing the attrOptions variable to L.control.attribution() as shown below.
// Attribution options
var attrOptions = {
prefix: 'attribution sample'
};
// Creating an attribution
var attr = L.control.attribution(attrOptions);
Step 5 − Add the attribution control object created in the previous step to the map using the addTo() method.
// Adding attribution to the map
attr.addTo(map);
The following code adds our own attribution control to your map, instead of the default one. Here, instead the text attribution sample will be displayed.
<!DOCTYPE html>
<html>
<head>
<title>Attribution Example</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width: 900px; height: 580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [17.385044, 78.486671],
zoom: 10,
attributionControl: false
}
var map = new L.map('map', mapOptions); // Creating a map object
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
map.addLayer(layer); // Adding layer to the map
// Attribution options
var attrOptions = {
prefix: 'attribution sample'
};
// Creating an attribution
var attr = L.control.attribution(attrOptions);
attr.addTo(map); // Adding attribution to the map
</script>
</body>
</html>>
It generates the following output −
To add a scale control of your own to the map using Leaflet JavaScript library, follow the steps given below −
Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Create scale control by passing the using L.control.scale() as shown below.
// Creating scale control
var scale = L.control.scale();
Step 5 − Add the scale control object created in the previous step to the map using the addTo() method as shown below.
// Adding scale control to the map
scale.addTo(map);
The following code adds scale control to your map.
<!DOCTYPE html>
<html>
<head>
<title>Scale Example</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width:900px; height:580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [17.385044, 78.486671],
zoom: 10
}
// Creating a map object
var map = new L.map('map', mapOptions);
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
map.addLayer(layer); // Adding layer to the map
var scale = L.control.scale(); // Creating scale control
scale.addTo(map); // Adding scale control to the map
</script>
</body>
</html>
It generates the following output −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1880,
"s": 1798,
"text": "Leaflet provides various controls such as zoom, attribution, scale, etc., where −"
},
{
"code": null,
"e": 2138,
"s": 1880,
"text": "Zoom − By default, this control exists at the top left corner of the map. It has two buttons \"+\" and \"–\", using which you can zoom-in or zoom-out the map. You can remove the default zoom control by setting the zoomControl option of the map options to false."
},
{
"code": null,
"e": 2396,
"s": 2138,
"text": "Zoom − By default, this control exists at the top left corner of the map. It has two buttons \"+\" and \"–\", using which you can zoom-in or zoom-out the map. You can remove the default zoom control by setting the zoomControl option of the map options to false."
},
{
"code": null,
"e": 2685,
"s": 2396,
"text": "Attribution − By default, this control exists at the bottom right corner of the map. It displays the attribution data in a small textbox. By default, it displays the text. You can remove the default attribution control by setting the attributionControl option of the map options to false."
},
{
"code": null,
"e": 2974,
"s": 2685,
"text": "Attribution − By default, this control exists at the bottom right corner of the map. It displays the attribution data in a small textbox. By default, it displays the text. You can remove the default attribution control by setting the attributionControl option of the map options to false."
},
{
"code": null,
"e": 3098,
"s": 2974,
"text": "Scale − By default, this control exists at the bottom left corner of the map. It displays the current center of the screen."
},
{
"code": null,
"e": 3222,
"s": 3098,
"text": "Scale − By default, this control exists at the bottom left corner of the map. It displays the current center of the screen."
},
{
"code": null,
"e": 3353,
"s": 3222,
"text": "In this chapter, we will explain how you can create and add all these three controls to your map using Leaflet JavaScript library."
},
{
"code": null,
"e": 3463,
"s": 3353,
"text": "To add a zoom control of your own to the map using Leaflet JavaScript library, follow the steps given below −"
},
{
"code": null,
"e": 3560,
"s": 3463,
"text": "Step 1 − Create a Map object by passing a element (String or object) and map options (optional)."
},
{
"code": null,
"e": 3631,
"s": 3560,
"text": "Step 2 − Create a Layer object by passing the URL of the desired tile."
},
{
"code": null,
"e": 3718,
"s": 3631,
"text": "Step 3 − Add the layer object to the map using the addLayer() method of the Map class."
},
{
"code": null,
"e": 3868,
"s": 3718,
"text": "Step 4 − Create the zoomOptions variable and define your own text values for the zoom-in and zoom-out options, instead of the default ones (+ and -)."
},
{
"code": null,
"e": 3970,
"s": 3868,
"text": "Then, create the zoom control by passing the zoomOptions variable to L.control.zoom() as shown below."
},
{
"code": null,
"e": 4124,
"s": 3970,
"text": "// zoom control options\nvar zoomOptions = {\n zoomInText: '1',\n zoomOutText: '0',\n};\n// Creating zoom control\nvar zoom = L.control.zoom(zoomOptions);\n"
},
{
"code": null,
"e": 4227,
"s": 4124,
"text": "Step 5 − Add the zoom control object created in the previous step to the map using the addTo() method."
},
{
"code": null,
"e": 4279,
"s": 4227,
"text": "// Adding zoom control to the map\nzoom.addTo(map);\n"
},
{
"code": null,
"e": 4448,
"s": 4279,
"text": "Following is the code to add your own zoom control to your map, instead of the default one. Here, on pressing 1, the map zooms in, and on pressing 0, the map zooms out."
},
{
"code": null,
"e": 5554,
"s": 4448,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Zoom Example</title>\n <link rel = \"stylesheet\" href = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css\"/>\n <script src = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js\"></script>\n </head>\n \n <body>\n <div id = \"map\" style = \"width:900px; height:580px\"></div>\n <script>\n // Creating map options\n var mapOptions = {\n center: [17.385044, 78.486671],\n zoom: 10,\n zoomControl: false\n }\n var map = new L.map('map', mapOptions); // Creating a map object\n \n // Creating a Layer object\n var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');\n map.addLayer(layer); // Adding layer to the map\n \n // zoom control options\n var zoomOptions = {\n zoomInText: '1',\n zoomOutText: '0',\n };\n var zoom = L.control.zoom(zoomOptions); // Creating zoom control\n zoom.addTo(map); // Adding zoom control to the map\n </script>\n </body>\n \n</html>"
},
{
"code": null,
"e": 5590,
"s": 5554,
"text": "It generates the following output −"
},
{
"code": null,
"e": 5700,
"s": 5590,
"text": "To add an attribution of your own to the map using Leaflet JavaScript library, follow the steps given below −"
},
{
"code": null,
"e": 5803,
"s": 5700,
"text": "Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional)."
},
{
"code": null,
"e": 5874,
"s": 5803,
"text": "Step 2 − Create a Layer object by passing the URL of the desired tile."
},
{
"code": null,
"e": 5961,
"s": 5874,
"text": "Step 3 − Add the layer object to the map using the addLayer() method of the Map class."
},
{
"code": null,
"e": 6073,
"s": 5961,
"text": "Step 4 − Create the attrOptions variable and define your own prefix value instead of the default one (leaflet)."
},
{
"code": null,
"e": 6189,
"s": 6073,
"text": "Then, create the attribution control by passing the attrOptions variable to L.control.attribution() as shown below."
},
{
"code": null,
"e": 6343,
"s": 6189,
"text": "// Attribution options\nvar attrOptions = {\n prefix: 'attribution sample'\n};\n\n// Creating an attribution\nvar attr = L.control.attribution(attrOptions);\n"
},
{
"code": null,
"e": 6453,
"s": 6343,
"text": "Step 5 − Add the attribution control object created in the previous step to the map using the addTo() method."
},
{
"code": null,
"e": 6504,
"s": 6453,
"text": "// Adding attribution to the map\nattr.addTo(map);\n"
},
{
"code": null,
"e": 6658,
"s": 6504,
"text": "The following code adds our own attribution control to your map, instead of the default one. Here, instead the text attribution sample will be displayed."
},
{
"code": null,
"e": 7787,
"s": 6658,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Attribution Example</title>\n <link rel = \"stylesheet\" href = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css\"/>\n <script src = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js\"></script>\n </head>\n \n <body>\n <div id = \"map\" style = \"width: 900px; height: 580px\"></div>\n <script>\n // Creating map options\n var mapOptions = {\n center: [17.385044, 78.486671],\n zoom: 10,\n attributionControl: false\n }\n var map = new L.map('map', mapOptions); // Creating a map object\n \n // Creating a Layer object\n var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');\n map.addLayer(layer); // Adding layer to the map\n \n // Attribution options\n var attrOptions = {\n prefix: 'attribution sample'\n };\n \n // Creating an attribution\n var attr = L.control.attribution(attrOptions);\n attr.addTo(map); // Adding attribution to the map\n </script>\n </body>\n \n</html>>"
},
{
"code": null,
"e": 7823,
"s": 7787,
"text": "It generates the following output −"
},
{
"code": null,
"e": 7934,
"s": 7823,
"text": "To add a scale control of your own to the map using Leaflet JavaScript library, follow the steps given below −"
},
{
"code": null,
"e": 8037,
"s": 7934,
"text": "Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional)."
},
{
"code": null,
"e": 8108,
"s": 8037,
"text": "Step 2 − Create a Layer object by passing the URL of the desired tile."
},
{
"code": null,
"e": 8195,
"s": 8108,
"text": "Step 3 − Add the layer object to the map using the addLayer() method of the Map class."
},
{
"code": null,
"e": 8280,
"s": 8195,
"text": "Step 4 − Create scale control by passing the using L.control.scale() as shown below."
},
{
"code": null,
"e": 8338,
"s": 8280,
"text": "// Creating scale control\nvar scale = L.control.scale();\n"
},
{
"code": null,
"e": 8457,
"s": 8338,
"text": "Step 5 − Add the scale control object created in the previous step to the map using the addTo() method as shown below."
},
{
"code": null,
"e": 8511,
"s": 8457,
"text": "// Adding scale control to the map\nscale.addTo(map);\n"
},
{
"code": null,
"e": 8562,
"s": 8511,
"text": "The following code adds scale control to your map."
},
{
"code": null,
"e": 9492,
"s": 8562,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Scale Example</title>\n <link rel = \"stylesheet\" href = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css\" />\n <script src = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js\"></script>\n </head>\n \n <body>\n <div id = \"map\" style = \"width:900px; height:580px\"></div>\n <script>\n // Creating map options\n var mapOptions = {\n center: [17.385044, 78.486671],\n zoom: 10\n }\n // Creating a map object\n var map = new L.map('map', mapOptions);\n \n // Creating a Layer object\n var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');\n map.addLayer(layer); // Adding layer to the map\n var scale = L.control.scale(); // Creating scale control\n scale.addTo(map); // Adding scale control to the map\n </script>\n </body>\n \n</html>"
},
{
"code": null,
"e": 9528,
"s": 9492,
"text": "It generates the following output −"
},
{
"code": null,
"e": 9535,
"s": 9528,
"text": " Print"
},
{
"code": null,
"e": 9546,
"s": 9535,
"text": " Add Notes"
}
]
|
Level Order Tree Traversal in Data Structures | In this section we will see the level-order traversal technique for binary search tree.
Suppose we have one tree like this −
The traversal sequence will be like: 10, 5, 16, 8, 15, 20, 23
levelOrderTraverse(root):
Begin
define queue que to store nodes
insert root into the que.
while que is not empty, do
item := item present at front position of queue
print the value of item
if left of the item is not null, then
insert left of item into que
end if
if right of the item is not null, then
insert right of item into que
end if
delete front element from que
done
End
Live Demo
#include<iostream>
#include<queue>
using namespace std;
class node{
public:
int h_left, h_right, bf, value;
node *left, *right;
};
class tree{
private:
node *get_node(int key);
public:
node *root;
tree(){
root = NULL; //set root as NULL at the beginning
}
void levelorder_traversal(node *r);
node *insert_node(node *root, int key);
};
node *tree::get_node(int key){
node *new_node;
new_node = new node; //create a new node dynamically
new_node->h_left = 0; new_node->h_right = 0;
new_node->bf = 0;
new_node->value = key; //store the value from given key
new_node->left = NULL; new_node->right = NULL;
return new_node;
}
void tree::levelorder_traversal(node *root){
queue <node*> que;
node *item;
que.push(root); //insert the root at first
while(!que.empty()){
item = que.front(); //get the element from the front end
cout << item->value << " ";
if(item->left != NULL) //When left child is present, insert into queue
que.push(item->left);
if(item->right != NULL) //When right child is present, insert into queue
que.push(item->right);
que.pop(); //remove the item from queue
}
}
node *tree::insert_node(node *root, int key){
if(root == NULL){
return (get_node(key)); //when tree is empty, create a node as root
}
if(key < root->value){ //when key is smaller than root value, go to the left
root->left = insert_node(root->left, key);
} else if(key > root->value) { //when key is greater than root value, go to the right
root->right = insert_node(root->right, key);
}
return root; //when key is already present, do not insert it again
}
main(){
node *root;
tree my_tree;
//Insert some keys into the tree.
my_tree.root = my_tree.insert_node(my_tree.root, 10);
my_tree.root = my_tree.insert_node(my_tree.root, 5);
my_tree.root = my_tree.insert_node(my_tree.root, 16);
my_tree.root = my_tree.insert_node(my_tree.root, 20);
my_tree.root = my_tree.insert_node(my_tree.root, 15);
my_tree.root = my_tree.insert_node(my_tree.root, 8);
my_tree.root = my_tree.insert_node(my_tree.root, 23);
cout << "Level-Order Traversal: ";
my_tree.levelorder_traversal(my_tree.root);
}
Level-Order Traversal: 10 5 16 8 15 20 23 | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In this section we will see the level-order traversal technique for binary search tree."
},
{
"code": null,
"e": 1187,
"s": 1150,
"text": "Suppose we have one tree like this −"
},
{
"code": null,
"e": 1249,
"s": 1187,
"text": "The traversal sequence will be like: 10, 5, 16, 8, 15, 20, 23"
},
{
"code": null,
"e": 1699,
"s": 1249,
"text": "levelOrderTraverse(root):\nBegin\n define queue que to store nodes\n insert root into the que.\n while que is not empty, do\n item := item present at front position of queue\n print the value of item\n if left of the item is not null, then\n insert left of item into que\n end if\n if right of the item is not null, then\n insert right of item into que\n end if\n delete front element from que\n done\nEnd"
},
{
"code": null,
"e": 1710,
"s": 1699,
"text": " Live Demo"
},
{
"code": null,
"e": 3991,
"s": 1710,
"text": "#include<iostream>\n#include<queue>\nusing namespace std;\nclass node{\n public:\n int h_left, h_right, bf, value;\n node *left, *right;\n};\nclass tree{\n private:\n node *get_node(int key);\n public:\n node *root;\n tree(){\n root = NULL; //set root as NULL at the beginning\n }\n void levelorder_traversal(node *r);\n node *insert_node(node *root, int key);\n};\nnode *tree::get_node(int key){\n node *new_node;\n new_node = new node; //create a new node dynamically\n new_node->h_left = 0; new_node->h_right = 0;\n new_node->bf = 0;\n new_node->value = key; //store the value from given key\n new_node->left = NULL; new_node->right = NULL;\n return new_node;\n}\nvoid tree::levelorder_traversal(node *root){\n queue <node*> que;\n node *item;\n que.push(root); //insert the root at first\n while(!que.empty()){\n item = que.front(); //get the element from the front end\n cout << item->value << \" \";\n if(item->left != NULL) //When left child is present, insert into queue\n que.push(item->left);\n if(item->right != NULL) //When right child is present, insert into queue\n que.push(item->right);\n que.pop(); //remove the item from queue\n }\n}\nnode *tree::insert_node(node *root, int key){\n if(root == NULL){\n return (get_node(key)); //when tree is empty, create a node as root\n }\n if(key < root->value){ //when key is smaller than root value, go to the left\n root->left = insert_node(root->left, key);\n } else if(key > root->value) { //when key is greater than root value, go to the right\n root->right = insert_node(root->right, key);\n }\n return root; //when key is already present, do not insert it again\n}\nmain(){\n node *root;\n tree my_tree;\n //Insert some keys into the tree.\n my_tree.root = my_tree.insert_node(my_tree.root, 10);\n my_tree.root = my_tree.insert_node(my_tree.root, 5);\n my_tree.root = my_tree.insert_node(my_tree.root, 16);\n my_tree.root = my_tree.insert_node(my_tree.root, 20);\n my_tree.root = my_tree.insert_node(my_tree.root, 15);\n my_tree.root = my_tree.insert_node(my_tree.root, 8);\n my_tree.root = my_tree.insert_node(my_tree.root, 23);\n cout << \"Level-Order Traversal: \";\n my_tree.levelorder_traversal(my_tree.root);\n}"
},
{
"code": null,
"e": 4033,
"s": 3991,
"text": "Level-Order Traversal: 10 5 16 8 15 20 23"
}
]
|
How to Publish your Data Science Project as a Web App using Julia and Genie | by Tobias Skovgaard Jepsen | Towards Data Science | Communication is often an integral part of a data science project and entire business have been built around exposing the results of a data science process. For instance, platforms such as wyscout and StatsBomb collect soccer data and present their analysis of the data as a web app.
In this guide, I give a short introduction on how to get started building a web app for your data science project using the programming language Julia and the Julia web framework Genie. A publicly available player value analysis from a research project is used as an example use case.
Disclaimer: I am writing this post as part of my own process of learning Julia and Genie. I am not an expert in either.
To install Julia, follow the instructions at https://julialang.org/downloads/platform/. Make sure that the Julia executable is added to PATH such that you can use the julia command from the command line.
It’s time to set up the project. First, create a directory for the project and navigate inside the folder on the command line:
mkdir projectnamecd projectname
Now is also a good time to setup version control for the project if you wish to do so. For instance, to setup the folder as a Git repostir, execute git init on the command line.
Next, we will set up a virtual environment for the project. You may be familiar with virtual environments from other programming languages such as Python. Virtual environments are a useful tool to help keep dependencies required by different projects separate since the dependencies in each virtual environment is isolated from the dependencies in any other virtual environment on the same machine. Virtual environments in Julia are created through the built-in package manage Pkg.
To create the virtual environment,
open the Julia REPL by executing julia from the command line,execute ] in the Julia REPL to enter the Pkg REPL, andexecute activate . within the Pkg REPL.
open the Julia REPL by executing julia from the command line,
execute ] in the Julia REPL to enter the Pkg REPL, and
execute activate . within the Pkg REPL.
This will create and activate the virtual environment for your project. In addition, the files Project.tomland Manifest.toml will be created in the projectname folder. As their extensions indicate, these files are written in the TOML format and are used to manage your project dependencies. For more information on Pkg, see http://pkgdocs.julialang.org/v1/api/.
This section is largely an abbreviated version of the official Genie tutorial. If you find Genie interesting, I recommend that you review the full tutorial which can find here.
Now it is time to install Genie. In brief,
Genie is a full-stack MVC web framework which promotes a streamlined and efficient workflow for developing modern web applications in Julia. — Genie
To install Genie, execute add Genie from within the Pkg REPL with your project virtual environment activated. If you closed it, simply run julia --project <filepath> in the projectname directory to open the Julia REPL with your virtual environment activated and type in ] to enter the Pkg REPL.
After executing add Genie, you can verify the installation by using backspace or CTRL+C to exit the Pkg REPL and return to the Julia REPL. Then, attempt to import Genie with using Genie. If no errors are returned, Genie has been installed correctly.
Now that we have Genie installed, it is time to set up the web app for the project. With the Julia REPL open and Genie imported, execute
Genie.newapp_webservice("webapp")
This will create a webapp folder in the projectname directory, which contains a simple skeleton web application for your data science project.
You can now launch the web app from the Julia REPL with
using GenieGenie.loadapp()up()
and find it by navigating to http://localhost:8000/ in your browser. You should see a stock welcome message on the landing page of your web app.
Now its time to publish your data science project. As an example project, I will use data from the paper “Actions speak louder than goals: Valuing player actions in soccer.” by Tom Decroos, Lotte Bransen, Jan Van Haaren, and Jesse Davis which they have made available through a GitHub repository.
Traditional metrics for assessing the impact of players in a soccer match focus on rare actions such as goals. The research paper therefore presents a technique for assigning value to all individual soccer actions, including those that do not result in scoring a goal. For the purposes of this guide, we will utilise only the data from the 2018 FIFA World Cup.
The objective of this small project is to expose the 2018 FIFA World Cup Player Analysis as a web app for all to see.
Create a data directory under the webapp directory and download the file player_stats.csv into the folder. You can find the file here. The full path to the file should be projectname/webapp/data/player_stats.csv. I recommend you have a brief look at the contents of the file to see the different columns.
Now it is time to load the data into the program. Open the routes.jl file under the webapp directory. This file is responsible for executing the right code when users access the pages of the web application. It already contains a bit of code, i.e.,
using Genie.Routerroute("/") do serve_static_file("welcome.html")end
which is the code that was responsible for showing you the welcome to Genie page after creating the skeleton web application.
Now it is time to add appropriate data structures to contain the information to publish from the player_stats.csvfile. Add the following structs:
struct Value total::Float64 offensive::Float64 defensive::Float64endstruct Player name::String minutes_played::Int value_per_minute::Valueend
With the Player data structure defined, it is time to construct Players from the player_stats.csv file. Since it is stored in CSV format, we will use the CSV package to load the file. To install it, open a Pkg REPL and add CSV.
Next, import the package by adding using CSV to the top of routes.jl. Finally, load the data from player_stats.csv by adding the list comprehension
players = [ Player(player.player_name, player.minutes_played, Value( player.vaep_rating, player.offensive_rating, player.defensive_rating)) for player in CSV.File("data/player_stats.csv")]
below the definition ofPlayer.
Import Genie.Renderer.Html by adding using Genie.Renderer.Html to the top of the file. Then, add a new route to the /players subpage
route("/players") do html(:players, :index, players=players)end
at the bottom of routes.jl. The call to html takes as input the list of players, along with two symbols to indicate the location of the appropriate HTML template to render them. As output, a string in HTML format is returned by invoking Genie’s template engine to fill out the templates. However, to do this, the template files
webapp/app/layouts/app.jl.html, and
webapp/app/resources/players/views/index.jl.html
must be created.
The file webapp/app/layouts/app.jl.html should contain
and webapp/app/resources/players/views/index.jl.html should contain
Both template files resemble HTML, but have embedded code in between the <% and %> tags. These are commands to the Genie template engine. The app.jl.html file contains the general layout for the site. For now, we are mostly interested in index.jl.html which is responsible for rendering the list of players. In this file, the embedded code loops over the input list of Players in lines 2–14, and the body of the loop accesses the fields of each Player struct to insert the data into an appropriate HTML structure for rendering in the browser.
With the templates in place, the web app can once again be launched from the Julia REPL with
using GenieGenie.loadapp()up()
If you navigate http://localhost:8000/players you should see the player statistics displayed on the page.
If you have followed the guide, you have built a simple web application to present the results of an analysis. This guide is not intended as the end, but just the beginning, to publishing a data science project as a web app. There is still plenty of room for improvement.
Improvement in terms of styling could be to reduce the precision of the value and reduce the amount of white space to utilise screen space more efficiently. Improvements in terms of features could be to include sorting or searching, which would make it easier to navigate the data. Finally, the data that you might want to present from your own data science project may be far more complex, e.g., include a hierarchy. For instance, analysing individual matches of each player.
You can find the complete project on GitHub. | [
{
"code": null,
"e": 330,
"s": 46,
"text": "Communication is often an integral part of a data science project and entire business have been built around exposing the results of a data science process. For instance, platforms such as wyscout and StatsBomb collect soccer data and present their analysis of the data as a web app."
},
{
"code": null,
"e": 615,
"s": 330,
"text": "In this guide, I give a short introduction on how to get started building a web app for your data science project using the programming language Julia and the Julia web framework Genie. A publicly available player value analysis from a research project is used as an example use case."
},
{
"code": null,
"e": 735,
"s": 615,
"text": "Disclaimer: I am writing this post as part of my own process of learning Julia and Genie. I am not an expert in either."
},
{
"code": null,
"e": 939,
"s": 735,
"text": "To install Julia, follow the instructions at https://julialang.org/downloads/platform/. Make sure that the Julia executable is added to PATH such that you can use the julia command from the command line."
},
{
"code": null,
"e": 1066,
"s": 939,
"text": "It’s time to set up the project. First, create a directory for the project and navigate inside the folder on the command line:"
},
{
"code": null,
"e": 1098,
"s": 1066,
"text": "mkdir projectnamecd projectname"
},
{
"code": null,
"e": 1276,
"s": 1098,
"text": "Now is also a good time to setup version control for the project if you wish to do so. For instance, to setup the folder as a Git repostir, execute git init on the command line."
},
{
"code": null,
"e": 1758,
"s": 1276,
"text": "Next, we will set up a virtual environment for the project. You may be familiar with virtual environments from other programming languages such as Python. Virtual environments are a useful tool to help keep dependencies required by different projects separate since the dependencies in each virtual environment is isolated from the dependencies in any other virtual environment on the same machine. Virtual environments in Julia are created through the built-in package manage Pkg."
},
{
"code": null,
"e": 1793,
"s": 1758,
"text": "To create the virtual environment,"
},
{
"code": null,
"e": 1948,
"s": 1793,
"text": "open the Julia REPL by executing julia from the command line,execute ] in the Julia REPL to enter the Pkg REPL, andexecute activate . within the Pkg REPL."
},
{
"code": null,
"e": 2010,
"s": 1948,
"text": "open the Julia REPL by executing julia from the command line,"
},
{
"code": null,
"e": 2065,
"s": 2010,
"text": "execute ] in the Julia REPL to enter the Pkg REPL, and"
},
{
"code": null,
"e": 2105,
"s": 2065,
"text": "execute activate . within the Pkg REPL."
},
{
"code": null,
"e": 2467,
"s": 2105,
"text": "This will create and activate the virtual environment for your project. In addition, the files Project.tomland Manifest.toml will be created in the projectname folder. As their extensions indicate, these files are written in the TOML format and are used to manage your project dependencies. For more information on Pkg, see http://pkgdocs.julialang.org/v1/api/."
},
{
"code": null,
"e": 2644,
"s": 2467,
"text": "This section is largely an abbreviated version of the official Genie tutorial. If you find Genie interesting, I recommend that you review the full tutorial which can find here."
},
{
"code": null,
"e": 2687,
"s": 2644,
"text": "Now it is time to install Genie. In brief,"
},
{
"code": null,
"e": 2836,
"s": 2687,
"text": "Genie is a full-stack MVC web framework which promotes a streamlined and efficient workflow for developing modern web applications in Julia. — Genie"
},
{
"code": null,
"e": 3131,
"s": 2836,
"text": "To install Genie, execute add Genie from within the Pkg REPL with your project virtual environment activated. If you closed it, simply run julia --project <filepath> in the projectname directory to open the Julia REPL with your virtual environment activated and type in ] to enter the Pkg REPL."
},
{
"code": null,
"e": 3381,
"s": 3131,
"text": "After executing add Genie, you can verify the installation by using backspace or CTRL+C to exit the Pkg REPL and return to the Julia REPL. Then, attempt to import Genie with using Genie. If no errors are returned, Genie has been installed correctly."
},
{
"code": null,
"e": 3518,
"s": 3381,
"text": "Now that we have Genie installed, it is time to set up the web app for the project. With the Julia REPL open and Genie imported, execute"
},
{
"code": null,
"e": 3552,
"s": 3518,
"text": "Genie.newapp_webservice(\"webapp\")"
},
{
"code": null,
"e": 3695,
"s": 3552,
"text": "This will create a webapp folder in the projectname directory, which contains a simple skeleton web application for your data science project."
},
{
"code": null,
"e": 3751,
"s": 3695,
"text": "You can now launch the web app from the Julia REPL with"
},
{
"code": null,
"e": 3782,
"s": 3751,
"text": "using GenieGenie.loadapp()up()"
},
{
"code": null,
"e": 3927,
"s": 3782,
"text": "and find it by navigating to http://localhost:8000/ in your browser. You should see a stock welcome message on the landing page of your web app."
},
{
"code": null,
"e": 4224,
"s": 3927,
"text": "Now its time to publish your data science project. As an example project, I will use data from the paper “Actions speak louder than goals: Valuing player actions in soccer.” by Tom Decroos, Lotte Bransen, Jan Van Haaren, and Jesse Davis which they have made available through a GitHub repository."
},
{
"code": null,
"e": 4585,
"s": 4224,
"text": "Traditional metrics for assessing the impact of players in a soccer match focus on rare actions such as goals. The research paper therefore presents a technique for assigning value to all individual soccer actions, including those that do not result in scoring a goal. For the purposes of this guide, we will utilise only the data from the 2018 FIFA World Cup."
},
{
"code": null,
"e": 4703,
"s": 4585,
"text": "The objective of this small project is to expose the 2018 FIFA World Cup Player Analysis as a web app for all to see."
},
{
"code": null,
"e": 5008,
"s": 4703,
"text": "Create a data directory under the webapp directory and download the file player_stats.csv into the folder. You can find the file here. The full path to the file should be projectname/webapp/data/player_stats.csv. I recommend you have a brief look at the contents of the file to see the different columns."
},
{
"code": null,
"e": 5257,
"s": 5008,
"text": "Now it is time to load the data into the program. Open the routes.jl file under the webapp directory. This file is responsible for executing the right code when users access the pages of the web application. It already contains a bit of code, i.e.,"
},
{
"code": null,
"e": 5326,
"s": 5257,
"text": "using Genie.Routerroute(\"/\") do serve_static_file(\"welcome.html\")end"
},
{
"code": null,
"e": 5452,
"s": 5326,
"text": "which is the code that was responsible for showing you the welcome to Genie page after creating the skeleton web application."
},
{
"code": null,
"e": 5598,
"s": 5452,
"text": "Now it is time to add appropriate data structures to contain the information to publish from the player_stats.csvfile. Add the following structs:"
},
{
"code": null,
"e": 5752,
"s": 5598,
"text": "struct Value total::Float64 offensive::Float64 defensive::Float64endstruct Player name::String minutes_played::Int value_per_minute::Valueend"
},
{
"code": null,
"e": 5980,
"s": 5752,
"text": "With the Player data structure defined, it is time to construct Players from the player_stats.csv file. Since it is stored in CSV format, we will use the CSV package to load the file. To install it, open a Pkg REPL and add CSV."
},
{
"code": null,
"e": 6128,
"s": 5980,
"text": "Next, import the package by adding using CSV to the top of routes.jl. Finally, load the data from player_stats.csv by adding the list comprehension"
},
{
"code": null,
"e": 6358,
"s": 6128,
"text": "players = [ Player(player.player_name, player.minutes_played, Value( player.vaep_rating, player.offensive_rating, player.defensive_rating)) for player in CSV.File(\"data/player_stats.csv\")]"
},
{
"code": null,
"e": 6389,
"s": 6358,
"text": "below the definition ofPlayer."
},
{
"code": null,
"e": 6522,
"s": 6389,
"text": "Import Genie.Renderer.Html by adding using Genie.Renderer.Html to the top of the file. Then, add a new route to the /players subpage"
},
{
"code": null,
"e": 6587,
"s": 6522,
"text": "route(\"/players\") do html(:players, :index, players=players)end"
},
{
"code": null,
"e": 6915,
"s": 6587,
"text": "at the bottom of routes.jl. The call to html takes as input the list of players, along with two symbols to indicate the location of the appropriate HTML template to render them. As output, a string in HTML format is returned by invoking Genie’s template engine to fill out the templates. However, to do this, the template files"
},
{
"code": null,
"e": 6951,
"s": 6915,
"text": "webapp/app/layouts/app.jl.html, and"
},
{
"code": null,
"e": 7000,
"s": 6951,
"text": "webapp/app/resources/players/views/index.jl.html"
},
{
"code": null,
"e": 7017,
"s": 7000,
"text": "must be created."
},
{
"code": null,
"e": 7072,
"s": 7017,
"text": "The file webapp/app/layouts/app.jl.html should contain"
},
{
"code": null,
"e": 7140,
"s": 7072,
"text": "and webapp/app/resources/players/views/index.jl.html should contain"
},
{
"code": null,
"e": 7683,
"s": 7140,
"text": "Both template files resemble HTML, but have embedded code in between the <% and %> tags. These are commands to the Genie template engine. The app.jl.html file contains the general layout for the site. For now, we are mostly interested in index.jl.html which is responsible for rendering the list of players. In this file, the embedded code loops over the input list of Players in lines 2–14, and the body of the loop accesses the fields of each Player struct to insert the data into an appropriate HTML structure for rendering in the browser."
},
{
"code": null,
"e": 7776,
"s": 7683,
"text": "With the templates in place, the web app can once again be launched from the Julia REPL with"
},
{
"code": null,
"e": 7807,
"s": 7776,
"text": "using GenieGenie.loadapp()up()"
},
{
"code": null,
"e": 7913,
"s": 7807,
"text": "If you navigate http://localhost:8000/players you should see the player statistics displayed on the page."
},
{
"code": null,
"e": 8185,
"s": 7913,
"text": "If you have followed the guide, you have built a simple web application to present the results of an analysis. This guide is not intended as the end, but just the beginning, to publishing a data science project as a web app. There is still plenty of room for improvement."
},
{
"code": null,
"e": 8662,
"s": 8185,
"text": "Improvement in terms of styling could be to reduce the precision of the value and reduce the amount of white space to utilise screen space more efficiently. Improvements in terms of features could be to include sorting or searching, which would make it easier to navigate the data. Finally, the data that you might want to present from your own data science project may be far more complex, e.g., include a hierarchy. For instance, analysing individual matches of each player."
}
]
|
How to Write a SQL Query For a Specific Date Range and Date Time? - GeeksforGeeks | 28 Oct, 2021
In SQL, some problems require us to retrieve rows based on their dates and times. For such cases, we use the DATETIME2 datatype present in SQL. For this article, we will be using the Microsoft SQL Server as our database.
Note – Here, we will use the WHERE and BETWEEN clauses along with the query to limit our rows to the given time. The pattern of saving date and time in MS SQL Server is yyyy:mm: dd hh:mm: ss. The time is represented in a 24-hour format. The date and time are collectively stored in a column using the datatype DATETIME2.
Syntax:
SELECT * FROM TABLE_NAME WHERE DATE_TIME_COLUMN
BETWEEN 'STARTING_DATE_TIME' AND 'ENDING_DATE_TIME';
Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks.
Query:
CREATE DATABASE GeeksForGeeks
Output:
Step 2: Use the GeeksForGeeks database. For this use the below command.
Query:
USE GeeksForGeeks
Output:
Step 3: Create a table PERSONAL inside the database GeeksForGeeks. This table has 3 columns namely BABY_NAME, WARD_NUMBER, and BIRTH_DATE_TIME containing the name, ward number, and date and time of birth of various babies.
Query:
CREATE TABLE PERSONAL(
BABY_NAME VARCHAR(10),
WARD_NUMBER INT,
BIRTH_DATE_TIME DATETIME2);
Output:
Step 4: Describe the structure of the table PERSONAL.
Query:
EXEC SP_COLUMNS PERSONAL;
Output:
Step 5: Insert 5 rows into the MARKS table.
Query:
INSERT INTO PERSONAL VALUES('TARA',3,'2001-01-10 10:40:50');
INSERT INTO PERSONAL VALUES('ANGEL',4,'2001-03-27 11:00:37');
INSERT INTO PERSONAL VALUES('AYUSH',1,'2002-09-18 13:45:21');
INSERT INTO PERSONAL VALUES('VEER',10,'2005-02-28 21:26:54');
INSERT INTO PERSONAL VALUES('ISHAN',2,'2008-12-25 00:01:00');
Output:
Step 6: Display all the rows of the MARKS table including the 0(zero) values.
Query:
SELECT * FROM PERSONAL;
Output:
Step 7: Retrieve the details of the babies born between 12:00 am, 1st January 2000 and 12:00 pm, 18th September 2002.
Query:
SELECT * FROM PERSONAL WHERE BIRTH_DATE_TIME BETWEEN
'2000-01-01 00:00:00' AND '2002-09-18 12:00:00';
Output:
Step 8: Retrieve the details of the babies born between 11:00 am, 1st May 2001 and 10:00 pm, 1st May 2005.
Query:
SELECT * FROM PERSONAL WHERE BIRTH_DATE_TIME BETWEEN
'2001-03-01 11:00:00' AND '2005-03-01 22:00:00';
Output:
Step 9: Retrieve the details of the babies born on or after the Christmas of 2005.
Query:
SELECT * FROM PERSONAL WHERE BIRTH_DATE_TIME >
'2005-12-25 00:00:00';
Output:
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Alter Multiple Columns at Once in SQL Server?
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query for Matching Multiple Values in the Same Column
SQL | Subquery
SQL Query to Insert Multiple Rows
SQL Query to Convert VARCHAR to INT
SQL | Date functions | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n28 Oct, 2021"
},
{
"code": null,
"e": 24433,
"s": 24212,
"text": "In SQL, some problems require us to retrieve rows based on their dates and times. For such cases, we use the DATETIME2 datatype present in SQL. For this article, we will be using the Microsoft SQL Server as our database."
},
{
"code": null,
"e": 24754,
"s": 24433,
"text": "Note – Here, we will use the WHERE and BETWEEN clauses along with the query to limit our rows to the given time. The pattern of saving date and time in MS SQL Server is yyyy:mm: dd hh:mm: ss. The time is represented in a 24-hour format. The date and time are collectively stored in a column using the datatype DATETIME2."
},
{
"code": null,
"e": 24762,
"s": 24754,
"text": "Syntax:"
},
{
"code": null,
"e": 24863,
"s": 24762,
"text": "SELECT * FROM TABLE_NAME WHERE DATE_TIME_COLUMN\nBETWEEN 'STARTING_DATE_TIME' AND 'ENDING_DATE_TIME';"
},
{
"code": null,
"e": 24963,
"s": 24863,
"text": "Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks."
},
{
"code": null,
"e": 24970,
"s": 24963,
"text": "Query:"
},
{
"code": null,
"e": 25000,
"s": 24970,
"text": "CREATE DATABASE GeeksForGeeks"
},
{
"code": null,
"e": 25008,
"s": 25000,
"text": "Output:"
},
{
"code": null,
"e": 25080,
"s": 25008,
"text": "Step 2: Use the GeeksForGeeks database. For this use the below command."
},
{
"code": null,
"e": 25087,
"s": 25080,
"text": "Query:"
},
{
"code": null,
"e": 25105,
"s": 25087,
"text": "USE GeeksForGeeks"
},
{
"code": null,
"e": 25113,
"s": 25105,
"text": "Output:"
},
{
"code": null,
"e": 25336,
"s": 25113,
"text": "Step 3: Create a table PERSONAL inside the database GeeksForGeeks. This table has 3 columns namely BABY_NAME, WARD_NUMBER, and BIRTH_DATE_TIME containing the name, ward number, and date and time of birth of various babies."
},
{
"code": null,
"e": 25343,
"s": 25336,
"text": "Query:"
},
{
"code": null,
"e": 25434,
"s": 25343,
"text": "CREATE TABLE PERSONAL(\nBABY_NAME VARCHAR(10),\nWARD_NUMBER INT,\nBIRTH_DATE_TIME DATETIME2);"
},
{
"code": null,
"e": 25442,
"s": 25434,
"text": "Output:"
},
{
"code": null,
"e": 25496,
"s": 25442,
"text": "Step 4: Describe the structure of the table PERSONAL."
},
{
"code": null,
"e": 25503,
"s": 25496,
"text": "Query:"
},
{
"code": null,
"e": 25529,
"s": 25503,
"text": "EXEC SP_COLUMNS PERSONAL;"
},
{
"code": null,
"e": 25537,
"s": 25529,
"text": "Output:"
},
{
"code": null,
"e": 25581,
"s": 25537,
"text": "Step 5: Insert 5 rows into the MARKS table."
},
{
"code": null,
"e": 25588,
"s": 25581,
"text": "Query:"
},
{
"code": null,
"e": 25897,
"s": 25588,
"text": "INSERT INTO PERSONAL VALUES('TARA',3,'2001-01-10 10:40:50');\nINSERT INTO PERSONAL VALUES('ANGEL',4,'2001-03-27 11:00:37');\nINSERT INTO PERSONAL VALUES('AYUSH',1,'2002-09-18 13:45:21');\nINSERT INTO PERSONAL VALUES('VEER',10,'2005-02-28 21:26:54');\nINSERT INTO PERSONAL VALUES('ISHAN',2,'2008-12-25 00:01:00');"
},
{
"code": null,
"e": 25905,
"s": 25897,
"text": "Output:"
},
{
"code": null,
"e": 25983,
"s": 25905,
"text": "Step 6: Display all the rows of the MARKS table including the 0(zero) values."
},
{
"code": null,
"e": 25990,
"s": 25983,
"text": "Query:"
},
{
"code": null,
"e": 26014,
"s": 25990,
"text": "SELECT * FROM PERSONAL;"
},
{
"code": null,
"e": 26022,
"s": 26014,
"text": "Output:"
},
{
"code": null,
"e": 26140,
"s": 26022,
"text": "Step 7: Retrieve the details of the babies born between 12:00 am, 1st January 2000 and 12:00 pm, 18th September 2002."
},
{
"code": null,
"e": 26147,
"s": 26140,
"text": "Query:"
},
{
"code": null,
"e": 26249,
"s": 26147,
"text": "SELECT * FROM PERSONAL WHERE BIRTH_DATE_TIME BETWEEN\n'2000-01-01 00:00:00' AND '2002-09-18 12:00:00';"
},
{
"code": null,
"e": 26257,
"s": 26249,
"text": "Output:"
},
{
"code": null,
"e": 26364,
"s": 26257,
"text": "Step 8: Retrieve the details of the babies born between 11:00 am, 1st May 2001 and 10:00 pm, 1st May 2005."
},
{
"code": null,
"e": 26371,
"s": 26364,
"text": "Query:"
},
{
"code": null,
"e": 26474,
"s": 26371,
"text": "SELECT * FROM PERSONAL WHERE BIRTH_DATE_TIME BETWEEN\n '2001-03-01 11:00:00' AND '2005-03-01 22:00:00';"
},
{
"code": null,
"e": 26482,
"s": 26474,
"text": "Output:"
},
{
"code": null,
"e": 26565,
"s": 26482,
"text": "Step 9: Retrieve the details of the babies born on or after the Christmas of 2005."
},
{
"code": null,
"e": 26572,
"s": 26565,
"text": "Query:"
},
{
"code": null,
"e": 26643,
"s": 26572,
"text": "SELECT * FROM PERSONAL WHERE BIRTH_DATE_TIME > \n'2005-12-25 00:00:00';"
},
{
"code": null,
"e": 26651,
"s": 26643,
"text": "Output:"
},
{
"code": null,
"e": 26658,
"s": 26651,
"text": "Picked"
},
{
"code": null,
"e": 26668,
"s": 26658,
"text": "SQL-Query"
},
{
"code": null,
"e": 26679,
"s": 26668,
"text": "SQL-Server"
},
{
"code": null,
"e": 26683,
"s": 26679,
"text": "SQL"
},
{
"code": null,
"e": 26687,
"s": 26683,
"text": "SQL"
},
{
"code": null,
"e": 26785,
"s": 26687,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26794,
"s": 26785,
"text": "Comments"
},
{
"code": null,
"e": 26807,
"s": 26794,
"text": "Old Comments"
},
{
"code": null,
"e": 26860,
"s": 26807,
"text": "How to Alter Multiple Columns at Once in SQL Server?"
},
{
"code": null,
"e": 26926,
"s": 26860,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26958,
"s": 26926,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26975,
"s": 26958,
"text": "SQL using Python"
},
{
"code": null,
"e": 27053,
"s": 26975,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27111,
"s": 27053,
"text": "SQL Query for Matching Multiple Values in the Same Column"
},
{
"code": null,
"e": 27126,
"s": 27111,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27160,
"s": 27126,
"text": "SQL Query to Insert Multiple Rows"
},
{
"code": null,
"e": 27196,
"s": 27160,
"text": "SQL Query to Convert VARCHAR to INT"
}
]
|
SAS - ODS | The output from a SAS program can be converted to more user friendly forms like .html or PDF. This is done by using the ODS statement available in SAS. ODS stands for output delivery system. It is mostly used to format the output data of a SAS program to nice reports which are good to look at and understand. That also helps sharing the output with other platforms and soft wares. It can also combine the results from multiple PROC statements in one single file.
The basic syntax for using the ODS statement in SAS is −
ODS outputtype
PATH path name
FILE = Filename and Path
STYLE = StyleName
;
PROC some proc
;
ODS outputtype CLOSE;
Following is the description of the parameters used −
PATH represents the statement used in case of HTML output. In other types of output we include the path in the filename.
PATH represents the statement used in case of HTML output. In other types of output we include the path in the filename.
Style represents one of the in-built styles available in the SAS environment.
Style represents one of the in-built styles available in the SAS environment.
We create HTML output using the ODS HTML statement.In the below example we create a html file in our desired path. We apply a style available in the styles library. We can see the output file in the mentioned path and we can download it to save in an environment different from the SAS environment. Please note that we have two proc SQL statements and both their output is captured into a single file.
ODS HTML
PATH = '/folders/myfolders/sasuser.v94/TutorialsPoint/'
FILE = 'CARS2.html'
STYLE = EGDefault;
proc SQL;
select make, model, invoice
from sashelp.cars
where make in ('Audi','BMW')
and type = 'Sports'
;
quit;
proc SQL;
select make,mean(horsepower)as meanhp
from sashelp.cars
where make in ('Audi','BMW')
group by make;
quit;
ODS HTML CLOSE;
When the above code is executed we get the following result −
In the below example we create a PDF file in our desired path. We apply a style available in the styles library. We can see the output file in the mentioned path and we can download it to save in an environment different from the SAS environment. Please note that we have two proc SQL statements and both their output is captured into a single file.
ODS PDF
FILE = '/folders/myfolders/sasuser.v94/TutorialsPoint/CARS2.pdf'
STYLE = EGDefault;
proc SQL;
select make, model, invoice
from sashelp.cars
where make in ('Audi','BMW')
and type = 'Sports'
;
quit;
proc SQL;
select make,mean(horsepower)as meanhp
from sashelp.cars
where make in ('Audi','BMW')
group by make;
quit;
ODS PDF CLOSE;
When the above code is executed we get the following result −
In the below example we create a RTF file in our desired path. We apply a style available in the styles library. We can see the output file in the mentioned path and we can download it to save in an environment different from the SAS environment. Please note that we have two proc SQL statements and both their output is captured into a single file.
ODS RTF
FILE = '/folders/myfolders/sasuser.v94/TutorialsPoint/CARS.rtf'
STYLE = EGDefault;
proc SQL;
select make, model, invoice
from sashelp.cars
where make in ('Audi','BMW')
and type = 'Sports'
;
quit;
proc SQL;
select make,mean(horsepower)as meanhp
from sashelp.cars
where make in ('Audi','BMW')
group by make;
quit;
ODS rtf CLOSE;
When the above code is executed we get the following result −
50 Lectures
5.5 hours
Code And Create
124 Lectures
30 hours
Juan Galvan
162 Lectures
31.5 hours
Yossef Ayman Zedan
35 Lectures
2.5 hours
Ermin Dedic
167 Lectures
45.5 hours
Muslim Helalee
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3047,
"s": 2583,
"text": "The output from a SAS program can be converted to more user friendly forms like .html or PDF. This is done by using the ODS statement available in SAS. ODS stands for output delivery system. It is mostly used to format the output data of a SAS program to nice reports which are good to look at and understand. That also helps sharing the output with other platforms and soft wares. It can also combine the results from multiple PROC statements in one single file."
},
{
"code": null,
"e": 3104,
"s": 3047,
"text": "The basic syntax for using the ODS statement in SAS is −"
},
{
"code": null,
"e": 3219,
"s": 3104,
"text": "ODS outputtype\nPATH path name\nFILE = Filename and Path\nSTYLE = StyleName\n;\nPROC some proc\n;\nODS outputtype CLOSE;\n"
},
{
"code": null,
"e": 3273,
"s": 3219,
"text": "Following is the description of the parameters used −"
},
{
"code": null,
"e": 3394,
"s": 3273,
"text": "PATH represents the statement used in case of HTML output. In other types of output we include the path in the filename."
},
{
"code": null,
"e": 3515,
"s": 3394,
"text": "PATH represents the statement used in case of HTML output. In other types of output we include the path in the filename."
},
{
"code": null,
"e": 3593,
"s": 3515,
"text": "Style represents one of the in-built styles available in the SAS environment."
},
{
"code": null,
"e": 3671,
"s": 3593,
"text": "Style represents one of the in-built styles available in the SAS environment."
},
{
"code": null,
"e": 4074,
"s": 3671,
"text": "We create HTML output using the ODS HTML statement.In the below example we create a html file in our desired path. We apply a style available in the styles library. We can see the output file in the mentioned path and we can download it to save in an environment different from the SAS environment. Please note that we have two proc SQL statements and both their output is captured into a single file."
},
{
"code": null,
"e": 4438,
"s": 4074,
"text": "ODS HTML \n PATH = '/folders/myfolders/sasuser.v94/TutorialsPoint/'\n FILE = 'CARS2.html'\n STYLE = EGDefault;\nproc SQL;\nselect make, model, invoice \nfrom sashelp.cars\nwhere make in ('Audi','BMW')\nand type = 'Sports'\n;\nquit;\n\nproc SQL;\nselect make,mean(horsepower)as meanhp\nfrom sashelp.cars\nwhere make in ('Audi','BMW')\ngroup by make;\nquit;\n\nODS HTML CLOSE; \n"
},
{
"code": null,
"e": 4500,
"s": 4438,
"text": "When the above code is executed we get the following result −"
},
{
"code": null,
"e": 4851,
"s": 4500,
"text": "In the below example we create a PDF file in our desired path. We apply a style available in the styles library. We can see the output file in the mentioned path and we can download it to save in an environment different from the SAS environment. Please note that we have two proc SQL statements and both their output is captured into a single file."
},
{
"code": null,
"e": 5199,
"s": 4851,
"text": "ODS PDF \n FILE = '/folders/myfolders/sasuser.v94/TutorialsPoint/CARS2.pdf'\n STYLE = EGDefault;\nproc SQL;\nselect make, model, invoice \nfrom sashelp.cars\nwhere make in ('Audi','BMW')\nand type = 'Sports'\n;\nquit;\n\nproc SQL;\nselect make,mean(horsepower)as meanhp\nfrom sashelp.cars\nwhere make in ('Audi','BMW')\ngroup by make;\nquit;\n\nODS PDF CLOSE; \n"
},
{
"code": null,
"e": 5261,
"s": 5199,
"text": "When the above code is executed we get the following result −"
},
{
"code": null,
"e": 5612,
"s": 5261,
"text": "In the below example we create a RTF file in our desired path. We apply a style available in the styles library. We can see the output file in the mentioned path and we can download it to save in an environment different from the SAS environment. Please note that we have two proc SQL statements and both their output is captured into a single file."
},
{
"code": null,
"e": 5953,
"s": 5612,
"text": "ODS RTF \nFILE = '/folders/myfolders/sasuser.v94/TutorialsPoint/CARS.rtf'\nSTYLE = EGDefault;\nproc SQL;\nselect make, model, invoice \nfrom sashelp.cars\nwhere make in ('Audi','BMW')\nand type = 'Sports'\n;\nquit;\n\nproc SQL;\nselect make,mean(horsepower)as meanhp\nfrom sashelp.cars\nwhere make in ('Audi','BMW')\ngroup by make;\nquit;\n\nODS rtf CLOSE; \n"
},
{
"code": null,
"e": 6015,
"s": 5953,
"text": "When the above code is executed we get the following result −"
},
{
"code": null,
"e": 6050,
"s": 6015,
"text": "\n 50 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6067,
"s": 6050,
"text": " Code And Create"
},
{
"code": null,
"e": 6102,
"s": 6067,
"text": "\n 124 Lectures \n 30 hours \n"
},
{
"code": null,
"e": 6115,
"s": 6102,
"text": " Juan Galvan"
},
{
"code": null,
"e": 6152,
"s": 6115,
"text": "\n 162 Lectures \n 31.5 hours \n"
},
{
"code": null,
"e": 6172,
"s": 6152,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 6207,
"s": 6172,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6220,
"s": 6207,
"text": " Ermin Dedic"
},
{
"code": null,
"e": 6257,
"s": 6220,
"text": "\n 167 Lectures \n 45.5 hours \n"
},
{
"code": null,
"e": 6273,
"s": 6257,
"text": " Muslim Helalee"
},
{
"code": null,
"e": 6280,
"s": 6273,
"text": " Print"
},
{
"code": null,
"e": 6291,
"s": 6280,
"text": " Add Notes"
}
]
|
Confidence Intervals vs Prediction Intervals | Towards Data Science | Both confidence intervals and prediction intervals express uncertainty in statistical estimates. However, each pertains to uncertainty coming from a different source. Sometimes, one can calculate both for the same quantity, which leads to confusion and potentially grave mistakes in interpreting statistical models. Let’s see how they differ, what uncertainties they express, and when to use each.
Let’s start practically by fitting a simple linear regression model to California housing data. We will use only the first 200 records and skip the first one as a test case. The model predicts the house value based on a single predictor, the median income in the neighborhood. We are using only one predictor to be able to easily see the regression line in 2D.
In the model summary, we see the following table.
=========================================================== coef std err t P>|t [0.025 0.975]-----------------------------------------------------------const 0.7548 0.078 9.633 0.000 0.600 0.909MedInc 0.3813 0.021 18.160 0.000 0.340 0.423
The coefficient of the median neighborhood income, MedInc, is 0.3813 with a 95% interval around it amounting to 0.340 — 0.423. This is a confidence interval. Confidence interval pertains to a statistic estimated from multiple values, in this case — the regression coefficient. It expresses sampling uncertainty, which comes from the fact that our data is just a random sample of the population we try to model. It can be interpreted as follows: if we had collected many other data sets on houses in California and had fit such a model to each of them, in 95% of the cases the true population coefficient (which we would know should we have data on all houses in California) would fall within the confidence interval.
Confidence interval pertains to a statistic estimated from multiple values. It expresses sampling uncertainty.
Now, let’s use the model to make a prediction for the first observation we have left out from training. Instead of the predict() method, we will use get_predict() combined with summary_frame() in order to extract some more information about the predictions.
We get the following data frame:
mean mean_se mean_ci_lower mean_ci_upper obs_ci_lower obs_ci_upper3.9295 0.1174 3.697902 4.161218 2.711407 5.147713
The predicted value for this particular house is 3.9295. Now, the mean_ci columns contain the lower and upper bounds of the confidence interval for this prediction, while the obs_ci columns contain the lower and upper bounds of the prediction interval for the prediction.
You can immediately see that the prediction interval is much wider than the confidence interval. We can visualize it nicely by using the model to predict house values for a range of different neighborhood incomes so that we can see the regression line and the intervals around the predicted values.
Now, pred is just like before, only with 500 rows, and contains predictions and interval bounds for 500 different income values ranging between 0 and 15. We can now use it to plot the regression line and the intervals around it.
There are two main things to see here. First, the confidence interval is thinner for median income values of 2 through 5 and wider at more extreme values. This is because, for most records in the data, the income is somewhere between 2 and 5. For such cases, the model has more data, hence the sampling uncertainty is smaller.
Second, the prediction interval is much wider than the confidence interval. This is because expresses more uncertainty. On top of the sampling uncertainty, the prediction interval also expresses inherent uncertainty in the particular data point.
Prediction interval expresses inherent uncertainty in the particular data point on top of the sampling uncertainty. Is it thus wider than the confidence interval.
This data-point-level uncertainty comes from the fact that there could be multiple houses of different values in the same neighborhood, and hence with the same predictor value in the model. This is obvious in this particular example, but can also be true in other cases. It happens that multiple exactly the same feature vectors are associated with the same target value.
Let’s recap:
Confidence intervals express sampling uncertainty in quantities estimated from many data points. The more data, the less sampling uncertainty, and hence the thinner the interval.
Prediction intervals, on top of the sampling uncertainty, also express uncertainty around a single value, which makes them wider than the confidence intervals.
But where do these intervals come from, and how come they encompass these different sources of uncertainty? Let’s take a look at it next!
In old-school statistics, one would calculate the intervals around the prediction y-hat as
where t-crit is the critical value from the t-distribution and SE is the standard error of prediction. Both numbers on the right-hand side will be different for the confidence interval and for the prediction interval and are computed based on various assumptions.
The times of parametric assumptions in statistics, however, are luckily coming to an end. The recent increase in computing power allows for using simple, one-size-fits-all resampling methods to do statistics (I’m planning to write more about it soon!). Hence, instead of boring you with derivations and formulas, let me show you how to construct both types of intervals via resampling. This approach is applicable not only to linear regression but essentially to any machine learning model you can think of. Moreover, it will make it instantaneously clear what kind of uncertainty is covered by which interval.
The resampling technique we will use is bootstrapping. It boils down to taking many, say 10 000, samples from the original data with replacement. These are called bootstrap samples, and since we are drawing with replacement, the same observation may appear multiple times in a single bootstrap sample. The point of this is to get many samples from a hypothetical population so that we can observe sampling uncertainty. Next, we perform whatever analysis or model we want on each bootstrap sample separately and compute a quantity of interest, such as a model parameter or a single prediction. Once we have 10 000 bootstrapped values for this quantity, we can look at the percentiles to get the intervals. The entire process is illustrated by the diagram below.
Let’s bootstrap confidence intervals for a house value prediction for a house located in the neighborhood with a median income of 3. We take 10 000 bootstrap samples, fit a regression model to each of them, and make a prediction for MedInc equal to 3. This way, we got 10 000 predictions. We can print their mean, and the percentiles denoting the lower and upper bound of the confidence interval.
Mean pred: 1.901916461064523295% CI: [1.83355697 1.97350956]
This bootstrap sample accounts for the sampling uncertainty, and so the interval we got is a confidence interval. Let’s now look at how to bootstrap a prediction interval.
Prediction interval, on top of the sampling uncertainty, should also account for the uncertainty in the particular prediction data point. To do this, we need one small change in the code. Once we obtain the prediction from the model, we also draw a random residual from the model and add it to this prediction. This way, we can include the individual prediction uncertainty in the bootstrap output.
Mean pred: 1.901463101316340695% PI: [1.07444778 2.72920388]
As expected, the prediction interval is significantly wider than the confidence interval, even though the mean prediction is the same.
Thanks for reading!
If you liked this post, why don’t you subscribe for email updates on my new articles? And by becoming a Medium member, you can support my writing and get unlimited access to all stories by other authors and myself.
Need consulting? You can ask me anything or book me for a 1:1 here.
You can also try one of my other articles. Can’t choose? Pick one of these: | [
{
"code": null,
"e": 569,
"s": 171,
"text": "Both confidence intervals and prediction intervals express uncertainty in statistical estimates. However, each pertains to uncertainty coming from a different source. Sometimes, one can calculate both for the same quantity, which leads to confusion and potentially grave mistakes in interpreting statistical models. Let’s see how they differ, what uncertainties they express, and when to use each."
},
{
"code": null,
"e": 930,
"s": 569,
"text": "Let’s start practically by fitting a simple linear regression model to California housing data. We will use only the first 200 records and skip the first one as a test case. The model predicts the house value based on a single predictor, the median income in the neighborhood. We are using only one predictor to be able to easily see the regression line in 2D."
},
{
"code": null,
"e": 980,
"s": 930,
"text": "In the model summary, we see the following table."
},
{
"code": null,
"e": 1266,
"s": 980,
"text": "=========================================================== coef std err t P>|t [0.025 0.975]-----------------------------------------------------------const 0.7548 0.078 9.633 0.000 0.600 0.909MedInc 0.3813 0.021 18.160 0.000 0.340 0.423"
},
{
"code": null,
"e": 1983,
"s": 1266,
"text": "The coefficient of the median neighborhood income, MedInc, is 0.3813 with a 95% interval around it amounting to 0.340 — 0.423. This is a confidence interval. Confidence interval pertains to a statistic estimated from multiple values, in this case — the regression coefficient. It expresses sampling uncertainty, which comes from the fact that our data is just a random sample of the population we try to model. It can be interpreted as follows: if we had collected many other data sets on houses in California and had fit such a model to each of them, in 95% of the cases the true population coefficient (which we would know should we have data on all houses in California) would fall within the confidence interval."
},
{
"code": null,
"e": 2094,
"s": 1983,
"text": "Confidence interval pertains to a statistic estimated from multiple values. It expresses sampling uncertainty."
},
{
"code": null,
"e": 2352,
"s": 2094,
"text": "Now, let’s use the model to make a prediction for the first observation we have left out from training. Instead of the predict() method, we will use get_predict() combined with summary_frame() in order to extract some more information about the predictions."
},
{
"code": null,
"e": 2385,
"s": 2352,
"text": "We get the following data frame:"
},
{
"code": null,
"e": 2522,
"s": 2385,
"text": " mean mean_se mean_ci_lower mean_ci_upper obs_ci_lower obs_ci_upper3.9295 0.1174 3.697902 4.161218 2.711407 5.147713"
},
{
"code": null,
"e": 2794,
"s": 2522,
"text": "The predicted value for this particular house is 3.9295. Now, the mean_ci columns contain the lower and upper bounds of the confidence interval for this prediction, while the obs_ci columns contain the lower and upper bounds of the prediction interval for the prediction."
},
{
"code": null,
"e": 3093,
"s": 2794,
"text": "You can immediately see that the prediction interval is much wider than the confidence interval. We can visualize it nicely by using the model to predict house values for a range of different neighborhood incomes so that we can see the regression line and the intervals around the predicted values."
},
{
"code": null,
"e": 3322,
"s": 3093,
"text": "Now, pred is just like before, only with 500 rows, and contains predictions and interval bounds for 500 different income values ranging between 0 and 15. We can now use it to plot the regression line and the intervals around it."
},
{
"code": null,
"e": 3649,
"s": 3322,
"text": "There are two main things to see here. First, the confidence interval is thinner for median income values of 2 through 5 and wider at more extreme values. This is because, for most records in the data, the income is somewhere between 2 and 5. For such cases, the model has more data, hence the sampling uncertainty is smaller."
},
{
"code": null,
"e": 3895,
"s": 3649,
"text": "Second, the prediction interval is much wider than the confidence interval. This is because expresses more uncertainty. On top of the sampling uncertainty, the prediction interval also expresses inherent uncertainty in the particular data point."
},
{
"code": null,
"e": 4058,
"s": 3895,
"text": "Prediction interval expresses inherent uncertainty in the particular data point on top of the sampling uncertainty. Is it thus wider than the confidence interval."
},
{
"code": null,
"e": 4430,
"s": 4058,
"text": "This data-point-level uncertainty comes from the fact that there could be multiple houses of different values in the same neighborhood, and hence with the same predictor value in the model. This is obvious in this particular example, but can also be true in other cases. It happens that multiple exactly the same feature vectors are associated with the same target value."
},
{
"code": null,
"e": 4443,
"s": 4430,
"text": "Let’s recap:"
},
{
"code": null,
"e": 4622,
"s": 4443,
"text": "Confidence intervals express sampling uncertainty in quantities estimated from many data points. The more data, the less sampling uncertainty, and hence the thinner the interval."
},
{
"code": null,
"e": 4782,
"s": 4622,
"text": "Prediction intervals, on top of the sampling uncertainty, also express uncertainty around a single value, which makes them wider than the confidence intervals."
},
{
"code": null,
"e": 4920,
"s": 4782,
"text": "But where do these intervals come from, and how come they encompass these different sources of uncertainty? Let’s take a look at it next!"
},
{
"code": null,
"e": 5011,
"s": 4920,
"text": "In old-school statistics, one would calculate the intervals around the prediction y-hat as"
},
{
"code": null,
"e": 5275,
"s": 5011,
"text": "where t-crit is the critical value from the t-distribution and SE is the standard error of prediction. Both numbers on the right-hand side will be different for the confidence interval and for the prediction interval and are computed based on various assumptions."
},
{
"code": null,
"e": 5886,
"s": 5275,
"text": "The times of parametric assumptions in statistics, however, are luckily coming to an end. The recent increase in computing power allows for using simple, one-size-fits-all resampling methods to do statistics (I’m planning to write more about it soon!). Hence, instead of boring you with derivations and formulas, let me show you how to construct both types of intervals via resampling. This approach is applicable not only to linear regression but essentially to any machine learning model you can think of. Moreover, it will make it instantaneously clear what kind of uncertainty is covered by which interval."
},
{
"code": null,
"e": 6647,
"s": 5886,
"text": "The resampling technique we will use is bootstrapping. It boils down to taking many, say 10 000, samples from the original data with replacement. These are called bootstrap samples, and since we are drawing with replacement, the same observation may appear multiple times in a single bootstrap sample. The point of this is to get many samples from a hypothetical population so that we can observe sampling uncertainty. Next, we perform whatever analysis or model we want on each bootstrap sample separately and compute a quantity of interest, such as a model parameter or a single prediction. Once we have 10 000 bootstrapped values for this quantity, we can look at the percentiles to get the intervals. The entire process is illustrated by the diagram below."
},
{
"code": null,
"e": 7044,
"s": 6647,
"text": "Let’s bootstrap confidence intervals for a house value prediction for a house located in the neighborhood with a median income of 3. We take 10 000 bootstrap samples, fit a regression model to each of them, and make a prediction for MedInc equal to 3. This way, we got 10 000 predictions. We can print their mean, and the percentiles denoting the lower and upper bound of the confidence interval."
},
{
"code": null,
"e": 7105,
"s": 7044,
"text": "Mean pred: 1.901916461064523295% CI: [1.83355697 1.97350956]"
},
{
"code": null,
"e": 7277,
"s": 7105,
"text": "This bootstrap sample accounts for the sampling uncertainty, and so the interval we got is a confidence interval. Let’s now look at how to bootstrap a prediction interval."
},
{
"code": null,
"e": 7676,
"s": 7277,
"text": "Prediction interval, on top of the sampling uncertainty, should also account for the uncertainty in the particular prediction data point. To do this, we need one small change in the code. Once we obtain the prediction from the model, we also draw a random residual from the model and add it to this prediction. This way, we can include the individual prediction uncertainty in the bootstrap output."
},
{
"code": null,
"e": 7737,
"s": 7676,
"text": "Mean pred: 1.901463101316340695% PI: [1.07444778 2.72920388]"
},
{
"code": null,
"e": 7872,
"s": 7737,
"text": "As expected, the prediction interval is significantly wider than the confidence interval, even though the mean prediction is the same."
},
{
"code": null,
"e": 7892,
"s": 7872,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 8107,
"s": 7892,
"text": "If you liked this post, why don’t you subscribe for email updates on my new articles? And by becoming a Medium member, you can support my writing and get unlimited access to all stories by other authors and myself."
},
{
"code": null,
"e": 8175,
"s": 8107,
"text": "Need consulting? You can ask me anything or book me for a 1:1 here."
}
]
|
Find all elements in array which have at-least two greater elements - GeeksforGeeks | 28 Apr, 2021
Given an array of n distinct elements, the task is to find all elements in array which have at-least two greater elements than themselves.
Examples :
Input : arr[] = {2, 8, 7, 1, 5};Output : 2 1 5 Explanation:The output three elements have two or more greater elements
Explanation:Input : arr[] = {7, -2, 3, 4, 9, -1};Output : -2 3 4 -1
Method 1 (Simple) The naive approach is to run two loops and check one by one element of array check that array elements have at-least two elements greater than itself or not. If it’s true then print array element.
C++
Java
Python3
C#
PHP
Javascript
// Simple C++ program to find// all elements in array which// have at-least two greater// elements itself.#include<bits/stdc++.h>using namespace std; void findElements(int arr[], int n){ // Pick elements one by one and // count greater elements. If // count is more than 2, print // that element. for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) if (arr[j] > arr[i]) count++; if (count >= 2) cout << arr[i] << " "; }} // Driver codeint main(){ int arr[] = { 2, -6 ,3 , 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); findElements(arr, n); return 0;}
// Java program to find all// elements in array which// have at-least two greater// elements itself.import java.util.*;import java.io.*; class GFG{ static void findElements(int arr[], int n){ // Pick elements one by one // and count greater elements. // If count is more than 2, // print that element. for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) if (arr[j] > arr[i]) count++; if (count >= 2) System.out.print(arr[i] + " "); }} // Driver codepublic static void main(String args[]){ int arr[] = { 2, -6 ,3 , 5, 1}; int n = arr.length; findElements(arr, n);}} // This code is contributed by Sahil_Bansall
# Python3 program to find# all elements in array# which have at-least two# greater elements itself. def findElements( arr, n): # Pick elements one by # one and count greater # elements. If count # is more than 2, print # that element. for i in range(n): count = 0 for j in range(0, n): if arr[j] > arr[i]: count = count + 1 if count >= 2 : print(arr[i], end=" ") # Driver codearr = [ 2, -6 ,3 , 5, 1]n = len(arr)findElements(arr, n) # This code is contributed by sunnysingh
// C# program to find all elements in// array which have at least two greater// elements itself.using System; class GFG{ static void findElements(int []arr, int n){ // Pick elements one by one and count // greater elements. If count is more // than 2, print that element. for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) if (arr[j] > arr[i]) count++; if (count >= 2) Console.Write(arr[i] + " "); }} // Driver codepublic static void Main(String []args){ int []arr = {2, -6 ,3 , 5, 1}; int n = arr.Length; findElements(arr, n); }} // This code is contributed by Parashar.
<?php// Simple PHP program to find// all elements in array which// have at-least two greater// elements itself. function findElements($arr, $n){ // Pick elements one by one and // count greater elements. If // count is more than 2, // print that element. for ($i = 0; $i < $n; $i++) { $count = 0; for ($j = 0; $j < $n; $j++) if ($arr[$j] > $arr[$i]) $count++; if ($count >= 2) echo $arr[$i]." "; }} // Driver code$arr = array( 2, -6 ,3 , 5, 1);$n = sizeof($arr);findElements($arr, $n); ?>
<script> // Simple Javascript program to find// all elements in array which// have at-least two greater// elements itself. function findElements(arr, n){ // Pick elements one by one and // count greater elements. If // count is more than 2, print // that element. for (let i = 0; i < n; i++) { let count = 0; for (let j = 0; j < n; j++) if (arr[j] > arr[i]) count++; if (count >= 2) document.write(arr[i] + " "); }} // Driver code let arr = [2, -6 ,3 , 5, 1]; let n = arr.length; findElements(arr, n); // This is code is contributed by Mayank Tyagi </script>
2 -6 1
Time Complexity: O(n2)
Method 2 (Use Sorting) We sort the array first in increasing order, then we print first n-2 elements where n is size of array.
C++
Java
Python3
C#
PHP
Javascript
// Sorting based C++ program to// find all elements in array// which have atleast two greater// elements itself.#include<bits/stdc++.h>using namespace std; void findElements(int arr[], int n){ sort(arr, arr + n); for (int i = 0; i < n - 2; i++) cout << arr[i] << " ";} // Driver Codeint main(){ int arr[] = { 2, -6 ,3 , 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); findElements(arr, n); return 0;}
// Sorting based Java program to find// all elements in array which have// atleast two greater elements itself.import java.util.*;import java.io.*; class GFG{ static void findElements(int arr[], int n){ Arrays.sort(arr); for (int i = 0; i < n - 2; i++) System.out.print(arr[i] + " ");} // Driver codepublic static void main(String args[]){ int arr[] = { 2, -6 ,3 , 5, 1}; int n = arr.length; findElements(arr, n); }} // This code is contributed by Sahil_Bansall
# Sorting based Python 3 program# to find all elements in array# which have atleast two greater# elements itself. def findElements(arr, n): arr.sort() for i in range(0, n-2): print(arr[i], end =" ") # Driven sourcearr = [2, -6, 3, 5, 1]n = len(arr)findElements(arr, n) # This code is contributed# by Smitha Dinesh Semwal
// Sorting based C# program to find// all elements in array which have// atleast two greater elements itself.using System; class GFG{ static void findElements(int []arr, int n){ Array.Sort(arr); for (int i = 0; i < n-2; i++) Console.Write(arr[i] + " ");} // Driver codepublic static void Main(String []args){ int []arr = { 2, -6 ,3 , 5, 1}; int n = arr.Length; findElements(arr, n); }} // This code is contributed by parashar
<?php// Sorting based PHP program to// find all elements in array// which have atleast two greater// elements itself. function findElements( $arr, $n){ sort($arr); for ($i = 0; $i < $n - 2; $i++) echo $arr[$i] , " ";} // Driver Code$arr = array( 2, -6 ,3 , 5, 1);$n = count($arr);findElements($arr, $n); // This code is contributed by anuj_67.?>;
<script> // Sorting based Javascript program to find // all elements in array which have // atleast two greater elements itself.function findElements(arr, n){ arr.sort(); for(let i = 0; i < n - 2; i++) document.write(arr[i] + " ");} // Driver code let arr = [ 2, -6 ,3 , 5, 1];let n = arr.length; findElements(arr, n); // This code is contributed by susmitakundugoaldanga </script>
-6 1 2
Time Complexity: O(n Log n)
Method 3 (Efficient) In the second method we simply calculate the second maximum element of the array and print all element which is less than or equal to the second maximum.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find all elements// in array which have atleast two// greater elements itself.#include<bits/stdc++.h>using namespace std; void findElements(int arr[], int n){ int first = INT_MIN, second = INT_MIN; for (int i = 0; i < n; i++) { /* If current element is smaller than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) second = arr[i]; } for (int i = 0; i < n; i++) if (arr[i] < second) cout << arr[i] << " ";} // Driver codeint main(){ int arr[] = { 2, -6, 3, 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); findElements(arr, n); return 0;}
// Java program to find all elements// in array which have atleast// two greater elements itself.import java.util.*;import java.io.*; class GFG{ static void findElements(int arr[], int n){ int first = Integer.MIN_VALUE; int second = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { // If current element is smaller // than first then update both // first and second if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) second = arr[i]; } for (int i = 0; i < n; i++) if (arr[i] < second) System.out.print(arr[i] + " ") ;}// Driver codepublic static void main(String args[]){ int arr[] = { 2, -6, 3, 5, 1}; int n = arr.length; findElements(arr, n);}} // This code is contributed by Sahil_Bansall
# Python3 program to find all elements# in array which have atleast two# greater elements itself.import sys def findElements(arr, n): first = -sys.maxsize second = -sys.maxsize for i in range(0, n): # If current element is smaller # than first then update both # first and second if (arr[i] > first): second = first first = arr[i] # If arr[i] is in between first # and second then update second elif (arr[i] > second): second = arr[i] for i in range(0, n): if (arr[i] < second): print(arr[i], end =" ") # Driver codearr = [2, -6, 3, 5, 1]n = len(arr)findElements(arr, n) # This code is contributed# by Smitha Dinesh Semwal
// C# program to find all elements// in array which have atleast// two greater elements itself.using System; class GFG{ static void findElements(int []arr, int n) { int first = int.MinValue; int second = int.MaxValue; for (int i = 0; i < n; i++) { // If current element is smaller // than first then update both // first and second if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) second = arr[i]; } for (int i = 0; i < n; i++) if (arr[i] < second) Console.Write(arr[i] + " ") ;}// Driver codepublic static void Main(String []args){ int []arr = { 2, -6, 3, 5, 1}; int n = arr.Length; findElements(arr, n);}} // This code is contributed by parashar...
<?php// PHP program to find all elements// in array which have atleast two// greater elements itself. function findElements($arr, $n){ $first = PHP_INT_MIN; $second = PHP_INT_MIN; for ($i = 0; $i < $n; $i++) { /* If current element is smaller than first then update both first and second */ if ($arr[$i] > $first) { $second = $first; $first = $arr[$i]; } /* If arr[i] is in between first and second then update second */ else if ($arr[$i] > $second) $second = $arr[$i]; } for($i = 0; $i < $n; $i++) if ($arr[$i] < $second) echo $arr[$i] , " ";} // Driver code $arr = array(2, -6, 3, 5, 1); $n = count($arr); findElements($arr, $n); // This code is contributed by vishal tripathi.?>
<script> // Javascript program to find all elements// in array which have atleast// two greater elements itself. function findElements(arr, n){ let first = Number.MIN_VALUE; let second = Number.MAX_VALUE; for(let i = 0; i < n; i++) { // If current element is smaller // than first then update both // first and second if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) second = arr[i]; } for(let i = 0; i < n; i++) if (arr[i] < second) document.write(arr[i] + " ") ;} // Driver codelet arr = [ 2, -6, 3, 5, 1 ];let n = arr.length; findElements(arr, n); // This code is contributed by divyesh072019 </script>
2 -6 1
Time Complexity: O(n)
This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
parashar
jit_t
vt_m
prakharcsegbu
mayanktyagi1709
susmitakundugoaldanga
divyesh072019
Amazon
Order-Statistics
Arrays
Sorting
Amazon
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Maximum and minimum of an array using minimum number of comparisons | [
{
"code": null,
"e": 24784,
"s": 24756,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 24923,
"s": 24784,
"text": "Given an array of n distinct elements, the task is to find all elements in array which have at-least two greater elements than themselves."
},
{
"code": null,
"e": 24935,
"s": 24923,
"text": "Examples : "
},
{
"code": null,
"e": 25057,
"s": 24935,
"text": "Input : arr[] = {2, 8, 7, 1, 5};Output : 2 1 5 Explanation:The output three elements have two or more greater elements"
},
{
"code": null,
"e": 25130,
"s": 25057,
"text": "Explanation:Input : arr[] = {7, -2, 3, 4, 9, -1};Output : -2 3 4 -1 "
},
{
"code": null,
"e": 25346,
"s": 25130,
"text": "Method 1 (Simple) The naive approach is to run two loops and check one by one element of array check that array elements have at-least two elements greater than itself or not. If it’s true then print array element. "
},
{
"code": null,
"e": 25350,
"s": 25346,
"text": "C++"
},
{
"code": null,
"e": 25355,
"s": 25350,
"text": "Java"
},
{
"code": null,
"e": 25363,
"s": 25355,
"text": "Python3"
},
{
"code": null,
"e": 25366,
"s": 25363,
"text": "C#"
},
{
"code": null,
"e": 25370,
"s": 25366,
"text": "PHP"
},
{
"code": null,
"e": 25381,
"s": 25370,
"text": "Javascript"
},
{
"code": "// Simple C++ program to find// all elements in array which// have at-least two greater// elements itself.#include<bits/stdc++.h>using namespace std; void findElements(int arr[], int n){ // Pick elements one by one and // count greater elements. If // count is more than 2, print // that element. for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) if (arr[j] > arr[i]) count++; if (count >= 2) cout << arr[i] << \" \"; }} // Driver codeint main(){ int arr[] = { 2, -6 ,3 , 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); findElements(arr, n); return 0;}",
"e": 26044,
"s": 25381,
"text": null
},
{
"code": "// Java program to find all// elements in array which// have at-least two greater// elements itself.import java.util.*;import java.io.*; class GFG{ static void findElements(int arr[], int n){ // Pick elements one by one // and count greater elements. // If count is more than 2, // print that element. for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) if (arr[j] > arr[i]) count++; if (count >= 2) System.out.print(arr[i] + \" \"); }} // Driver codepublic static void main(String args[]){ int arr[] = { 2, -6 ,3 , 5, 1}; int n = arr.length; findElements(arr, n);}} // This code is contributed by Sahil_Bansall",
"e": 26800,
"s": 26044,
"text": null
},
{
"code": "# Python3 program to find# all elements in array# which have at-least two# greater elements itself. def findElements( arr, n): # Pick elements one by # one and count greater # elements. If count # is more than 2, print # that element. for i in range(n): count = 0 for j in range(0, n): if arr[j] > arr[i]: count = count + 1 if count >= 2 : print(arr[i], end=\" \") # Driver codearr = [ 2, -6 ,3 , 5, 1]n = len(arr)findElements(arr, n) # This code is contributed by sunnysingh",
"e": 27419,
"s": 26800,
"text": null
},
{
"code": "// C# program to find all elements in// array which have at least two greater// elements itself.using System; class GFG{ static void findElements(int []arr, int n){ // Pick elements one by one and count // greater elements. If count is more // than 2, print that element. for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) if (arr[j] > arr[i]) count++; if (count >= 2) Console.Write(arr[i] + \" \"); }} // Driver codepublic static void Main(String []args){ int []arr = {2, -6 ,3 , 5, 1}; int n = arr.Length; findElements(arr, n); }} // This code is contributed by Parashar.",
"e": 28104,
"s": 27419,
"text": null
},
{
"code": "<?php// Simple PHP program to find// all elements in array which// have at-least two greater// elements itself. function findElements($arr, $n){ // Pick elements one by one and // count greater elements. If // count is more than 2, // print that element. for ($i = 0; $i < $n; $i++) { $count = 0; for ($j = 0; $j < $n; $j++) if ($arr[$j] > $arr[$i]) $count++; if ($count >= 2) echo $arr[$i].\" \"; }} // Driver code$arr = array( 2, -6 ,3 , 5, 1);$n = sizeof($arr);findElements($arr, $n); ?>",
"e": 28673,
"s": 28104,
"text": null
},
{
"code": "<script> // Simple Javascript program to find// all elements in array which// have at-least two greater// elements itself. function findElements(arr, n){ // Pick elements one by one and // count greater elements. If // count is more than 2, print // that element. for (let i = 0; i < n; i++) { let count = 0; for (let j = 0; j < n; j++) if (arr[j] > arr[i]) count++; if (count >= 2) document.write(arr[i] + \" \"); }} // Driver code let arr = [2, -6 ,3 , 5, 1]; let n = arr.length; findElements(arr, n); // This is code is contributed by Mayank Tyagi </script>",
"e": 29323,
"s": 28673,
"text": null
},
{
"code": null,
"e": 29331,
"s": 29323,
"text": "2 -6 1 "
},
{
"code": null,
"e": 29354,
"s": 29331,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 29482,
"s": 29354,
"text": "Method 2 (Use Sorting) We sort the array first in increasing order, then we print first n-2 elements where n is size of array. "
},
{
"code": null,
"e": 29486,
"s": 29482,
"text": "C++"
},
{
"code": null,
"e": 29491,
"s": 29486,
"text": "Java"
},
{
"code": null,
"e": 29499,
"s": 29491,
"text": "Python3"
},
{
"code": null,
"e": 29502,
"s": 29499,
"text": "C#"
},
{
"code": null,
"e": 29506,
"s": 29502,
"text": "PHP"
},
{
"code": null,
"e": 29517,
"s": 29506,
"text": "Javascript"
},
{
"code": "// Sorting based C++ program to// find all elements in array// which have atleast two greater// elements itself.#include<bits/stdc++.h>using namespace std; void findElements(int arr[], int n){ sort(arr, arr + n); for (int i = 0; i < n - 2; i++) cout << arr[i] << \" \";} // Driver Codeint main(){ int arr[] = { 2, -6 ,3 , 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); findElements(arr, n); return 0;}",
"e": 29937,
"s": 29517,
"text": null
},
{
"code": "// Sorting based Java program to find// all elements in array which have// atleast two greater elements itself.import java.util.*;import java.io.*; class GFG{ static void findElements(int arr[], int n){ Arrays.sort(arr); for (int i = 0; i < n - 2; i++) System.out.print(arr[i] + \" \");} // Driver codepublic static void main(String args[]){ int arr[] = { 2, -6 ,3 , 5, 1}; int n = arr.length; findElements(arr, n); }} // This code is contributed by Sahil_Bansall",
"e": 30418,
"s": 29937,
"text": null
},
{
"code": "# Sorting based Python 3 program# to find all elements in array# which have atleast two greater# elements itself. def findElements(arr, n): arr.sort() for i in range(0, n-2): print(arr[i], end =\" \") # Driven sourcearr = [2, -6, 3, 5, 1]n = len(arr)findElements(arr, n) # This code is contributed# by Smitha Dinesh Semwal",
"e": 30754,
"s": 30418,
"text": null
},
{
"code": "// Sorting based C# program to find// all elements in array which have// atleast two greater elements itself.using System; class GFG{ static void findElements(int []arr, int n){ Array.Sort(arr); for (int i = 0; i < n-2; i++) Console.Write(arr[i] + \" \");} // Driver codepublic static void Main(String []args){ int []arr = { 2, -6 ,3 , 5, 1}; int n = arr.Length; findElements(arr, n); }} // This code is contributed by parashar",
"e": 31203,
"s": 30754,
"text": null
},
{
"code": "<?php// Sorting based PHP program to// find all elements in array// which have atleast two greater// elements itself. function findElements( $arr, $n){ sort($arr); for ($i = 0; $i < $n - 2; $i++) echo $arr[$i] , \" \";} // Driver Code$arr = array( 2, -6 ,3 , 5, 1);$n = count($arr);findElements($arr, $n); // This code is contributed by anuj_67.?>;",
"e": 31560,
"s": 31203,
"text": null
},
{
"code": "<script> // Sorting based Javascript program to find // all elements in array which have // atleast two greater elements itself.function findElements(arr, n){ arr.sort(); for(let i = 0; i < n - 2; i++) document.write(arr[i] + \" \");} // Driver code let arr = [ 2, -6 ,3 , 5, 1];let n = arr.length; findElements(arr, n); // This code is contributed by susmitakundugoaldanga </script>",
"e": 31966,
"s": 31560,
"text": null
},
{
"code": null,
"e": 31974,
"s": 31966,
"text": "-6 1 2 "
},
{
"code": null,
"e": 32002,
"s": 31974,
"text": "Time Complexity: O(n Log n)"
},
{
"code": null,
"e": 32178,
"s": 32002,
"text": "Method 3 (Efficient) In the second method we simply calculate the second maximum element of the array and print all element which is less than or equal to the second maximum. "
},
{
"code": null,
"e": 32182,
"s": 32178,
"text": "C++"
},
{
"code": null,
"e": 32187,
"s": 32182,
"text": "Java"
},
{
"code": null,
"e": 32195,
"s": 32187,
"text": "Python3"
},
{
"code": null,
"e": 32198,
"s": 32195,
"text": "C#"
},
{
"code": null,
"e": 32202,
"s": 32198,
"text": "PHP"
},
{
"code": null,
"e": 32213,
"s": 32202,
"text": "Javascript"
},
{
"code": "// C++ program to find all elements// in array which have atleast two// greater elements itself.#include<bits/stdc++.h>using namespace std; void findElements(int arr[], int n){ int first = INT_MIN, second = INT_MIN; for (int i = 0; i < n; i++) { /* If current element is smaller than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) second = arr[i]; } for (int i = 0; i < n; i++) if (arr[i] < second) cout << arr[i] << \" \";} // Driver codeint main(){ int arr[] = { 2, -6, 3, 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); findElements(arr, n); return 0;}",
"e": 33058,
"s": 32213,
"text": null
},
{
"code": "// Java program to find all elements// in array which have atleast// two greater elements itself.import java.util.*;import java.io.*; class GFG{ static void findElements(int arr[], int n){ int first = Integer.MIN_VALUE; int second = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { // If current element is smaller // than first then update both // first and second if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) second = arr[i]; } for (int i = 0; i < n; i++) if (arr[i] < second) System.out.print(arr[i] + \" \") ;}// Driver codepublic static void main(String args[]){ int arr[] = { 2, -6, 3, 5, 1}; int n = arr.length; findElements(arr, n);}} // This code is contributed by Sahil_Bansall",
"e": 34006,
"s": 33058,
"text": null
},
{
"code": "# Python3 program to find all elements# in array which have atleast two# greater elements itself.import sys def findElements(arr, n): first = -sys.maxsize second = -sys.maxsize for i in range(0, n): # If current element is smaller # than first then update both # first and second if (arr[i] > first): second = first first = arr[i] # If arr[i] is in between first # and second then update second elif (arr[i] > second): second = arr[i] for i in range(0, n): if (arr[i] < second): print(arr[i], end =\" \") # Driver codearr = [2, -6, 3, 5, 1]n = len(arr)findElements(arr, n) # This code is contributed# by Smitha Dinesh Semwal",
"e": 34772,
"s": 34006,
"text": null
},
{
"code": "// C# program to find all elements// in array which have atleast// two greater elements itself.using System; class GFG{ static void findElements(int []arr, int n) { int first = int.MinValue; int second = int.MaxValue; for (int i = 0; i < n; i++) { // If current element is smaller // than first then update both // first and second if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) second = arr[i]; } for (int i = 0; i < n; i++) if (arr[i] < second) Console.Write(arr[i] + \" \") ;}// Driver codepublic static void Main(String []args){ int []arr = { 2, -6, 3, 5, 1}; int n = arr.Length; findElements(arr, n);}} // This code is contributed by parashar...",
"e": 35710,
"s": 34772,
"text": null
},
{
"code": "<?php// PHP program to find all elements// in array which have atleast two// greater elements itself. function findElements($arr, $n){ $first = PHP_INT_MIN; $second = PHP_INT_MIN; for ($i = 0; $i < $n; $i++) { /* If current element is smaller than first then update both first and second */ if ($arr[$i] > $first) { $second = $first; $first = $arr[$i]; } /* If arr[i] is in between first and second then update second */ else if ($arr[$i] > $second) $second = $arr[$i]; } for($i = 0; $i < $n; $i++) if ($arr[$i] < $second) echo $arr[$i] , \" \";} // Driver code $arr = array(2, -6, 3, 5, 1); $n = count($arr); findElements($arr, $n); // This code is contributed by vishal tripathi.?>",
"e": 36608,
"s": 35710,
"text": null
},
{
"code": "<script> // Javascript program to find all elements// in array which have atleast// two greater elements itself. function findElements(arr, n){ let first = Number.MIN_VALUE; let second = Number.MAX_VALUE; for(let i = 0; i < n; i++) { // If current element is smaller // than first then update both // first and second if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) second = arr[i]; } for(let i = 0; i < n; i++) if (arr[i] < second) document.write(arr[i] + \" \") ;} // Driver codelet arr = [ 2, -6, 3, 5, 1 ];let n = arr.length; findElements(arr, n); // This code is contributed by divyesh072019 </script>",
"e": 37480,
"s": 36608,
"text": null
},
{
"code": null,
"e": 37488,
"s": 37480,
"text": "2 -6 1 "
},
{
"code": null,
"e": 37510,
"s": 37488,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 37929,
"s": 37510,
"text": "This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 37938,
"s": 37929,
"text": "parashar"
},
{
"code": null,
"e": 37944,
"s": 37938,
"text": "jit_t"
},
{
"code": null,
"e": 37949,
"s": 37944,
"text": "vt_m"
},
{
"code": null,
"e": 37963,
"s": 37949,
"text": "prakharcsegbu"
},
{
"code": null,
"e": 37979,
"s": 37963,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 38001,
"s": 37979,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 38015,
"s": 38001,
"text": "divyesh072019"
},
{
"code": null,
"e": 38022,
"s": 38015,
"text": "Amazon"
},
{
"code": null,
"e": 38039,
"s": 38022,
"text": "Order-Statistics"
},
{
"code": null,
"e": 38046,
"s": 38039,
"text": "Arrays"
},
{
"code": null,
"e": 38054,
"s": 38046,
"text": "Sorting"
},
{
"code": null,
"e": 38061,
"s": 38054,
"text": "Amazon"
},
{
"code": null,
"e": 38068,
"s": 38061,
"text": "Arrays"
},
{
"code": null,
"e": 38076,
"s": 38068,
"text": "Sorting"
},
{
"code": null,
"e": 38174,
"s": 38076,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38183,
"s": 38174,
"text": "Comments"
},
{
"code": null,
"e": 38196,
"s": 38183,
"text": "Old Comments"
},
{
"code": null,
"e": 38240,
"s": 38196,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 38263,
"s": 38240,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 38295,
"s": 38263,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 38309,
"s": 38295,
"text": "Linear Search"
}
]
|
Find minimum sum of factors of number using C++. | Here we will see how to get a minimum sum of factors of a given number. Suppose a number is 12. We can factorize this in different ways −
12 = 12 * 1 (12 + 1 = 13)
12 = 2 * 6 (2 + 6 = 8)
12 = 3 * 4 (3 + 4 = 7)
12 = 2 * 2 * 3 (2 + 2 + 3 = 7)
The minimum sum is 7. We will take a number, and try to find the minimum factor sum. To get the minimum factor sum, we have to factorize the number as long as possible. In other words, we can say if we try to find the sum S by adding prime factors, then the sum will be minimized.
Live Demo
#include<iostream>
using namespace std;
int primeFactorSum(int n) {
int s = 0;
for (int i = 2; i * i <= n; i++) {
while (n % i == 0) {
s += i;
n /= i;
}
}
s += n;
return s;
}
int main() {
int n = 12;
cout << "Minimum sum of factors: " << primeFactorSum(n);
}
Minimum sum of factors: 7 | [
{
"code": null,
"e": 1200,
"s": 1062,
"text": "Here we will see how to get a minimum sum of factors of a given number. Suppose a number is 12. We can factorize this in different ways −"
},
{
"code": null,
"e": 1226,
"s": 1200,
"text": "12 = 12 * 1 (12 + 1 = 13)"
},
{
"code": null,
"e": 1249,
"s": 1226,
"text": "12 = 2 * 6 (2 + 6 = 8)"
},
{
"code": null,
"e": 1272,
"s": 1249,
"text": "12 = 3 * 4 (3 + 4 = 7)"
},
{
"code": null,
"e": 1303,
"s": 1272,
"text": "12 = 2 * 2 * 3 (2 + 2 + 3 = 7)"
},
{
"code": null,
"e": 1584,
"s": 1303,
"text": "The minimum sum is 7. We will take a number, and try to find the minimum factor sum. To get the minimum factor sum, we have to factorize the number as long as possible. In other words, we can say if we try to find the sum S by adding prime factors, then the sum will be minimized."
},
{
"code": null,
"e": 1595,
"s": 1584,
"text": " Live Demo"
},
{
"code": null,
"e": 1905,
"s": 1595,
"text": "#include<iostream>\nusing namespace std;\nint primeFactorSum(int n) {\n int s = 0;\n for (int i = 2; i * i <= n; i++) {\n while (n % i == 0) {\n s += i;\n n /= i;\n }\n }\n s += n;\n return s;\n}\nint main() {\n int n = 12;\n cout << \"Minimum sum of factors: \" << primeFactorSum(n);\n}"
},
{
"code": null,
"e": 1931,
"s": 1905,
"text": "Minimum sum of factors: 7"
}
]
|
SAP ABAP - Constants & Literals | Literals are unnamed data objects that you create within the source code of a program. They are fully defined by their value. You can’t change the value of a literal. Constants are named data objects created statically by using declarative statements. A constant is declared by assigning a value to it that is stored in the program's memory area. The value assigned to a constant can’t be changed during the execution of the program. These fixed values can also be considered as literals. There are two types of literals − numeric and character.
Number literals are sequences of digits which can have a prefixed sign. In number literals, there are no decimal separators and no notation with mantissa and exponent.
Following are some examples of numeric literals −
183.
-97.
+326.
Character literals are sequences of alphanumeric characters in the source code of an ABAP program enclosed in single quotation marks. Character literals enclosed in quotation marks have the predefined ABAP type C and are described as text field literals. Literals enclosed in “back quotes” have the ABAP type STRING and are described as string literals. The field length is defined by the number of characters.
Note − In text field literals, trailing blanks are ignored, but in string literals they are taken into account.
Following are some examples of character literals.
REPORT YR_SEP_12.
Write 'Tutorials Point'.
Write / 'ABAP Tutorial'.
REPORT YR_SEP_12.
Write `Tutorials Point `.
Write / `ABAP Tutorial `.
The output is same in both the above cases −
Tutorials Point
ABAP Tutorial
Note − When we try to change the value of the constant, a syntax or run-time error may occur. Constants that you declare in the declaration part of a class or an interface belong to the static attributes of that class or interface.
We can declare the named data objects with the help of CONSTANTS statement.
Following is the syntax −
CONSTANTS <f> TYPE <type> VALUE <val>.
The CONSTANTS statement is similar to the DATA statement.
<f> specifies a name for the constant. TYPE <type> represents a constant named <f>, which inherits the same technical attributes as the existing data type <type>. VALUE <val> assigns an initial value to the declared constant name <f>.
Note − We should use the VALUE clause in the CONSTANTS statement. The clause ‘VALUE’ is used to assign an initial value to the constant during its declaration.
We have 3 types of constants such as elementary, complex and reference constants. The following statement shows how to define constants by using the CONSTANTS statement −
REPORT YR_SEP_12.
CONSTANTS PQR TYPE P DECIMALS 4 VALUE '1.2356'.
Write: / 'The value of PQR is:', PQR.
The output is −
The value of PQR is: 1.2356
Here it refers to elementary data type and is known as elementary constant.
Following is an example for complex constants −
BEGIN OF EMPLOYEE,
Name(25) TYPE C VALUE 'Management Team',
Organization(40) TYPE C VALUE 'Tutorials Point Ltd',
Place(10) TYPE C VALUE 'India',
END OF EMPLOYEE.
In the above code snippet, EMPLOYEE is a complex constant that is composed of the Name, Organization and Place fields.
The following statement declares a constant reference −
CONSTANTS null_pointer TYPE REF TO object VALUE IS INITIAL.
We can use the constant reference in comparisons or we may pass it on to procedures.
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": 3444,
"s": 2898,
"text": "Literals are unnamed data objects that you create within the source code of a program. They are fully defined by their value. You can’t change the value of a literal. Constants are named data objects created statically by using declarative statements. A constant is declared by assigning a value to it that is stored in the program's memory area. The value assigned to a constant can’t be changed during the execution of the program. These fixed values can also be considered as literals. There are two types of literals − numeric and character."
},
{
"code": null,
"e": 3612,
"s": 3444,
"text": "Number literals are sequences of digits which can have a prefixed sign. In number literals, there are no decimal separators and no notation with mantissa and exponent."
},
{
"code": null,
"e": 3662,
"s": 3612,
"text": "Following are some examples of numeric literals −"
},
{
"code": null,
"e": 3681,
"s": 3662,
"text": "183. \n-97. \n+326.\n"
},
{
"code": null,
"e": 4092,
"s": 3681,
"text": "Character literals are sequences of alphanumeric characters in the source code of an ABAP program enclosed in single quotation marks. Character literals enclosed in quotation marks have the predefined ABAP type C and are described as text field literals. Literals enclosed in “back quotes” have the ABAP type STRING and are described as string literals. The field length is defined by the number of characters."
},
{
"code": null,
"e": 4204,
"s": 4092,
"text": "Note − In text field literals, trailing blanks are ignored, but in string literals they are taken into account."
},
{
"code": null,
"e": 4255,
"s": 4204,
"text": "Following are some examples of character literals."
},
{
"code": null,
"e": 4327,
"s": 4255,
"text": "REPORT YR_SEP_12. \nWrite 'Tutorials Point'. \nWrite / 'ABAP Tutorial'. "
},
{
"code": null,
"e": 4400,
"s": 4327,
"text": "REPORT YR_SEP_12. \nWrite `Tutorials Point `. \nWrite / `ABAP Tutorial `. "
},
{
"code": null,
"e": 4445,
"s": 4400,
"text": "The output is same in both the above cases −"
},
{
"code": null,
"e": 4478,
"s": 4445,
"text": "Tutorials Point \nABAP Tutorial\n"
},
{
"code": null,
"e": 4710,
"s": 4478,
"text": "Note − When we try to change the value of the constant, a syntax or run-time error may occur. Constants that you declare in the declaration part of a class or an interface belong to the static attributes of that class or interface."
},
{
"code": null,
"e": 4786,
"s": 4710,
"text": "We can declare the named data objects with the help of CONSTANTS statement."
},
{
"code": null,
"e": 4812,
"s": 4786,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 4851,
"s": 4812,
"text": "CONSTANTS <f> TYPE <type> VALUE <val>."
},
{
"code": null,
"e": 4909,
"s": 4851,
"text": "The CONSTANTS statement is similar to the DATA statement."
},
{
"code": null,
"e": 5144,
"s": 4909,
"text": "<f> specifies a name for the constant. TYPE <type> represents a constant named <f>, which inherits the same technical attributes as the existing data type <type>. VALUE <val> assigns an initial value to the declared constant name <f>."
},
{
"code": null,
"e": 5304,
"s": 5144,
"text": "Note − We should use the VALUE clause in the CONSTANTS statement. The clause ‘VALUE’ is used to assign an initial value to the constant during its declaration."
},
{
"code": null,
"e": 5475,
"s": 5304,
"text": "We have 3 types of constants such as elementary, complex and reference constants. The following statement shows how to define constants by using the CONSTANTS statement −"
},
{
"code": null,
"e": 5581,
"s": 5475,
"text": "REPORT YR_SEP_12. \nCONSTANTS PQR TYPE P DECIMALS 4 VALUE '1.2356'. \nWrite: / 'The value of PQR is:', PQR."
},
{
"code": null,
"e": 5597,
"s": 5581,
"text": "The output is −"
},
{
"code": null,
"e": 5626,
"s": 5597,
"text": "The value of PQR is: 1.2356\n"
},
{
"code": null,
"e": 5702,
"s": 5626,
"text": "Here it refers to elementary data type and is known as elementary constant."
},
{
"code": null,
"e": 5750,
"s": 5702,
"text": "Following is an example for complex constants −"
},
{
"code": null,
"e": 5920,
"s": 5750,
"text": "BEGIN OF EMPLOYEE, \nName(25) TYPE C VALUE 'Management Team', \nOrganization(40) TYPE C VALUE 'Tutorials Point Ltd', \nPlace(10) TYPE C VALUE 'India', \nEND OF EMPLOYEE."
},
{
"code": null,
"e": 6039,
"s": 5920,
"text": "In the above code snippet, EMPLOYEE is a complex constant that is composed of the Name, Organization and Place fields."
},
{
"code": null,
"e": 6095,
"s": 6039,
"text": "The following statement declares a constant reference −"
},
{
"code": null,
"e": 6156,
"s": 6095,
"text": "CONSTANTS null_pointer TYPE REF TO object VALUE IS INITIAL.\n"
},
{
"code": null,
"e": 6241,
"s": 6156,
"text": "We can use the constant reference in comparisons or we may pass it on to procedures."
},
{
"code": null,
"e": 6274,
"s": 6241,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6288,
"s": 6274,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 6321,
"s": 6288,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6333,
"s": 6321,
"text": " Neha Gupta"
},
{
"code": null,
"e": 6368,
"s": 6333,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6383,
"s": 6368,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 6416,
"s": 6383,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6431,
"s": 6416,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 6466,
"s": 6431,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6478,
"s": 6466,
"text": " Neha Malik"
},
{
"code": null,
"e": 6513,
"s": 6478,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6525,
"s": 6513,
"text": " Neha Malik"
},
{
"code": null,
"e": 6532,
"s": 6525,
"text": " Print"
},
{
"code": null,
"e": 6543,
"s": 6532,
"text": " Add Notes"
}
]
|
Convert Snake Case string to Camel Case in Java - GeeksforGeeks | 01 Aug, 2020
Given a string in Snake Case, the task is to write a Java program to convert the given string from snake case to camel case and print the modified string.
Examples:
Input: str = “geeks_for_geeks”Output: GeeksForGeeks
Input: str = “snake_case_to_camel_case”Output: SnakeCaseToCamelCase
The idea is to first capitalize the first letter of the string.Then convert the string to string builder.Then traverse the string character by character from the first index to the last index and check if the character is underscored then delete the character and capitalize the next character of the underscore.Print the modified string.
The idea is to first capitalize the first letter of the string.
Then convert the string to string builder.
Then traverse the string character by character from the first index to the last index and check if the character is underscored then delete the character and capitalize the next character of the underscore.
Print the modified string.
Below is the implementation of the above approach:
Java
// Java program for the above approach import java.io.*; class GFG { // Function to convert snake case // to camel case public static String snakeToCamel(String str) { // Capitalize first letter of string str = str.substring(0, 1).toUpperCase() + str.substring(1); // Convert to StringBuilder StringBuilder builder = new StringBuilder(str); // Traverse the string character by // character and remove underscore // and capitalize next letter for (int i = 0; i < builder.length(); i++) { // Check char is underscore if (builder.charAt(i) == '_') { builder.deleteCharAt(i); builder.replace( i, i + 1, String.valueOf( Character.toUpperCase( builder.charAt(i)))); } } // Return in String type return builder.toString(); } // Driver Code public static void main(String[] args) { // Given String String str = "geeks_for_geeks"; // Function Call str = snakeToCamel(str); // Modified String System.out.println(str); }}
GeeksForGeeks
Method 2: Using String.replaceFirst() method
The idea is to use String.replaceFirst() method to convert the given string from snake case to camel case.First, capitalize the first letter of the string.Run a loop till the string contains underscore (_).Replace the first occurrence of a letter that present after the underscore to the capitalized form of the next letter of the underscore.Print the modified string.
The idea is to use String.replaceFirst() method to convert the given string from snake case to camel case.
First, capitalize the first letter of the string.
Run a loop till the string contains underscore (_).
Replace the first occurrence of a letter that present after the underscore to the capitalized form of the next letter of the underscore.
Print the modified string.
Below is the implementation of the above approach:
Java
// Java program for the above approach class GFG { // Function to convert the string // from snake case to camel case public static String snakeToCamel(String str) { // Capitalize first letter of string str = str.substring(0, 1).toUpperCase() + str.substring(1); // Run a loop till string // string contains underscore while (str.contains("_")) { // Replace the first occurrence // of letter that present after // the underscore, to capitalize // form of next letter of underscore str = str .replaceFirst( "_[a-z]", String.valueOf( Character.toUpperCase( str.charAt( str.indexOf("_") + 1)))); } // Return string return str; } // Driver Code public static void main(String args[]) { // Given string String str = "geeks_for_geeks"; // Print the modified string System.out.print(snakeToCamel(str)); }}
GeeksForGeeks
Java-String-Programs
strings
Java Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Iterate HashMap in Java?
Iterate through List in Java
Java Program to Remove Duplicate Elements From the Array
Factory method design pattern in Java
Iterate Over the Characters of a String in Java
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string | [
{
"code": null,
"e": 24548,
"s": 24520,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 24703,
"s": 24548,
"text": "Given a string in Snake Case, the task is to write a Java program to convert the given string from snake case to camel case and print the modified string."
},
{
"code": null,
"e": 24713,
"s": 24703,
"text": "Examples:"
},
{
"code": null,
"e": 24765,
"s": 24713,
"text": "Input: str = “geeks_for_geeks”Output: GeeksForGeeks"
},
{
"code": null,
"e": 24833,
"s": 24765,
"text": "Input: str = “snake_case_to_camel_case”Output: SnakeCaseToCamelCase"
},
{
"code": null,
"e": 25172,
"s": 24833,
"text": "The idea is to first capitalize the first letter of the string.Then convert the string to string builder.Then traverse the string character by character from the first index to the last index and check if the character is underscored then delete the character and capitalize the next character of the underscore.Print the modified string."
},
{
"code": null,
"e": 25236,
"s": 25172,
"text": "The idea is to first capitalize the first letter of the string."
},
{
"code": null,
"e": 25279,
"s": 25236,
"text": "Then convert the string to string builder."
},
{
"code": null,
"e": 25487,
"s": 25279,
"text": "Then traverse the string character by character from the first index to the last index and check if the character is underscored then delete the character and capitalize the next character of the underscore."
},
{
"code": null,
"e": 25514,
"s": 25487,
"text": "Print the modified string."
},
{
"code": null,
"e": 25565,
"s": 25514,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25570,
"s": 25565,
"text": "Java"
},
{
"code": "// Java program for the above approach import java.io.*; class GFG { // Function to convert snake case // to camel case public static String snakeToCamel(String str) { // Capitalize first letter of string str = str.substring(0, 1).toUpperCase() + str.substring(1); // Convert to StringBuilder StringBuilder builder = new StringBuilder(str); // Traverse the string character by // character and remove underscore // and capitalize next letter for (int i = 0; i < builder.length(); i++) { // Check char is underscore if (builder.charAt(i) == '_') { builder.deleteCharAt(i); builder.replace( i, i + 1, String.valueOf( Character.toUpperCase( builder.charAt(i)))); } } // Return in String type return builder.toString(); } // Driver Code public static void main(String[] args) { // Given String String str = \"geeks_for_geeks\"; // Function Call str = snakeToCamel(str); // Modified String System.out.println(str); }}",
"e": 26834,
"s": 25570,
"text": null
},
{
"code": null,
"e": 26849,
"s": 26834,
"text": "GeeksForGeeks\n"
},
{
"code": null,
"e": 26894,
"s": 26849,
"text": "Method 2: Using String.replaceFirst() method"
},
{
"code": null,
"e": 27263,
"s": 26894,
"text": "The idea is to use String.replaceFirst() method to convert the given string from snake case to camel case.First, capitalize the first letter of the string.Run a loop till the string contains underscore (_).Replace the first occurrence of a letter that present after the underscore to the capitalized form of the next letter of the underscore.Print the modified string."
},
{
"code": null,
"e": 27370,
"s": 27263,
"text": "The idea is to use String.replaceFirst() method to convert the given string from snake case to camel case."
},
{
"code": null,
"e": 27420,
"s": 27370,
"text": "First, capitalize the first letter of the string."
},
{
"code": null,
"e": 27472,
"s": 27420,
"text": "Run a loop till the string contains underscore (_)."
},
{
"code": null,
"e": 27609,
"s": 27472,
"text": "Replace the first occurrence of a letter that present after the underscore to the capitalized form of the next letter of the underscore."
},
{
"code": null,
"e": 27636,
"s": 27609,
"text": "Print the modified string."
},
{
"code": null,
"e": 27687,
"s": 27636,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27692,
"s": 27687,
"text": "Java"
},
{
"code": "// Java program for the above approach class GFG { // Function to convert the string // from snake case to camel case public static String snakeToCamel(String str) { // Capitalize first letter of string str = str.substring(0, 1).toUpperCase() + str.substring(1); // Run a loop till string // string contains underscore while (str.contains(\"_\")) { // Replace the first occurrence // of letter that present after // the underscore, to capitalize // form of next letter of underscore str = str .replaceFirst( \"_[a-z]\", String.valueOf( Character.toUpperCase( str.charAt( str.indexOf(\"_\") + 1)))); } // Return string return str; } // Driver Code public static void main(String args[]) { // Given string String str = \"geeks_for_geeks\"; // Print the modified string System.out.print(snakeToCamel(str)); }}",
"e": 28859,
"s": 27692,
"text": null
},
{
"code": null,
"e": 28874,
"s": 28859,
"text": "GeeksForGeeks\n"
},
{
"code": null,
"e": 28895,
"s": 28874,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 28903,
"s": 28895,
"text": "strings"
},
{
"code": null,
"e": 28917,
"s": 28903,
"text": "Java Programs"
},
{
"code": null,
"e": 28925,
"s": 28917,
"text": "Strings"
},
{
"code": null,
"e": 28933,
"s": 28925,
"text": "Strings"
},
{
"code": null,
"e": 29031,
"s": 28933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29040,
"s": 29031,
"text": "Comments"
},
{
"code": null,
"e": 29053,
"s": 29040,
"text": "Old Comments"
},
{
"code": null,
"e": 29085,
"s": 29053,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 29114,
"s": 29085,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 29171,
"s": 29114,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 29209,
"s": 29171,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 29257,
"s": 29209,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 29282,
"s": 29257,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 29328,
"s": 29282,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 29362,
"s": 29328,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 29377,
"s": 29362,
"text": "C++ Data Types"
}
]
|
C# | Remove all elements from the ArrayList - GeeksforGeeks | 01 Feb, 2019
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Clear method is used to remove all the elements from the ArrayList.
Properties:
Elements can be added or removed from the Array List collection at any point in time.
The ArrayList is not guaranteed to be sorted.
The capacity of an ArrayList is the number of elements the ArrayList can hold.
Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
It also allows duplicate elements.
Using multidimensional arrays as elements in an ArrayList collection is not supported.
Syntax:
public virtual void Clear ();
Exceptions: This method will give NotSupportedException if the ArrayList is read-only or the ArrayList has a fixed size.
Note:
This method is an O(n) operation, where n is Count.
Count is set to zero, and references to other objects from elements of the collection are also released.
Capacity remains unchanged.
Below programs illustrate the use of ArrayList.Clear Method:
Example 1 :
// C# code to remove all elements// from an ArrayListusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(10); // Adding elements to ArrayList myList.Add("A"); myList.Add("B"); myList.Add("C"); myList.Add("D"); myList.Add("E"); myList.Add("F"); // Displaying the elements in ArrayList Console.WriteLine("Number of elements in ArrayList initially : " + myList.Count); // Removing all elements from ArrayList myList.Clear(); // Displaying the elements in ArrayList // after Removing all the elements Console.WriteLine("Number of elements in ArrayList : " + myList.Count); }}
Number of elements in ArrayList initially : 6
Number of elements in ArrayList : 0
Example 2:
// C# code to remove all elements// from an ArrayListusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(10); // Adding elements to ArrayList myList.Add(3); myList.Add(5); myList.Add(7); myList.Add(9); myList.Add(11); // Displaying the elements in ArrayList Console.WriteLine("Number of elements in ArrayList initially : " + myList.Count); // Removing all elements from ArrayList myList.Clear(); // Displaying the elements in ArrayList // after Removing all the elements Console.WriteLine("Number of elements in ArrayList : " + myList.Count); }}
Number of elements in ArrayList initially : 5
Number of elements in ArrayList : 0
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.clear?view=netframework-4.7.2
CSharp-Collections-ArrayList
CSharp-Collections-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Replace() Method
C# | Class and Object
Introduction to .NET Framework
C# | Constructors | [
{
"code": null,
"e": 26343,
"s": 26315,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 26646,
"s": 26343,
"text": "ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Clear method is used to remove all the elements from the ArrayList."
},
{
"code": null,
"e": 26658,
"s": 26646,
"text": "Properties:"
},
{
"code": null,
"e": 26744,
"s": 26658,
"text": "Elements can be added or removed from the Array List collection at any point in time."
},
{
"code": null,
"e": 26790,
"s": 26744,
"text": "The ArrayList is not guaranteed to be sorted."
},
{
"code": null,
"e": 26869,
"s": 26790,
"text": "The capacity of an ArrayList is the number of elements the ArrayList can hold."
},
{
"code": null,
"e": 26980,
"s": 26869,
"text": "Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based."
},
{
"code": null,
"e": 27015,
"s": 26980,
"text": "It also allows duplicate elements."
},
{
"code": null,
"e": 27102,
"s": 27015,
"text": "Using multidimensional arrays as elements in an ArrayList collection is not supported."
},
{
"code": null,
"e": 27110,
"s": 27102,
"text": "Syntax:"
},
{
"code": null,
"e": 27141,
"s": 27110,
"text": "public virtual void Clear ();\n"
},
{
"code": null,
"e": 27262,
"s": 27141,
"text": "Exceptions: This method will give NotSupportedException if the ArrayList is read-only or the ArrayList has a fixed size."
},
{
"code": null,
"e": 27268,
"s": 27262,
"text": "Note:"
},
{
"code": null,
"e": 27320,
"s": 27268,
"text": "This method is an O(n) operation, where n is Count."
},
{
"code": null,
"e": 27425,
"s": 27320,
"text": "Count is set to zero, and references to other objects from elements of the collection are also released."
},
{
"code": null,
"e": 27453,
"s": 27425,
"text": "Capacity remains unchanged."
},
{
"code": null,
"e": 27514,
"s": 27453,
"text": "Below programs illustrate the use of ArrayList.Clear Method:"
},
{
"code": null,
"e": 27526,
"s": 27514,
"text": "Example 1 :"
},
{
"code": "// C# code to remove all elements// from an ArrayListusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(10); // Adding elements to ArrayList myList.Add(\"A\"); myList.Add(\"B\"); myList.Add(\"C\"); myList.Add(\"D\"); myList.Add(\"E\"); myList.Add(\"F\"); // Displaying the elements in ArrayList Console.WriteLine(\"Number of elements in ArrayList initially : \" + myList.Count); // Removing all elements from ArrayList myList.Clear(); // Displaying the elements in ArrayList // after Removing all the elements Console.WriteLine(\"Number of elements in ArrayList : \" + myList.Count); }}",
"e": 28391,
"s": 27526,
"text": null
},
{
"code": null,
"e": 28474,
"s": 28391,
"text": "Number of elements in ArrayList initially : 6\nNumber of elements in ArrayList : 0\n"
},
{
"code": null,
"e": 28485,
"s": 28474,
"text": "Example 2:"
},
{
"code": "// C# code to remove all elements// from an ArrayListusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(10); // Adding elements to ArrayList myList.Add(3); myList.Add(5); myList.Add(7); myList.Add(9); myList.Add(11); // Displaying the elements in ArrayList Console.WriteLine(\"Number of elements in ArrayList initially : \" + myList.Count); // Removing all elements from ArrayList myList.Clear(); // Displaying the elements in ArrayList // after Removing all the elements Console.WriteLine(\"Number of elements in ArrayList : \" + myList.Count); }}",
"e": 29319,
"s": 28485,
"text": null
},
{
"code": null,
"e": 29402,
"s": 29319,
"text": "Number of elements in ArrayList initially : 5\nNumber of elements in ArrayList : 0\n"
},
{
"code": null,
"e": 29413,
"s": 29402,
"text": "Reference:"
},
{
"code": null,
"e": 29516,
"s": 29413,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.clear?view=netframework-4.7.2"
},
{
"code": null,
"e": 29545,
"s": 29516,
"text": "CSharp-Collections-ArrayList"
},
{
"code": null,
"e": 29574,
"s": 29545,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 29588,
"s": 29574,
"text": "CSharp-method"
},
{
"code": null,
"e": 29591,
"s": 29588,
"text": "C#"
},
{
"code": null,
"e": 29689,
"s": 29591,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29717,
"s": 29689,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 29732,
"s": 29717,
"text": "C# | Delegates"
},
{
"code": null,
"e": 29755,
"s": 29732,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 29777,
"s": 29755,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 29823,
"s": 29777,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 29846,
"s": 29823,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29868,
"s": 29846,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 29890,
"s": 29868,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 29921,
"s": 29890,
"text": "Introduction to .NET Framework"
}
]
|
ArrayList iterator() method in Java with Examples - GeeksforGeeks | 11 Dec, 2018
The iterator() method of ArrayList class in Java Collection Framework is used to get an iterator over the elements in this list in proper sequence. The returned iterator is fail-fast.
Syntax:
Iterator iterator()
Parameter: This method do not accept any parameter.
Return Value: This method returns an iterator over the elements in this list in proper sequence
Below examples illustrate the ArrayList.iterator() method:
Program 1:
// Java code to illustrate iterator() import java.util.*; public class GFG { public static void main(String[] args) { // Create and populate the list ArrayList<String> list = new ArrayList<>(); list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("is"); list.add("a"); list.add("CS"); list.add("Students"); list.add("Portal"); // Displaying the list System.out.println("The list is: \n" + list); // Create an iterator for the list // using iterator() method Iterator<String> iter = list.iterator(); // Displaying the values after iterating // through the list System.out.println("\nThe iterator values" + " of list are: "); while (iter.hasNext()) { System.out.print(iter.next() + " "); } }}
The list is:
[Geeks, for, Geeks, is, a, CS, Students, Portal]
The iterator values of list are:
Geeks for Geeks is a CS Students Portal
Program 2:
// Java code to illustrate iterator() import java.util.*; public class GFG { public static void main(String args[]) { // Creating an empty ArrayList ArrayList<Integer> list = new ArrayList<Integer>(); // Use add() method to add // elements into the list list.add(10); list.add(15); list.add(30); list.add(20); list.add(5); // Displaying the list System.out.println("The list is: \n" + list); // Create an iterator for the list // using iterator() method Iterator<Integer> iter = list.iterator(); // Displaying the values // after iterating through the list System.out.println("\nThe iterator values" + " of list are: "); while (iter.hasNext()) { System.out.print(iter.next() + " "); } }}
The list is:
[10, 15, 30, 20, 5]
The iterator values of list are:
10 15 30 20 5
Java-ArrayList
Java-Collections
Java-Functions
Picked
Technical Scripter 2018
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Overriding in Java
Stack Class in Java
Set in Java | [
{
"code": null,
"e": 23970,
"s": 23942,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 24154,
"s": 23970,
"text": "The iterator() method of ArrayList class in Java Collection Framework is used to get an iterator over the elements in this list in proper sequence. The returned iterator is fail-fast."
},
{
"code": null,
"e": 24162,
"s": 24154,
"text": "Syntax:"
},
{
"code": null,
"e": 24183,
"s": 24162,
"text": " Iterator iterator()"
},
{
"code": null,
"e": 24235,
"s": 24183,
"text": "Parameter: This method do not accept any parameter."
},
{
"code": null,
"e": 24331,
"s": 24235,
"text": "Return Value: This method returns an iterator over the elements in this list in proper sequence"
},
{
"code": null,
"e": 24390,
"s": 24331,
"text": "Below examples illustrate the ArrayList.iterator() method:"
},
{
"code": null,
"e": 24401,
"s": 24390,
"text": "Program 1:"
},
{
"code": "// Java code to illustrate iterator() import java.util.*; public class GFG { public static void main(String[] args) { // Create and populate the list ArrayList<String> list = new ArrayList<>(); list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"is\"); list.add(\"a\"); list.add(\"CS\"); list.add(\"Students\"); list.add(\"Portal\"); // Displaying the list System.out.println(\"The list is: \\n\" + list); // Create an iterator for the list // using iterator() method Iterator<String> iter = list.iterator(); // Displaying the values after iterating // through the list System.out.println(\"\\nThe iterator values\" + \" of list are: \"); while (iter.hasNext()) { System.out.print(iter.next() + \" \"); } }}",
"e": 25349,
"s": 24401,
"text": null
},
{
"code": null,
"e": 25488,
"s": 25349,
"text": "The list is: \n[Geeks, for, Geeks, is, a, CS, Students, Portal]\n\nThe iterator values of list are: \nGeeks for Geeks is a CS Students Portal\n"
},
{
"code": null,
"e": 25499,
"s": 25488,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate iterator() import java.util.*; public class GFG { public static void main(String args[]) { // Creating an empty ArrayList ArrayList<Integer> list = new ArrayList<Integer>(); // Use add() method to add // elements into the list list.add(10); list.add(15); list.add(30); list.add(20); list.add(5); // Displaying the list System.out.println(\"The list is: \\n\" + list); // Create an iterator for the list // using iterator() method Iterator<Integer> iter = list.iterator(); // Displaying the values // after iterating through the list System.out.println(\"\\nThe iterator values\" + \" of list are: \"); while (iter.hasNext()) { System.out.print(iter.next() + \" \"); } }}",
"e": 26415,
"s": 25499,
"text": null
},
{
"code": null,
"e": 26499,
"s": 26415,
"text": "The list is: \n[10, 15, 30, 20, 5]\n\nThe iterator values of list are: \n10 15 30 20 5\n"
},
{
"code": null,
"e": 26514,
"s": 26499,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 26531,
"s": 26514,
"text": "Java-Collections"
},
{
"code": null,
"e": 26546,
"s": 26531,
"text": "Java-Functions"
},
{
"code": null,
"e": 26553,
"s": 26546,
"text": "Picked"
},
{
"code": null,
"e": 26577,
"s": 26553,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 26582,
"s": 26577,
"text": "Java"
},
{
"code": null,
"e": 26601,
"s": 26582,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26606,
"s": 26601,
"text": "Java"
},
{
"code": null,
"e": 26623,
"s": 26606,
"text": "Java-Collections"
},
{
"code": null,
"e": 26721,
"s": 26623,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26730,
"s": 26721,
"text": "Comments"
},
{
"code": null,
"e": 26743,
"s": 26730,
"text": "Old Comments"
},
{
"code": null,
"e": 26775,
"s": 26743,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26805,
"s": 26775,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26824,
"s": 26805,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26875,
"s": 26824,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26893,
"s": 26875,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26924,
"s": 26893,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26956,
"s": 26924,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26975,
"s": 26956,
"text": "Overriding in Java"
},
{
"code": null,
"e": 26995,
"s": 26975,
"text": "Stack Class in Java"
}
]
|
Styling Tables with CSS | For styling the tables with CSS, we can set borders, collapse, set width and height. We can also set the padding, alig text in it, etc. Let us see some examples −
To add borders to a table in CSS, use the borders property. Let us now see an example −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 2px dashed orange;
}
</style>
</head>
<body>
<h2>Team Ranking Table</h2>
<table>
<tr>
<th>Team</th>
<th>Rank</th>
<th>Points</th>
</tr>
<tr>
<td>India</td>
<td>1</td>
<td>200</td>
</tr>
<tr>
<td>England</td>
<td>2</td>
<td>180</td>
</tr>
<tr>
<td>Australia</td>
<td>3</td>
<td>150</td>
</tr>
<tr>
<td>NewZealand</td>
<td>4</td>
<td>130</td>
</tr>
<tr>
<td>SouthAfrica</td>
<td>5</td>
<td>100</td>
</tr>
<tr>
<td>WestIndies</td>
<td>6</td>
<td>80</td>
</tr>
<tr>
<td>Pakistan</td>
<td>7</td>
<td>70</td>
</tr>
</table>
</body>
</html>
To collapse table borders, use the border-collapse property in CSS. Let us see an example to collapse table borders −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
table {
border-collapse: collapse;
background-color: black;
color: white;
}
th, td {
border: 2px dashed yellow;
}
</style>
</head>
<body>
<h2>Team Ranking Table</h2>
<table>
<tr>
<th>Team</th>
<th>Rank</th>
<th>Points</th>
</tr>
<tr>
<td>India</td>
<td>1</td>
<td>200</td>
</tr>
<tr>
<td>England</td>
<td>2</td>
<td>180</td>
</tr>
<tr>
<td>Australia</td>
<td>3</td>
<td>150</td>
</tr>
<tr>
<td>NewZealand</td>
<td>4</td>
<td>130</td>
</tr>
<tr>
<td>SouthAfrica</td>
<td>5</td>
<td>100</td>
</tr>
<tr>
<td>WestIndies</td>
<td>6</td>
<td>80</td>
</tr>
<tr>
<td>Pakistan</td>
<td>7</td>
<td>70</td>
</tr>
</table>
</body>
</html>
To set the space between border and content, use the padding property as in the below example −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
table {
border: 1px solid black;
background-color: blue;
color: white;
}
th, td {
border: 1px solid black;
padding: 20px;
text-align: center;
}
table#demo {
table-layout: fixed;
width: 100%;
}
</style>
</head>
<body>
<h2>Team Ranking Table</h2>
<table id="demo">
<tr>
<th>Team</th>
<th>Rank</th>
<th>Points</th>
</tr>
<tr>
<td>India</td>
<td>1</td>
<td>200</td>
</tr>
<tr>
<td>England</td>
<td>2</td>
<td>180</td>
</tr>
<tr>
<td>Australia</td>
<td>3</td>
<td>150</td>
</tr>
<tr>
<td>NewZealand</td>
<td>4</td>
<td>130</td>
</tr>
<tr>
<td>SouthAfrica</td>
<td>5</td>
<td>100</td>
</tr>
</table>
</body>
</html> | [
{
"code": null,
"e": 1225,
"s": 1062,
"text": "For styling the tables with CSS, we can set borders, collapse, set width and height. We can also set the padding, alig text in it, etc. Let us see some examples −"
},
{
"code": null,
"e": 1313,
"s": 1225,
"text": "To add borders to a table in CSS, use the borders property. Let us now see an example −"
},
{
"code": null,
"e": 1324,
"s": 1313,
"text": " Live Demo"
},
{
"code": null,
"e": 1923,
"s": 1324,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ntable, th, td {\n border: 2px dashed orange;\n}\n</style>\n</head>\n<body>\n<h2>Team Ranking Table</h2>\n<table>\n<tr>\n<th>Team</th>\n<th>Rank</th>\n<th>Points</th>\n</tr>\n<tr>\n<td>India</td>\n<td>1</td>\n<td>200</td>\n</tr>\n<tr>\n<td>England</td>\n<td>2</td>\n<td>180</td>\n</tr>\n<tr>\n<td>Australia</td>\n<td>3</td>\n<td>150</td>\n</tr>\n<tr>\n<td>NewZealand</td>\n<td>4</td>\n<td>130</td>\n</tr>\n<tr>\n<td>SouthAfrica</td>\n<td>5</td>\n<td>100</td>\n</tr>\n<tr>\n<td>WestIndies</td>\n<td>6</td>\n<td>80</td>\n</tr>\n<tr>\n<td>Pakistan</td>\n<td>7</td>\n<td>70</td>\n</tr>\n</table>\n</body>\n</html>"
},
{
"code": null,
"e": 2041,
"s": 1923,
"text": "To collapse table borders, use the border-collapse property in CSS. Let us see an example to collapse table borders −"
},
{
"code": null,
"e": 2052,
"s": 2041,
"text": " Live Demo"
},
{
"code": null,
"e": 2729,
"s": 2052,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ntable {\n border-collapse: collapse;\n background-color: black;\n color: white;\n}\nth, td {\n border: 2px dashed yellow;\n}\n</style>\n</head>\n<body>\n<h2>Team Ranking Table</h2>\n<table>\n<tr>\n<th>Team</th>\n<th>Rank</th>\n<th>Points</th>\n</tr>\n<tr>\n<td>India</td>\n<td>1</td>\n<td>200</td>\n</tr>\n<tr>\n<td>England</td>\n<td>2</td>\n<td>180</td>\n</tr>\n<tr>\n<td>Australia</td>\n<td>3</td>\n<td>150</td>\n</tr>\n<tr>\n<td>NewZealand</td>\n<td>4</td>\n<td>130</td>\n</tr>\n<tr>\n<td>SouthAfrica</td>\n<td>5</td>\n<td>100</td>\n</tr>\n<tr>\n<td>WestIndies</td>\n<td>6</td>\n<td>80</td>\n</tr>\n<tr>\n<td>Pakistan</td>\n<td>7</td>\n<td>70</td>\n</tr>\n</table>\n</body>\n</html>"
},
{
"code": null,
"e": 2825,
"s": 2729,
"text": "To set the space between border and content, use the padding property as in the below example −"
},
{
"code": null,
"e": 2836,
"s": 2825,
"text": " Live Demo"
},
{
"code": null,
"e": 3508,
"s": 2836,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ntable {\n border: 1px solid black;\n background-color: blue;\n color: white;\n}\nth, td {\n border: 1px solid black;\n padding: 20px;\n text-align: center;\n}\ntable#demo {\n table-layout: fixed;\n width: 100%;\n}\n</style>\n</head>\n<body>\n<h2>Team Ranking Table</h2>\n<table id=\"demo\">\n<tr>\n<th>Team</th>\n<th>Rank</th>\n<th>Points</th>\n</tr>\n<tr>\n<td>India</td>\n<td>1</td>\n<td>200</td>\n</tr>\n<tr>\n<td>England</td>\n<td>2</td>\n<td>180</td>\n</tr>\n<tr>\n<td>Australia</td>\n<td>3</td>\n<td>150</td>\n</tr>\n<tr>\n<td>NewZealand</td>\n<td>4</td>\n<td>130</td>\n</tr>\n<tr>\n<td>SouthAfrica</td>\n<td>5</td>\n<td>100</td>\n</tr>\n</table>\n</body>\n</html>"
}
]
|
How to Vertically Align Text Next to an Image using CSS ? - GeeksforGeeks | 08 Feb, 2022
Introduction: We often add images to our website and there are times when that text needs to be vertically aligned next to an image. For example, in case of a profile image of the user, the name of the user should be visible right after his/her profile picture and it should be vertically aligned. In this article, we will see how to align text next to an image using various methods.Approaches: There are two methods are available to vertically align the text next to an image as given below:
Using flexbox
Using vertical-align CSS property
Using flexbox: In this approach, we will use flexbox. For this, we will use CSS display property combined with align-items property. We need to create a parent element that contain both image and text. After declaring the parent element as flexbox using display: flex; we can align the items to the center using align-items: center;.Syntax:
.class_name {
display: flex;
align-items:center;
}
Example: This example uses flexbox to vertically align text next to an image using CSS.
html
<!DOCTYPE html><html> <head> <title> How to Vertically Align Text Next to an Image using CSS ? </title> <style> .aligned { display: flex; align-items: center; } span { padding: 10px; } </style></head> <body> <div class="aligned"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png" width="50" alt=""> <span>GeeksforGeeks</span> </div></body> </html>
Output:
Using vertical-align CSS property: In this approach, we don’t need to wrap our element in a parent element and use vertical-align property to vertically align elements directly.Syntax:
.class_name { vertical-align: middle; }
Example: This example uses vertical-align property to vertically align text next to an image using CSS.
html
<!DOCTYPE html><html> <head> <title> How to Vertically Align Text Next to an Image using CSS ? </title> <style> img { vertical-align: middle; } </style></head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png" width="50" alt=""> <span> GeeksforGeeks (using vertical-align) </span></body> </html>
Output:
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
blalverma92
CSS-Misc
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26329,
"s": 26301,
"text": "\n08 Feb, 2022"
},
{
"code": null,
"e": 26825,
"s": 26329,
"text": "Introduction: We often add images to our website and there are times when that text needs to be vertically aligned next to an image. For example, in case of a profile image of the user, the name of the user should be visible right after his/her profile picture and it should be vertically aligned. In this article, we will see how to align text next to an image using various methods.Approaches: There are two methods are available to vertically align the text next to an image as given below: "
},
{
"code": null,
"e": 26839,
"s": 26825,
"text": "Using flexbox"
},
{
"code": null,
"e": 26873,
"s": 26839,
"text": "Using vertical-align CSS property"
},
{
"code": null,
"e": 27216,
"s": 26873,
"text": "Using flexbox: In this approach, we will use flexbox. For this, we will use CSS display property combined with align-items property. We need to create a parent element that contain both image and text. After declaring the parent element as flexbox using display: flex; we can align the items to the center using align-items: center;.Syntax: "
},
{
"code": null,
"e": 27276,
"s": 27216,
"text": ".class_name { \n display: flex;\n align-items:center;\n}"
},
{
"code": null,
"e": 27365,
"s": 27276,
"text": "Example: This example uses flexbox to vertically align text next to an image using CSS. "
},
{
"code": null,
"e": 27370,
"s": 27365,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to Vertically Align Text Next to an Image using CSS ? </title> <style> .aligned { display: flex; align-items: center; } span { padding: 10px; } </style></head> <body> <div class=\"aligned\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png\" width=\"50\" alt=\"\"> <span>GeeksforGeeks</span> </div></body> </html>",
"e": 27905,
"s": 27370,
"text": null
},
{
"code": null,
"e": 27915,
"s": 27905,
"text": "Output: "
},
{
"code": null,
"e": 28102,
"s": 27915,
"text": "Using vertical-align CSS property: In this approach, we don’t need to wrap our element in a parent element and use vertical-align property to vertically align elements directly.Syntax: "
},
{
"code": null,
"e": 28143,
"s": 28102,
"text": ".class_name { vertical-align: middle; } "
},
{
"code": null,
"e": 28248,
"s": 28143,
"text": "Example: This example uses vertical-align property to vertically align text next to an image using CSS. "
},
{
"code": null,
"e": 28253,
"s": 28248,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to Vertically Align Text Next to an Image using CSS ? </title> <style> img { vertical-align: middle; } </style></head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png\" width=\"50\" alt=\"\"> <span> GeeksforGeeks (using vertical-align) </span></body> </html>",
"e": 28694,
"s": 28253,
"text": null
},
{
"code": null,
"e": 28704,
"s": 28694,
"text": "Output: "
},
{
"code": null,
"e": 28892,
"s": 28706,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 28904,
"s": 28892,
"text": "blalverma92"
},
{
"code": null,
"e": 28913,
"s": 28904,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28917,
"s": 28913,
"text": "CSS"
},
{
"code": null,
"e": 28934,
"s": 28917,
"text": "Web Technologies"
},
{
"code": null,
"e": 28961,
"s": 28934,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29059,
"s": 28961,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29107,
"s": 29059,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29162,
"s": 29107,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 29199,
"s": 29162,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 29263,
"s": 29199,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 29302,
"s": 29263,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29342,
"s": 29302,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29375,
"s": 29342,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29420,
"s": 29375,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29463,
"s": 29420,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Visualizing The Non-linearity of Neural Networks | by Cihan Soylu | Towards Data Science | In this article I will go over a basic example demonstrating the power of non-linear activation functions in neural networks. For this purpose, I have created an artificial dataset. Each data point has two features and a class label, 0 or 1. So we have a binary classification problem. If we call the features x1 and x2, then the plot of the data in (x1, x2)-space is as follows:
Here the red points are corresponding to the negative class and the blue points are corresponding to the positive class. Notice that the data is not linearly separable, meaning there is no line that separates the blue and red points. Hence a linear classifier wouldn’t be useful with the given feature representation. Now we will train a neural network with one hidden layer with two units and a non-linear tanh activation function and visualize the features learned by this network.
In order to create the model, I will use Tensorflow 2.0 and tf.keras :
inputs = tf.keras.Input(shape=(2,))x = tf.keras.layers.Dense(2, activation=tf.nn.tanh)(inputs)outputs = tf.keras.layers.Dense(1, activation=tf.nn.sigmoid)(x)model = tf.keras.Model(inputs=inputs, outputs=outputs)model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
Let’s denote the weights and the biases of the hidden layer as follows:
The initial values of the weights and biases define two lines in the (x1, x2)-space,
These initial lines before training together with the data are shown below:
Notice that these two initial lines are not dividing the given two classes nicely. Now let’s train the model and see what happens to these lines.
model.fit(x_train, y_train, batch_size = 16, epochs=100)Epoch 100/100400/400 [==============================] - 0s 80us/sample - loss: 0.1116 - accuracy: 1.0000
Our training accuracy is 100% after 100 epochs so the model is classifying all points in the training data correctly.
Note that you can get the parameters of a keras model by using model.weights which returns a list of weights and biases:
[<tf.Variable ‘dense/kernel:0’ shape=(2, 2) dtype=float32, numpy= array([[-3.2753847, 3.2302036], [ 3.3264563, -3.2554653]], dtype=float32)>, <tf.Variable ‘dense/bias:0’ shape=(2,) dtype=float32, numpy=array([1.5562934, 1.5492057], dtype=float32)>, <tf.Variable ‘dense_1/kernel:0’ shape=(2, 1) dtype=float32, numpy= array([[2.625529], [2.670275]], dtype=float32)>, <tf.Variable ‘dense_1/bias:0’ shape=(1,) dtype=float32, numpy=array([-2.0918093], dtype=float32)>]
The first two elements in this list are the weights and biases of the hidden layer and the last two elements are weights and biases of the output layer. All these elements are tensors and you can get the values as numpy arrays using numpy() method. For example, the following will give you the weights of the hidden layer as a numpy array,
model.weights[0].numpy()array([[-3.2753847, 3.2302036], [ 3.3264563, -3.2554653]], dtype=float32)
The coefficients of the first line are -3.27 and 3.32; and the coefficients of the second line are 3.23 and -3.25. You can see their biases by running model.weights[1].numpy()
Let’s visualize the lines defined by the learned weights and biases of the hidden layer,
As you can see now the lines divide the space in a way that the classes are contained in separate regions. The coefficients of these lines are telling us the positive side of each line. For the blue line the positive direction is the upper side and for the orange line the positive side is the downside. So the blue points are in the positive side of both lines and the red points are on the negative side of one line and the positive side of the other.
Now let’s apply the non-linear activation function tanh and visualize the data in the new feature space (a1, a2). The activations of the hidden layer are computed as follows,
For each data point the arguments of the tanh are determined by the position of the data point in relation to the above lines. We can think of a1 and a2 as the new features and (a1,a2)-space as the new feature space. The weights and the bias of the output layer define a line in this new feature space given by the following equation
This line together with the data in this new feature space is plotted below,
Note that in this new feature space our data becomes linearly separable and the line defined by the output layer separates the two classes. The blue points has both a1 and a2 coordinates positive because those points in the (x1, x2) space are on the positive side of both lines defined by the hidden layer parameters and after applying tanh both coordinates are positive. For the red points one of a1 and a2 is positive because in the (x1, x2)-space the red points are on the positive side of only one of the lines defined by the hidden layer parameters and depending on this line they have only one of their coordinates in the new feature space positive and the other is negative. This explains the data plot in (a1,a2)-space above.
Conclusion: Neural networks learn a new representation of the data which makes it easy to classify with respect to this new representation.
Here is a link to the google colab notebook I used for this article.
Thanks for reading. | [
{
"code": null,
"e": 552,
"s": 172,
"text": "In this article I will go over a basic example demonstrating the power of non-linear activation functions in neural networks. For this purpose, I have created an artificial dataset. Each data point has two features and a class label, 0 or 1. So we have a binary classification problem. If we call the features x1 and x2, then the plot of the data in (x1, x2)-space is as follows:"
},
{
"code": null,
"e": 1036,
"s": 552,
"text": "Here the red points are corresponding to the negative class and the blue points are corresponding to the positive class. Notice that the data is not linearly separable, meaning there is no line that separates the blue and red points. Hence a linear classifier wouldn’t be useful with the given feature representation. Now we will train a neural network with one hidden layer with two units and a non-linear tanh activation function and visualize the features learned by this network."
},
{
"code": null,
"e": 1107,
"s": 1036,
"text": "In order to create the model, I will use Tensorflow 2.0 and tf.keras :"
},
{
"code": null,
"e": 1426,
"s": 1107,
"text": "inputs = tf.keras.Input(shape=(2,))x = tf.keras.layers.Dense(2, activation=tf.nn.tanh)(inputs)outputs = tf.keras.layers.Dense(1, activation=tf.nn.sigmoid)(x)model = tf.keras.Model(inputs=inputs, outputs=outputs)model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])"
},
{
"code": null,
"e": 1498,
"s": 1426,
"text": "Let’s denote the weights and the biases of the hidden layer as follows:"
},
{
"code": null,
"e": 1583,
"s": 1498,
"text": "The initial values of the weights and biases define two lines in the (x1, x2)-space,"
},
{
"code": null,
"e": 1659,
"s": 1583,
"text": "These initial lines before training together with the data are shown below:"
},
{
"code": null,
"e": 1805,
"s": 1659,
"text": "Notice that these two initial lines are not dividing the given two classes nicely. Now let’s train the model and see what happens to these lines."
},
{
"code": null,
"e": 1966,
"s": 1805,
"text": "model.fit(x_train, y_train, batch_size = 16, epochs=100)Epoch 100/100400/400 [==============================] - 0s 80us/sample - loss: 0.1116 - accuracy: 1.0000"
},
{
"code": null,
"e": 2084,
"s": 1966,
"text": "Our training accuracy is 100% after 100 epochs so the model is classifying all points in the training data correctly."
},
{
"code": null,
"e": 2205,
"s": 2084,
"text": "Note that you can get the parameters of a keras model by using model.weights which returns a list of weights and biases:"
},
{
"code": null,
"e": 2669,
"s": 2205,
"text": "[<tf.Variable ‘dense/kernel:0’ shape=(2, 2) dtype=float32, numpy= array([[-3.2753847, 3.2302036], [ 3.3264563, -3.2554653]], dtype=float32)>, <tf.Variable ‘dense/bias:0’ shape=(2,) dtype=float32, numpy=array([1.5562934, 1.5492057], dtype=float32)>, <tf.Variable ‘dense_1/kernel:0’ shape=(2, 1) dtype=float32, numpy= array([[2.625529], [2.670275]], dtype=float32)>, <tf.Variable ‘dense_1/bias:0’ shape=(1,) dtype=float32, numpy=array([-2.0918093], dtype=float32)>]"
},
{
"code": null,
"e": 3009,
"s": 2669,
"text": "The first two elements in this list are the weights and biases of the hidden layer and the last two elements are weights and biases of the output layer. All these elements are tensors and you can get the values as numpy arrays using numpy() method. For example, the following will give you the weights of the hidden layer as a numpy array,"
},
{
"code": null,
"e": 3115,
"s": 3009,
"text": "model.weights[0].numpy()array([[-3.2753847, 3.2302036], [ 3.3264563, -3.2554653]], dtype=float32)"
},
{
"code": null,
"e": 3291,
"s": 3115,
"text": "The coefficients of the first line are -3.27 and 3.32; and the coefficients of the second line are 3.23 and -3.25. You can see their biases by running model.weights[1].numpy()"
},
{
"code": null,
"e": 3380,
"s": 3291,
"text": "Let’s visualize the lines defined by the learned weights and biases of the hidden layer,"
},
{
"code": null,
"e": 3834,
"s": 3380,
"text": "As you can see now the lines divide the space in a way that the classes are contained in separate regions. The coefficients of these lines are telling us the positive side of each line. For the blue line the positive direction is the upper side and for the orange line the positive side is the downside. So the blue points are in the positive side of both lines and the red points are on the negative side of one line and the positive side of the other."
},
{
"code": null,
"e": 4009,
"s": 3834,
"text": "Now let’s apply the non-linear activation function tanh and visualize the data in the new feature space (a1, a2). The activations of the hidden layer are computed as follows,"
},
{
"code": null,
"e": 4343,
"s": 4009,
"text": "For each data point the arguments of the tanh are determined by the position of the data point in relation to the above lines. We can think of a1 and a2 as the new features and (a1,a2)-space as the new feature space. The weights and the bias of the output layer define a line in this new feature space given by the following equation"
},
{
"code": null,
"e": 4420,
"s": 4343,
"text": "This line together with the data in this new feature space is plotted below,"
},
{
"code": null,
"e": 5154,
"s": 4420,
"text": "Note that in this new feature space our data becomes linearly separable and the line defined by the output layer separates the two classes. The blue points has both a1 and a2 coordinates positive because those points in the (x1, x2) space are on the positive side of both lines defined by the hidden layer parameters and after applying tanh both coordinates are positive. For the red points one of a1 and a2 is positive because in the (x1, x2)-space the red points are on the positive side of only one of the lines defined by the hidden layer parameters and depending on this line they have only one of their coordinates in the new feature space positive and the other is negative. This explains the data plot in (a1,a2)-space above."
},
{
"code": null,
"e": 5294,
"s": 5154,
"text": "Conclusion: Neural networks learn a new representation of the data which makes it easy to classify with respect to this new representation."
},
{
"code": null,
"e": 5363,
"s": 5294,
"text": "Here is a link to the google colab notebook I used for this article."
}
]
|
Python program to convert a list to string | 27 Jun, 2022
There are various situations we might encounter when a list is given and we convert it to a string. For example, conversion to string from the list of strings or the list of integers or mixed data types.
Example:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Input: ['Geeks', 'for', 'Geeks']
Output: Geeks for Geeks
Input: ['I', 'want', 4, 'apples', 'and', 18, 'bananas']
Output: I want 4 apples and 18 bananas
Let’s see various ways we can convert the list to string.
Method#1: The first method is to assign a list and traverse each element using for loop and adding it to an empty string.
Python3
s = ['Geeks', 'for', 'Geeks']str1 = ""# traverse in the string for i in s: str1 += i print(str1)
Output:
GeeksforGeeks
type(str1)
str
Method #2: The Second method used here is using a function that traverse each element of the list using for loop and keep adding the element for every index in some empty string.
Python3
# Python program to convert a list to string # Function to convert def listToString(s): # initialize an empty string str1 = "" # traverse in the string for ele in s: str1 += ele # return string return str1 # Driver code s = ['Geeks', 'for', 'Geeks']print(listToString(s))
GeeksforGeeks
Method #3: Using .join() method
Python3
# Python program to convert a list# to string using join() function # Function to convert def listToString(s): # initialize an empty string str1 = " " # return string return (str1.join(s)) # Driver code s = ['Geeks', 'for', 'Geeks']print(listToString(s))
Geeks for Geeks
But what if the list contains both string and integer as its element. In those cases, above code won’t work. We need to convert it to string while adding to string.
Method #4: Using list comprehension
Python3
# Python program to convert a list# to string using list comprehension s = ['I', 'want', 4, 'apples', 'and', 18, 'bananas'] # using list comprehensionlistToStr = ' '.join([str(elem) for elem in s]) print(listToStr)
I want 4 apples and 18 bananas
Method #5: Using map() Use map() method for mapping str (for converting elements in list to string) with given iterator, the list.
Python3
# Python program to convert a list# to string using list comprehension s = ['I', 'want', 4, 'apples', 'and', 18, 'bananas'] # using list comprehensionlistToStr = ' '.join(map(str, s)) print(listToStr)
I want 4 apples and 18 bananas
nidhi_biet
sheetal18june
Python list-programs
Python string-programs
python-list
python-string
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n27 Jun, 2022"
},
{
"code": null,
"e": 257,
"s": 53,
"text": "There are various situations we might encounter when a list is given and we convert it to a string. For example, conversion to string from the list of strings or the list of integers or mixed data types."
},
{
"code": null,
"e": 267,
"s": 257,
"text": " Example:"
},
{
"code": null,
"e": 276,
"s": 267,
"text": "Chapters"
},
{
"code": null,
"e": 303,
"s": 276,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 353,
"s": 303,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 376,
"s": 353,
"text": "captions off, selected"
},
{
"code": null,
"e": 384,
"s": 376,
"text": "English"
},
{
"code": null,
"e": 408,
"s": 384,
"text": "This is a modal window."
},
{
"code": null,
"e": 477,
"s": 408,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 499,
"s": 477,
"text": "End of dialog window."
},
{
"code": null,
"e": 652,
"s": 499,
"text": "Input: ['Geeks', 'for', 'Geeks']\nOutput: Geeks for Geeks\n\nInput: ['I', 'want', 4, 'apples', 'and', 18, 'bananas']\nOutput: I want 4 apples and 18 bananas"
},
{
"code": null,
"e": 711,
"s": 652,
"text": "Let’s see various ways we can convert the list to string. "
},
{
"code": null,
"e": 833,
"s": 711,
"text": "Method#1: The first method is to assign a list and traverse each element using for loop and adding it to an empty string."
},
{
"code": null,
"e": 841,
"s": 833,
"text": "Python3"
},
{
"code": "s = ['Geeks', 'for', 'Geeks']str1 = \"\"# traverse in the string for i in s: str1 += i print(str1)",
"e": 941,
"s": 841,
"text": null
},
{
"code": null,
"e": 949,
"s": 941,
"text": "Output:"
},
{
"code": null,
"e": 963,
"s": 949,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 978,
"s": 963,
"text": "type(str1)\nstr"
},
{
"code": null,
"e": 1158,
"s": 978,
"text": "Method #2: The Second method used here is using a function that traverse each element of the list using for loop and keep adding the element for every index in some empty string. "
},
{
"code": null,
"e": 1166,
"s": 1158,
"text": "Python3"
},
{
"code": "# Python program to convert a list to string # Function to convert def listToString(s): # initialize an empty string str1 = \"\" # traverse in the string for ele in s: str1 += ele # return string return str1 # Driver code s = ['Geeks', 'for', 'Geeks']print(listToString(s))",
"e": 1492,
"s": 1166,
"text": null
},
{
"code": null,
"e": 1506,
"s": 1492,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 1539,
"s": 1506,
"text": "Method #3: Using .join() method "
},
{
"code": null,
"e": 1547,
"s": 1539,
"text": "Python3"
},
{
"code": "# Python program to convert a list# to string using join() function # Function to convert def listToString(s): # initialize an empty string str1 = \" \" # return string return (str1.join(s)) # Driver code s = ['Geeks', 'for', 'Geeks']print(listToString(s))",
"e": 1838,
"s": 1547,
"text": null
},
{
"code": null,
"e": 1854,
"s": 1838,
"text": "Geeks for Geeks"
},
{
"code": null,
"e": 2020,
"s": 1854,
"text": "But what if the list contains both string and integer as its element. In those cases, above code won’t work. We need to convert it to string while adding to string. "
},
{
"code": null,
"e": 2057,
"s": 2020,
"text": "Method #4: Using list comprehension "
},
{
"code": null,
"e": 2065,
"s": 2057,
"text": "Python3"
},
{
"code": "# Python program to convert a list# to string using list comprehension s = ['I', 'want', 4, 'apples', 'and', 18, 'bananas'] # using list comprehensionlistToStr = ' '.join([str(elem) for elem in s]) print(listToStr)",
"e": 2281,
"s": 2065,
"text": null
},
{
"code": null,
"e": 2312,
"s": 2281,
"text": "I want 4 apples and 18 bananas"
},
{
"code": null,
"e": 2444,
"s": 2312,
"text": "Method #5: Using map() Use map() method for mapping str (for converting elements in list to string) with given iterator, the list. "
},
{
"code": null,
"e": 2452,
"s": 2444,
"text": "Python3"
},
{
"code": "# Python program to convert a list# to string using list comprehension s = ['I', 'want', 4, 'apples', 'and', 18, 'bananas'] # using list comprehensionlistToStr = ' '.join(map(str, s)) print(listToStr)",
"e": 2654,
"s": 2452,
"text": null
},
{
"code": null,
"e": 2685,
"s": 2654,
"text": "I want 4 apples and 18 bananas"
},
{
"code": null,
"e": 2696,
"s": 2685,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2710,
"s": 2696,
"text": "sheetal18june"
},
{
"code": null,
"e": 2731,
"s": 2710,
"text": "Python list-programs"
},
{
"code": null,
"e": 2754,
"s": 2731,
"text": "Python string-programs"
},
{
"code": null,
"e": 2766,
"s": 2754,
"text": "python-list"
},
{
"code": null,
"e": 2780,
"s": 2766,
"text": "python-string"
},
{
"code": null,
"e": 2787,
"s": 2780,
"text": "Python"
},
{
"code": null,
"e": 2803,
"s": 2787,
"text": "Python Programs"
},
{
"code": null,
"e": 2815,
"s": 2803,
"text": "python-list"
}
]
|
Replace special characters in a string with underscore (_) in JavaScript | 23 May, 2019
JavaScript replace() method is used to replace all special characters from a string with _ (underscore) which is described below:
replace() method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value.Syntax:string.replace(searchVal, newvalue)Parameters:searchVal: It is required parameter. It specifies the value, or regular expression, that is going to replace by the new value.newvalue: It is required parameter. It specifies the value to replace the search value with.Return value: It returns a new string where the defines value has been replaced by the new value.
Syntax:
string.replace(searchVal, newvalue)
Parameters:
searchVal: It is required parameter. It specifies the value, or regular expression, that is going to replace by the new value.
newvalue: It is required parameter. It specifies the value to replace the search value with.
Return value: It returns a new string where the defines value has been replaced by the new value.
Example 1: This example replaces all special characters with _ (underscore) using replace() method.
<!DOCTYPE HTML> <html> <head> <title> Replace special characters in a string with _ (underscore) </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 16px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> Click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "This, is# GeeksForGeeks!"; el_up.innerHTML = str; function gfg_Run() { el_down.innerHTML = str.replace(/[&\/\\#, +()$~%.'":*?<>{}]/g, '_'); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example replace a unique special character with _ (underscore). This example goes to each character and checks if it is a special character that we are looking for, then it will replace the character. In this example the unique character is $(dollar sign).
<!DOCTYPE HTML> <html> <head> <title> Replace special characters with _ (underscore) </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 16px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> Click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "A$computer$science$portal$for$Geeks"; el_up.innerHTML = str; function gfg_Run() { var newStr = ""; for(var i=0; i<str.length; i++) { if (str[i] == '$') { newStr += '_'; } else { newStr += str[i]; } } el_down.innerHTML = newStr; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2019"
},
{
"code": null,
"e": 158,
"s": 28,
"text": "JavaScript replace() method is used to replace all special characters from a string with _ (underscore) which is described below:"
},
{
"code": null,
"e": 678,
"s": 158,
"text": "replace() method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value.Syntax:string.replace(searchVal, newvalue)Parameters:searchVal: It is required parameter. It specifies the value, or regular expression, that is going to replace by the new value.newvalue: It is required parameter. It specifies the value to replace the search value with.Return value: It returns a new string where the defines value has been replaced by the new value."
},
{
"code": null,
"e": 686,
"s": 678,
"text": "Syntax:"
},
{
"code": null,
"e": 722,
"s": 686,
"text": "string.replace(searchVal, newvalue)"
},
{
"code": null,
"e": 734,
"s": 722,
"text": "Parameters:"
},
{
"code": null,
"e": 861,
"s": 734,
"text": "searchVal: It is required parameter. It specifies the value, or regular expression, that is going to replace by the new value."
},
{
"code": null,
"e": 954,
"s": 861,
"text": "newvalue: It is required parameter. It specifies the value to replace the search value with."
},
{
"code": null,
"e": 1052,
"s": 954,
"text": "Return value: It returns a new string where the defines value has been replaced by the new value."
},
{
"code": null,
"e": 1152,
"s": 1052,
"text": "Example 1: This example replaces all special characters with _ (underscore) using replace() method."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Replace special characters in a string with _ (underscore) </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 16px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> Click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var str = \"This, is# GeeksForGeeks!\"; el_up.innerHTML = str; function gfg_Run() { el_down.innerHTML = str.replace(/[&\\/\\\\#, +()$~%.'\":*?<>{}]/g, '_'); } </script> </body> </html> ",
"e": 2200,
"s": 1152,
"text": null
},
{
"code": null,
"e": 2208,
"s": 2200,
"text": "Output:"
},
{
"code": null,
"e": 2239,
"s": 2208,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 2269,
"s": 2239,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 2542,
"s": 2269,
"text": "Example 2: This example replace a unique special character with _ (underscore). This example goes to each character and checks if it is a special character that we are looking for, then it will replace the character. In this example the unique character is $(dollar sign)."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Replace special characters with _ (underscore) </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 16px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> Click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var str = \"A$computer$science$portal$for$Geeks\"; el_up.innerHTML = str; function gfg_Run() { var newStr = \"\"; for(var i=0; i<str.length; i++) { if (str[i] == '$') { newStr += '_'; } else { newStr += str[i]; } } el_down.innerHTML = newStr; } </script> </body> </html> ",
"e": 3846,
"s": 2542,
"text": null
},
{
"code": null,
"e": 3854,
"s": 3846,
"text": "Output:"
},
{
"code": null,
"e": 3885,
"s": 3854,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 3915,
"s": 3885,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 3931,
"s": 3915,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3942,
"s": 3931,
"text": "JavaScript"
},
{
"code": null,
"e": 3959,
"s": 3942,
"text": "Web Technologies"
},
{
"code": null,
"e": 3986,
"s": 3959,
"text": "Web technologies Questions"
}
]
|
Sheppard’s Correction for Moments | ML | 23 Jan, 2020
Prerequisite: Raw and Central Moments
We assume in grouped data that the frequencies are concentrated in the middle part of the class interval. This assumption does not hold true in general and grouping error is introduced. Such an effect can be corrected in calculating the moments by using the information on the width of the class interval.
Sheppard’s Correction for grouping error is nothing but the adjustment to calculated sample moments for the grouped data or continuous data. Prof. W.F. Sheppard proved that if the frequency distribution is continuous and the frequency tapers off to zero in both directions, the grouping error can be corrected as follows:
Let ‘c’ be the width of the class interval. Then,Raw Moments
Central Moments
What Kind of data can be corrected?
This method of correction to moments is only possible for the continuous variables i.e. the continuous data.The width of the class interval should be equal.Frequencies should be symmetrical. Frequency should taper off to zero in both directions.
This method of correction to moments is only possible for the continuous variables i.e. the continuous data.
The width of the class interval should be equal.
Frequencies should be symmetrical. Frequency should taper off to zero in both directions.
Consider the given distribution of marks.
For the distribution of marks above, the value for moments are given below:
Raw Moments –, is the rth raw moment, where is the frequency count and is the mid value of class.
So, using the above formula for the Raw Moment we get following values for moments.
Sheppard’s correction for Raw Moments –
Similarly central moments can be corrected using Sheppard’s Correction.
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 66,
"s": 28,
"text": "Prerequisite: Raw and Central Moments"
},
{
"code": null,
"e": 372,
"s": 66,
"text": "We assume in grouped data that the frequencies are concentrated in the middle part of the class interval. This assumption does not hold true in general and grouping error is introduced. Such an effect can be corrected in calculating the moments by using the information on the width of the class interval."
},
{
"code": null,
"e": 694,
"s": 372,
"text": "Sheppard’s Correction for grouping error is nothing but the adjustment to calculated sample moments for the grouped data or continuous data. Prof. W.F. Sheppard proved that if the frequency distribution is continuous and the frequency tapers off to zero in both directions, the grouping error can be corrected as follows:"
},
{
"code": null,
"e": 755,
"s": 694,
"text": "Let ‘c’ be the width of the class interval. Then,Raw Moments"
},
{
"code": null,
"e": 771,
"s": 755,
"text": "Central Moments"
},
{
"code": null,
"e": 807,
"s": 771,
"text": "What Kind of data can be corrected?"
},
{
"code": null,
"e": 1053,
"s": 807,
"text": "This method of correction to moments is only possible for the continuous variables i.e. the continuous data.The width of the class interval should be equal.Frequencies should be symmetrical. Frequency should taper off to zero in both directions."
},
{
"code": null,
"e": 1162,
"s": 1053,
"text": "This method of correction to moments is only possible for the continuous variables i.e. the continuous data."
},
{
"code": null,
"e": 1211,
"s": 1162,
"text": "The width of the class interval should be equal."
},
{
"code": null,
"e": 1301,
"s": 1211,
"text": "Frequencies should be symmetrical. Frequency should taper off to zero in both directions."
},
{
"code": null,
"e": 1343,
"s": 1301,
"text": "Consider the given distribution of marks."
},
{
"code": null,
"e": 1419,
"s": 1343,
"text": "For the distribution of marks above, the value for moments are given below:"
},
{
"code": null,
"e": 1519,
"s": 1419,
"text": "Raw Moments –, is the rth raw moment, where is the frequency count and is the mid value of class."
},
{
"code": null,
"e": 1603,
"s": 1519,
"text": "So, using the above formula for the Raw Moment we get following values for moments."
},
{
"code": null,
"e": 1643,
"s": 1603,
"text": "Sheppard’s correction for Raw Moments –"
},
{
"code": null,
"e": 1715,
"s": 1643,
"text": "Similarly central moments can be corrected using Sheppard’s Correction."
},
{
"code": null,
"e": 1732,
"s": 1715,
"text": "Machine Learning"
},
{
"code": null,
"e": 1749,
"s": 1732,
"text": "Machine Learning"
}
]
|
Maximum score possible after performing given operations on an Array | 02 Jun, 2021
Given an array A of size N, the task is to find the maximum score possible of this array. The score of an array is calculated by performing the following operations on the array N times:
If the operation is odd-numbered, the score is incremented by the sum of all elements of the current array. If the operation is even-numbered, the score is decremented by the sum of all elements of the current array. After every operation, either remove the first or the last element of the remaining array.
If the operation is odd-numbered, the score is incremented by the sum of all elements of the current array.
If the operation is even-numbered, the score is decremented by the sum of all elements of the current array.
After every operation, either remove the first or the last element of the remaining array.
Examples:
Input: A = {1, 2, 3, 4, 2, 6} Output: 13 Explanation: The optimal operations are: 1. Operation 1 is odd. -> So add the sum of the array to the score: Score = 0 + 18 = 18 -> remove 6 from last, -> new array A = [1, 2, 3, 4, 2] 2. Operation 2 is even. -> So subtract the sum of the array from the score: Score = 18 – 12 = 6 -> remove 2 from last, -> new array A = [1, 2, 3, 4] 3. Operation 1 is odd. -> So add the sum of the array to the score: Score = 6 + 10 = 16 -> remove 4 from last, -> new array A = [1, 2, 3] 4. Operation 4 is even. -> So subtract the sum of the array from the score: Score = 16 – 6 = 10 -> remove 1 from start, -> new array A = [2, 3] 5. Operation 5 is odd. -> So add the sum of the array to the score: Score = 10 + 5 = 15 -> remove 3 from last, -> new array A = [2] 6. Operation 6 is even. -> So subtract the sum of the array from the score: Score = 15 – 2 = 13 -> remove 2 from first, -> new array A = [] The array is empty so no further operations are possible.Input: A = [5, 2, 2, 8, 1, 16, 7, 9, 12, 4] Output: 50
Naive approach
In each operation, we have to remove either the leftmost or the rightmost element. A simple way would be to consider all possible ways to remove elements and for each branch compute the score and find the maximum score out of all. This can simply be done using recursion. The information we need to keep in each step would be The remaining array [l, r], where l represents the leftmost index and r the rightmost,The operation number, andThe current score.In order to calculate the sum of any array from [l, r] in each recursive step optimally, we will keep a prefix sum array. Using prefix sum array, new sum from [l, r] can be calculated in O(1) as:
In each operation, we have to remove either the leftmost or the rightmost element. A simple way would be to consider all possible ways to remove elements and for each branch compute the score and find the maximum score out of all. This can simply be done using recursion.
The information we need to keep in each step would be The remaining array [l, r], where l represents the leftmost index and r the rightmost,The operation number, andThe current score.
The remaining array [l, r], where l represents the leftmost index and r the rightmost,
The operation number, and
The current score.
In order to calculate the sum of any array from [l, r] in each recursive step optimally, we will keep a prefix sum array. Using prefix sum array, new sum from [l, r] can be calculated in O(1) as:
Sum(l, r) = prefix_sum[r] – prefix_sum[l-1]
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the maximum// score after given operations #include <bits/stdc++.h>using namespace std; // Function to calculate// maximum score recursivelyint maxScore( int l, int r, int prefix_sum[], int num){ // Base case if (l > r) return 0; // Sum of array in range (l, r) int current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, by removing // leftmost and rightmost element // and selecting the maximum value return current_sum + max( maxScore( l + 1, r, prefix_sum, num + 1), maxScore( l, r - 1, prefix_sum, num + 1));} // Function to find the max scoreint findMaxScore(int a[], int n){ // Prefix sum array int prefix_sum[n] = { 0 }; prefix_sum[0] = a[0]; // Calculating prefix_sum for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } return maxScore(0, n - 1, prefix_sum, 1);} // Driver codeint main(){ int n = 6; int A[n] = { 1, 2, 3, 4, 2, 6 }; cout << findMaxScore(A, n); return 0;}
// Java program to find the maximum// score after given operationsimport java.util.*; class GFG{ // Function to calculate// maximum score recursivelystatic int maxScore( int l, int r, int prefix_sum[], int num){ // Base case if (l > r) return 0; // Sum of array in range (l, r) int current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, by removing // leftmost and rightmost element // and selecting the maximum value return current_sum + Math.max(maxScore(l + 1, r, prefix_sum, num + 1), maxScore(l, r - 1, prefix_sum, num + 1));} // Function to find the max scorestatic int findMaxScore(int a[], int n){ // Prefix sum array int prefix_sum[] = new int[n]; prefix_sum[0] = a[0]; // Calculating prefix_sum for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } return maxScore(0, n - 1, prefix_sum, 1);} // Driver codepublic static void main(String[] args){ int n = 6; int A[] = { 1, 2, 3, 4, 2, 6 }; System.out.print(findMaxScore(A, n));}} // This code is contributed by sapnasingh4991
# Python3 program to find the maximum# score after given operations # Function to calculate maximum# score recursivelydef maxScore(l, r, prefix_sum, num): # Base case if (l > r): return 0; # Sum of array in range (l, r) if((l - 1) >= 0): current_sum = (prefix_sum[r] - prefix_sum[l - 1]) else: current_sum = prefix_sum[r] - 0 # If the operation is even-numbered # the score is decremented if (num % 2 == 0): current_sum *= -1; # Exploring all paths, by removing # leftmost and rightmost element # and selecting the maximum value return current_sum + max(maxScore(l + 1, r, prefix_sum, num + 1), maxScore(l, r - 1, prefix_sum, num + 1)); # Function to find the max scoredef findMaxScore(a, n): # Prefix sum array prefix_sum = [0] * n prefix_sum[0] = a[0] # Calculating prefix_sum for i in range(1, n): prefix_sum[i] = prefix_sum[i - 1] + a[i]; return maxScore(0, n - 1, prefix_sum, 1); # Driver coden = 6;A = [ 1, 2, 3, 4, 2, 6 ]ans = findMaxScore(A, n) print(ans) # This code is contributed by SoumikMondal
// C# program to find the maximum// score after given operationsusing System; class GFG{ // Function to calculate// maximum score recursivelystatic int maxScore( int l, int r, int []prefix_sum, int num){ // Base case if (l > r) return 0; // Sum of array in range (l, r) int current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, by removing // leftmost and rightmost element // and selecting the maximum value return current_sum + Math.Max(maxScore(l + 1, r, prefix_sum, num + 1), maxScore(l, r - 1, prefix_sum, num + 1));} // Function to find the max scorestatic int findMaxScore(int []a, int n){ // Prefix sum array int []prefix_sum = new int[n]; prefix_sum[0] = a[0]; // Calculating prefix_sum for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } return maxScore(0, n - 1, prefix_sum, 1);} // Driver codepublic static void Main(String[] args){ int n = 6; int []A = { 1, 2, 3, 4, 2, 6 }; Console.Write(findMaxScore(A, n));}} // This code is contributed by 29AjayKumar
<script> // JavaScript program to find the maximum// score after given operations // Function to calculate// maximum score recursivelyfunction maxScore(l, r, prefix_sum, num){ // Base case if (l > r) return 0; // Sum of array in range (l, r) let current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, by removing // leftmost and rightmost element // and selecting the maximum value return current_sum + Math.max( maxScore( l + 1, r, prefix_sum, num + 1), maxScore( l, r - 1, prefix_sum, num + 1));} // Function to find the max scorefunction findMaxScore(a, n){ // Prefix sum array let prefix_sum = new Uint8Array(n); prefix_sum[0] = a[0]; // Calculating prefix_sum for (let i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } return maxScore(0, n - 1, prefix_sum, 1);} // Driver code let n = 6; let A = [ 1, 2, 3, 4, 2, 6 ]; document.write(findMaxScore(A, n)); // This code is contributed by Surbhi Tyagi. </script>
13
Time complexity: O(2N)Efficient approach
In the previous approach it can be observed that we are calculating same subproblems many times, i.e. it follows the property of Overlapping Subproblems. So we can use Dynamic programming to solve the problem
In the recursive solution stated above, we only need to add memoization using a dp table. The states will be:
DP table states = dp[l][r][num]where l and r represent the endpoints of the current array and num represents the operation number.
Below is the implementation of the Memoization approach of the recursive code:
C++
Java
Python3
C#
Javascript
// C++ program to find the maximum// Score after given operations #include <bits/stdc++.h>using namespace std; // Memoizing by the use of a tableint dp[100][100][100]; // Function to calculate maximum scoreint MaximumScoreDP(int l, int r, int prefix_sum[], int num){ // Bse case if (l > r) return 0; // If the same state has // already been computed if (dp[l][r][num] != -1) return dp[l][r][num]; // Sum of array in range (l, r) int current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, and storing // maximum value in DP table to avoid // further repetitive recursive calls dp[l][r][num] = current_sum + max( MaximumScoreDP( l + 1, r, prefix_sum, num + 1), MaximumScoreDP( l, r - 1, prefix_sum, num + 1)); return dp[l][r][num];} // Function to find the max scoreint findMaxScore(int a[], int n){ // Prefix sum array int prefix_sum[n] = { 0 }; prefix_sum[0] = a[0]; // Calculating prefix_sum for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } // Initialising the DP table, // -1 represents the subproblem // hasn't been solved yet memset(dp, -1, sizeof(dp)); return MaximumScoreDP( 0, n - 1, prefix_sum, 1);} // Driver codeint main(){ int n = 6; int A[n] = { 1, 2, 3, 4, 2, 6 }; cout << findMaxScore(A, n); return 0;}
// Java program to find the maximum// Score after given operations class GFG{ // Memoizing by the use of a tablestatic int [][][]dp = new int[100][100][100]; // Function to calculate maximum scorestatic int MaximumScoreDP(int l, int r, int prefix_sum[], int num){ // Bse case if (l > r) return 0; // If the same state has // already been computed if (dp[l][r][num] != -1) return dp[l][r][num]; // Sum of array in range (l, r) int current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, and storing // maximum value in DP table to avoid // further repetitive recursive calls dp[l][r][num] = current_sum + Math.max( MaximumScoreDP( l + 1, r, prefix_sum, num + 1), MaximumScoreDP( l, r - 1, prefix_sum, num + 1)); return dp[l][r][num];} // Function to find the max scorestatic int findMaxScore(int a[], int n){ // Prefix sum array int []prefix_sum = new int[n]; prefix_sum[0] = a[0]; // Calculating prefix_sum for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } // Initialising the DP table, // -1 represents the subproblem // hasn't been solved yet for(int i = 0;i<100;i++){ for(int j = 0;j<100;j++){ for(int l=0;l<100;l++) dp[i][j][l]=-1; } } return MaximumScoreDP( 0, n - 1, prefix_sum, 1);} // Driver codepublic static void main(String[] args){ int n = 6; int A[] = { 1, 2, 3, 4, 2, 6 }; System.out.print(findMaxScore(A, n));}} // This code contributed by sapnasingh4991
# python3 program to find the maximum# Score after given operations # Memoizing by the use of a tabledp = [[[-1 for x in range(100)]for y in range(100)]for z in range(100)] # Function to calculate maximum score def MaximumScoreDP(l, r, prefix_sum, num): # Bse case if (l > r): return 0 # If the same state has # already been computed if (dp[l][r][num] != -1): return dp[l][r][num] # Sum of array in range (l, r) current_sum = prefix_sum[r] if (l - 1 >= 0): current_sum -= prefix_sum[l - 1] # If the operation is even-numbered # the score is decremented if (num % 2 == 0): current_sum *= -1 # Exploring all paths, and storing # maximum value in DP table to avoid # further repetitive recursive calls dp[l][r][num] = (current_sum + max( MaximumScoreDP( l + 1, r, prefix_sum, num + 1), MaximumScoreDP( l, r - 1, prefix_sum, num + 1))) return dp[l][r][num] # Function to find the max scoredef findMaxScore(a, n): # Prefix sum array prefix_sum = [0]*n prefix_sum[0] = a[0] # Calculating prefix_sum for i in range(1, n): prefix_sum[i] = prefix_sum[i - 1] + a[i] # Initialising the DP table, # -1 represents the subproblem # hasn't been solved yet global dp return MaximumScoreDP( 0, n - 1, prefix_sum, 1) # Driver codeif __name__ == "__main__": n = 6 A = [1, 2, 3, 4, 2, 6] print(findMaxScore(A, n))
// C# program to find the maximum// Score after given operations using System; public class GFG{ // Memoizing by the use of a tablestatic int [,,]dp = new int[100,100,100]; // Function to calculate maximum scorestatic int MaximumScoreDP(int l, int r, int []prefix_sum, int num){ // Bse case if (l > r) return 0; // If the same state has // already been computed if (dp[l,r,num] != -1) return dp[l,r,num]; // Sum of array in range (l, r) int current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, and storing // maximum value in DP table to avoid // further repetitive recursive calls dp[l,r,num] = current_sum + Math.Max( MaximumScoreDP( l + 1, r, prefix_sum, num + 1), MaximumScoreDP( l, r - 1, prefix_sum, num + 1)); return dp[l,r,num];} // Function to find the max scorestatic int findMaxScore(int []a, int n){ // Prefix sum array int []prefix_sum = new int[n]; prefix_sum[0] = a[0]; // Calculating prefix_sum for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } // Initialising the DP table, // -1 represents the subproblem // hasn't been solved yet for(int i = 0;i<100;i++){ for(int j = 0;j<100;j++){ for(int l=0;l<100;l++) dp[i,j,l]=-1; } } return MaximumScoreDP( 0, n - 1, prefix_sum, 1);} // Driver codepublic static void Main(String[] args){ int n = 6; int []A = { 1, 2, 3, 4, 2, 6 }; Console.Write(findMaxScore(A, n));}} // This code contributed by PrinciRaj1992
<script> // JavaScript program to find the maximum// Score after given operations // Memoizing by the use of a tablelet dp = new Array(100);// Initialising the DP table, // -1 represents the subproblem // hasn't been solved yetfor(let i=0;i<100;i++){ dp[i]=new Array(100); for(let j=0;j<100;j++) { dp[i][j]=new Array(100); for(let k=0;k<100;k++) { dp[i][j][k]=-1; } }} // Function to calculate maximum scorefunction MaximumScoreDP(l,r,prefix_sum,num){ // Bse case if (l > r) return 0; // If the same state has // already been computed if (dp[l][r][num] != -1) return dp[l][r][num]; // Sum of array in range (l, r) let current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, and storing // maximum value in DP table to avoid // further repetitive recursive calls dp[l][r][num] = current_sum + Math.max( MaximumScoreDP( l + 1, r, prefix_sum, num + 1), MaximumScoreDP( l, r - 1, prefix_sum, num + 1)); return dp[l][r][num];} // Function to find the max scorefunction findMaxScore(a,n){ // Prefix sum array let prefix_sum = new Array(n); prefix_sum[0] = a[0]; // Calculating prefix_sum for (let i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } // Initialising the DP table, // -1 represents the subproblem // hasn't been solved yet return MaximumScoreDP( 0, n - 1, prefix_sum, 1);} // Driver codelet n = 6;let A=[1, 2, 3, 4, 2, 6 ];document.write(findMaxScore(A, n)); // This code is contributed by rag2127 </script>
13
Time complexity: O(N3)
sapnasingh4991
29AjayKumar
princiraj1992
SoumikMondal
ukasp
surbhityagi15
rag2127
Arrays
Dynamic Programming
Recursion
Arrays
Dynamic Programming
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 243,
"s": 54,
"text": "Given an array A of size N, the task is to find the maximum score possible of this array. The score of an array is calculated by performing the following operations on the array N times: "
},
{
"code": null,
"e": 555,
"s": 243,
"text": "If the operation is odd-numbered, the score is incremented by the sum of all elements of the current array. If the operation is even-numbered, the score is decremented by the sum of all elements of the current array. After every operation, either remove the first or the last element of the remaining array. "
},
{
"code": null,
"e": 665,
"s": 555,
"text": "If the operation is odd-numbered, the score is incremented by the sum of all elements of the current array. "
},
{
"code": null,
"e": 776,
"s": 665,
"text": "If the operation is even-numbered, the score is decremented by the sum of all elements of the current array. "
},
{
"code": null,
"e": 869,
"s": 776,
"text": "After every operation, either remove the first or the last element of the remaining array. "
},
{
"code": null,
"e": 881,
"s": 869,
"text": "Examples: "
},
{
"code": null,
"e": 1924,
"s": 881,
"text": "Input: A = {1, 2, 3, 4, 2, 6} Output: 13 Explanation: The optimal operations are: 1. Operation 1 is odd. -> So add the sum of the array to the score: Score = 0 + 18 = 18 -> remove 6 from last, -> new array A = [1, 2, 3, 4, 2] 2. Operation 2 is even. -> So subtract the sum of the array from the score: Score = 18 – 12 = 6 -> remove 2 from last, -> new array A = [1, 2, 3, 4] 3. Operation 1 is odd. -> So add the sum of the array to the score: Score = 6 + 10 = 16 -> remove 4 from last, -> new array A = [1, 2, 3] 4. Operation 4 is even. -> So subtract the sum of the array from the score: Score = 16 – 6 = 10 -> remove 1 from start, -> new array A = [2, 3] 5. Operation 5 is odd. -> So add the sum of the array to the score: Score = 10 + 5 = 15 -> remove 3 from last, -> new array A = [2] 6. Operation 6 is even. -> So subtract the sum of the array from the score: Score = 15 – 2 = 13 -> remove 2 from first, -> new array A = [] The array is empty so no further operations are possible.Input: A = [5, 2, 2, 8, 1, 16, 7, 9, 12, 4] Output: 50 "
},
{
"code": null,
"e": 1943,
"s": 1926,
"text": "Naive approach "
},
{
"code": null,
"e": 2597,
"s": 1943,
"text": "In each operation, we have to remove either the leftmost or the rightmost element. A simple way would be to consider all possible ways to remove elements and for each branch compute the score and find the maximum score out of all. This can simply be done using recursion. The information we need to keep in each step would be The remaining array [l, r], where l represents the leftmost index and r the rightmost,The operation number, andThe current score.In order to calculate the sum of any array from [l, r] in each recursive step optimally, we will keep a prefix sum array. Using prefix sum array, new sum from [l, r] can be calculated in O(1) as: "
},
{
"code": null,
"e": 2871,
"s": 2597,
"text": "In each operation, we have to remove either the leftmost or the rightmost element. A simple way would be to consider all possible ways to remove elements and for each branch compute the score and find the maximum score out of all. This can simply be done using recursion. "
},
{
"code": null,
"e": 3055,
"s": 2871,
"text": "The information we need to keep in each step would be The remaining array [l, r], where l represents the leftmost index and r the rightmost,The operation number, andThe current score."
},
{
"code": null,
"e": 3142,
"s": 3055,
"text": "The remaining array [l, r], where l represents the leftmost index and r the rightmost,"
},
{
"code": null,
"e": 3168,
"s": 3142,
"text": "The operation number, and"
},
{
"code": null,
"e": 3187,
"s": 3168,
"text": "The current score."
},
{
"code": null,
"e": 3385,
"s": 3187,
"text": "In order to calculate the sum of any array from [l, r] in each recursive step optimally, we will keep a prefix sum array. Using prefix sum array, new sum from [l, r] can be calculated in O(1) as: "
},
{
"code": null,
"e": 3431,
"s": 3385,
"text": "Sum(l, r) = prefix_sum[r] – prefix_sum[l-1] "
},
{
"code": null,
"e": 3484,
"s": 3431,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 3488,
"s": 3484,
"text": "C++"
},
{
"code": null,
"e": 3493,
"s": 3488,
"text": "Java"
},
{
"code": null,
"e": 3501,
"s": 3493,
"text": "Python3"
},
{
"code": null,
"e": 3504,
"s": 3501,
"text": "C#"
},
{
"code": null,
"e": 3515,
"s": 3504,
"text": "Javascript"
},
{
"code": "// C++ program to find the maximum// score after given operations #include <bits/stdc++.h>using namespace std; // Function to calculate// maximum score recursivelyint maxScore( int l, int r, int prefix_sum[], int num){ // Base case if (l > r) return 0; // Sum of array in range (l, r) int current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, by removing // leftmost and rightmost element // and selecting the maximum value return current_sum + max( maxScore( l + 1, r, prefix_sum, num + 1), maxScore( l, r - 1, prefix_sum, num + 1));} // Function to find the max scoreint findMaxScore(int a[], int n){ // Prefix sum array int prefix_sum[n] = { 0 }; prefix_sum[0] = a[0]; // Calculating prefix_sum for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } return maxScore(0, n - 1, prefix_sum, 1);} // Driver codeint main(){ int n = 6; int A[n] = { 1, 2, 3, 4, 2, 6 }; cout << findMaxScore(A, n); return 0;}",
"e": 4923,
"s": 3515,
"text": null
},
{
"code": "// Java program to find the maximum// score after given operationsimport java.util.*; class GFG{ // Function to calculate// maximum score recursivelystatic int maxScore( int l, int r, int prefix_sum[], int num){ // Base case if (l > r) return 0; // Sum of array in range (l, r) int current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, by removing // leftmost and rightmost element // and selecting the maximum value return current_sum + Math.max(maxScore(l + 1, r, prefix_sum, num + 1), maxScore(l, r - 1, prefix_sum, num + 1));} // Function to find the max scorestatic int findMaxScore(int a[], int n){ // Prefix sum array int prefix_sum[] = new int[n]; prefix_sum[0] = a[0]; // Calculating prefix_sum for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } return maxScore(0, n - 1, prefix_sum, 1);} // Driver codepublic static void main(String[] args){ int n = 6; int A[] = { 1, 2, 3, 4, 2, 6 }; System.out.print(findMaxScore(A, n));}} // This code is contributed by sapnasingh4991",
"e": 6376,
"s": 4923,
"text": null
},
{
"code": "# Python3 program to find the maximum# score after given operations # Function to calculate maximum# score recursivelydef maxScore(l, r, prefix_sum, num): # Base case if (l > r): return 0; # Sum of array in range (l, r) if((l - 1) >= 0): current_sum = (prefix_sum[r] - prefix_sum[l - 1]) else: current_sum = prefix_sum[r] - 0 # If the operation is even-numbered # the score is decremented if (num % 2 == 0): current_sum *= -1; # Exploring all paths, by removing # leftmost and rightmost element # and selecting the maximum value return current_sum + max(maxScore(l + 1, r, prefix_sum, num + 1), maxScore(l, r - 1, prefix_sum, num + 1)); # Function to find the max scoredef findMaxScore(a, n): # Prefix sum array prefix_sum = [0] * n prefix_sum[0] = a[0] # Calculating prefix_sum for i in range(1, n): prefix_sum[i] = prefix_sum[i - 1] + a[i]; return maxScore(0, n - 1, prefix_sum, 1); # Driver coden = 6;A = [ 1, 2, 3, 4, 2, 6 ]ans = findMaxScore(A, n) print(ans) # This code is contributed by SoumikMondal",
"e": 7694,
"s": 6376,
"text": null
},
{
"code": "// C# program to find the maximum// score after given operationsusing System; class GFG{ // Function to calculate// maximum score recursivelystatic int maxScore( int l, int r, int []prefix_sum, int num){ // Base case if (l > r) return 0; // Sum of array in range (l, r) int current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, by removing // leftmost and rightmost element // and selecting the maximum value return current_sum + Math.Max(maxScore(l + 1, r, prefix_sum, num + 1), maxScore(l, r - 1, prefix_sum, num + 1));} // Function to find the max scorestatic int findMaxScore(int []a, int n){ // Prefix sum array int []prefix_sum = new int[n]; prefix_sum[0] = a[0]; // Calculating prefix_sum for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } return maxScore(0, n - 1, prefix_sum, 1);} // Driver codepublic static void Main(String[] args){ int n = 6; int []A = { 1, 2, 3, 4, 2, 6 }; Console.Write(findMaxScore(A, n));}} // This code is contributed by 29AjayKumar",
"e": 9144,
"s": 7694,
"text": null
},
{
"code": "<script> // JavaScript program to find the maximum// score after given operations // Function to calculate// maximum score recursivelyfunction maxScore(l, r, prefix_sum, num){ // Base case if (l > r) return 0; // Sum of array in range (l, r) let current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, by removing // leftmost and rightmost element // and selecting the maximum value return current_sum + Math.max( maxScore( l + 1, r, prefix_sum, num + 1), maxScore( l, r - 1, prefix_sum, num + 1));} // Function to find the max scorefunction findMaxScore(a, n){ // Prefix sum array let prefix_sum = new Uint8Array(n); prefix_sum[0] = a[0]; // Calculating prefix_sum for (let i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } return maxScore(0, n - 1, prefix_sum, 1);} // Driver code let n = 6; let A = [ 1, 2, 3, 4, 2, 6 ]; document.write(findMaxScore(A, n)); // This code is contributed by Surbhi Tyagi. </script>",
"e": 10531,
"s": 9144,
"text": null
},
{
"code": null,
"e": 10534,
"s": 10531,
"text": "13"
},
{
"code": null,
"e": 10579,
"s": 10536,
"text": "Time complexity: O(2N)Efficient approach "
},
{
"code": null,
"e": 10790,
"s": 10579,
"text": "In the previous approach it can be observed that we are calculating same subproblems many times, i.e. it follows the property of Overlapping Subproblems. So we can use Dynamic programming to solve the problem "
},
{
"code": null,
"e": 10902,
"s": 10790,
"text": "In the recursive solution stated above, we only need to add memoization using a dp table. The states will be: "
},
{
"code": null,
"e": 11035,
"s": 10902,
"text": "DP table states = dp[l][r][num]where l and r represent the endpoints of the current array and num represents the operation number. "
},
{
"code": null,
"e": 11116,
"s": 11035,
"text": "Below is the implementation of the Memoization approach of the recursive code: "
},
{
"code": null,
"e": 11120,
"s": 11116,
"text": "C++"
},
{
"code": null,
"e": 11125,
"s": 11120,
"text": "Java"
},
{
"code": null,
"e": 11133,
"s": 11125,
"text": "Python3"
},
{
"code": null,
"e": 11136,
"s": 11133,
"text": "C#"
},
{
"code": null,
"e": 11147,
"s": 11136,
"text": "Javascript"
},
{
"code": "// C++ program to find the maximum// Score after given operations #include <bits/stdc++.h>using namespace std; // Memoizing by the use of a tableint dp[100][100][100]; // Function to calculate maximum scoreint MaximumScoreDP(int l, int r, int prefix_sum[], int num){ // Bse case if (l > r) return 0; // If the same state has // already been computed if (dp[l][r][num] != -1) return dp[l][r][num]; // Sum of array in range (l, r) int current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, and storing // maximum value in DP table to avoid // further repetitive recursive calls dp[l][r][num] = current_sum + max( MaximumScoreDP( l + 1, r, prefix_sum, num + 1), MaximumScoreDP( l, r - 1, prefix_sum, num + 1)); return dp[l][r][num];} // Function to find the max scoreint findMaxScore(int a[], int n){ // Prefix sum array int prefix_sum[n] = { 0 }; prefix_sum[0] = a[0]; // Calculating prefix_sum for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } // Initialising the DP table, // -1 represents the subproblem // hasn't been solved yet memset(dp, -1, sizeof(dp)); return MaximumScoreDP( 0, n - 1, prefix_sum, 1);} // Driver codeint main(){ int n = 6; int A[n] = { 1, 2, 3, 4, 2, 6 }; cout << findMaxScore(A, n); return 0;}",
"e": 13008,
"s": 11147,
"text": null
},
{
"code": "// Java program to find the maximum// Score after given operations class GFG{ // Memoizing by the use of a tablestatic int [][][]dp = new int[100][100][100]; // Function to calculate maximum scorestatic int MaximumScoreDP(int l, int r, int prefix_sum[], int num){ // Bse case if (l > r) return 0; // If the same state has // already been computed if (dp[l][r][num] != -1) return dp[l][r][num]; // Sum of array in range (l, r) int current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, and storing // maximum value in DP table to avoid // further repetitive recursive calls dp[l][r][num] = current_sum + Math.max( MaximumScoreDP( l + 1, r, prefix_sum, num + 1), MaximumScoreDP( l, r - 1, prefix_sum, num + 1)); return dp[l][r][num];} // Function to find the max scorestatic int findMaxScore(int a[], int n){ // Prefix sum array int []prefix_sum = new int[n]; prefix_sum[0] = a[0]; // Calculating prefix_sum for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } // Initialising the DP table, // -1 represents the subproblem // hasn't been solved yet for(int i = 0;i<100;i++){ for(int j = 0;j<100;j++){ for(int l=0;l<100;l++) dp[i][j][l]=-1; } } return MaximumScoreDP( 0, n - 1, prefix_sum, 1);} // Driver codepublic static void main(String[] args){ int n = 6; int A[] = { 1, 2, 3, 4, 2, 6 }; System.out.print(findMaxScore(A, n));}} // This code contributed by sapnasingh4991",
"e": 15066,
"s": 13008,
"text": null
},
{
"code": "# python3 program to find the maximum# Score after given operations # Memoizing by the use of a tabledp = [[[-1 for x in range(100)]for y in range(100)]for z in range(100)] # Function to calculate maximum score def MaximumScoreDP(l, r, prefix_sum, num): # Bse case if (l > r): return 0 # If the same state has # already been computed if (dp[l][r][num] != -1): return dp[l][r][num] # Sum of array in range (l, r) current_sum = prefix_sum[r] if (l - 1 >= 0): current_sum -= prefix_sum[l - 1] # If the operation is even-numbered # the score is decremented if (num % 2 == 0): current_sum *= -1 # Exploring all paths, and storing # maximum value in DP table to avoid # further repetitive recursive calls dp[l][r][num] = (current_sum + max( MaximumScoreDP( l + 1, r, prefix_sum, num + 1), MaximumScoreDP( l, r - 1, prefix_sum, num + 1))) return dp[l][r][num] # Function to find the max scoredef findMaxScore(a, n): # Prefix sum array prefix_sum = [0]*n prefix_sum[0] = a[0] # Calculating prefix_sum for i in range(1, n): prefix_sum[i] = prefix_sum[i - 1] + a[i] # Initialising the DP table, # -1 represents the subproblem # hasn't been solved yet global dp return MaximumScoreDP( 0, n - 1, prefix_sum, 1) # Driver codeif __name__ == \"__main__\": n = 6 A = [1, 2, 3, 4, 2, 6] print(findMaxScore(A, n))",
"e": 16766,
"s": 15066,
"text": null
},
{
"code": "// C# program to find the maximum// Score after given operations using System; public class GFG{ // Memoizing by the use of a tablestatic int [,,]dp = new int[100,100,100]; // Function to calculate maximum scorestatic int MaximumScoreDP(int l, int r, int []prefix_sum, int num){ // Bse case if (l > r) return 0; // If the same state has // already been computed if (dp[l,r,num] != -1) return dp[l,r,num]; // Sum of array in range (l, r) int current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, and storing // maximum value in DP table to avoid // further repetitive recursive calls dp[l,r,num] = current_sum + Math.Max( MaximumScoreDP( l + 1, r, prefix_sum, num + 1), MaximumScoreDP( l, r - 1, prefix_sum, num + 1)); return dp[l,r,num];} // Function to find the max scorestatic int findMaxScore(int []a, int n){ // Prefix sum array int []prefix_sum = new int[n]; prefix_sum[0] = a[0]; // Calculating prefix_sum for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } // Initialising the DP table, // -1 represents the subproblem // hasn't been solved yet for(int i = 0;i<100;i++){ for(int j = 0;j<100;j++){ for(int l=0;l<100;l++) dp[i,j,l]=-1; } } return MaximumScoreDP( 0, n - 1, prefix_sum, 1);} // Driver codepublic static void Main(String[] args){ int n = 6; int []A = { 1, 2, 3, 4, 2, 6 }; Console.Write(findMaxScore(A, n));}} // This code contributed by PrinciRaj1992",
"e": 18841,
"s": 16766,
"text": null
},
{
"code": "<script> // JavaScript program to find the maximum// Score after given operations // Memoizing by the use of a tablelet dp = new Array(100);// Initialising the DP table, // -1 represents the subproblem // hasn't been solved yetfor(let i=0;i<100;i++){ dp[i]=new Array(100); for(let j=0;j<100;j++) { dp[i][j]=new Array(100); for(let k=0;k<100;k++) { dp[i][j][k]=-1; } }} // Function to calculate maximum scorefunction MaximumScoreDP(l,r,prefix_sum,num){ // Bse case if (l > r) return 0; // If the same state has // already been computed if (dp[l][r][num] != -1) return dp[l][r][num]; // Sum of array in range (l, r) let current_sum = prefix_sum[r] - (l - 1 >= 0 ? prefix_sum[l - 1] : 0); // If the operation is even-numbered // the score is decremented if (num % 2 == 0) current_sum *= -1; // Exploring all paths, and storing // maximum value in DP table to avoid // further repetitive recursive calls dp[l][r][num] = current_sum + Math.max( MaximumScoreDP( l + 1, r, prefix_sum, num + 1), MaximumScoreDP( l, r - 1, prefix_sum, num + 1)); return dp[l][r][num];} // Function to find the max scorefunction findMaxScore(a,n){ // Prefix sum array let prefix_sum = new Array(n); prefix_sum[0] = a[0]; // Calculating prefix_sum for (let i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + a[i]; } // Initialising the DP table, // -1 represents the subproblem // hasn't been solved yet return MaximumScoreDP( 0, n - 1, prefix_sum, 1);} // Driver codelet n = 6;let A=[1, 2, 3, 4, 2, 6 ];document.write(findMaxScore(A, n)); // This code is contributed by rag2127 </script>",
"e": 20917,
"s": 18841,
"text": null
},
{
"code": null,
"e": 20920,
"s": 20917,
"text": "13"
},
{
"code": null,
"e": 20946,
"s": 20922,
"text": "Time complexity: O(N3) "
},
{
"code": null,
"e": 20961,
"s": 20946,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 20973,
"s": 20961,
"text": "29AjayKumar"
},
{
"code": null,
"e": 20987,
"s": 20973,
"text": "princiraj1992"
},
{
"code": null,
"e": 21000,
"s": 20987,
"text": "SoumikMondal"
},
{
"code": null,
"e": 21006,
"s": 21000,
"text": "ukasp"
},
{
"code": null,
"e": 21020,
"s": 21006,
"text": "surbhityagi15"
},
{
"code": null,
"e": 21028,
"s": 21020,
"text": "rag2127"
},
{
"code": null,
"e": 21035,
"s": 21028,
"text": "Arrays"
},
{
"code": null,
"e": 21055,
"s": 21035,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 21065,
"s": 21055,
"text": "Recursion"
},
{
"code": null,
"e": 21072,
"s": 21065,
"text": "Arrays"
},
{
"code": null,
"e": 21092,
"s": 21072,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 21102,
"s": 21092,
"text": "Recursion"
}
]
|
MathF.Abs() Method in C# with Examples | 04 Apr, 2019
MathF.Abs(Single) Method is used to return the absolute value of a specified float number.
Syntax: public static float Abs (float x);Here, it takes a standard floating point number.
Return Value: This method returns a floating point value less than Single.MaxValue.
Example 1:
// C# program to demonstrate the// MathF.Abs(Single) Methodusing System; class GFG { // Main Method public static void Main() { // Declaring and initializing value float value = 4.5f; // Getting absolute float // using Abs() method float round = MathF.Abs(value); // Display the value Console.WriteLine("Absolute float value is {0}", round); }}
Absolute float value is 4.5
Example 2:
// C# program to demonstrate the// MathF.Abs(Single) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method get(20f); get(30.5f); get(40.5f); get(4294.586f); } // defining get() method public static void get(float value) { // getting absolute float // using Abs() method float round = MathF.Abs(value); // Display the value Console.WriteLine("Float value is {0}", round); }}
Float value is 20
Float value is 30.5
Float value is 40.5
Float value is 4294.586
CSharp-MathF-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 119,
"s": 28,
"text": "MathF.Abs(Single) Method is used to return the absolute value of a specified float number."
},
{
"code": null,
"e": 210,
"s": 119,
"text": "Syntax: public static float Abs (float x);Here, it takes a standard floating point number."
},
{
"code": null,
"e": 294,
"s": 210,
"text": "Return Value: This method returns a floating point value less than Single.MaxValue."
},
{
"code": null,
"e": 305,
"s": 294,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// MathF.Abs(Single) Methodusing System; class GFG { // Main Method public static void Main() { // Declaring and initializing value float value = 4.5f; // Getting absolute float // using Abs() method float round = MathF.Abs(value); // Display the value Console.WriteLine(\"Absolute float value is {0}\", round); }}",
"e": 769,
"s": 305,
"text": null
},
{
"code": null,
"e": 798,
"s": 769,
"text": "Absolute float value is 4.5\n"
},
{
"code": null,
"e": 809,
"s": 798,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the// MathF.Abs(Single) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method get(20f); get(30.5f); get(40.5f); get(4294.586f); } // defining get() method public static void get(float value) { // getting absolute float // using Abs() method float round = MathF.Abs(value); // Display the value Console.WriteLine(\"Float value is {0}\", round); }}",
"e": 1358,
"s": 809,
"text": null
},
{
"code": null,
"e": 1441,
"s": 1358,
"text": "Float value is 20\nFloat value is 30.5\nFloat value is 40.5\nFloat value is 4294.586\n"
},
{
"code": null,
"e": 1460,
"s": 1441,
"text": "CSharp-MathF-Class"
},
{
"code": null,
"e": 1474,
"s": 1460,
"text": "CSharp-method"
},
{
"code": null,
"e": 1477,
"s": 1474,
"text": "C#"
}
]
|
Python | Lemmatization with NLTK | 18 May, 2022
Lemmatization is the process of grouping together the different inflected forms of a word so they can be analyzed as a single item. Lemmatization is similar to stemming but it brings context to the words. So it links words with similar meanings to one word. Text preprocessing includes both Stemming as well as Lemmatization. Many times people find these two terms confusing. Some treat these two as the same. Actually, lemmatization is preferred over Stemming because lemmatization does morphological analysis of the words.Applications of lemmatization are:
Used in comprehensive retrieval systems like search engines.
Used in compact indexing
Examples of lemmatization:
-> rocks : rock
-> corpora : corpus
-> better : good
One major difference with stemming is that lemmatize takes a part of speech parameter, “pos” If not supplied, the default is “noun.”Below is the implementation of lemmatization words using NLTK:
Python3
# import these modulesfrom nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() print("rocks :", lemmatizer.lemmatize("rocks"))print("corpora :", lemmatizer.lemmatize("corpora")) # a denotes adjective in "pos"print("better :", lemmatizer.lemmatize("better", pos ="a"))
Output :
rocks : rock
corpora : corpus
better : good
tanwarsinghvaibhav
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Introduction to Recurrent Neural Network
Getting started with Machine Learning
ML | Underfitting and Overfitting
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 May, 2022"
},
{
"code": null,
"e": 614,
"s": 53,
"text": "Lemmatization is the process of grouping together the different inflected forms of a word so they can be analyzed as a single item. Lemmatization is similar to stemming but it brings context to the words. So it links words with similar meanings to one word. Text preprocessing includes both Stemming as well as Lemmatization. Many times people find these two terms confusing. Some treat these two as the same. Actually, lemmatization is preferred over Stemming because lemmatization does morphological analysis of the words.Applications of lemmatization are: "
},
{
"code": null,
"e": 675,
"s": 614,
"text": "Used in comprehensive retrieval systems like search engines."
},
{
"code": null,
"e": 700,
"s": 675,
"text": "Used in compact indexing"
},
{
"code": null,
"e": 783,
"s": 702,
"text": "Examples of lemmatization:\n\n-> rocks : rock\n-> corpora : corpus\n-> better : good"
},
{
"code": null,
"e": 979,
"s": 783,
"text": "One major difference with stemming is that lemmatize takes a part of speech parameter, “pos” If not supplied, the default is “noun.”Below is the implementation of lemmatization words using NLTK: "
},
{
"code": null,
"e": 987,
"s": 979,
"text": "Python3"
},
{
"code": "# import these modulesfrom nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() print(\"rocks :\", lemmatizer.lemmatize(\"rocks\"))print(\"corpora :\", lemmatizer.lemmatize(\"corpora\")) # a denotes adjective in \"pos\"print(\"better :\", lemmatizer.lemmatize(\"better\", pos =\"a\"))",
"e": 1274,
"s": 987,
"text": null
},
{
"code": null,
"e": 1285,
"s": 1274,
"text": "Output : "
},
{
"code": null,
"e": 1329,
"s": 1285,
"text": "rocks : rock\ncorpora : corpus\nbetter : good"
},
{
"code": null,
"e": 1350,
"s": 1331,
"text": "tanwarsinghvaibhav"
},
{
"code": null,
"e": 1367,
"s": 1350,
"text": "Machine Learning"
},
{
"code": null,
"e": 1374,
"s": 1367,
"text": "Python"
},
{
"code": null,
"e": 1391,
"s": 1374,
"text": "Machine Learning"
},
{
"code": null,
"e": 1489,
"s": 1391,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1525,
"s": 1489,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 1549,
"s": 1525,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 1590,
"s": 1549,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 1628,
"s": 1590,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 1662,
"s": 1628,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 1690,
"s": 1662,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 1740,
"s": 1690,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 1762,
"s": 1740,
"text": "Python map() function"
},
{
"code": null,
"e": 1780,
"s": 1762,
"text": "Python Dictionary"
}
]
|
matplotlib.pyplot.plot_date() in Python | 22 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The plot_date() function in pyplot module of matplotlib library is used to plot with data that contains dates.
Syntax:
matplotlib.pyplot.plot_date(x, y, fmt='o', tz=None, xdate=True, ydate=False, hold=None, data=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
x, y: These parameter are the horizontal and vertical coordinates of the data points.
fmt: This parameter is an optional parameter and it contains the string value.
tz: This parameter is the time zone to use in labeling dates.It contain timezone string.
xdate: This parameter is also an optional parameter. And it contain boolean values with default value True. If True, the x-axis will be interpreted as Matplotlib dates.
ydate: This parameter is also an optional parameter. And it contain boolean values with default value True. If True, the y-axis will be interpreted as Matplotlib dates.
Returns: This returns the following:
lines:This returns the list of Line2D objects representing the plotted data.
Below examples illustrate the matplotlib.pyplot.plot_date() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import drangeimport numpy as np date1 = datetime.datetime(2020, 4, 2)date2 = datetime.datetime(2020, 4, 12)delta = datetime.timedelta(hours = 24)dates = drange(date1, date2, delta) y = np.arange(len(dates)) plt.plot_date(dates, y ** 2)plt.title('matplotlib.pyplot.plot_date() function Example', fontweight ="bold")plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter, drangeimport numpy as np date1 = datetime.datetime(2020, 4, 2)date2 = datetime.datetime(2020, 4, 6)delta = datetime.timedelta(hours = 6)dates = drange(date1, date2, delta) y = np.arange(len(dates)) fig, ax = plt.subplots()ax.plot_date(dates, y ** 2, 'g') ax.set_xlim(dates[0], dates[-1]) ax.xaxis.set_major_locator(DayLocator())ax.xaxis.set_minor_locator(HourLocator(range(0, 25, 6)))ax.xaxis.set_major_formatter(DateFormatter('% Y-% m-% d')) ax.fmt_xdata = DateFormatter('% Y-% m-% d % H:% M:% S')fig.autofmt_xdate()plt.title('matplotlib.pyplot.plot_date() function Example', fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 223,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface."
},
{
"code": null,
"e": 334,
"s": 223,
"text": "The plot_date() function in pyplot module of matplotlib library is used to plot with data that contains dates."
},
{
"code": null,
"e": 342,
"s": 334,
"text": "Syntax:"
},
{
"code": null,
"e": 452,
"s": 342,
"text": "matplotlib.pyplot.plot_date(x, y, fmt='o', tz=None, xdate=True, ydate=False, hold=None, data=None, **kwargs)\n"
},
{
"code": null,
"e": 534,
"s": 452,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 620,
"s": 534,
"text": "x, y: These parameter are the horizontal and vertical coordinates of the data points."
},
{
"code": null,
"e": 699,
"s": 620,
"text": "fmt: This parameter is an optional parameter and it contains the string value."
},
{
"code": null,
"e": 788,
"s": 699,
"text": "tz: This parameter is the time zone to use in labeling dates.It contain timezone string."
},
{
"code": null,
"e": 957,
"s": 788,
"text": "xdate: This parameter is also an optional parameter. And it contain boolean values with default value True. If True, the x-axis will be interpreted as Matplotlib dates."
},
{
"code": null,
"e": 1126,
"s": 957,
"text": "ydate: This parameter is also an optional parameter. And it contain boolean values with default value True. If True, the y-axis will be interpreted as Matplotlib dates."
},
{
"code": null,
"e": 1163,
"s": 1126,
"text": "Returns: This returns the following:"
},
{
"code": null,
"e": 1240,
"s": 1163,
"text": "lines:This returns the list of Line2D objects representing the plotted data."
},
{
"code": null,
"e": 1331,
"s": 1240,
"text": "Below examples illustrate the matplotlib.pyplot.plot_date() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 1343,
"s": 1331,
"text": "Example #1:"
},
{
"code": "# Implementation of matplotlib functionimport datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import drangeimport numpy as np date1 = datetime.datetime(2020, 4, 2)date2 = datetime.datetime(2020, 4, 12)delta = datetime.timedelta(hours = 24)dates = drange(date1, date2, delta) y = np.arange(len(dates)) plt.plot_date(dates, y ** 2)plt.title('matplotlib.pyplot.plot_date() function Example', fontweight =\"bold\")plt.show()",
"e": 1781,
"s": 1343,
"text": null
},
{
"code": null,
"e": 1789,
"s": 1781,
"text": "Output:"
},
{
"code": null,
"e": 1801,
"s": 1789,
"text": "Example #2:"
},
{
"code": "# Implementation of matplotlib functionimport datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter, drangeimport numpy as np date1 = datetime.datetime(2020, 4, 2)date2 = datetime.datetime(2020, 4, 6)delta = datetime.timedelta(hours = 6)dates = drange(date1, date2, delta) y = np.arange(len(dates)) fig, ax = plt.subplots()ax.plot_date(dates, y ** 2, 'g') ax.set_xlim(dates[0], dates[-1]) ax.xaxis.set_major_locator(DayLocator())ax.xaxis.set_minor_locator(HourLocator(range(0, 25, 6)))ax.xaxis.set_major_formatter(DateFormatter('% Y-% m-% d')) ax.fmt_xdata = DateFormatter('% Y-% m-% d % H:% M:% S')fig.autofmt_xdate()plt.title('matplotlib.pyplot.plot_date() function Example', fontweight =\"bold\")plt.show()",
"e": 2574,
"s": 1801,
"text": null
},
{
"code": null,
"e": 2582,
"s": 2574,
"text": "Output:"
},
{
"code": null,
"e": 2600,
"s": 2582,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2607,
"s": 2600,
"text": "Python"
}
]
|
Matplotlib.dates.datestr2num() in Python | 21 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.dates.datestr2num() function is used to convert a date string to a datenum by the uses of dateutil.parser.parser().
Syntax: matplotlib.dates.datestr2num(d, default=None)
Parameters:
d: It is a string or a sequence of strings representing the dates.default: This is an optional parameter that is a datetime instance. This is used when fields are not present in d, as a default.
d: It is a string or a sequence of strings representing the dates.
default: This is an optional parameter that is a datetime instance. This is used when fields are not present in d, as a default.
Example 1:
from datetime import datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import ( DateFormatter, AutoDateLocator, AutoDateFormatter, datestr2num) days = [ '30/01/2019', '31/01/2019', '01/02/2019', '02/02/2019', '03/02/2019', '04/02/2019']data1 = [2, 5, 13, 6, 11, 7]data2 = [6, 3, 10, 3, 6, 5] z = datestr2num([ datetime.strptime(day, '%d/%m/%Y').strftime('%m/%d/%Y') for day in days]) r = 0.25 figure = plt.figure(figsize =(8, 4))axes = figure.add_subplot(111) axes.bar(z - r, data1, width = 2 * r, color ='g', align ='center', tick_label = day) axes.bar(z + r, data2, width = 2 * r, color ='y', align ='center', tick_label = day) axes.xaxis_date()axes.xaxis.set_major_locator( AutoDateLocator(minticks = 3, interval_multiples = False)) axes.xaxis.set_major_formatter(DateFormatter("%d/%m/%y")) plt.show()
Output:
Example 2:
import matplotlibimport matplotlib.pyplot as pltimport matplotlib.dates dates = ['1920-05-06', '1920-05-07', '1947-05-08', '1920-05-09'] converted_dates = matplotlib.dates.datestr2num(dates) x_axis = (converted_dates)y_axis = range(0, 4) plt.plot_date( x_axis, y_axis, '-' ) plt.show()
Output:
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 240,
"s": 28,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack."
},
{
"code": null,
"e": 371,
"s": 240,
"text": "The matplotlib.dates.datestr2num() function is used to convert a date string to a datenum by the uses of dateutil.parser.parser()."
},
{
"code": null,
"e": 425,
"s": 371,
"text": "Syntax: matplotlib.dates.datestr2num(d, default=None)"
},
{
"code": null,
"e": 437,
"s": 425,
"text": "Parameters:"
},
{
"code": null,
"e": 632,
"s": 437,
"text": "d: It is a string or a sequence of strings representing the dates.default: This is an optional parameter that is a datetime instance. This is used when fields are not present in d, as a default."
},
{
"code": null,
"e": 699,
"s": 632,
"text": "d: It is a string or a sequence of strings representing the dates."
},
{
"code": null,
"e": 828,
"s": 699,
"text": "default: This is an optional parameter that is a datetime instance. This is used when fields are not present in d, as a default."
},
{
"code": null,
"e": 839,
"s": 828,
"text": "Example 1:"
},
{
"code": "from datetime import datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import ( DateFormatter, AutoDateLocator, AutoDateFormatter, datestr2num) days = [ '30/01/2019', '31/01/2019', '01/02/2019', '02/02/2019', '03/02/2019', '04/02/2019']data1 = [2, 5, 13, 6, 11, 7]data2 = [6, 3, 10, 3, 6, 5] z = datestr2num([ datetime.strptime(day, '%d/%m/%Y').strftime('%m/%d/%Y') for day in days]) r = 0.25 figure = plt.figure(figsize =(8, 4))axes = figure.add_subplot(111) axes.bar(z - r, data1, width = 2 * r, color ='g', align ='center', tick_label = day) axes.bar(z + r, data2, width = 2 * r, color ='y', align ='center', tick_label = day) axes.xaxis_date()axes.xaxis.set_major_locator( AutoDateLocator(minticks = 3, interval_multiples = False)) axes.xaxis.set_major_formatter(DateFormatter(\"%d/%m/%y\")) plt.show()",
"e": 1732,
"s": 839,
"text": null
},
{
"code": null,
"e": 1740,
"s": 1732,
"text": "Output:"
},
{
"code": null,
"e": 1751,
"s": 1740,
"text": "Example 2:"
},
{
"code": "import matplotlibimport matplotlib.pyplot as pltimport matplotlib.dates dates = ['1920-05-06', '1920-05-07', '1947-05-08', '1920-05-09'] converted_dates = matplotlib.dates.datestr2num(dates) x_axis = (converted_dates)y_axis = range(0, 4) plt.plot_date( x_axis, y_axis, '-' ) plt.show()",
"e": 2075,
"s": 1751,
"text": null
},
{
"code": null,
"e": 2083,
"s": 2075,
"text": "Output:"
},
{
"code": null,
"e": 2101,
"s": 2083,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2108,
"s": 2101,
"text": "Python"
},
{
"code": null,
"e": 2124,
"s": 2108,
"text": "Write From Home"
},
{
"code": null,
"e": 2222,
"s": 2124,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2240,
"s": 2222,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2282,
"s": 2240,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2304,
"s": 2282,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2330,
"s": 2304,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2362,
"s": 2330,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2398,
"s": 2362,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2434,
"s": 2398,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 2495,
"s": 2434,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 2511,
"s": 2495,
"text": "Python infinity"
}
]
|
GATE | GATE-CS-2009 | Question 60 | 28 Jun, 2021
The below DFA accepts the set of all strings over {0,1} that
(A) begin either with 0 or 1(B) end with 0(C) end with 00(D) contain the substring 00.Answer: (C)Explanation: If the strings beginning with 0 and 1 are 01 and 11 respectively, then the DFA doesn’t accept these( because it doesn’t reach to the final terminating/accepting state). Hence not option A.
If the string ending with 0 is 10, then the DFA doesn’t accept this also. Hence not option B.
If the string which contains substring 00 is 1001, then the DFA doesn’t accept this also. Hence not option D.
Now, take any string which ends with 00, like 00, 100, 1100, 10100, 0100 all are accepted by the given DFA. Hence option C.
Intuitively we can also observe here by looking at the DFA that there is only one direct path to reach the final terminating state C ( lets say given 3 states(circles) are A, B and C from left to right in the diagram ), then the path is A–>B–>C , and this path requires 00 in the current substring of the input to reach from A to C.
Now after reaching C, either the string should terminate to be accepted by the given DFA, or it can also have any number of 0’s following it, for the string to be accepted. In either of the case the string would be ending with 00.Quiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 89,
"s": 28,
"text": "The below DFA accepts the set of all strings over {0,1} that"
},
{
"code": null,
"e": 388,
"s": 89,
"text": "(A) begin either with 0 or 1(B) end with 0(C) end with 00(D) contain the substring 00.Answer: (C)Explanation: If the strings beginning with 0 and 1 are 01 and 11 respectively, then the DFA doesn’t accept these( because it doesn’t reach to the final terminating/accepting state). Hence not option A."
},
{
"code": null,
"e": 482,
"s": 388,
"text": "If the string ending with 0 is 10, then the DFA doesn’t accept this also. Hence not option B."
},
{
"code": null,
"e": 592,
"s": 482,
"text": "If the string which contains substring 00 is 1001, then the DFA doesn’t accept this also. Hence not option D."
},
{
"code": null,
"e": 716,
"s": 592,
"text": "Now, take any string which ends with 00, like 00, 100, 1100, 10100, 0100 all are accepted by the given DFA. Hence option C."
},
{
"code": null,
"e": 1049,
"s": 716,
"text": "Intuitively we can also observe here by looking at the DFA that there is only one direct path to reach the final terminating state C ( lets say given 3 states(circles) are A, B and C from left to right in the diagram ), then the path is A–>B–>C , and this path requires 00 in the current substring of the input to reach from A to C."
},
{
"code": null,
"e": 1301,
"s": 1049,
"text": "Now after reaching C, either the string should terminate to be accepted by the given DFA, or it can also have any number of 0’s following it, for the string to be accepted. In either of the case the string would be ending with 00.Quiz of this Question"
},
{
"code": null,
"e": 1314,
"s": 1301,
"text": "GATE-CS-2009"
},
{
"code": null,
"e": 1332,
"s": 1314,
"text": "GATE-GATE-CS-2009"
},
{
"code": null,
"e": 1337,
"s": 1332,
"text": "GATE"
}
]
|
Check if a number can be represented as sum of two consecutive perfect cubes | 08 Apr, 2021
Given an integer N, the task is to check if this number can be represented as the sum of two consecutive perfect cubes or not.
Examples:
Input: N = 35Output: YesExplanation:Since, 35 = 23 + 33, therefore the required answer is Yes.
Input: N = 14Output: No
Naive Approach: The simplest approach to solve the problem is to iterate from 1 to cube root of N and check if the sum of perfect cubes of any two consecutive numbers is equal to N or not. If found to be true, print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program of the// above approach #include <bits/stdc++.h>using namespace std; // Function to check if a number// can be expressed as the sum of// cubes of two consecutive numbersbool isCubeSum(int n){ for (int i = 1; i * i * i <= n; i++) { if (i * i * i + (i + 1) * (i + 1) * (i + 1) == n) return true; } return false;} // Driver Codeint main(){ int n = 35; if (isCubeSum(n)) cout << "Yes"; else cout << "No";}
// Java program of the// above approachimport java.util.*; class GFG{ // Function to check if a number// can be expressed as the sum of// cubes of two consecutive numbersstatic boolean isCubeSum(int n){ for(int i = 1; i * i * i <= n; i++) { if (i * i * i + (i + 1) * (i + 1) * (i + 1) == n) return true; } return false;} // Driver Codepublic static void main(String[] args){ int n = 35; if (isCubeSum(n)) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by Amit Katiyar
# Python3 program of the# above approach # Function to check if a number# can be expressed as the sum of# cubes of two consecutive numbersdef isCubeSum(n): for i in range(1, int(pow(n, 1 / 3)) + 1): if (i * i * i + (i + 1) * (i + 1) * (i + 1) == n): return True; return False; # Driver Codeif __name__ == '__main__': n = 35; if (isCubeSum(n)): print("Yes"); else: print("No"); # This code is contributed by Amit Katiyar
// C# program of the// above approachusing System; class GFG{ // Function to check if a number// can be expressed as the sum of// cubes of two consecutive numbersstatic bool isCubeSum(int n){ for(int i = 1; i * i * i <= n; i++) { if (i * i * i + (i + 1) * (i + 1) * (i + 1) == n) return true; } return false;} // Driver Codepublic static void Main(String[] args){ int n = 35; if (isCubeSum(n)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by Amit Katiyar
<script> // Javascript Program of the// above approach // Function to check if a number// can be expressed as the sum of// cubes of two consecutive numbersfunction isCubeSum(n){ for (var i = 1; i * i * i <= n; i++) { if (i * i * i + (i + 1) * (i + 1) * (i + 1) == n) return true; } return false;} // Driver Codevar n = 35;if (isCubeSum(n)) document.write("Yes");else document.write("No"); </script>
Yes
Efficient Approach: The above approach can be optimized based on the following observations:
A number can be represented as the sum of the perfect cube of two consecutive numbers if the sum of the cube root of both consecutive numbers is equal to N.
This can be checked by the formula:
For example, if N = 35, then check of the equation below os equal to N or not:
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to// implement above approach #include <bits/stdc++.h>using namespace std; // Function to check that a number// is the sum of cubes of 2// consecutive numbers or notbool isSumCube(int N){ int a = cbrt(N); int b = a - 1; // Condition to check if a // number is the sum of cubes of 2 // consecutive numbers or not return ((a * a * a + b * b * b) == N);} // Driver Codeint main(){ int i = 35; // Function call if (isSumCube(i)) { cout << "Yes"; } else { cout << "No"; } return 0;}
// Java program to implement// above approachclass GFG{ // Function to check that a number// is the sum of cubes of 2// consecutive numbers or notstatic boolean isSumCube(int N){ int a = (int)Math.cbrt(N); int b = a - 1; // Condition to check if a // number is the sum of cubes of 2 // consecutive numbers or not return ((a * a * a + b * b * b) == N);} // Driver Codepublic static void main(String[] args){ int i = 35; // Function call if (isSumCube(i)) { System.out.print("Yes"); } else { System.out.print("No"); }}} // This code is contributed by Amit Katiyar
# Python3 program to# implement above approach # Function to check that a number# is the sum of cubes of 2# consecutive numbers or notdef isSumCube(N): a = int(pow(N, 1 / 3)) b = a - 1 # Condition to check if a # number is the sum of cubes of 2 # consecutive numbers or not ans = ((a * a * a + b * b * b) == N) return ans # Driver Codei = 35 # Function callif(isSumCube(i)): print("Yes")else: print("No") # This code is contributed by Shivam Singh
// C# program to implement// above approachusing System;class GFG{ // Function to check that a number// is the sum of cubes of 2// consecutive numbers or notstatic bool isSumCube(int N){ int a = (int)Math.Pow(N, (double) 1 / 3); int b = a - 1; // Condition to check if a // number is the sum of cubes of 2 // consecutive numbers or not return ((a * a * a + b * b * b) == N);} // Driver Codepublic static void Main(String[] args){ int i = 35; // Function call if (isSumCube(i)) { Console.Write("Yes"); } else { Console.Write("No"); }}} // This code is contributed by 29AjayKumar
<script> // Javascript program to implement// above approach // Function to check that a number// is the sum of cubes of 2// consecutive numbers or notfunction isSumCube(N){ var a = parseInt(Math.cbrt(N)); var b = a - 1; // Condition to check if a // number is the sum of cubes of 2 // consecutive numbers or not return ((a * a * a + b * b * b) == N);} // Driver Codevar i = 35; // Function callif (isSumCube(i)){ document.write("Yes");}else{ document.write("No");} // This code is contributed by todaysgaurav </script>
Yes
Time Complexity: O(1) Auxiliary Space: O(1)
SHIVAMSINGH67
amit143katiyar
29AjayKumar
noob2000
todaysgaurav
maths-perfect-cube
maths-power
Greedy
Mathematical
Searching
Searching
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Apr, 2021"
},
{
"code": null,
"e": 155,
"s": 28,
"text": "Given an integer N, the task is to check if this number can be represented as the sum of two consecutive perfect cubes or not."
},
{
"code": null,
"e": 165,
"s": 155,
"text": "Examples:"
},
{
"code": null,
"e": 260,
"s": 165,
"text": "Input: N = 35Output: YesExplanation:Since, 35 = 23 + 33, therefore the required answer is Yes."
},
{
"code": null,
"e": 284,
"s": 260,
"text": "Input: N = 14Output: No"
},
{
"code": null,
"e": 530,
"s": 284,
"text": "Naive Approach: The simplest approach to solve the problem is to iterate from 1 to cube root of N and check if the sum of perfect cubes of any two consecutive numbers is equal to N or not. If found to be true, print “Yes”. Otherwise, print “No”."
},
{
"code": null,
"e": 581,
"s": 530,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 585,
"s": 581,
"text": "C++"
},
{
"code": null,
"e": 590,
"s": 585,
"text": "Java"
},
{
"code": null,
"e": 598,
"s": 590,
"text": "Python3"
},
{
"code": null,
"e": 601,
"s": 598,
"text": "C#"
},
{
"code": null,
"e": 612,
"s": 601,
"text": "Javascript"
},
{
"code": "// C++ Program of the// above approach #include <bits/stdc++.h>using namespace std; // Function to check if a number// can be expressed as the sum of// cubes of two consecutive numbersbool isCubeSum(int n){ for (int i = 1; i * i * i <= n; i++) { if (i * i * i + (i + 1) * (i + 1) * (i + 1) == n) return true; } return false;} // Driver Codeint main(){ int n = 35; if (isCubeSum(n)) cout << \"Yes\"; else cout << \"No\";}",
"e": 1106,
"s": 612,
"text": null
},
{
"code": "// Java program of the// above approachimport java.util.*; class GFG{ // Function to check if a number// can be expressed as the sum of// cubes of two consecutive numbersstatic boolean isCubeSum(int n){ for(int i = 1; i * i * i <= n; i++) { if (i * i * i + (i + 1) * (i + 1) * (i + 1) == n) return true; } return false;} // Driver Codepublic static void main(String[] args){ int n = 35; if (isCubeSum(n)) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by Amit Katiyar",
"e": 1678,
"s": 1106,
"text": null
},
{
"code": "# Python3 program of the# above approach # Function to check if a number# can be expressed as the sum of# cubes of two consecutive numbersdef isCubeSum(n): for i in range(1, int(pow(n, 1 / 3)) + 1): if (i * i * i + (i + 1) * (i + 1) * (i + 1) == n): return True; return False; # Driver Codeif __name__ == '__main__': n = 35; if (isCubeSum(n)): print(\"Yes\"); else: print(\"No\"); # This code is contributed by Amit Katiyar",
"e": 2170,
"s": 1678,
"text": null
},
{
"code": "// C# program of the// above approachusing System; class GFG{ // Function to check if a number// can be expressed as the sum of// cubes of two consecutive numbersstatic bool isCubeSum(int n){ for(int i = 1; i * i * i <= n; i++) { if (i * i * i + (i + 1) * (i + 1) * (i + 1) == n) return true; } return false;} // Driver Codepublic static void Main(String[] args){ int n = 35; if (isCubeSum(n)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by Amit Katiyar",
"e": 2725,
"s": 2170,
"text": null
},
{
"code": "<script> // Javascript Program of the// above approach // Function to check if a number// can be expressed as the sum of// cubes of two consecutive numbersfunction isCubeSum(n){ for (var i = 1; i * i * i <= n; i++) { if (i * i * i + (i + 1) * (i + 1) * (i + 1) == n) return true; } return false;} // Driver Codevar n = 35;if (isCubeSum(n)) document.write(\"Yes\");else document.write(\"No\"); </script>",
"e": 3184,
"s": 2725,
"text": null
},
{
"code": null,
"e": 3188,
"s": 3184,
"text": "Yes"
},
{
"code": null,
"e": 3281,
"s": 3188,
"text": "Efficient Approach: The above approach can be optimized based on the following observations:"
},
{
"code": null,
"e": 3438,
"s": 3281,
"text": "A number can be represented as the sum of the perfect cube of two consecutive numbers if the sum of the cube root of both consecutive numbers is equal to N."
},
{
"code": null,
"e": 3474,
"s": 3438,
"text": "This can be checked by the formula:"
},
{
"code": null,
"e": 3553,
"s": 3474,
"text": "For example, if N = 35, then check of the equation below os equal to N or not:"
},
{
"code": null,
"e": 3604,
"s": 3553,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 3608,
"s": 3604,
"text": "C++"
},
{
"code": null,
"e": 3613,
"s": 3608,
"text": "Java"
},
{
"code": null,
"e": 3621,
"s": 3613,
"text": "Python3"
},
{
"code": null,
"e": 3624,
"s": 3621,
"text": "C#"
},
{
"code": null,
"e": 3635,
"s": 3624,
"text": "Javascript"
},
{
"code": "// C++ Program to// implement above approach #include <bits/stdc++.h>using namespace std; // Function to check that a number// is the sum of cubes of 2// consecutive numbers or notbool isSumCube(int N){ int a = cbrt(N); int b = a - 1; // Condition to check if a // number is the sum of cubes of 2 // consecutive numbers or not return ((a * a * a + b * b * b) == N);} // Driver Codeint main(){ int i = 35; // Function call if (isSumCube(i)) { cout << \"Yes\"; } else { cout << \"No\"; } return 0;}",
"e": 4182,
"s": 3635,
"text": null
},
{
"code": "// Java program to implement// above approachclass GFG{ // Function to check that a number// is the sum of cubes of 2// consecutive numbers or notstatic boolean isSumCube(int N){ int a = (int)Math.cbrt(N); int b = a - 1; // Condition to check if a // number is the sum of cubes of 2 // consecutive numbers or not return ((a * a * a + b * b * b) == N);} // Driver Codepublic static void main(String[] args){ int i = 35; // Function call if (isSumCube(i)) { System.out.print(\"Yes\"); } else { System.out.print(\"No\"); }}} // This code is contributed by Amit Katiyar",
"e": 4806,
"s": 4182,
"text": null
},
{
"code": "# Python3 program to# implement above approach # Function to check that a number# is the sum of cubes of 2# consecutive numbers or notdef isSumCube(N): a = int(pow(N, 1 / 3)) b = a - 1 # Condition to check if a # number is the sum of cubes of 2 # consecutive numbers or not ans = ((a * a * a + b * b * b) == N) return ans # Driver Codei = 35 # Function callif(isSumCube(i)): print(\"Yes\")else: print(\"No\") # This code is contributed by Shivam Singh",
"e": 5284,
"s": 4806,
"text": null
},
{
"code": "// C# program to implement// above approachusing System;class GFG{ // Function to check that a number// is the sum of cubes of 2// consecutive numbers or notstatic bool isSumCube(int N){ int a = (int)Math.Pow(N, (double) 1 / 3); int b = a - 1; // Condition to check if a // number is the sum of cubes of 2 // consecutive numbers or not return ((a * a * a + b * b * b) == N);} // Driver Codepublic static void Main(String[] args){ int i = 35; // Function call if (isSumCube(i)) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }}} // This code is contributed by 29AjayKumar",
"e": 5886,
"s": 5284,
"text": null
},
{
"code": "<script> // Javascript program to implement// above approach // Function to check that a number// is the sum of cubes of 2// consecutive numbers or notfunction isSumCube(N){ var a = parseInt(Math.cbrt(N)); var b = a - 1; // Condition to check if a // number is the sum of cubes of 2 // consecutive numbers or not return ((a * a * a + b * b * b) == N);} // Driver Codevar i = 35; // Function callif (isSumCube(i)){ document.write(\"Yes\");}else{ document.write(\"No\");} // This code is contributed by todaysgaurav </script>",
"e": 6434,
"s": 5886,
"text": null
},
{
"code": null,
"e": 6438,
"s": 6434,
"text": "Yes"
},
{
"code": null,
"e": 6483,
"s": 6438,
"text": "Time Complexity: O(1) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 6497,
"s": 6483,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 6512,
"s": 6497,
"text": "amit143katiyar"
},
{
"code": null,
"e": 6524,
"s": 6512,
"text": "29AjayKumar"
},
{
"code": null,
"e": 6533,
"s": 6524,
"text": "noob2000"
},
{
"code": null,
"e": 6546,
"s": 6533,
"text": "todaysgaurav"
},
{
"code": null,
"e": 6565,
"s": 6546,
"text": "maths-perfect-cube"
},
{
"code": null,
"e": 6577,
"s": 6565,
"text": "maths-power"
},
{
"code": null,
"e": 6584,
"s": 6577,
"text": "Greedy"
},
{
"code": null,
"e": 6597,
"s": 6584,
"text": "Mathematical"
},
{
"code": null,
"e": 6607,
"s": 6597,
"text": "Searching"
},
{
"code": null,
"e": 6617,
"s": 6607,
"text": "Searching"
},
{
"code": null,
"e": 6624,
"s": 6617,
"text": "Greedy"
},
{
"code": null,
"e": 6637,
"s": 6624,
"text": "Mathematical"
}
]
|
Batch Script - Comparing Registry Keys | Comparing registry keys is done via the REG COMPARE command.
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/v ValueName] [Output] [/s]
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/ve] [Output] [/s]
Wherein Output − /od (only differences) /os (only matches) /oa (all) /on (no output).
@echo off
REG COMPARE HKEY_CURRENT_USER\Console HKEY_CURRENT_USER\Console\Test
The above program will compare all of the values between the registry keys HKEY_CURRENT_USER\Console & HKEY_CURRENT_USER\Console\Test.
Result Compared: Identical
The operation completed successfully.
If there is a difference between the values in either registry key, it will be shown in the output as shown in the following result. The following output shows that the value ‘EnableColorSelection’ is extra I the registry key ‘HKEY_CURRENT_USER\Console’.
< Value: HKEY_CURRENT_USER\Console EnableColorSelection REG_DWORD 0x0
Result Compared: Different
The operation completed successfully.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2230,
"s": 2169,
"text": "Comparing registry keys is done via the REG COMPARE command."
},
{
"code": null,
"e": 2360,
"s": 2230,
"text": "REG COMPARE [ROOT\\]RegKey [ROOT\\]RegKey [/v ValueName] [Output] [/s]\nREG COMPARE [ROOT\\]RegKey [ROOT\\]RegKey [/ve] [Output] [/s]\n"
},
{
"code": null,
"e": 2446,
"s": 2360,
"text": "Wherein Output − /od (only differences) /os (only matches) /oa (all) /on (no output)."
},
{
"code": null,
"e": 2525,
"s": 2446,
"text": "@echo off\nREG COMPARE HKEY_CURRENT_USER\\Console HKEY_CURRENT_USER\\Console\\Test"
},
{
"code": null,
"e": 2660,
"s": 2525,
"text": "The above program will compare all of the values between the registry keys HKEY_CURRENT_USER\\Console & HKEY_CURRENT_USER\\Console\\Test."
},
{
"code": null,
"e": 2726,
"s": 2660,
"text": "Result Compared: Identical\nThe operation completed successfully.\n"
},
{
"code": null,
"e": 2981,
"s": 2726,
"text": "If there is a difference between the values in either registry key, it will be shown in the output as shown in the following result. The following output shows that the value ‘EnableColorSelection’ is extra I the registry key ‘HKEY_CURRENT_USER\\Console’."
},
{
"code": null,
"e": 3117,
"s": 2981,
"text": "< Value: HKEY_CURRENT_USER\\Console EnableColorSelection REG_DWORD 0x0\nResult Compared: Different\nThe operation completed successfully.\n"
},
{
"code": null,
"e": 3124,
"s": 3117,
"text": " Print"
},
{
"code": null,
"e": 3135,
"s": 3124,
"text": " Add Notes"
}
]
|
Selecting optimal K for K-means clustering | by Tamjid Ahsan | Towards Data Science | K-means clustering is a way of vector quantization, originally from signal processing that aims to cluster observations based on mean. Lets start with clarifying the premise of clustering case that is explored here; to segment clients . Client segmentation is the method of partitioning an organization’s clients into clusters that reflect likeness among clients in each grouping. The objective of such dissection of clients is to determine how to identify with clients in each fragment to increase the worth of every client to the business.
One of the popular machine learning techniques for this is K-means clustering, one of the simplest and popular unsupervised machine learning algorithms. Typically, unsupervised algorithms make inferences from datasets using only input vectors without referring to known, or labelled, outcomes.
In Steve Jobs: The Exclusive Biography by Walter Isaacson, although often misinterpreted, Jobs Said:
“Some people say, ‘Give customers what they want.’ But that’s not my approach. Our job is to figure out what they’re going to want before they do. I think Henry Ford once said, ‘If I’d asked customers what they wanted, they would have told me, “A faster horse!”. People don’t know what they want until you show it to them. That’s why I never rely on market research. Our task is to read things that are not yet on the page.”
It made some believe that market research is not important according to him, but in reality, what Mr. Jobs meant was to go beyond typical market research, and decipher and discover customer need in advance. For this market segmentation is a good approach and running targeted market research on each cluster. As an example, a college freshman’s need is not the same as a middle-aged head of a household who is shopping for financial services, marketing approach for both of them should not be the same.
It is crucial for marketers and policy makers to be aware of different classes of clients to address their need to serve them better. Attracting new customers is no longer a good strategy for mature businesses since the cost of assisting existing customers is much lower. Which attributes should be used for this segmentation? Well that depends.
Four types of client segmentation:
Behavioral segmentation: focuses on the habits of the client. E.g., usage-based segmentation.
Psychographic segmentation: segmentation based on traits that are not immediately obviously apparent. E.g., values or opinions.
Demographic segmentation: based on cursory traits. E.g., occupation, marital status.
Geographic segmentation: based on location. E.g., city, country.
By doing customer segmentation, you will find similar characteristics in each customer’s behavior and needs. Then, those are generalized into groups which can be used to satisfy specific demands with a myriad of strategies. Moreover, those strategies can be an input of:
Targeted marketing
Introducing features aligning with the client demand
Development of the product roadmap
Using unsupervised clustering also raises a question of how many clusters to create? This is a tricky one to give a straight answer. Often time manager or CEO will have a specific requirement on the number of clusters based on specific business goal. But how do you decide if you are expected to come up with the number of clusters as the data divulges. In this blog post I shall depict the technique that can be used to get that number. Being said so it is important to know that what the algorithm suggests might not be optimal number of clusters. The analyst should use business judgement to justify her choice. It is more of an art than science and selecting the number of clusters is detrimental for the success of the strategy formulated upon the analysis, as nonsense input data leads to nonsense output.
For this demo, the dataset from LEAPS Analyttica is used. The dataset is minimally cleaned, and then numerical data are scaled using StandardScaler and categorical variables are One-Hot-Encoded using OneHotEncoder for use in machine learning algorithms using scikit-learn API. All the transformation is performed using scikit-learn pipeline and transformers.
Method 1: Using K-means++ with different ‘K’s
Total 20 models are created, and inertia, Silhouette Score and Calinski Harabasz Score scores are plotted. Code for this is following:
This produced following plot:
Higher Silhouette Coefficient score relates to a model with better defined clusters. And higher Calinski-Harabasz score relates to a model with better defined clusters.
Although by looking at the visual no obvious optimal K can be spotted.
Based on the Silhouette Score and Sum of squared error (a.k.a. Elbow plot), 5 segmentation seemed optimal for initial model. Calinski Harabasz Score also supports this segmentation.
Method 2: using yellowbrick package
Testing K-means models with K of 2 to 10, using a random state for reproducibility and not showing timing of model fit. Code used:
This plot suggests K=5 as the optimal number of cluster.
Now using principal component analysis to visualize the clustering in two dimensional space using yellowbrick.
A clear separation between clusters is detected.
Method 3: using MeanShfit to discover cluster
Mean shift clustering aims to discover “blobs” in a smooth density of samples. It is a centroid-based algorithm, which works by updating candidates for centroids to be the mean of the points within a given region. These candidates are then filtered in a post-processing stage to eliminate near-duplicates to form the final set of centroids. (From scikit-learn documentation)
Code used:
output of the code is:
Number of estimated clusters : 5
MeanShift suggests 5 as the optimal number of cluster.
Now I created a K-means++ model with K=5 for my analysis. With PCA of 3 those clusters are visualized. Those PCA of 3 can explain 40% of the dataset. Decent distinction between clusters is observed.
Pretty good looking clustering, is it not so?
Supervising unsupervised clustering:
Next I validated my clustering by using a Random Forrest classification model. I used prediction from the clustering model as dependent variable for the Random Forest classification model, after splitting the dataset in train-test by the ratio of 80%–20%. And tested prediction ability of the model. If the clustering makes sense, the Random Forest model will be able to predict the clusters more accurately. The model achieved a model accuracy of 0.93 on test set. Then clusters are explored to identify characteristics, with insights from a combination of feature importance of the Random Forest model and a permutation importance for further exploration of features, both intra-cluster and inter-cluster. The K-means model was able to cluster fairly good based on the observed attributes of the clusters.
Model report of the Random Forest classifier:
Distribution of clusters:
After exploring each clusters, they are labeled as:
Cluster 0: Low value frequent users of services.
Cluster 1: High risk clients segmentation.
Cluster 2: Regular clients.
Cluster 3: Most loyal clients. (mostly consists of older clients)
Cluster 4: High value clients.
This workflow is a good option for deciding on optimal K for an unsupervised clustering model and validate the choice with a supervised classification model.
All of this can be found on GitHub following this link. This analysis is expanded with churn analysis, which can be found on GitHub using this link.
That's all for today. Until next time! | [
{
"code": null,
"e": 714,
"s": 172,
"text": "K-means clustering is a way of vector quantization, originally from signal processing that aims to cluster observations based on mean. Lets start with clarifying the premise of clustering case that is explored here; to segment clients . Client segmentation is the method of partitioning an organization’s clients into clusters that reflect likeness among clients in each grouping. The objective of such dissection of clients is to determine how to identify with clients in each fragment to increase the worth of every client to the business."
},
{
"code": null,
"e": 1008,
"s": 714,
"text": "One of the popular machine learning techniques for this is K-means clustering, one of the simplest and popular unsupervised machine learning algorithms. Typically, unsupervised algorithms make inferences from datasets using only input vectors without referring to known, or labelled, outcomes."
},
{
"code": null,
"e": 1109,
"s": 1008,
"text": "In Steve Jobs: The Exclusive Biography by Walter Isaacson, although often misinterpreted, Jobs Said:"
},
{
"code": null,
"e": 1534,
"s": 1109,
"text": "“Some people say, ‘Give customers what they want.’ But that’s not my approach. Our job is to figure out what they’re going to want before they do. I think Henry Ford once said, ‘If I’d asked customers what they wanted, they would have told me, “A faster horse!”. People don’t know what they want until you show it to them. That’s why I never rely on market research. Our task is to read things that are not yet on the page.”"
},
{
"code": null,
"e": 2037,
"s": 1534,
"text": "It made some believe that market research is not important according to him, but in reality, what Mr. Jobs meant was to go beyond typical market research, and decipher and discover customer need in advance. For this market segmentation is a good approach and running targeted market research on each cluster. As an example, a college freshman’s need is not the same as a middle-aged head of a household who is shopping for financial services, marketing approach for both of them should not be the same."
},
{
"code": null,
"e": 2383,
"s": 2037,
"text": "It is crucial for marketers and policy makers to be aware of different classes of clients to address their need to serve them better. Attracting new customers is no longer a good strategy for mature businesses since the cost of assisting existing customers is much lower. Which attributes should be used for this segmentation? Well that depends."
},
{
"code": null,
"e": 2418,
"s": 2383,
"text": "Four types of client segmentation:"
},
{
"code": null,
"e": 2512,
"s": 2418,
"text": "Behavioral segmentation: focuses on the habits of the client. E.g., usage-based segmentation."
},
{
"code": null,
"e": 2640,
"s": 2512,
"text": "Psychographic segmentation: segmentation based on traits that are not immediately obviously apparent. E.g., values or opinions."
},
{
"code": null,
"e": 2725,
"s": 2640,
"text": "Demographic segmentation: based on cursory traits. E.g., occupation, marital status."
},
{
"code": null,
"e": 2790,
"s": 2725,
"text": "Geographic segmentation: based on location. E.g., city, country."
},
{
"code": null,
"e": 3061,
"s": 2790,
"text": "By doing customer segmentation, you will find similar characteristics in each customer’s behavior and needs. Then, those are generalized into groups which can be used to satisfy specific demands with a myriad of strategies. Moreover, those strategies can be an input of:"
},
{
"code": null,
"e": 3080,
"s": 3061,
"text": "Targeted marketing"
},
{
"code": null,
"e": 3133,
"s": 3080,
"text": "Introducing features aligning with the client demand"
},
{
"code": null,
"e": 3168,
"s": 3133,
"text": "Development of the product roadmap"
},
{
"code": null,
"e": 3980,
"s": 3168,
"text": "Using unsupervised clustering also raises a question of how many clusters to create? This is a tricky one to give a straight answer. Often time manager or CEO will have a specific requirement on the number of clusters based on specific business goal. But how do you decide if you are expected to come up with the number of clusters as the data divulges. In this blog post I shall depict the technique that can be used to get that number. Being said so it is important to know that what the algorithm suggests might not be optimal number of clusters. The analyst should use business judgement to justify her choice. It is more of an art than science and selecting the number of clusters is detrimental for the success of the strategy formulated upon the analysis, as nonsense input data leads to nonsense output."
},
{
"code": null,
"e": 4339,
"s": 3980,
"text": "For this demo, the dataset from LEAPS Analyttica is used. The dataset is minimally cleaned, and then numerical data are scaled using StandardScaler and categorical variables are One-Hot-Encoded using OneHotEncoder for use in machine learning algorithms using scikit-learn API. All the transformation is performed using scikit-learn pipeline and transformers."
},
{
"code": null,
"e": 4385,
"s": 4339,
"text": "Method 1: Using K-means++ with different ‘K’s"
},
{
"code": null,
"e": 4520,
"s": 4385,
"text": "Total 20 models are created, and inertia, Silhouette Score and Calinski Harabasz Score scores are plotted. Code for this is following:"
},
{
"code": null,
"e": 4550,
"s": 4520,
"text": "This produced following plot:"
},
{
"code": null,
"e": 4719,
"s": 4550,
"text": "Higher Silhouette Coefficient score relates to a model with better defined clusters. And higher Calinski-Harabasz score relates to a model with better defined clusters."
},
{
"code": null,
"e": 4790,
"s": 4719,
"text": "Although by looking at the visual no obvious optimal K can be spotted."
},
{
"code": null,
"e": 4972,
"s": 4790,
"text": "Based on the Silhouette Score and Sum of squared error (a.k.a. Elbow plot), 5 segmentation seemed optimal for initial model. Calinski Harabasz Score also supports this segmentation."
},
{
"code": null,
"e": 5008,
"s": 4972,
"text": "Method 2: using yellowbrick package"
},
{
"code": null,
"e": 5139,
"s": 5008,
"text": "Testing K-means models with K of 2 to 10, using a random state for reproducibility and not showing timing of model fit. Code used:"
},
{
"code": null,
"e": 5196,
"s": 5139,
"text": "This plot suggests K=5 as the optimal number of cluster."
},
{
"code": null,
"e": 5307,
"s": 5196,
"text": "Now using principal component analysis to visualize the clustering in two dimensional space using yellowbrick."
},
{
"code": null,
"e": 5356,
"s": 5307,
"text": "A clear separation between clusters is detected."
},
{
"code": null,
"e": 5402,
"s": 5356,
"text": "Method 3: using MeanShfit to discover cluster"
},
{
"code": null,
"e": 5777,
"s": 5402,
"text": "Mean shift clustering aims to discover “blobs” in a smooth density of samples. It is a centroid-based algorithm, which works by updating candidates for centroids to be the mean of the points within a given region. These candidates are then filtered in a post-processing stage to eliminate near-duplicates to form the final set of centroids. (From scikit-learn documentation)"
},
{
"code": null,
"e": 5788,
"s": 5777,
"text": "Code used:"
},
{
"code": null,
"e": 5811,
"s": 5788,
"text": "output of the code is:"
},
{
"code": null,
"e": 5844,
"s": 5811,
"text": "Number of estimated clusters : 5"
},
{
"code": null,
"e": 5899,
"s": 5844,
"text": "MeanShift suggests 5 as the optimal number of cluster."
},
{
"code": null,
"e": 6098,
"s": 5899,
"text": "Now I created a K-means++ model with K=5 for my analysis. With PCA of 3 those clusters are visualized. Those PCA of 3 can explain 40% of the dataset. Decent distinction between clusters is observed."
},
{
"code": null,
"e": 6144,
"s": 6098,
"text": "Pretty good looking clustering, is it not so?"
},
{
"code": null,
"e": 6181,
"s": 6144,
"text": "Supervising unsupervised clustering:"
},
{
"code": null,
"e": 6989,
"s": 6181,
"text": "Next I validated my clustering by using a Random Forrest classification model. I used prediction from the clustering model as dependent variable for the Random Forest classification model, after splitting the dataset in train-test by the ratio of 80%–20%. And tested prediction ability of the model. If the clustering makes sense, the Random Forest model will be able to predict the clusters more accurately. The model achieved a model accuracy of 0.93 on test set. Then clusters are explored to identify characteristics, with insights from a combination of feature importance of the Random Forest model and a permutation importance for further exploration of features, both intra-cluster and inter-cluster. The K-means model was able to cluster fairly good based on the observed attributes of the clusters."
},
{
"code": null,
"e": 7035,
"s": 6989,
"text": "Model report of the Random Forest classifier:"
},
{
"code": null,
"e": 7061,
"s": 7035,
"text": "Distribution of clusters:"
},
{
"code": null,
"e": 7113,
"s": 7061,
"text": "After exploring each clusters, they are labeled as:"
},
{
"code": null,
"e": 7162,
"s": 7113,
"text": "Cluster 0: Low value frequent users of services."
},
{
"code": null,
"e": 7205,
"s": 7162,
"text": "Cluster 1: High risk clients segmentation."
},
{
"code": null,
"e": 7233,
"s": 7205,
"text": "Cluster 2: Regular clients."
},
{
"code": null,
"e": 7299,
"s": 7233,
"text": "Cluster 3: Most loyal clients. (mostly consists of older clients)"
},
{
"code": null,
"e": 7330,
"s": 7299,
"text": "Cluster 4: High value clients."
},
{
"code": null,
"e": 7488,
"s": 7330,
"text": "This workflow is a good option for deciding on optimal K for an unsupervised clustering model and validate the choice with a supervised classification model."
},
{
"code": null,
"e": 7637,
"s": 7488,
"text": "All of this can be found on GitHub following this link. This analysis is expanded with churn analysis, which can be found on GitHub using this link."
}
]
|
How to escape parentheses in MySQL REGEXP clause and display only specific values with parentheses? | Let us first create a table −
mysql> create table DemoTable1908
(
Code text
);
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1908 values('MySQL(1)Database');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1908 values('MongoDB 2 Database');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1908 values('MySQL(3)Database');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1908 values('SQL Server(10)Database');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1908 values('MySQL 8 Database');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1908;
This will produce the following output −
+------------------------+
| Code |
+------------------------+
| MySQL(1)Database |
| MongoDB 2 Database |
| MySQL(3)Database |
| SQL Server(10)Database |
| MySQL 8 Database |
+------------------------+
5 rows in set (0.00 sec)
Here is the query to escape parentheses in a REGEXP clause and display only the paratheses value with () −
mysql> select * from DemoTable1908 where Code regexp '^MySQL[(][0-9][)]Database';
This will produce the following output −
+------------------+
| Code |
+------------------+
| MySQL(1)Database |
| MySQL(3)Database |
+------------------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1187,
"s": 1092,
"text": "mysql> create table DemoTable1908\n (\n Code text\n );\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 1243,
"s": 1187,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1736,
"s": 1243,
"text": "mysql> insert into DemoTable1908 values('MySQL(1)Database');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1908 values('MongoDB 2 Database');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1908 values('MySQL(3)Database');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1908 values('SQL Server(10)Database');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1908 values('MySQL 8 Database');\nQuery OK, 1 row affected (0.00 sec)"
},
{
"code": null,
"e": 1796,
"s": 1736,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1832,
"s": 1796,
"text": "mysql> select * from DemoTable1908;"
},
{
"code": null,
"e": 1873,
"s": 1832,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2141,
"s": 1873,
"text": "+------------------------+\n| Code |\n+------------------------+\n| MySQL(1)Database |\n| MongoDB 2 Database |\n| MySQL(3)Database |\n| SQL Server(10)Database |\n| MySQL 8 Database |\n+------------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2248,
"s": 2141,
"text": "Here is the query to escape parentheses in a REGEXP clause and display only the paratheses value with () −"
},
{
"code": null,
"e": 2330,
"s": 2248,
"text": "mysql> select * from DemoTable1908 where Code regexp '^MySQL[(][0-9][)]Database';"
},
{
"code": null,
"e": 2371,
"s": 2330,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2522,
"s": 2371,
"text": "+------------------+\n| Code |\n+------------------+\n| MySQL(1)Database |\n| MySQL(3)Database |\n+------------------+\n2 rows in set (0.00 sec)"
}
]
|
Tryit Editor v3.7 | Tryit: HTML picture element | []
|
Kotlin Abstract class - GeeksforGeeks | 28 Mar, 2022
In Kotlin, abstract class is declared using the abstract keyword in front of class. An abstract class can not instantiated means we can not create object for the abstract class.
Abstract class declaration:
abstract class className {
.........
}
Points to remember:
We can’t create an object for abstract class.All the variables (properties) and member functions of an abstract class are by default non-abstract. So, if we want to override these members in the child class then we need to use open keyword.If we declare a member function as abstract then we does not need to annotate with open keyword because these are open by default.An abstract member function doesn’t have a body, and it must be implemented in the derived class.
We can’t create an object for abstract class.
All the variables (properties) and member functions of an abstract class are by default non-abstract. So, if we want to override these members in the child class then we need to use open keyword.
If we declare a member function as abstract then we does not need to annotate with open keyword because these are open by default.
An abstract member function doesn’t have a body, and it must be implemented in the derived class.
An abstract class can contain both abstract and non-abstract members as shown below:
abstract class className(val x: String) { // Non-Abstract Property
abstract var y: Int // Abstract Property
abstract fun method1() // Abstract Methods
fun method2() { // Non-Abstract Method
println("Non abstract function")
}
}
Kotlin program of using both abstract and non-abstract members in an abstract class-
Kotlin
//abstract classabstract class Employee(val name: String,val experience: Int) { // Non-Abstract // Property // Abstract Property (Must be overridden by Subclasses) abstract var salary: Double // Abstract Methods (Must be implemented by Subclasses) abstract fun dateOfBirth(date:String) // Non-Abstract Method fun employeeDetails() { println("Name of the employee: $name") println("Experience in years: $experience") println("Annual Salary: $salary") }}// derived classclass Engineer(name: String,experience: Int) : Employee(name,experience) { override var salary = 500000.00 override fun dateOfBirth(date:String){ println("Date of Birth is: $date") }}fun main(args: Array<String>) { val eng = Engineer("Praveen",2) eng.employeeDetails() eng.dateOfBirth("02 December 1994")}
Output:
Name of the employee: Praveen
Experience in years: 2
Annual Salary: 500000.0
Date of Birth is: 02 December 1994
Explanation:In the above program, Engineer class is derived from the Employee class. An object eng is instantiated for the Engineer class. We have passed two parameters to the primary constructor while creating it. This initializes the non-abstract properties name and experienceof Employee class. The
Then employeeDetails() method is called using the eng object. It will print the values of name, experience and the overridden salary of the employee.
In the end, dateOfBirth() is called using the eng object and we have passed the parameter date to the primary constructor. It overrides the abstract fun of Employee class and prints the value of passed as parameter to the standard output.
In Kotlin we can override the non-abstract open member function of the open class using the override keyword followed by an abstract in the abstract class. In the below program we will do it.
Kotlin program of overriding a non-abstract open function by an abstract class –
Kotlin
open class Livingthings { open fun breathe() { println("All living things breathe") }}abstract class Animal : Livingthings() { override abstract fun breathe()}class Dog: Animal(){ override fun breathe() { println("Dog can also breathe") }}fun main(args: Array<String>){ val lt = Livingthings() lt.breathe() val d = Dog() d.breathe()}
Output:
All living things breathe
Dog can also breathe
An abstract member of an abstract class can be overridden in all the derived classes. In the program, we overrides the cal function in three derived class of calculator.
Kotlin program of overriding the abstract function in more than one derived class –
Kotlin
// abstract classabstract class Calculator { abstract fun cal(x: Int, y: Int) : Int}// addition of two numbersclass Add : Calculator() { override fun cal(x: Int, y: Int): Int { return x + y }}// subtraction of two numbersclass Sub : Calculator() { override fun cal(x: Int, y: Int): Int { return x - y }}// multiplication of two numbersclass Mul : Calculator() { override fun cal(x: Int, y: Int): Int { return x * y }}fun main(args: Array<String>) { var add: Calculator = Add() var x1 = add.cal(4, 6) println("Addition of two numbers $x1") var sub: Calculator = Sub() var x2 = sub.cal(10,6) println("Subtraction of two numbers $x2") var mul: Calculator = Mul() var x3 = mul.cal(20,6) println("Multiplication of two numbers $x3")}
Output:
Addition of two numbers 10
Subtraction of two numbers 4
Multiplication of two numbers 120
Division of two numbers 3
m01nak77
ayushpandey3july
Kotlin OOPs
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Android UI Layouts
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
How to Change the Color of Status Bar in an Android App?
Android Menus
ImageView in Android with Example
How to Get Current Location in Android?
Kotlin Android Tutorial | [
{
"code": null,
"e": 23575,
"s": 23547,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 23753,
"s": 23575,
"text": "In Kotlin, abstract class is declared using the abstract keyword in front of class. An abstract class can not instantiated means we can not create object for the abstract class."
},
{
"code": null,
"e": 23781,
"s": 23753,
"text": "Abstract class declaration:"
},
{
"code": null,
"e": 23826,
"s": 23781,
"text": "abstract class className {\n .........\n} \n"
},
{
"code": null,
"e": 23846,
"s": 23826,
"text": "Points to remember:"
},
{
"code": null,
"e": 24314,
"s": 23846,
"text": "We can’t create an object for abstract class.All the variables (properties) and member functions of an abstract class are by default non-abstract. So, if we want to override these members in the child class then we need to use open keyword.If we declare a member function as abstract then we does not need to annotate with open keyword because these are open by default.An abstract member function doesn’t have a body, and it must be implemented in the derived class."
},
{
"code": null,
"e": 24360,
"s": 24314,
"text": "We can’t create an object for abstract class."
},
{
"code": null,
"e": 24556,
"s": 24360,
"text": "All the variables (properties) and member functions of an abstract class are by default non-abstract. So, if we want to override these members in the child class then we need to use open keyword."
},
{
"code": null,
"e": 24687,
"s": 24556,
"text": "If we declare a member function as abstract then we does not need to annotate with open keyword because these are open by default."
},
{
"code": null,
"e": 24785,
"s": 24687,
"text": "An abstract member function doesn’t have a body, and it must be implemented in the derived class."
},
{
"code": null,
"e": 24870,
"s": 24785,
"text": "An abstract class can contain both abstract and non-abstract members as shown below:"
},
{
"code": null,
"e": 25152,
"s": 24870,
"text": "abstract class className(val x: String) { // Non-Abstract Property\n \n abstract var y: Int // Abstract Property\n\n abstract fun method1() // Abstract Methods\n\n fun method2() { // Non-Abstract Method\n println(\"Non abstract function\")\n }\n}\n"
},
{
"code": null,
"e": 25237,
"s": 25152,
"text": "Kotlin program of using both abstract and non-abstract members in an abstract class-"
},
{
"code": null,
"e": 25244,
"s": 25237,
"text": "Kotlin"
},
{
"code": "//abstract classabstract class Employee(val name: String,val experience: Int) { // Non-Abstract // Property // Abstract Property (Must be overridden by Subclasses) abstract var salary: Double // Abstract Methods (Must be implemented by Subclasses) abstract fun dateOfBirth(date:String) // Non-Abstract Method fun employeeDetails() { println(\"Name of the employee: $name\") println(\"Experience in years: $experience\") println(\"Annual Salary: $salary\") }}// derived classclass Engineer(name: String,experience: Int) : Employee(name,experience) { override var salary = 500000.00 override fun dateOfBirth(date:String){ println(\"Date of Birth is: $date\") }}fun main(args: Array<String>) { val eng = Engineer(\"Praveen\",2) eng.employeeDetails() eng.dateOfBirth(\"02 December 1994\")}",
"e": 26160,
"s": 25244,
"text": null
},
{
"code": null,
"e": 26168,
"s": 26160,
"text": "Output:"
},
{
"code": null,
"e": 26281,
"s": 26168,
"text": "Name of the employee: Praveen\nExperience in years: 2\nAnnual Salary: 500000.0\nDate of Birth is: 02 December 1994\n"
},
{
"code": null,
"e": 26583,
"s": 26281,
"text": "Explanation:In the above program, Engineer class is derived from the Employee class. An object eng is instantiated for the Engineer class. We have passed two parameters to the primary constructor while creating it. This initializes the non-abstract properties name and experienceof Employee class. The"
},
{
"code": null,
"e": 26733,
"s": 26583,
"text": "Then employeeDetails() method is called using the eng object. It will print the values of name, experience and the overridden salary of the employee."
},
{
"code": null,
"e": 26972,
"s": 26733,
"text": "In the end, dateOfBirth() is called using the eng object and we have passed the parameter date to the primary constructor. It overrides the abstract fun of Employee class and prints the value of passed as parameter to the standard output."
},
{
"code": null,
"e": 27164,
"s": 26972,
"text": "In Kotlin we can override the non-abstract open member function of the open class using the override keyword followed by an abstract in the abstract class. In the below program we will do it."
},
{
"code": null,
"e": 27245,
"s": 27164,
"text": "Kotlin program of overriding a non-abstract open function by an abstract class –"
},
{
"code": null,
"e": 27252,
"s": 27245,
"text": "Kotlin"
},
{
"code": "open class Livingthings { open fun breathe() { println(\"All living things breathe\") }}abstract class Animal : Livingthings() { override abstract fun breathe()}class Dog: Animal(){ override fun breathe() { println(\"Dog can also breathe\") }}fun main(args: Array<String>){ val lt = Livingthings() lt.breathe() val d = Dog() d.breathe()}",
"e": 27627,
"s": 27252,
"text": null
},
{
"code": null,
"e": 27635,
"s": 27627,
"text": "Output:"
},
{
"code": null,
"e": 27683,
"s": 27635,
"text": "All living things breathe\nDog can also breathe\n"
},
{
"code": null,
"e": 27853,
"s": 27683,
"text": "An abstract member of an abstract class can be overridden in all the derived classes. In the program, we overrides the cal function in three derived class of calculator."
},
{
"code": null,
"e": 27937,
"s": 27853,
"text": "Kotlin program of overriding the abstract function in more than one derived class –"
},
{
"code": null,
"e": 27944,
"s": 27937,
"text": "Kotlin"
},
{
"code": "// abstract classabstract class Calculator { abstract fun cal(x: Int, y: Int) : Int}// addition of two numbersclass Add : Calculator() { override fun cal(x: Int, y: Int): Int { return x + y }}// subtraction of two numbersclass Sub : Calculator() { override fun cal(x: Int, y: Int): Int { return x - y }}// multiplication of two numbersclass Mul : Calculator() { override fun cal(x: Int, y: Int): Int { return x * y }}fun main(args: Array<String>) { var add: Calculator = Add() var x1 = add.cal(4, 6) println(\"Addition of two numbers $x1\") var sub: Calculator = Sub() var x2 = sub.cal(10,6) println(\"Subtraction of two numbers $x2\") var mul: Calculator = Mul() var x3 = mul.cal(20,6) println(\"Multiplication of two numbers $x3\")}",
"e": 28742,
"s": 27944,
"text": null
},
{
"code": null,
"e": 28750,
"s": 28742,
"text": "Output:"
},
{
"code": null,
"e": 28867,
"s": 28750,
"text": "Addition of two numbers 10\nSubtraction of two numbers 4\nMultiplication of two numbers 120\nDivision of two numbers 3\n"
},
{
"code": null,
"e": 28876,
"s": 28867,
"text": "m01nak77"
},
{
"code": null,
"e": 28893,
"s": 28876,
"text": "ayushpandey3july"
},
{
"code": null,
"e": 28905,
"s": 28893,
"text": "Kotlin OOPs"
},
{
"code": null,
"e": 28912,
"s": 28905,
"text": "Kotlin"
},
{
"code": null,
"e": 29010,
"s": 28912,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29019,
"s": 29010,
"text": "Comments"
},
{
"code": null,
"e": 29032,
"s": 29019,
"text": "Old Comments"
},
{
"code": null,
"e": 29075,
"s": 29032,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 29106,
"s": 29075,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 29125,
"s": 29106,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 29167,
"s": 29125,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 29209,
"s": 29167,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 29266,
"s": 29209,
"text": "How to Change the Color of Status Bar in an Android App?"
},
{
"code": null,
"e": 29280,
"s": 29266,
"text": "Android Menus"
},
{
"code": null,
"e": 29314,
"s": 29280,
"text": "ImageView in Android with Example"
},
{
"code": null,
"e": 29354,
"s": 29314,
"text": "How to Get Current Location in Android?"
}
]
|
Encrypt and Decrypt Data in NodeJS | NodeJS provides inbuilt library crypto to encrypt and decrypt data in NodeJS. We can use this library to encrypt data of any type. You can do the cryptographic operations on a string, buffer, and even a stream of data. The crypto also holds multiple crypto algorithms for encryption. Please check the official resources for the same. In this article, we will use the most popular AES (Advanced Encryption Standard) for encryption.
In your project, check if NodeJS is initialized or not. If not, use the following command to initialize NodeJS.
In your project, check if NodeJS is initialized or not. If not, use the following command to initialize NodeJS.
>> npm init -y
The 'crypto' library is automatically added while installing the node manually. If not, you can use the following command to install crypto.
The 'crypto' library is automatically added while installing the node manually. If not, you can use the following command to install crypto.
>> npm install crypto –save
Encrypting and Decrypting Data
//Checking the crypto module
const crypto = require('crypto');
const algorithm = 'aes-256-cbc'; //Using AES encryption
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
//Encrypting text
function encrypt(text) {
let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };
}
// Decrypting text
function decrypt(text) {
let iv = Buffer.from(text.iv, 'hex');
let encryptedText = Buffer.from(text.encryptedData, 'hex');
let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
// Text send to encrypt function
var hw = encrypt("Welcome to Tutorials Point...")
console.log(hw)
console.log(decrypt(hw))
C:\\Users\mysql-test>> node encrypt.js
{ iv: '61add9b0068d5d85e940ff3bba0a00e6', encryptedData:
'787ff81611b84c9ab2a55aa45e3c1d3e824e3ff583b0cb75c20b8947a4130d16' }
//Encrypted text
Welcome to Tutorials Point... //Decrypted text | [
{
"code": null,
"e": 1493,
"s": 1062,
"text": "NodeJS provides inbuilt library crypto to encrypt and decrypt data in NodeJS. We can use this library to encrypt data of any type. You can do the cryptographic operations on a string, buffer, and even a stream of data. The crypto also holds multiple crypto algorithms for encryption. Please check the official resources for the same. In this article, we will use the most popular AES (Advanced Encryption Standard) for encryption."
},
{
"code": null,
"e": 1605,
"s": 1493,
"text": "In your project, check if NodeJS is initialized or not. If not, use the following command to initialize NodeJS."
},
{
"code": null,
"e": 1717,
"s": 1605,
"text": "In your project, check if NodeJS is initialized or not. If not, use the following command to initialize NodeJS."
},
{
"code": null,
"e": 1732,
"s": 1717,
"text": ">> npm init -y"
},
{
"code": null,
"e": 1873,
"s": 1732,
"text": "The 'crypto' library is automatically added while installing the node manually. If not, you can use the following command to install crypto."
},
{
"code": null,
"e": 2014,
"s": 1873,
"text": "The 'crypto' library is automatically added while installing the node manually. If not, you can use the following command to install crypto."
},
{
"code": null,
"e": 2042,
"s": 2014,
"text": ">> npm install crypto –save"
},
{
"code": null,
"e": 2073,
"s": 2042,
"text": "Encrypting and Decrypting Data"
},
{
"code": null,
"e": 3064,
"s": 2073,
"text": "//Checking the crypto module\nconst crypto = require('crypto');\nconst algorithm = 'aes-256-cbc'; //Using AES encryption\nconst key = crypto.randomBytes(32);\nconst iv = crypto.randomBytes(16);\n\n//Encrypting text\nfunction encrypt(text) {\n let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);\n let encrypted = cipher.update(text);\n encrypted = Buffer.concat([encrypted, cipher.final()]);\n return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };\n}\n\n// Decrypting text\nfunction decrypt(text) {\n let iv = Buffer.from(text.iv, 'hex');\n let encryptedText = Buffer.from(text.encryptedData, 'hex');\n let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);\n let decrypted = decipher.update(encryptedText);\n decrypted = Buffer.concat([decrypted, decipher.final()]);\n return decrypted.toString();\n}\n\n// Text send to encrypt function\nvar hw = encrypt(\"Welcome to Tutorials Point...\")\nconsole.log(hw)\nconsole.log(decrypt(hw))"
},
{
"code": null,
"e": 3293,
"s": 3064,
"text": "C:\\\\Users\\mysql-test>> node encrypt.js\n{ iv: '61add9b0068d5d85e940ff3bba0a00e6', encryptedData:\n'787ff81611b84c9ab2a55aa45e3c1d3e824e3ff583b0cb75c20b8947a4130d16' }\n//Encrypted text\nWelcome to Tutorials Point... //Decrypted text"
}
]
|
How to use pip or easy_install Tkinter on Windows? | Tkinter is a Python library that is used to develop desktop-based GUI applications. In order to develop a Tkinter application, we have to make sure that Python is installed in our local system. We can install Tkinter in our local machine by using the pip install tkinter command in the Command Prompt or shell.
Once we enter the command pip install tkinter in the command shell, it will just start running the process of installing Tkinter in the local system.
First, we will make sure that Python is installed in our system. In order to check if Python is installed, use the following command −
First, we will make sure that Python is installed in our system. In order to check if Python is installed, use the following command −
python --version
Next, check if you have Pip preinstalled or not, by typing the following command in the shell,
Next, check if you have Pip preinstalled or not, by typing the following command in the shell,
pip -V
Now, install Tkinter by using the following command −
Now, install Tkinter by using the following command −
pip install tkinter | [
{
"code": null,
"e": 1373,
"s": 1062,
"text": "Tkinter is a Python library that is used to develop desktop-based GUI applications. In order to develop a Tkinter application, we have to make sure that Python is installed in our local system. We can install Tkinter in our local machine by using the pip install tkinter command in the Command Prompt or shell."
},
{
"code": null,
"e": 1523,
"s": 1373,
"text": "Once we enter the command pip install tkinter in the command shell, it will just start running the process of installing Tkinter in the local system."
},
{
"code": null,
"e": 1658,
"s": 1523,
"text": "First, we will make sure that Python is installed in our system. In order to check if Python is installed, use the following command −"
},
{
"code": null,
"e": 1793,
"s": 1658,
"text": "First, we will make sure that Python is installed in our system. In order to check if Python is installed, use the following command −"
},
{
"code": null,
"e": 1810,
"s": 1793,
"text": "python --version"
},
{
"code": null,
"e": 1905,
"s": 1810,
"text": "Next, check if you have Pip preinstalled or not, by typing the following command in the shell,"
},
{
"code": null,
"e": 2000,
"s": 1905,
"text": "Next, check if you have Pip preinstalled or not, by typing the following command in the shell,"
},
{
"code": null,
"e": 2007,
"s": 2000,
"text": "pip -V"
},
{
"code": null,
"e": 2061,
"s": 2007,
"text": "Now, install Tkinter by using the following command −"
},
{
"code": null,
"e": 2115,
"s": 2061,
"text": "Now, install Tkinter by using the following command −"
},
{
"code": null,
"e": 2135,
"s": 2115,
"text": "pip install tkinter"
}
]
|
Deploy a Python API on AWS. Flask + Lambda + API Gateway | by Jeremy Zhang | Towards Data Science | The very first idea of creating my own app and deploying it on the cloud so that everyone could use it is super exciting to me, and this is what inspired me to write this post. If this idea also intrigues you, please follow through and from this post, you will learn how to deploy a python app step by step.
You will need to wrap your idea in an app, or say an API, which can process calls from the internet. An example is here. This is a flask app,
where the key lies in the app.py file, and this app receives your resume and help refer you internally. Notice that we don’t even need a docker file, the AWS Lambda is so light-weighted that you don’t even need to wrap your code in a container!
Zappa, a quote from the official docs, it
makes it super easy to build and deploy server-less, event-driven Python applications (including, but not limited to, WSGI web apps) on AWS Lambda + API Gateway. Think of it as “serverless” web hosting for your Python apps. That means infinite scaling, zero downtime, zero maintenance — and at a fraction of the cost of your current deployments!
If you’ve been using AWS service for a while, you would know that to deploy a service on the cloud with the usage of multiple different services and configurations is no easy task, but Zappa comes to the rescue, that with simple commands(trust me, it’s really just a few lines!), all the heavy lifting configurations would be done!
pip install zappa
BTW, I assume you have all the packages installed in the project virtual environment, if not, do
virtualenv -p `which python3` env
(you need to have virtualenv pre-installed)
Now do
zappa init
Go through the settings one by one, if you don’t understand just use the default, and you will still be able to change it afterwards. After this, you would have a zappa_setting.json in your root folder, mine looks like this
{ "production": { "app_function": "app.app", "aws_region": "ap-southeast-1", "profile_name": "default", "project_name": "referral-api", "runtime": "python3.7", "s3_bucket": "zappa-referral-api-eu2hzy8sf" }}
Now you need to go to your AWS console, but wait, you said Zappa would do all the AWS work for us? Yes, but think it this way, before Zappa could make any changes on your behalf, it needs access to you AWS resources, and this step is to give Zappa the credential to do such thing.
You can follow the steps here deploy-serverless-app (trust me, this one is really an illustrative guide through with all the images you need).
For the policy attached to the group, use this one! (The one in the link above does not enable you to update your app)
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "iam:AttachRolePolicy", "iam:GetRole", "iam:CreateRole", "iam:PassRole", "iam:PutRolePolicy" ], "Resource": [ "arn:aws:iam::XXXXXXXXXXXXXXXX:role/*-ZappaLambdaExecutionRole" ] }, { "Effect": "Allow", "Action": [ "lambda:CreateFunction", "lambda:ListVersionsByFunction", "logs:DescribeLogStreams", "events:PutRule", "lambda:GetFunctionConfiguration", "cloudformation:DescribeStackResource", "apigateway:DELETE", "apigateway:UpdateRestApiPolicy", "events:ListRuleNamesByTarget", "apigateway:PATCH", "events:ListRules", "cloudformation:UpdateStack", "lambda:DeleteFunction", "events:RemoveTargets", "logs:FilterLogEvents", "apigateway:GET", "lambda:GetAlias", "events:ListTargetsByRule", "cloudformation:ListStackResources", "events:DescribeRule", "logs:DeleteLogGroup", "apigateway:PUT", "lambda:InvokeFunction", "lambda:GetFunction", "lambda:UpdateFunctionConfiguration", "cloudformation:DescribeStacks", "lambda:UpdateFunctionCode", "lambda:DeleteFunctionConcurrency", "events:DeleteRule", "events:PutTargets", "lambda:AddPermission", "cloudformation:CreateStack", "cloudformation:DeleteStack", "apigateway:POST", "lambda:RemovePermission", "lambda:GetPolicy" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "s3:ListBucketMultipartUploads", "s3:CreateBucket", "s3:ListBucket" ], "Resource": "arn:aws:s3:::zappa-*" }, { "Effect": "Allow", "Action": [ "s3:PutObject", "s3:GetObject", "s3:AbortMultipartUpload", "s3:DeleteObject", "s3:ListMultipartUploadParts" ], "Resource": "arn:aws:s3:::zappa-*/*" } ]}
Now you add the credentials you created for Zappa to your local file (credentials and configs), mine looks like this
[default]aws_access_key_id = ****aws_secret_access_key = ****[zappa]aws_access_key_id = ****aws_secret_access_key = ****
and config like this
[default]region = ap-southeast-1output = json[zappa]region = ap-southeast-1output = json
I created one especially for Zappa, because I believe most of us would have a default credential for ourself, this setting would allow you to switch between different profiles.
Now it is ready to deploy!
export AWS_DEFAULT_PROFILE=zappazappa deploy production
You would see your API url right after the command line. Now go to your AWS Lambda you should see our API deployed:
And in API Gateway you can see:
Now that I can test the public endpoint on postman and get a response:
Congrats! Now you have your app fully deployed to AWS with Lambda and API Gateway!
You can stop here if this already satisfies your need, but if you would like to distribute your API and add restrictions for it, you can continue to the next part.
You might have noticed that so far our API is publicly accessible, which means anyone can access our API and it is susceptible to malicious attack. To avoid such undesired visits, we need to add extra limitations on our API usage (Usage Plan) and credentials (x-api-key) to restrict visits.
To add a key to your API, follow the steps here.
RapidAPI is where for everyone to freely open and sell their API to the world as long as someone is willing to pay for it.
Go to RapidAPI and click Add New APIFill in the basic info of your APIFor the URL of your API, paste the AWS url we previous got after deploying though ZappaIn the access control add your api key as follow
Go to RapidAPI and click Add New API
Fill in the basic info of your API
For the URL of your API, paste the AWS url we previous got after deploying though Zappa
In the access control add your api key as follow
5. Add a pricing plan and you are ready to launch it to the public!
Lastly, if you are interested, you can check out my referral API. If you are looking for a new career, so far it helps you to refer you to the company of Bytedance and Grab through the internal portal.
This is post is initially inspired by this, a great post helped me to start the plan, feel free to check that out! | [
{
"code": null,
"e": 480,
"s": 172,
"text": "The very first idea of creating my own app and deploying it on the cloud so that everyone could use it is super exciting to me, and this is what inspired me to write this post. If this idea also intrigues you, please follow through and from this post, you will learn how to deploy a python app step by step."
},
{
"code": null,
"e": 622,
"s": 480,
"text": "You will need to wrap your idea in an app, or say an API, which can process calls from the internet. An example is here. This is a flask app,"
},
{
"code": null,
"e": 867,
"s": 622,
"text": "where the key lies in the app.py file, and this app receives your resume and help refer you internally. Notice that we don’t even need a docker file, the AWS Lambda is so light-weighted that you don’t even need to wrap your code in a container!"
},
{
"code": null,
"e": 909,
"s": 867,
"text": "Zappa, a quote from the official docs, it"
},
{
"code": null,
"e": 1255,
"s": 909,
"text": "makes it super easy to build and deploy server-less, event-driven Python applications (including, but not limited to, WSGI web apps) on AWS Lambda + API Gateway. Think of it as “serverless” web hosting for your Python apps. That means infinite scaling, zero downtime, zero maintenance — and at a fraction of the cost of your current deployments!"
},
{
"code": null,
"e": 1587,
"s": 1255,
"text": "If you’ve been using AWS service for a while, you would know that to deploy a service on the cloud with the usage of multiple different services and configurations is no easy task, but Zappa comes to the rescue, that with simple commands(trust me, it’s really just a few lines!), all the heavy lifting configurations would be done!"
},
{
"code": null,
"e": 1605,
"s": 1587,
"text": "pip install zappa"
},
{
"code": null,
"e": 1702,
"s": 1605,
"text": "BTW, I assume you have all the packages installed in the project virtual environment, if not, do"
},
{
"code": null,
"e": 1736,
"s": 1702,
"text": "virtualenv -p `which python3` env"
},
{
"code": null,
"e": 1780,
"s": 1736,
"text": "(you need to have virtualenv pre-installed)"
},
{
"code": null,
"e": 1787,
"s": 1780,
"text": "Now do"
},
{
"code": null,
"e": 1798,
"s": 1787,
"text": "zappa init"
},
{
"code": null,
"e": 2022,
"s": 1798,
"text": "Go through the settings one by one, if you don’t understand just use the default, and you will still be able to change it afterwards. After this, you would have a zappa_setting.json in your root folder, mine looks like this"
},
{
"code": null,
"e": 2277,
"s": 2022,
"text": "{ \"production\": { \"app_function\": \"app.app\", \"aws_region\": \"ap-southeast-1\", \"profile_name\": \"default\", \"project_name\": \"referral-api\", \"runtime\": \"python3.7\", \"s3_bucket\": \"zappa-referral-api-eu2hzy8sf\" }}"
},
{
"code": null,
"e": 2558,
"s": 2277,
"text": "Now you need to go to your AWS console, but wait, you said Zappa would do all the AWS work for us? Yes, but think it this way, before Zappa could make any changes on your behalf, it needs access to you AWS resources, and this step is to give Zappa the credential to do such thing."
},
{
"code": null,
"e": 2701,
"s": 2558,
"text": "You can follow the steps here deploy-serverless-app (trust me, this one is really an illustrative guide through with all the images you need)."
},
{
"code": null,
"e": 2820,
"s": 2701,
"text": "For the policy attached to the group, use this one! (The one in the link above does not enable you to update your app)"
},
{
"code": null,
"e": 4867,
"s": 2820,
"text": "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Effect\": \"Allow\", \"Action\": [ \"iam:AttachRolePolicy\", \"iam:GetRole\", \"iam:CreateRole\", \"iam:PassRole\", \"iam:PutRolePolicy\" ], \"Resource\": [ \"arn:aws:iam::XXXXXXXXXXXXXXXX:role/*-ZappaLambdaExecutionRole\" ] }, { \"Effect\": \"Allow\", \"Action\": [ \"lambda:CreateFunction\", \"lambda:ListVersionsByFunction\", \"logs:DescribeLogStreams\", \"events:PutRule\", \"lambda:GetFunctionConfiguration\", \"cloudformation:DescribeStackResource\", \"apigateway:DELETE\", \"apigateway:UpdateRestApiPolicy\", \"events:ListRuleNamesByTarget\", \"apigateway:PATCH\", \"events:ListRules\", \"cloudformation:UpdateStack\", \"lambda:DeleteFunction\", \"events:RemoveTargets\", \"logs:FilterLogEvents\", \"apigateway:GET\", \"lambda:GetAlias\", \"events:ListTargetsByRule\", \"cloudformation:ListStackResources\", \"events:DescribeRule\", \"logs:DeleteLogGroup\", \"apigateway:PUT\", \"lambda:InvokeFunction\", \"lambda:GetFunction\", \"lambda:UpdateFunctionConfiguration\", \"cloudformation:DescribeStacks\", \"lambda:UpdateFunctionCode\", \"lambda:DeleteFunctionConcurrency\", \"events:DeleteRule\", \"events:PutTargets\", \"lambda:AddPermission\", \"cloudformation:CreateStack\", \"cloudformation:DeleteStack\", \"apigateway:POST\", \"lambda:RemovePermission\", \"lambda:GetPolicy\" ], \"Resource\": \"*\" }, { \"Effect\": \"Allow\", \"Action\": [ \"s3:ListBucketMultipartUploads\", \"s3:CreateBucket\", \"s3:ListBucket\" ], \"Resource\": \"arn:aws:s3:::zappa-*\" }, { \"Effect\": \"Allow\", \"Action\": [ \"s3:PutObject\", \"s3:GetObject\", \"s3:AbortMultipartUpload\", \"s3:DeleteObject\", \"s3:ListMultipartUploadParts\" ], \"Resource\": \"arn:aws:s3:::zappa-*/*\" } ]}"
},
{
"code": null,
"e": 4984,
"s": 4867,
"text": "Now you add the credentials you created for Zappa to your local file (credentials and configs), mine looks like this"
},
{
"code": null,
"e": 5105,
"s": 4984,
"text": "[default]aws_access_key_id = ****aws_secret_access_key = ****[zappa]aws_access_key_id = ****aws_secret_access_key = ****"
},
{
"code": null,
"e": 5126,
"s": 5105,
"text": "and config like this"
},
{
"code": null,
"e": 5215,
"s": 5126,
"text": "[default]region = ap-southeast-1output = json[zappa]region = ap-southeast-1output = json"
},
{
"code": null,
"e": 5392,
"s": 5215,
"text": "I created one especially for Zappa, because I believe most of us would have a default credential for ourself, this setting would allow you to switch between different profiles."
},
{
"code": null,
"e": 5419,
"s": 5392,
"text": "Now it is ready to deploy!"
},
{
"code": null,
"e": 5475,
"s": 5419,
"text": "export AWS_DEFAULT_PROFILE=zappazappa deploy production"
},
{
"code": null,
"e": 5591,
"s": 5475,
"text": "You would see your API url right after the command line. Now go to your AWS Lambda you should see our API deployed:"
},
{
"code": null,
"e": 5623,
"s": 5591,
"text": "And in API Gateway you can see:"
},
{
"code": null,
"e": 5694,
"s": 5623,
"text": "Now that I can test the public endpoint on postman and get a response:"
},
{
"code": null,
"e": 5777,
"s": 5694,
"text": "Congrats! Now you have your app fully deployed to AWS with Lambda and API Gateway!"
},
{
"code": null,
"e": 5941,
"s": 5777,
"text": "You can stop here if this already satisfies your need, but if you would like to distribute your API and add restrictions for it, you can continue to the next part."
},
{
"code": null,
"e": 6232,
"s": 5941,
"text": "You might have noticed that so far our API is publicly accessible, which means anyone can access our API and it is susceptible to malicious attack. To avoid such undesired visits, we need to add extra limitations on our API usage (Usage Plan) and credentials (x-api-key) to restrict visits."
},
{
"code": null,
"e": 6281,
"s": 6232,
"text": "To add a key to your API, follow the steps here."
},
{
"code": null,
"e": 6404,
"s": 6281,
"text": "RapidAPI is where for everyone to freely open and sell their API to the world as long as someone is willing to pay for it."
},
{
"code": null,
"e": 6610,
"s": 6404,
"text": "Go to RapidAPI and click Add New APIFill in the basic info of your APIFor the URL of your API, paste the AWS url we previous got after deploying though ZappaIn the access control add your api key as follow"
},
{
"code": null,
"e": 6647,
"s": 6610,
"text": "Go to RapidAPI and click Add New API"
},
{
"code": null,
"e": 6682,
"s": 6647,
"text": "Fill in the basic info of your API"
},
{
"code": null,
"e": 6770,
"s": 6682,
"text": "For the URL of your API, paste the AWS url we previous got after deploying though Zappa"
},
{
"code": null,
"e": 6819,
"s": 6770,
"text": "In the access control add your api key as follow"
},
{
"code": null,
"e": 6887,
"s": 6819,
"text": "5. Add a pricing plan and you are ready to launch it to the public!"
},
{
"code": null,
"e": 7089,
"s": 6887,
"text": "Lastly, if you are interested, you can check out my referral API. If you are looking for a new career, so far it helps you to refer you to the company of Bytedance and Grab through the internal portal."
}
]
|
Kotlin - Delegation | Kotlin supports “delegation” design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object. The following example demonstrates how this happens in Kotlin.
interface Base {
fun printMe() //abstract method
}
class BaseImpl(val x: Int) : Base {
override fun printMe() { println(x) } //implementation of the method
}
class Derived(b: Base) : Base by b // delegating the public method on the object b
fun main(args: Array<String>) {
val b = BaseImpl(10)
Derived(b).printMe() // prints 10 :: accessing the printMe() method
}
In the example, we have one interface “Base” with its abstract method named “printme()”. In the BaseImpl class, we are implementing this “printme()” and later from another class we are using this implementation using “by” keyword.
The above piece of code will yield the following output in the browser.
10
In the previous section, we have learned about the delegation design pattern using “by” keyword. In this section, we will learn about delegation of properties using some standard methods mentioned in Kotlin library.
Delegation means passing the responsibility to another class or method. When a property is already declared in some places, then we should reuse the same code to initialize them. In the following examples, we will use some standard delegation methodology provided by Kotlin and some standard library function while implementing delegation in our examples.
Lazy is a lambda function which takes a property as an input and in return gives an instance of Lazy<T>, where <T> is basically the type of the properties it is using. Let us take a look at the following to understand how it works.
val myVar: String by lazy {
"Hello"
}
fun main(args: Array<String>) {
println(myVar +" My dear friend")
}
In the above piece of code, we are passing a variable “myVar” to the Lazy function, which in return assigns the value to its object and returns the same to the main function. Following is the output in the browser.
Hello My dear friend
Observable() takes two arguments to initialize the object and returns the same to the called function. In the following example, we will see how to use Observable() method in order to implement delegation.
import kotlin.properties.Delegates
class User {
var name: String by Delegates.observable("Welcome to Tutorialspoint.com") {
prop, old, new ->
println("$old -> $new")
}
}
fun main(args: Array<String>) {
val user = User()
user.name = "first"
user.name = "second"
}
The above piece of code will yield the following output in the browser.
first -> second
In general, the syntax is the expression after the “by” keyword is delegated. The get() and set() methods of the variable p will be delegated to its getValue() and setValue() methods defined in the Delegate class.
class Example {
var p: String by Delegate()
}
For the above piece of code, following is the delegate class that we need to generate in order to assign the value in the variable p.
class Delegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return "$thisRef, thank you for delegating '${property.name}' to me!"
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("$value has been assigned to '${property.name} in $thisRef.'")
}
}
While reading, getValue() method will be called and while setting the variable setValue() method will be called.
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": 2733,
"s": 2425,
"text": "Kotlin supports “delegation” design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object. The following example demonstrates how this happens in Kotlin."
},
{
"code": null,
"e": 3114,
"s": 2733,
"text": "interface Base {\n fun printMe() //abstract method\n}\nclass BaseImpl(val x: Int) : Base {\n override fun printMe() { println(x) } //implementation of the method\n}\nclass Derived(b: Base) : Base by b // delegating the public method on the object b\n\nfun main(args: Array<String>) {\n val b = BaseImpl(10)\n Derived(b).printMe() // prints 10 :: accessing the printMe() method \n}"
},
{
"code": null,
"e": 3345,
"s": 3114,
"text": "In the example, we have one interface “Base” with its abstract method named “printme()”. In the BaseImpl class, we are implementing this “printme()” and later from another class we are using this implementation using “by” keyword."
},
{
"code": null,
"e": 3417,
"s": 3345,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 3421,
"s": 3417,
"text": "10\n"
},
{
"code": null,
"e": 3637,
"s": 3421,
"text": "In the previous section, we have learned about the delegation design pattern using “by” keyword. In this section, we will learn about delegation of properties using some standard methods mentioned in Kotlin library."
},
{
"code": null,
"e": 3993,
"s": 3637,
"text": "Delegation means passing the responsibility to another class or method. When a property is already declared in some places, then we should reuse the same code to initialize them. In the following examples, we will use some standard delegation methodology provided by Kotlin and some standard library function while implementing delegation in our examples."
},
{
"code": null,
"e": 4225,
"s": 3993,
"text": "Lazy is a lambda function which takes a property as an input and in return gives an instance of Lazy<T>, where <T> is basically the type of the properties it is using. Let us take a look at the following to understand how it works."
},
{
"code": null,
"e": 4337,
"s": 4225,
"text": "val myVar: String by lazy {\n \"Hello\"\n}\nfun main(args: Array<String>) {\n println(myVar +\" My dear friend\")\n}"
},
{
"code": null,
"e": 4552,
"s": 4337,
"text": "In the above piece of code, we are passing a variable “myVar” to the Lazy function, which in return assigns the value to its object and returns the same to the main function. Following is the output in the browser."
},
{
"code": null,
"e": 4574,
"s": 4552,
"text": "Hello My dear friend\n"
},
{
"code": null,
"e": 4780,
"s": 4574,
"text": "Observable() takes two arguments to initialize the object and returns the same to the called function. In the following example, we will see how to use Observable() method in order to implement delegation."
},
{
"code": null,
"e": 5070,
"s": 4780,
"text": "import kotlin.properties.Delegates\nclass User {\n var name: String by Delegates.observable(\"Welcome to Tutorialspoint.com\") {\n prop, old, new ->\n println(\"$old -> $new\")\n }\n}\nfun main(args: Array<String>) {\n val user = User()\n user.name = \"first\"\n user.name = \"second\"\n}"
},
{
"code": null,
"e": 5142,
"s": 5070,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 5159,
"s": 5142,
"text": "first -> second\n"
},
{
"code": null,
"e": 5373,
"s": 5159,
"text": "In general, the syntax is the expression after the “by” keyword is delegated. The get() and set() methods of the variable p will be delegated to its getValue() and setValue() methods defined in the Delegate class."
},
{
"code": null,
"e": 5422,
"s": 5373,
"text": "class Example {\n var p: String by Delegate()\n}"
},
{
"code": null,
"e": 5556,
"s": 5422,
"text": "For the above piece of code, following is the delegate class that we need to generate in order to assign the value in the variable p."
},
{
"code": null,
"e": 5893,
"s": 5556,
"text": "class Delegate {\n operator fun getValue(thisRef: Any?, property: KProperty<*>): String {\n return \"$thisRef, thank you for delegating '${property.name}' to me!\"\n }\n operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {\n println(\"$value has been assigned to '${property.name} in $thisRef.'\")\n }\n}"
},
{
"code": null,
"e": 6006,
"s": 5893,
"text": "While reading, getValue() method will be called and while setting the variable setValue() method will be called."
},
{
"code": null,
"e": 6041,
"s": 6006,
"text": "\n 68 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6060,
"s": 6041,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6095,
"s": 6060,
"text": "\n 71 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6112,
"s": 6095,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6147,
"s": 6112,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6164,
"s": 6147,
"text": " Mahmoud Ramadan"
},
{
"code": null,
"e": 6197,
"s": 6164,
"text": "\n 49 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6213,
"s": 6197,
"text": " Catalin Stefan"
},
{
"code": null,
"e": 6248,
"s": 6213,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6268,
"s": 6248,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 6301,
"s": 6268,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6318,
"s": 6301,
"text": " CLEMENT OCHIENG"
},
{
"code": null,
"e": 6325,
"s": 6318,
"text": " Print"
},
{
"code": null,
"e": 6336,
"s": 6325,
"text": " Add Notes"
}
]
|
Basic Time Series Manipulation with Pandas | by Laura Fedoruk | Towards Data Science | As someone who works with time series data on almost a daily basis, I have found the pandas Python package to be extremely useful for time series manipulation and analysis.
This basic introduction to time series data manipulation with pandas should allow you to get started in your time series analysis. Specific objectives are to show you how to:
create a date range
work with timestamp data
convert string data to a timestamp
index and slice your time series data in a data frame
resample your time series for different time period aggregates/summary statistics
compute a rolling statistic such as a rolling average
work with missing data
understand the basics of unix/epoch time
understand common pitfalls of time series data analysis
Let’s get started. If you want to play with real data that you have, you may want to start by using pandas read_csv to read in your file to a data frame, however we’re going to start by playing with generated data.
First import the libraries we’ll be working with and then use them to create a date range
import pandas as pdfrom datetime import datetimeimport numpy as npdate_rng = pd.date_range(start='1/1/2018', end='1/08/2018', freq='H')
This date range has timestamps with an hourly frequency. If we call date_rng we’ll see that it looks like the following:
DatetimeIndex(['2018-01-01 00:00:00', '2018-01-01 01:00:00', '2018-01-01 02:00:00', '2018-01-01 03:00:00', '2018-01-01 04:00:00', '2018-01-01 05:00:00', '2018-01-01 06:00:00', '2018-01-01 07:00:00', '2018-01-01 08:00:00', '2018-01-01 09:00:00', ... '2018-01-07 15:00:00', '2018-01-07 16:00:00', '2018-01-07 17:00:00', '2018-01-07 18:00:00', '2018-01-07 19:00:00', '2018-01-07 20:00:00', '2018-01-07 21:00:00', '2018-01-07 22:00:00', '2018-01-07 23:00:00', '2018-01-08 00:00:00'], dtype='datetime64[ns]', length=169, freq='H')
We can check the type of the first element:
type(date_rng[0])#returnspandas._libs.tslib.Timestamp
Let’s create an example data frame with the timestamp data and look at the first 15 elements:
df = pd.DataFrame(date_rng, columns=['date'])df['data'] = np.random.randint(0,100,size=(len(date_rng)))df.head(15)
If we want to do time series manipulation, we’ll need to have a date time index so that our data frame is indexed on the timestamp.
Convert the data frame index to a datetime index then show the first elements:
df['datetime'] = pd.to_datetime(df['date'])df = df.set_index('datetime')df.drop(['date'], axis=1, inplace=True)df.head()
What if our ‘time’ stamps in our data are actually string type vs. numerical? Let’s convert our date_rng to a list of strings and then convert the strings to timestamps.
string_date_rng = [str(x) for x in date_rng]string_date_rng#returns['2018-01-01 00:00:00', '2018-01-01 01:00:00', '2018-01-01 02:00:00', '2018-01-01 03:00:00', '2018-01-01 04:00:00', '2018-01-01 05:00:00', '2018-01-01 06:00:00', '2018-01-01 07:00:00', '2018-01-01 08:00:00', '2018-01-01 09:00:00',...
We can convert the strings to timestamps by inferring their format, then look at the values:
timestamp_date_rng = pd.to_datetime(string_date_rng, infer_datetime_format=True)timestamp_date_rng#returnsDatetimeIndex(['2018-01-01 00:00:00', '2018-01-01 01:00:00', '2018-01-01 02:00:00', '2018-01-01 03:00:00', '2018-01-01 04:00:00', '2018-01-01 05:00:00', '2018-01-01 06:00:00', '2018-01-01 07:00:00', '2018-01-01 08:00:00', '2018-01-01 09:00:00', ... '2018-01-07 15:00:00', '2018-01-07 16:00:00', '2018-01-07 17:00:00', '2018-01-07 18:00:00', '2018-01-07 19:00:00', '2018-01-07 20:00:00', '2018-01-07 21:00:00', '2018-01-07 22:00:00', '2018-01-07 23:00:00', '2018-01-08 00:00:00'], dtype='datetime64[ns]', length=169, freq=None)
But what about if we need to convert a unique string format?
Let’s create an arbitrary list of dates that are strings and convert them to timestamps:
string_date_rng_2 = ['June-01-2018', 'June-02-2018', 'June-03-2018']timestamp_date_rng_2 = [datetime.strptime(x,'%B-%d-%Y') for x in string_date_rng_2]timestamp_date_rng_2#returns[datetime.datetime(2018, 6, 1, 0, 0), datetime.datetime(2018, 6, 2, 0, 0), datetime.datetime(2018, 6, 3, 0, 0)]
What does it look like if we put this into a data frame?
df2 = pd.DataFrame(timestamp_date_rng_2, columns=['date'])df2
Going back to our original data frame, let’s look at the data by parsing on timestamp index:
Say we just want to see data where the date is the 2nd of the month, we could use the index as per below.
df[df.index.day == 2]
The top of this looks like:
We could also directly call a date that we want to look at via the index of the data frame:
df['2018-01-03']
What about selecting data between certain dates?
df['2018-01-04':'2018-01-06']
The basic data frame that we’ve populated gives us data on an hourly frequency, but we can resample the data at a different frequency and specify how we would like to compute the summary statistic for the new sample frequency. We could take the min, max, average, sum, etc., of the data at a daily frequency instead of an hourly frequency as per the example below where we compute the daily average of the data:
df.resample('D').mean()
What about window statistics such as a rolling mean or a rolling sum?
Let’s create a new column in our original df that computes the rolling sum over a 3 window period and then look at the top of the data frame:
df['rolling_sum'] = df.rolling(3).sum()df.head(10)
We can see that this is computing correctly and that it only starts having valid values when there are three periods over which to look back.
This is a good chance to see how we can do forward or backfilling of data when working with missing data values.
Here’s our df but with a new column that takes the rolling sum and backfills the data:
df['rolling_sum_backfilled'] = df['rolling_sum'].fillna(method='backfill')df.head(10)
It’s often useful to be able to fill your missing data with realistic values such as the average of a time period, but always remember that if you are working with a time series problem and want your data to be realistic, you should not do a backfill of your data as that’s like looking into the future and getting information you would never have at that time period. Likely you will want to forward fill your data more frequently than you backfill.
When working with time series data, you may come across time values that are in Unix time. Unix time, also called Epoch time is the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. Using Unix time helps to disambiguate time stamps so that we don’t get confused by time zones, daylight savings time, etc.
Here’s an example of a time t that is in Epoch time and converting unix/epoch time to a regular time stamp in UTC:
epoch_t = 1529272655real_t = pd.to_datetime(epoch_t, unit='s')real_t#returnsTimestamp('2018-06-17 21:57:35')
If I wanted to convert that time that is in UTC to my own time zone, I could simply do the following:
real_t.tz_localize('UTC').tz_convert('US/Pacific')#returnsTimestamp('2018-06-17 14:57:35-0700', tz='US/Pacific')
With these basics, you should be all set to work with your time series data.
Here are a few tips to keep in mind and common pitfalls to avoid when working with time series data:
Check for discrepancies in your data that may be caused by region specific time changes like daylight savings time.
Keep track of time zones meticulously — let others going through your code know what time zone your data is in, and think about converting to UTC or a standardized value in order to keep your data standardized.
Missing data can occur frequently — make sure you document your cleaning rules and think about not backfilling information you wouldn’t have been able to have at the time of a sample.
Remember that as you resample your data or fill in missing values, you’re losing a certain amount of information about your original data set. I’d suggest keeping track of all of your data transformations and tracking the root cause of your data issues.
When you resample your data, the best method (mean, min, max, sum, etc.) will be dependent on the kind of data you have and how it was sampled. Be thoughtful about how you resample your data for your analysis. | [
{
"code": null,
"e": 345,
"s": 172,
"text": "As someone who works with time series data on almost a daily basis, I have found the pandas Python package to be extremely useful for time series manipulation and analysis."
},
{
"code": null,
"e": 520,
"s": 345,
"text": "This basic introduction to time series data manipulation with pandas should allow you to get started in your time series analysis. Specific objectives are to show you how to:"
},
{
"code": null,
"e": 540,
"s": 520,
"text": "create a date range"
},
{
"code": null,
"e": 565,
"s": 540,
"text": "work with timestamp data"
},
{
"code": null,
"e": 600,
"s": 565,
"text": "convert string data to a timestamp"
},
{
"code": null,
"e": 654,
"s": 600,
"text": "index and slice your time series data in a data frame"
},
{
"code": null,
"e": 736,
"s": 654,
"text": "resample your time series for different time period aggregates/summary statistics"
},
{
"code": null,
"e": 790,
"s": 736,
"text": "compute a rolling statistic such as a rolling average"
},
{
"code": null,
"e": 813,
"s": 790,
"text": "work with missing data"
},
{
"code": null,
"e": 854,
"s": 813,
"text": "understand the basics of unix/epoch time"
},
{
"code": null,
"e": 910,
"s": 854,
"text": "understand common pitfalls of time series data analysis"
},
{
"code": null,
"e": 1125,
"s": 910,
"text": "Let’s get started. If you want to play with real data that you have, you may want to start by using pandas read_csv to read in your file to a data frame, however we’re going to start by playing with generated data."
},
{
"code": null,
"e": 1215,
"s": 1125,
"text": "First import the libraries we’ll be working with and then use them to create a date range"
},
{
"code": null,
"e": 1351,
"s": 1215,
"text": "import pandas as pdfrom datetime import datetimeimport numpy as npdate_rng = pd.date_range(start='1/1/2018', end='1/08/2018', freq='H')"
},
{
"code": null,
"e": 1472,
"s": 1351,
"text": "This date range has timestamps with an hourly frequency. If we call date_rng we’ll see that it looks like the following:"
},
{
"code": null,
"e": 2151,
"s": 1472,
"text": "DatetimeIndex(['2018-01-01 00:00:00', '2018-01-01 01:00:00', '2018-01-01 02:00:00', '2018-01-01 03:00:00', '2018-01-01 04:00:00', '2018-01-01 05:00:00', '2018-01-01 06:00:00', '2018-01-01 07:00:00', '2018-01-01 08:00:00', '2018-01-01 09:00:00', ... '2018-01-07 15:00:00', '2018-01-07 16:00:00', '2018-01-07 17:00:00', '2018-01-07 18:00:00', '2018-01-07 19:00:00', '2018-01-07 20:00:00', '2018-01-07 21:00:00', '2018-01-07 22:00:00', '2018-01-07 23:00:00', '2018-01-08 00:00:00'], dtype='datetime64[ns]', length=169, freq='H')"
},
{
"code": null,
"e": 2195,
"s": 2151,
"text": "We can check the type of the first element:"
},
{
"code": null,
"e": 2249,
"s": 2195,
"text": "type(date_rng[0])#returnspandas._libs.tslib.Timestamp"
},
{
"code": null,
"e": 2343,
"s": 2249,
"text": "Let’s create an example data frame with the timestamp data and look at the first 15 elements:"
},
{
"code": null,
"e": 2458,
"s": 2343,
"text": "df = pd.DataFrame(date_rng, columns=['date'])df['data'] = np.random.randint(0,100,size=(len(date_rng)))df.head(15)"
},
{
"code": null,
"e": 2590,
"s": 2458,
"text": "If we want to do time series manipulation, we’ll need to have a date time index so that our data frame is indexed on the timestamp."
},
{
"code": null,
"e": 2669,
"s": 2590,
"text": "Convert the data frame index to a datetime index then show the first elements:"
},
{
"code": null,
"e": 2790,
"s": 2669,
"text": "df['datetime'] = pd.to_datetime(df['date'])df = df.set_index('datetime')df.drop(['date'], axis=1, inplace=True)df.head()"
},
{
"code": null,
"e": 2960,
"s": 2790,
"text": "What if our ‘time’ stamps in our data are actually string type vs. numerical? Let’s convert our date_rng to a list of strings and then convert the strings to timestamps."
},
{
"code": null,
"e": 3261,
"s": 2960,
"text": "string_date_rng = [str(x) for x in date_rng]string_date_rng#returns['2018-01-01 00:00:00', '2018-01-01 01:00:00', '2018-01-01 02:00:00', '2018-01-01 03:00:00', '2018-01-01 04:00:00', '2018-01-01 05:00:00', '2018-01-01 06:00:00', '2018-01-01 07:00:00', '2018-01-01 08:00:00', '2018-01-01 09:00:00',..."
},
{
"code": null,
"e": 3354,
"s": 3261,
"text": "We can convert the strings to timestamps by inferring their format, then look at the values:"
},
{
"code": null,
"e": 4140,
"s": 3354,
"text": "timestamp_date_rng = pd.to_datetime(string_date_rng, infer_datetime_format=True)timestamp_date_rng#returnsDatetimeIndex(['2018-01-01 00:00:00', '2018-01-01 01:00:00', '2018-01-01 02:00:00', '2018-01-01 03:00:00', '2018-01-01 04:00:00', '2018-01-01 05:00:00', '2018-01-01 06:00:00', '2018-01-01 07:00:00', '2018-01-01 08:00:00', '2018-01-01 09:00:00', ... '2018-01-07 15:00:00', '2018-01-07 16:00:00', '2018-01-07 17:00:00', '2018-01-07 18:00:00', '2018-01-07 19:00:00', '2018-01-07 20:00:00', '2018-01-07 21:00:00', '2018-01-07 22:00:00', '2018-01-07 23:00:00', '2018-01-08 00:00:00'], dtype='datetime64[ns]', length=169, freq=None)"
},
{
"code": null,
"e": 4201,
"s": 4140,
"text": "But what about if we need to convert a unique string format?"
},
{
"code": null,
"e": 4290,
"s": 4201,
"text": "Let’s create an arbitrary list of dates that are strings and convert them to timestamps:"
},
{
"code": null,
"e": 4581,
"s": 4290,
"text": "string_date_rng_2 = ['June-01-2018', 'June-02-2018', 'June-03-2018']timestamp_date_rng_2 = [datetime.strptime(x,'%B-%d-%Y') for x in string_date_rng_2]timestamp_date_rng_2#returns[datetime.datetime(2018, 6, 1, 0, 0), datetime.datetime(2018, 6, 2, 0, 0), datetime.datetime(2018, 6, 3, 0, 0)]"
},
{
"code": null,
"e": 4638,
"s": 4581,
"text": "What does it look like if we put this into a data frame?"
},
{
"code": null,
"e": 4700,
"s": 4638,
"text": "df2 = pd.DataFrame(timestamp_date_rng_2, columns=['date'])df2"
},
{
"code": null,
"e": 4793,
"s": 4700,
"text": "Going back to our original data frame, let’s look at the data by parsing on timestamp index:"
},
{
"code": null,
"e": 4899,
"s": 4793,
"text": "Say we just want to see data where the date is the 2nd of the month, we could use the index as per below."
},
{
"code": null,
"e": 4921,
"s": 4899,
"text": "df[df.index.day == 2]"
},
{
"code": null,
"e": 4949,
"s": 4921,
"text": "The top of this looks like:"
},
{
"code": null,
"e": 5041,
"s": 4949,
"text": "We could also directly call a date that we want to look at via the index of the data frame:"
},
{
"code": null,
"e": 5058,
"s": 5041,
"text": "df['2018-01-03']"
},
{
"code": null,
"e": 5107,
"s": 5058,
"text": "What about selecting data between certain dates?"
},
{
"code": null,
"e": 5137,
"s": 5107,
"text": "df['2018-01-04':'2018-01-06']"
},
{
"code": null,
"e": 5549,
"s": 5137,
"text": "The basic data frame that we’ve populated gives us data on an hourly frequency, but we can resample the data at a different frequency and specify how we would like to compute the summary statistic for the new sample frequency. We could take the min, max, average, sum, etc., of the data at a daily frequency instead of an hourly frequency as per the example below where we compute the daily average of the data:"
},
{
"code": null,
"e": 5573,
"s": 5549,
"text": "df.resample('D').mean()"
},
{
"code": null,
"e": 5643,
"s": 5573,
"text": "What about window statistics such as a rolling mean or a rolling sum?"
},
{
"code": null,
"e": 5785,
"s": 5643,
"text": "Let’s create a new column in our original df that computes the rolling sum over a 3 window period and then look at the top of the data frame:"
},
{
"code": null,
"e": 5836,
"s": 5785,
"text": "df['rolling_sum'] = df.rolling(3).sum()df.head(10)"
},
{
"code": null,
"e": 5978,
"s": 5836,
"text": "We can see that this is computing correctly and that it only starts having valid values when there are three periods over which to look back."
},
{
"code": null,
"e": 6091,
"s": 5978,
"text": "This is a good chance to see how we can do forward or backfilling of data when working with missing data values."
},
{
"code": null,
"e": 6178,
"s": 6091,
"text": "Here’s our df but with a new column that takes the rolling sum and backfills the data:"
},
{
"code": null,
"e": 6264,
"s": 6178,
"text": "df['rolling_sum_backfilled'] = df['rolling_sum'].fillna(method='backfill')df.head(10)"
},
{
"code": null,
"e": 6715,
"s": 6264,
"text": "It’s often useful to be able to fill your missing data with realistic values such as the average of a time period, but always remember that if you are working with a time series problem and want your data to be realistic, you should not do a backfill of your data as that’s like looking into the future and getting information you would never have at that time period. Likely you will want to forward fill your data more frequently than you backfill."
},
{
"code": null,
"e": 7081,
"s": 6715,
"text": "When working with time series data, you may come across time values that are in Unix time. Unix time, also called Epoch time is the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. Using Unix time helps to disambiguate time stamps so that we don’t get confused by time zones, daylight savings time, etc."
},
{
"code": null,
"e": 7196,
"s": 7081,
"text": "Here’s an example of a time t that is in Epoch time and converting unix/epoch time to a regular time stamp in UTC:"
},
{
"code": null,
"e": 7305,
"s": 7196,
"text": "epoch_t = 1529272655real_t = pd.to_datetime(epoch_t, unit='s')real_t#returnsTimestamp('2018-06-17 21:57:35')"
},
{
"code": null,
"e": 7407,
"s": 7305,
"text": "If I wanted to convert that time that is in UTC to my own time zone, I could simply do the following:"
},
{
"code": null,
"e": 7520,
"s": 7407,
"text": "real_t.tz_localize('UTC').tz_convert('US/Pacific')#returnsTimestamp('2018-06-17 14:57:35-0700', tz='US/Pacific')"
},
{
"code": null,
"e": 7597,
"s": 7520,
"text": "With these basics, you should be all set to work with your time series data."
},
{
"code": null,
"e": 7698,
"s": 7597,
"text": "Here are a few tips to keep in mind and common pitfalls to avoid when working with time series data:"
},
{
"code": null,
"e": 7814,
"s": 7698,
"text": "Check for discrepancies in your data that may be caused by region specific time changes like daylight savings time."
},
{
"code": null,
"e": 8025,
"s": 7814,
"text": "Keep track of time zones meticulously — let others going through your code know what time zone your data is in, and think about converting to UTC or a standardized value in order to keep your data standardized."
},
{
"code": null,
"e": 8209,
"s": 8025,
"text": "Missing data can occur frequently — make sure you document your cleaning rules and think about not backfilling information you wouldn’t have been able to have at the time of a sample."
},
{
"code": null,
"e": 8463,
"s": 8209,
"text": "Remember that as you resample your data or fill in missing values, you’re losing a certain amount of information about your original data set. I’d suggest keeping track of all of your data transformations and tracking the root cause of your data issues."
}
]
|
ReactJS UI Ant Design TreeSelect Component - GeeksforGeeks | 03 Jun, 2021
Ant Design Library has this component pre-built, and it is very easy to integrate as well. TreeSelect Component is used for the Tree selection control. It is similar to the Select component but here the values are provided in a tree-like structure. We can use the following approach in ReactJS to use the Ant Design TreeSelect Component.
TreeSelect Props:
allowClear: It is used to indicate whether to allow clear or not.
autoClearSearchValue: It is used to auto clear the search input value.
bordered; It is used to indicate whether it has border style or not.
defaultValue: It is used to set the initially selected treeNodes.
disabled: It is used to indicate whether it is Disabled or not.
dropdownClassName: It is used to pass the class name of the dropdown menu.
dropdownMatchSelectWidth: It is used to determine whether the dropdown menu and select input are the same widths or not.
dropdownRender: It is used to customize dropdown content.
dropdownStyle: It is used to set the style of the dropdown menu.
filterTreeNode: It is used to indicate whether to filter treeNodes by input value.
getPopupContainer: It is used to set the container of the dropdown menu.
labelInValue: It is used to indicate whether to embed label in value.
listHeight: It is used to define the config popup height.
loadData: It is used to load data asynchronously.
maxTagCount: It is used to define the max tag count to show.
maxTagPlaceholder: It is used to define the placeholder for not showing tags.
multiple: It is used to support multiple selections if treeCheckable is enabled.
placeholder: It is used to define the placeholder of the select input.
searchValue: It is used to make search value controlled and it works with onSearch.
showArrow: It is used to indicate whether to show the suffixIcon.
showCheckedStrategy: It is used to show the selected item in the box when treeCheckable is set to true.
showSearch: It is used to denote whether to support search or not.
size: It is used to set the size of the select input.
suffixIcon: It is used for the custom suffix icon.
switcherIcon: It is used to customize collapse.
treeCheckable: It is used to indicate whether to show a checkbox on the treeNodes or not.
treeCheckStrictly: It is used to indicate whether to check nodes precisely or not.
treeData: It is used to denote the data of the treeNodes.
treeDataSimpleMode: It is used to enable the simple mode of treeData.
treeDefaultExpandAll: It is used to indicate whether to expand all treeNodes by default or not.
treeDefaultExpandedKeys: It is used to denote the default expanded treeNode.
treeExpandedKeys: It is used to set expanded keys.
treeIcon: It is used to show the icon before a TreeNode’s title.
treeNodeFilterProp: It is used to define the filter which will be used for filtering if filterTreeNode returns true.
treeNodeLabelProp: It is used to define props that will render as the content of select.
value: It is used to set the currently selected treeNodes.
virtual: It is used to disable virtual scroll when set it is set to false.
onChange: It is a callback function that is triggered when selected treeNodes or input value change.
onDropdownVisibleChange: It is a callback function that is triggered when the dropdown opens.
onSearch: It is a callback function that is triggered when the search input changes.
onSelect: It is a callback function that is triggered when you select a treeNode.
onTreeExpand: It is a callback function that is triggered when treeNode expanded.
Tree Methods:
blur(): This method is used to remove the focus.
focus(): This method is used to get the focus.
TreeNode Props:
checkable: It is used to display the Checkbox for TreeNode if Tree is checkable.
disableCheckbox: It is used to disable the checkbox of the treeNode.
disabled: It is used to indicate whether it is disabled or not.
isLeaf: It is used to indicate whether it is a leaf node or not.
key: It is used for the unique identification of elements.
selectable: It is used to indicate whether it can be selected or not.
title: It is used to denote the content showed on the treeNodes.
value: It is used to define the value which will be treated as treeNodeFilterProp by default.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install antd
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React, { useState } from 'react';import { TreeSelect } from 'antd';import "antd/dist/antd.css"; const { TreeNode } = TreeSelect; export default function App() { // States to manage current value const [value, setValue] = useState(undefined); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design TreeSelect Component</h4> <> <TreeSelect placeholder="Select from the Tree" allowClear showSearch value={value} onChange={() => { setValue(value); }} > <TreeNode value="Parent" title="Parent"> <TreeNode value="ChildLeaf1" title="ChildLeaf1" /> <TreeNode value="ChildLeaf2" title="ChildLeaf2" /> <TreeNode value="ChildLeaf3" title="ChildLeaf3" /> <TreeNode value="ChildLeaf4" title="ChildLeaf4" /> <TreeNode value="ChildLeaf5" title="ChildLeaf5" /> </TreeNode> </TreeSelect> </> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://ant.design/components/tree-select/
ReactJS-Ant Design
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to redirect to another page in ReactJS ?
How to fetch data from an API in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to navigate on path by button click in react router ?
How to set background images in ReactJS ?
Express.js express.Router() Function
Installation of Node.js on Linux
How to create footer to stay at the bottom of a Web page?
Convert a string to an integer in JavaScript
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 33847,
"s": 33819,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 34185,
"s": 33847,
"text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. TreeSelect Component is used for the Tree selection control. It is similar to the Select component but here the values are provided in a tree-like structure. We can use the following approach in ReactJS to use the Ant Design TreeSelect Component."
},
{
"code": null,
"e": 34203,
"s": 34185,
"text": "TreeSelect Props:"
},
{
"code": null,
"e": 34269,
"s": 34203,
"text": "allowClear: It is used to indicate whether to allow clear or not."
},
{
"code": null,
"e": 34340,
"s": 34269,
"text": "autoClearSearchValue: It is used to auto clear the search input value."
},
{
"code": null,
"e": 34409,
"s": 34340,
"text": "bordered; It is used to indicate whether it has border style or not."
},
{
"code": null,
"e": 34475,
"s": 34409,
"text": "defaultValue: It is used to set the initially selected treeNodes."
},
{
"code": null,
"e": 34539,
"s": 34475,
"text": "disabled: It is used to indicate whether it is Disabled or not."
},
{
"code": null,
"e": 34614,
"s": 34539,
"text": "dropdownClassName: It is used to pass the class name of the dropdown menu."
},
{
"code": null,
"e": 34735,
"s": 34614,
"text": "dropdownMatchSelectWidth: It is used to determine whether the dropdown menu and select input are the same widths or not."
},
{
"code": null,
"e": 34793,
"s": 34735,
"text": "dropdownRender: It is used to customize dropdown content."
},
{
"code": null,
"e": 34858,
"s": 34793,
"text": "dropdownStyle: It is used to set the style of the dropdown menu."
},
{
"code": null,
"e": 34941,
"s": 34858,
"text": "filterTreeNode: It is used to indicate whether to filter treeNodes by input value."
},
{
"code": null,
"e": 35014,
"s": 34941,
"text": "getPopupContainer: It is used to set the container of the dropdown menu."
},
{
"code": null,
"e": 35084,
"s": 35014,
"text": "labelInValue: It is used to indicate whether to embed label in value."
},
{
"code": null,
"e": 35142,
"s": 35084,
"text": "listHeight: It is used to define the config popup height."
},
{
"code": null,
"e": 35192,
"s": 35142,
"text": "loadData: It is used to load data asynchronously."
},
{
"code": null,
"e": 35253,
"s": 35192,
"text": "maxTagCount: It is used to define the max tag count to show."
},
{
"code": null,
"e": 35331,
"s": 35253,
"text": "maxTagPlaceholder: It is used to define the placeholder for not showing tags."
},
{
"code": null,
"e": 35412,
"s": 35331,
"text": "multiple: It is used to support multiple selections if treeCheckable is enabled."
},
{
"code": null,
"e": 35483,
"s": 35412,
"text": "placeholder: It is used to define the placeholder of the select input."
},
{
"code": null,
"e": 35567,
"s": 35483,
"text": "searchValue: It is used to make search value controlled and it works with onSearch."
},
{
"code": null,
"e": 35633,
"s": 35567,
"text": "showArrow: It is used to indicate whether to show the suffixIcon."
},
{
"code": null,
"e": 35737,
"s": 35633,
"text": "showCheckedStrategy: It is used to show the selected item in the box when treeCheckable is set to true."
},
{
"code": null,
"e": 35804,
"s": 35737,
"text": "showSearch: It is used to denote whether to support search or not."
},
{
"code": null,
"e": 35858,
"s": 35804,
"text": "size: It is used to set the size of the select input."
},
{
"code": null,
"e": 35909,
"s": 35858,
"text": "suffixIcon: It is used for the custom suffix icon."
},
{
"code": null,
"e": 35957,
"s": 35909,
"text": "switcherIcon: It is used to customize collapse."
},
{
"code": null,
"e": 36047,
"s": 35957,
"text": "treeCheckable: It is used to indicate whether to show a checkbox on the treeNodes or not."
},
{
"code": null,
"e": 36130,
"s": 36047,
"text": "treeCheckStrictly: It is used to indicate whether to check nodes precisely or not."
},
{
"code": null,
"e": 36188,
"s": 36130,
"text": "treeData: It is used to denote the data of the treeNodes."
},
{
"code": null,
"e": 36258,
"s": 36188,
"text": "treeDataSimpleMode: It is used to enable the simple mode of treeData."
},
{
"code": null,
"e": 36354,
"s": 36258,
"text": "treeDefaultExpandAll: It is used to indicate whether to expand all treeNodes by default or not."
},
{
"code": null,
"e": 36431,
"s": 36354,
"text": "treeDefaultExpandedKeys: It is used to denote the default expanded treeNode."
},
{
"code": null,
"e": 36482,
"s": 36431,
"text": "treeExpandedKeys: It is used to set expanded keys."
},
{
"code": null,
"e": 36547,
"s": 36482,
"text": "treeIcon: It is used to show the icon before a TreeNode’s title."
},
{
"code": null,
"e": 36664,
"s": 36547,
"text": "treeNodeFilterProp: It is used to define the filter which will be used for filtering if filterTreeNode returns true."
},
{
"code": null,
"e": 36753,
"s": 36664,
"text": "treeNodeLabelProp: It is used to define props that will render as the content of select."
},
{
"code": null,
"e": 36812,
"s": 36753,
"text": "value: It is used to set the currently selected treeNodes."
},
{
"code": null,
"e": 36887,
"s": 36812,
"text": "virtual: It is used to disable virtual scroll when set it is set to false."
},
{
"code": null,
"e": 36988,
"s": 36887,
"text": "onChange: It is a callback function that is triggered when selected treeNodes or input value change."
},
{
"code": null,
"e": 37082,
"s": 36988,
"text": "onDropdownVisibleChange: It is a callback function that is triggered when the dropdown opens."
},
{
"code": null,
"e": 37167,
"s": 37082,
"text": "onSearch: It is a callback function that is triggered when the search input changes."
},
{
"code": null,
"e": 37249,
"s": 37167,
"text": "onSelect: It is a callback function that is triggered when you select a treeNode."
},
{
"code": null,
"e": 37331,
"s": 37249,
"text": "onTreeExpand: It is a callback function that is triggered when treeNode expanded."
},
{
"code": null,
"e": 37345,
"s": 37331,
"text": "Tree Methods:"
},
{
"code": null,
"e": 37394,
"s": 37345,
"text": "blur(): This method is used to remove the focus."
},
{
"code": null,
"e": 37441,
"s": 37394,
"text": "focus(): This method is used to get the focus."
},
{
"code": null,
"e": 37457,
"s": 37441,
"text": "TreeNode Props:"
},
{
"code": null,
"e": 37538,
"s": 37457,
"text": "checkable: It is used to display the Checkbox for TreeNode if Tree is checkable."
},
{
"code": null,
"e": 37607,
"s": 37538,
"text": "disableCheckbox: It is used to disable the checkbox of the treeNode."
},
{
"code": null,
"e": 37671,
"s": 37607,
"text": "disabled: It is used to indicate whether it is disabled or not."
},
{
"code": null,
"e": 37736,
"s": 37671,
"text": "isLeaf: It is used to indicate whether it is a leaf node or not."
},
{
"code": null,
"e": 37795,
"s": 37736,
"text": "key: It is used for the unique identification of elements."
},
{
"code": null,
"e": 37865,
"s": 37795,
"text": "selectable: It is used to indicate whether it can be selected or not."
},
{
"code": null,
"e": 37930,
"s": 37865,
"text": "title: It is used to denote the content showed on the treeNodes."
},
{
"code": null,
"e": 38024,
"s": 37930,
"text": "value: It is used to define the value which will be treated as treeNodeFilterProp by default."
},
{
"code": null,
"e": 38076,
"s": 38026,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 38171,
"s": 38076,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 38235,
"s": 38171,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 38267,
"s": 38235,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 38380,
"s": 38267,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 38480,
"s": 38380,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 38494,
"s": 38480,
"text": "cd foldername"
},
{
"code": null,
"e": 38615,
"s": 38494,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd"
},
{
"code": null,
"e": 38720,
"s": 38615,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 38737,
"s": 38720,
"text": "npm install antd"
},
{
"code": null,
"e": 38789,
"s": 38737,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 38807,
"s": 38789,
"text": "Project Structure"
},
{
"code": null,
"e": 38937,
"s": 38807,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 38944,
"s": 38937,
"text": "App.js"
},
{
"code": "import React, { useState } from 'react';import { TreeSelect } from 'antd';import \"antd/dist/antd.css\"; const { TreeNode } = TreeSelect; export default function App() { // States to manage current value const [value, setValue] = useState(undefined); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design TreeSelect Component</h4> <> <TreeSelect placeholder=\"Select from the Tree\" allowClear showSearch value={value} onChange={() => { setValue(value); }} > <TreeNode value=\"Parent\" title=\"Parent\"> <TreeNode value=\"ChildLeaf1\" title=\"ChildLeaf1\" /> <TreeNode value=\"ChildLeaf2\" title=\"ChildLeaf2\" /> <TreeNode value=\"ChildLeaf3\" title=\"ChildLeaf3\" /> <TreeNode value=\"ChildLeaf4\" title=\"ChildLeaf4\" /> <TreeNode value=\"ChildLeaf5\" title=\"ChildLeaf5\" /> </TreeNode> </TreeSelect> </> </div> );}",
"e": 39972,
"s": 38944,
"text": null
},
{
"code": null,
"e": 40085,
"s": 39972,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 40095,
"s": 40085,
"text": "npm start"
},
{
"code": null,
"e": 40194,
"s": 40095,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 40248,
"s": 40194,
"text": "Reference: https://ant.design/components/tree-select/"
},
{
"code": null,
"e": 40267,
"s": 40248,
"text": "ReactJS-Ant Design"
},
{
"code": null,
"e": 40275,
"s": 40267,
"text": "ReactJS"
},
{
"code": null,
"e": 40292,
"s": 40275,
"text": "Web Technologies"
},
{
"code": null,
"e": 40390,
"s": 40292,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40399,
"s": 40390,
"text": "Comments"
},
{
"code": null,
"e": 40412,
"s": 40399,
"text": "Old Comments"
},
{
"code": null,
"e": 40457,
"s": 40412,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 40500,
"s": 40457,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 40565,
"s": 40500,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 40623,
"s": 40565,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 40665,
"s": 40623,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 40702,
"s": 40665,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 40735,
"s": 40702,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 40793,
"s": 40735,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 40838,
"s": 40793,
"text": "Convert a string to an integer in JavaScript"
}
]
|
Concordion - Quick Guide | Concordion is a powerful tool to write and manage automated acceptance tests in Java based projects. It directly integrates with JUnit framework, making it ready to be used with all popular JAVA based IDEs like Netbeans, Eclipse, IntelliJ IDEA.
Active software specification is a way to specify the behaviour of a feature. It also provides a way to implement and verify the software specification by having a connection with the system under development.
An active specification in Concordion is of two parts:
A cleanly written requirement document which describes the desired functionality written using XHTML. The XHTML based specifications contain descriptions of the functionality provided with acceptance test examples. Example's data is marked using simple HTML tags.
Acceptance tests are written in Java language called fixture code. Using a Concordion extension of a standard JUnit test case, test are implemented. It is the responsiblity of Fixture Code to find the example's data marked by tag and use them to verify the software under development.
A cleanly written requirement document which describes the desired functionality written using XHTML. The XHTML based specifications contain descriptions of the functionality provided with acceptance test examples. Example's data is marked using simple HTML tags.
A cleanly written requirement document which describes the desired functionality written using XHTML. The XHTML based specifications contain descriptions of the functionality provided with acceptance test examples. Example's data is marked using simple HTML tags.
Acceptance tests are written in Java language called fixture code. Using a Concordion extension of a standard JUnit test case, test are implemented. It is the responsiblity of Fixture Code to find the example's data marked by tag and use them to verify the software under development.
Acceptance tests are written in Java language called fixture code. Using a Concordion extension of a standard JUnit test case, test are implemented. It is the responsiblity of Fixture Code to find the example's data marked by tag and use them to verify the software under development.
When Concordion active specification tests are run, outpu XHTML files shows the original specification and test results. Successful test are highlighted using "green" color and failed test are highlighted using "red". As any change in system will result in failing the test, which helps to identify that specifiction are to be updated, Concordion terms these specifications as active specifications. Therefore specifications are always up-to-date.
Following are the key features of Concordion:
Specifications as documentation - Concordion specification being highly readable can be used as active system documentation. As Concordion based specifications are written in HTML, these documents can be hyperlinked.
Specifications as documentation - Concordion specification being highly readable can be used as active system documentation. As Concordion based specifications are written in HTML, these documents can be hyperlinked.
Specifications are live - Concordion specification contains working examples of behavior which are executed against the system. Specifications are color coded so that any one can see whether examples are working or not. Executing Concordion specifications regularly makes documentation up-to-date.
Specifications are live - Concordion specification contains working examples of behavior which are executed against the system. Specifications are color coded so that any one can see whether examples are working or not. Executing Concordion specifications regularly makes documentation up-to-date.
Separate "what?" from "how?" - Concordion specification helps in maintaining seperation between implementation and required behaviour of system. It provides flexibility that implementation can be changed later on.
Separate "what?" from "how?" - Concordion specification helps in maintaining seperation between implementation and required behaviour of system. It provides flexibility that implementation can be changed later on.
Simple to learn - Concordion library is designed keeping learning curve short and concise. It has very few commands to learn and examples are automated using JUnit tests so that tests can be run easily and can be integrated with existing projects easily.
Simple to learn - Concordion library is designed keeping learning curve short and concise. It has very few commands to learn and examples are automated using JUnit tests so that tests can be run easily and can be integrated with existing projects easily.
Powerful Customization - Concordion provides extensions API which allows to add functionality. For example, Excel spreadsheets can be used as specifications, screenshots can be added to the output, logging information can be displayed, and much more.
Powerful Customization - Concordion provides extensions API which allows to add functionality. For example, Excel spreadsheets can be used as specifications, screenshots can be added to the output, logging information can be displayed, and much more.
This tutorial will guide you on how to prepare a development environment to start your work with Spring Framework. This tutorial will also teach you how to setup JDK, Tomcat and Eclipse on your machine before you setup Spring Framework:
You can download the latest version of SDK from Oracle's Java site: Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and installed the JDK in C:\jdk1.7.0_75, you would have to put the following line in your C:\autoexec.bat file.
set PATH=C:\jdk1.7.0_75\bin;%PATH%
set JAVA_HOME=C:\jdk1.7.0_75
Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.7.0_75 and you use the C shell, you would put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.7.0_75/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.7.0_75
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given document of the IDE.
All the examples in this tutorial have been written using Eclipse IDE. So I would suggest you should have latest version of Eclipse installed on your machine.
To install Eclipse IDE, download the latest Eclipse binaries from http://www.eclipse.org/downloads/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately.
Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe
%C:\eclipse\eclipse.exe
Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:
$/usr/local/eclipse/eclipse
After a successful startup, if everything is fine then it should display following result:
Download latest version of JUnit jar file from http://www.junit.org. At the time of writing this tutorial, I downloaded Junit-4.10.jar and copied it into C:\>JUnit folder.
Set the JUNIT_HOME environment variable to point to the base directory location where JUNIT jar is stored on your machine. Assuming, we've stored junit4.10.jar in JUNIT folder on various Operating Systems as follows.
Set the CLASSPATH environment variable to point to the JUNIT jar location. Assuming, we've stored junit4.10.jar in JUNIT folder on various Operating Systems as follows.
Now if everything is fine, then you can proceed to setup your Concordion libraries. Following are the simple steps to download and install the framework on your machine.
Download the latest version of Concordion framework binaries from http://dl.bintray.com/concordion/downloads/concordion-1.5.1.zip.
At the time of writing this tutorial, I downloaded concordion-1.5.1 on my Windows machine and when you unzip the downloaded file it will give you following directory structure inside E:\concordion-1.5.1 as follows.
lib - Library folder
hamcrest-core-1.3.jar
junit-4.12.jar
ognl-2.6.9.jar
xom-1.2.5.jar
lib - Library folder
hamcrest-core-1.3.jar
hamcrest-core-1.3.jar
junit-4.12.jar
junit-4.12.jar
ognl-2.6.9.jar
ognl-2.6.9.jar
xom-1.2.5.jar
xom-1.2.5.jar
src - Source code folder
main
test
test-dummies
src - Source code folder
main
main
test
test
test-dummies
test-dummies
concordion-1.5.1.jar
concordion-1.5.1.jar
You will find all the Concordion dependency libraries in the directory E:\concordion\lib. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face problem while running your application. If you are using Eclipse then it is not required to set CLASSPATH because all the setting will be done through Eclipse.
Once you are done with this last step, you are ready to proceed for your first Concordion Example which you will see in the next chapter.
Let us start programming with Concordion. Before you start writing your first example using Concordion, you have to make sure that you have set up your Concordion environment properly as explained in Concordion - Environment Setup tutorial. We also assume that you have a little bit working knowledge of Eclipse IDE.
So let us proceed to write a simple Concordion application which will print the following acceptance test −
Example
When Robert logs in the system, a greeting "Hello Robert!" is displayed.
The first step is to create a simple Java project using Eclipse IDE. Follow the option File → New → Project and finally select Java Project wizard from the wizard list. Now name your project as Concordion using the wizard window as follows −
Once your project is created successfully, you will have the following content in your Project Explorer −
Let us add concordion and its dependencies in our project. To do this, right-click on your project name concordion and then follow the options available in the context menu: Build Path → Configure Build Path to display the Java Build Path window as follows −
Now use Add External JARs button available under Libraries tab to add the following core JAR from the Concordion folder.
concordion-1.5.1
hamcrest-core-1.3
junit-4.12
ognl-2.6.9
xom-1.2.5
Now let us create actual source files under the concordion project. First, we need to create a package called com.tutorialspoint. To do this, right-click on src in the package explorer section and follow the option : New → Package.
Next, we will create System .java file under the com.tutorialspoint package.
Here is the content of System.java file −
package com.tutorialspoint;
public class System {
public String getGreeting(String userName){
return "Hello " + userName + "!";
}
}
Now let us create actual specification files under the concordion project. First, we need to create a new source folder named specs. This folder will contain specification files like JUnitFixture or test runner and html files which are specifications. Now we need to create a package called specs.tutorialspoint. To do this, right-click on spec in the package explorer section and follow the option : New → Package.
Next, we will create System.html and SystemFixture.java files under the specs.tutorialspoint package. Thereafter, we will add concordion.css under specs source folder.
Here is the content of the System.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type="text/css" />
</head>
<body>
<h1>System Specifications</h1>
<p>We are building specifications for our online order tracking application.</p>
<p>Following is the requirement to show greeting to logged in user:</p>
<div class = "example">
<h3>Example</h3>
<p>When <span concordion:set = "#userName">Robert</span>
logs in the system, a greeting "<span concordion:assertEquals = "getGreeting(#userName)">
Hello Robert!</span>" is displayed.</p>
</div>
</body>
</html>
Here is the content of the SystemFixture.java file −
package specs.tutorialspoint;
import com.tutorialspoint.System;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
@RunWith(ConcordionRunner.class)
public class SystemFixture {
System system = new System();
public String getGreeting(String userName){
return system.getGreeting(userName);
}
}
Here is the content of the concordion.css file −
* {
font-family: Arial;
}
body {
padding: 32px;
}
pre {
padding: 6px 28px 6px 28px;
background-color: #E8EEF7;
}
pre, pre *, code, code *, kbd {
font-family: Courier New, Courier;
font-size: 10pt;
}
h1, h1 * {
font-size: 24pt;
}
p, td, th, li, .breadcrumbs {
font-size: 10pt;
}
p, li {
line-height: 140%;
}
table {
border-collapse: collapse;
empty-cells: show;
margin: 8px 0px 8px 0px;
}
th, td {
border: 1px solid black;
padding: 3px;
}
td {
background-color: white;
vertical-align: top;
}
th {
background-color: #C3D9FF;
}
li {
margin-top: 6px;
margin-bottom: 6px;
}
.example {
padding: 6px 16px 6px 16px;
border: 1px solid #D7D7D7;
margin: 6px 0px 28px 0px;
background-color: #F7F7F7;
}
.example h3 {
margin-top: 8px;
margin-bottom: 8px;
font-size: 12pt;
}
.special {
font-style: italic;
}
.idea {
font-size: 9pt;
color: #888;
font-style: italic;
}
.tight li {
margin-top: 1px;
margin-bottom: 1px;
}
.commentary {
float: right;
width: 200px;
background-color: #ffffd0;
padding:8px;
border: 3px solid #eeeeb0;
margin: 10px 0px 10px 10px;
}
.commentary, .commentary * {
font-size: 8pt;
}
There are two important points to note about the specification html file and the Test Fixture −
System.html is the specification html file that uses the concordion namespace.
System.html is the specification html file that uses the concordion namespace.
<html xmlns:concordion="http://www.concordion.org/2007/concordion">
System.html uses concordion:set command to set a value of temporary variables userName to be Robert. Here, userName is the parameter to be passed to the getGreeting method of System fixture.
System.html uses concordion:set command to set a value of temporary variables userName to be Robert. Here, userName is the parameter to be passed to the getGreeting method of System fixture.
When <span concordion:set="#userName">Robert</span> logs in the system
System.html uses concordion:assertEquals command to check the output of getGreeting(userName) function to be Hello Robert!.
System.html uses concordion:assertEquals command to check the output of getGreeting(userName) function to be Hello Robert!.
a greeting "<span concordion:assertEquals="getGreeting(#userName)">
Hello Robert!</span>" is displayed.
SystemFixture is a JUnit test fixture annotated with ConcordionRunner.class.
SystemFixture is a JUnit test fixture annotated with ConcordionRunner.class.
@RunWith(ConcordionRunner.class)
public class SystemFixture {
SystemFixture has a getGreeting method that returns greetings to the user.
SystemFixture has a getGreeting method that returns greetings to the user.
public String getGreeting(String userName){
return system.getGreeting(userName);
}
Right-click on the content area of SystemFixture and select Run as > JUnit Test Case. You will see the following output with junit success.
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 1, Failures: 0
System.html is the output of Concordion test run.
Congratulations, you have created your first Concordion Acceptance test successfully. Further, let us start doing something more interesting in the next few chapters.
Concordion set command is used to store temporary variables that can be used in other Concordion commands.
Consider the following requirement −
The Sum of two numbers 2 and 3 will be 5.
If we want the numbers 2 and 3 to be as parameters and pass them to the sum function as parameter so that they can be verified against the result returned by the system, then we can use concordion:set command within span tags around the numbers.
<p>The Sum of two numbers <span concordion:set = "#firstNumber">2</span>
and <span concordion:set = "#secondNumber">3</span> will be
<span concordion:assertEquals = "sum(#firstNumber, #secondNumber)">5
</span>.</p>
When Concordion parses the document, it will set a temporary variable #firstNumber to be the value "2" and #secondNumber to be the value "3" and then call the sum() method with parameters as #firstNumber and #secondNumber and check that the result is equal to "5".
Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −
Here is the content of System.java file −
package com.tutorialspoint;
public class System {
public int sum(int firstNumber, int secondNumber) {
return firstNumber + secondNumber;
}
}
Following is the content of SystemFixture.java file −
package specs.tutorialspoint;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
import com.tutorialspoint.System;
@RunWith(ConcordionRunner.class)
public class SystemFixture {
System system = new System();
public int sum(int firstNumber, int secondNumber) {
return system.sum(firstNumber, secondNumber);
}
}
Following is the content of System.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type = "text/css" />
</head>
<body>
<h1>Calculator Specifications</h1>
<p>We are building online calculator support in our website.</p>
<p>Following is the requirement to add two numbers:</p>
<div class = "example">
<h3>Example</h3>
<p>The Sum of two numbers <span concordion:set = "#firstNumber">2</span>
and <span concordion:set = "#secondNumber">3</span> will be
<span concordion:execute = "#result = sum(#firstNumber, #secondNumber)"></span>
<span concordion:assertEquals = "#result">5</span>.</p>
</div>
</body>
</html>
Once you are done with creating source and specification files, let us run the application as JUnit test. If everything is fine with your application, it will produce the following result −
C:\DOCUME>1\ADMINI>1\LOCALS>1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 1, Failures: 0
System.html is the output of concordion test run.
Concordion assertEquals command is used to check Java bean property or method result against a specified value.
Consider the following requirement −
The sum of two numbers 2 and 3 will be 5.
If we want the numbers 2 and 3 to be as parameters and pass them to sum function as parameter so that it can be verified against the result as 5 returned by the system then we can use concordion:assertEquals command within span tag around the sum function.
<p>The Sum of two numbers <span concordion:set="#firstNumber">2</span>
and <span concordion:set="#secondNumber">3</span> will be
<span concordion:assertEquals="sum(#firstNumber, #secondNumber)">5</span>.</p>
When Concordion parses the document, it will set a temporary variable #firstNumber to be the value "2" and #secondNumber to be the value "3" using set command and then call the sum() method with parameters as #firstNumber and #secondNumber and check that the result is equal to "5" using the assertEquals command.
Let us have working Eclipse IDE in place and follow the following steps to create a Concordion application −
Here is the content of the System.java file −
package com.tutorialspoint;
public class System {
public int sum(int firstNumber, int secondNumber) {
return firstNumber + secondNumber;
}
}
Following is the content of the SystemFixture.java file −
package specs.tutorialspoint;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
import com.tutorialspoint.System;
@RunWith(ConcordionRunner.class)
public class SystemFixture {
System system = new System();
public int sum(int firstNumber, int secondNumber) {
return system.sum(firstNumber, secondNumber);
}
}
Following is the content of the System.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type = "text/css" />
</head>
<body>
<h1>Calculator Specifications</h1>
<p>We are building online calculator support in our website.</p>
<p>Following is the requirement to add two numbers:</p>
<div class = "example">
<h3>Example</h3>
<p>The Sum of two numbers <span concordion:set = "#firstNumber">2</span>
and <span concordion:set = "#secondNumber">3</span> will be
<span concordion:assertEquals = "sum(#firstNumber, #secondNumber)">5</span>.</p>
</div>
</body>
</html>
Once you are done with creating source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will show the following result −
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 1, Failures: 0
System.html is the output of Concordion test run.
Successes: 1, Failures: 0
Concordion assertTrue command is used when the fixture needs to know the expected result in order to perform a test.
Consider the following requirement −
User Name : Robert De
The User name starts with R.
The User name starts with S == false.
If we want a test to be executed on the User Name and check whether the user name starts with R or not.
<p>User Name :<span concordion:set = "#userName">Robert De</span></p>
<p>The User name <span concordion:assertTrue = "#userName.startsWith(#letter)">starts
with <b concordion:set = "#letter">R</b></span>.</p>
<p>The User name <span concordion:assertTrue = "#userName.startsWith(#letter)">starts
with <b concordion:set = "#letter">S</b></span>.</p>
When Concordion parses the document, it will set a temporary variable #userName to be the value "Robert De". Then it will check if the userName starts with the letter specified by #letter variable set in next command.
Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −
Here is the content of the System.java file −
package com.tutorialspoint;
public class System {
}
Following is the content of the SystemFixture.java file −
package specs.tutorialspoint;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
@RunWith(ConcordionRunner.class)
public class SystemFixture {
}
Following is the content of the System.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type = "text/css" />
</head>
<body>
<h1>System Specifications</h1>
<p>We are building specifications for our online order tracking application.</p>
<p>Following is the requirement to split full name of a logged in user to
its constituents by splitting name by whitespace:</p>
<div class = "example">
<h3>Example</h3>
<p>User Name :<span concordion:set = "#userName">Robert De</span></p>
<p>The User name <span concordion:assertTrue = "#userName.startsWith(#letter)">starts
with <b concordion:set = "#letter">R</b></span>.</p>
<p>The User name <span concordion:assertTrue = "#userName.startsWith(#letter)">starts
with <b concordion:set = "#letter">S</b></span>.</p>
</div>
</body>
</html>
Once you are done with creating source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 1, Failures: 1
System.html is the output of Concordion test run.
Concordion assertFalse command is used when the fixture needs to know the expected result in order to perform a test.
Consider the following requirement −
User Name : Robert De
The User name does not start with S.
If we want a test to be executed on the User Name and check that the user name does not start with S.
<p>User Name :<span concordion:set = "#userName">Robert De</span></p>
<p>The User name <span concordion:assertFalse = "#userName.startsWith(#letter)">does not start
with <b concordion:set = "#letter">S</b></span>.</p>
When Concordion parses the document, it will set a temporary variable #userName to be the value "Robert De". Then, it will check if the userName starts with the letter specified by #letter variable set in next command.
Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −
Here is the content of the System.java file −
package com.tutorialspoint;
public class System {
}
Following is the content of the SystemFixture.java file −
package specs.tutorialspoint;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
@RunWith(ConcordionRunner.class)
public class SystemFixture {
}
Following is the content of the System.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type = "text/css" />
</head>
<body>
<h1>System Specifications</h1>
<p>We are building specifications for our online order tracking application.</p>
<p>Following is the requirement to split full name of a logged in user to its
constituents by splitting name by whitespace:</p>
<div class = "example">
<h3>Example</h3>
<p>User Name :<span concordion:set = "#userName">Robert De</span></p>
<p>The User name <span concordion:assertFalse = "#userName.startsWith(#letter)">
does not start with <b concordion:set = "#letter">
S</b></span>.</p>
</div>
</body>
</html>
Once you are done with creating source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 1, Failures: 0
System.html is the output of Concordion test run.
Concordion execute command is used run the operation of concordion fixture. Consider the following requirement −
The sum of two numbers 2 and 3 will be 5.
If we want to write a specification for a sum function which will accept two numbers and output their sum, then the specification will be as follows −
<p>The Sum of two numbers <span concordion:set = "#firstNumber">2</span> and
<span concordion:set = "#secondNumber">3</span> will be
<span concordion:execute = "#result = sum(#firstNumber, #secondNumber)">
</span><span concordion:assertEquals = "#result">5</span>.</p>
When Concordion parses the document, it will set a temporary variable #firstNumber to be the value "2" and #secondNumber to be the value "3" and then execute the sum() method with parameters as #firstNumber and #secondNumber using the execute command and set the result into #result variable and check that the #result variable is equal to "5".
Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −
Here is the content of the System.java file −
package com.tutorialspoint;
public class System {
public int sum(int firstNumber, int secondNumber) {
return firstNumber + secondNumber;
}
}
Following is the content of the SystemFixture.java file −
package specs.tutorialspoint;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
import com.tutorialspoint.System;
@RunWith(ConcordionRunner.class)
public class SystemFixture {
System system = new System();
public int sum(int firstNumber, int secondNumber) {
return system.sum(firstNumber, secondNumber);
}
}
Following is the content of the System.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type = "text/css" />
</head>
<body>
<h1>Calculator Specifications</h1>
<p>We are building online calculator support in our website.</p>
<p>Following is the requirement to add two numbers:</p>
<div class = "example">
<h3>Example</h3>
<p>The Sum of two numbers <span concordion:set = "#firstNumber">2</span>
and <span concordion:set = "#secondNumber">3</span> will be
<span concordion:execute = "#result = sum(#firstNumber, #secondNumber)">
</span><span concordion:assertEquals = "#result">5</span>.</p>
</div>
</body>
</html>
Once you are done with creating source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 1, Failures: 0
System.html is the output of Concordion test run.
Concordion execute command can be used to get the result of a behavior in the form of object using which we can get multiple outputs of a behavior. For example, consider the following requirement −
The full name Robert De is to be broken into first name Robert and last name De.
Here we need to have a split function which accepts a user name and returns a result object having the first name and the last name as its properties so that we can use them.
If we want to write a specification for such a split function which will expect a user name and output a result object, then the following will be the specification −
<p>The full name <span concordion:execute = "#result = split(#TEXT)">Robert
De</span> is to be broken into first name
<span concordion:assertEquals = "#result.firstName">Robert</span> and last name
<span concordion:assertEquals = "#result.lastName">De</span>.</p>
When Concordion parses the document, it will set the value of the special variable #TEXT as the value of the current element as "Robert De" and pass it to the split function. Then it will execute the split() method with parameters as #TEXT using the execute command and set the result into the #result variable and using the result object, print the firstName and the lastName properties as the output.
Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −
Here is the content of Result.java file −
package com.tutorialspoint;
public class Result {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Here is the content of System.java file −
package com.tutorialspoint;
public class System {
public Result split(String userName){
Result result = new Result();
String[] words = userName.split(" ");
result.setFirstName(words[0]);
result.setLastName(words[1]);
return result;
}
}
Following is the content of SystemFixture.java file−
package specs.tutorialspoint;
import com.tutorialspoint.Result;
import com.tutorialspoint.System;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
@RunWith(ConcordionRunner.class)
public class SystemFixture {
System system = new System();
public Result split(String userName){
return system.split(userName);
}
}
Following is the content of System.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type = "text/css" />
</head>
<body>
<h1>System Specifications</h1>
<p>We are building specifications for our online order tracking application.</p>
<p>Following is the requirement to split full name of a logged in user to its
constituents by splitting name by whitespace:</p>
<div class = "example">
<h3>Example</h3>
<p>The full name <span concordion:execute = "#result = split(#TEXT)">Robert
De</span> is to be broken into first name <span
concordion:assertEquals = "#result.firstName">Robert</span> and last name <span
concordion:assertEquals = "#result.lastName">De</span>.</p>
</div>
</body>
</html>
Once you are done with creating the source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 1, Failures: 0
System.html is the output of Concordion test run.
Concordion execute command can be used to get the result of a behavior in the form of a Map using which we can get multiple outputs of a behavior. For example, consider the following requirement −
The full name Robert De is to be broken into its first name Robert and last name De.
Here we need to have a spilt function which accepts a user name and returns a Map object having the firstName and the lastName as its keys having corresponding values so that we can use them.
If we want to write a specification for such a split function which will accept a user name and output a result object, then the following will be the specification −
<p>The full name <span concordion:execute = "#result = split(#TEXT)">Robert
De</span> is to be broken into first name <span
concordion:assertEquals = "#result.firstName">Robert</span> and last name <span
concordion:assertEquals = "#result.lastName">De</span>.</p>
When Concordion parses the document, it will set the value of the special variable #TEXT to be the value of the current element as "Robert De" and pass it to the split function. Then it will execute the split() method with parameters as #TEXT using the execute command and set the result into the #result variable and using result map, print the firstName and lastName values as output.
Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −
Here is the content of System.java file −
package com.tutorialspoint;
import java.util.HashMap;
import java.util.Map;
public class System {
public Map split(String userName){
Map<String, String> result = new HashMap<String, String>();
String[] words = userName.split(" ");
result.put("firstName", words[0]);
result.put("lastName", words[1]);
return result;
}
}
Following is the content of SystemFixture.java file −
package specs.tutorialspoint;
import java.util.Map;
import com.tutorialspoint.Result;
import com.tutorialspoint.System;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
@RunWith(ConcordionRunner.class)
public class SystemFixture {
System system = new System();
public Map<String, String> split(String userName){
return system.split(userName);
}
}
Following is the content of System.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type = "text/css" />
</head>
<body>
<h1>System Specifications</h1>
<p>We are building specifications for our online order tracking application.</p>
<p>Following is the requirement to split full name of a logged in user to its
constituents by splitting name by whitespace:</p>
<div class = "example">
<h3>Example</h3>
<p>The full name <span concordion:execute = "#result = split(#TEXT)">Robert
De</span> is to be broken into first name <span
concordion:assertEquals = "#result.firstName">Robert</span> and last name
<span concordion:assertEquals = "#result.lastName">De</span>.</p>
</div>
</body>
</html>
Once you are done with creating the source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 1, Failures: 0
System.html is the output of Concordion test run.
Concordion execute command can be used to get the result of a behavior in the form of a Map using which we can get multiple outputs of a behavior. For example, consider the following requirement −
The full name Robert De is to be broken into its first name Robert and last name De.
Here we need to have a split function which accepts a user name and returns a Map object having firstName and lastName as its keys with their corresponding values so that we can use them.
If we want write a specification for such a split function which will accept a user name and output a result object, then the specification would be as follows −
<p>The full name <span concordion:execute = "#result = split(#TEXT)">Robert
De</span> is to be broken into first name
<span concordion:assertEquals = "#result.firstName">Robert</span> and last name
<span concordion:assertEquals = "#result.lastName">De</span>.</p>
When Concordion parses the document, it will set the value of the special variable #TEXT to be the value of current element as "Robert De" and pass it to the split function. Then it will execute the split() method with parameters as #TEXT using execute command and set the result into the #result variable and using result map, print the firstName and lastName values as the output.
Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −
Here is the content of System.java file −
package com.tutorialspoint;
import org.concordion.api.MultiValueResult;
public class System {
public MultiValueResult split(String userName){
MultiValueResult result = new MultiValueResult();
String[] words = userName.split(" ");
result.with("firstName", words[0]).with("lastName", words[1]);
return result;
}
}
Following is the content of SystemFixture.java file −
package specs.tutorialspoint;
import org.concordion.api.MultiValueResult;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
import com.tutorialspoint.System;
@RunWith(ConcordionRunner.class)
public class SystemFixture {
System system = new System();
public MultiValueResult split(String userName){
return system.split(userName);
}
}
Following is the content of System.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type = "text/css" />
</head>
<body>
<h1>System Specifications</h1>
<p>We are building specifications for our online order tracking application.</p>
<p>Following is the requirement to split full name of a logged in
user to its constituents by splitting name by whitespace:</p>
<div class = "example">
<h3>Example</h3>
<p>The full name <span concordion:execute = "#result = split(#TEXT)">Robert De</span>
is to be broken into first name <span
concordion:assertEquals = "#result.firstName">Robert</span> and last name <span
concordion:assertEquals = "#result.lastName">De</span>.</p>
</div>
</body>
</html>
Once you are done with creating the source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 2, Failures: 0
System.html is the output of Concordion test run.
Concordion execute command can be used to run the operation of concordion fixture in a repeating manner. For example, it will be useful if we want to illustrate a requirement with multiple examples in the form of a table.
Consider the following requirement −
<table>
<tr><th>First Number</th><th>Second Number</th><th>Sum</th></tr>
<tr><td>2</td><td>3</td><td>5</td></tr>
<tr><td>4</td><td>5</td><td>9</td></tr>
</table>
If we want to write a specification for a sum function which will accept two numbers and output their sum, then the specification would be as follows −
<table>
<tr><th>First Number</th><th>Second Number</th><th>Sum</th></tr>
<tr concordion:execute = "#result = sum(#fullName)">
<td concordion:set = "#firstNumber">2</td>
<td concordion:set = "#secondNumber">3</td>
<td concordion:assertEquals = "#result">5</td>
</tr>
<tr concordion:execute = "#result = sum(#fullName)">
<td concordion:set = "#firstNumber">4</td>
<td concordion:set = "#secondNumber">5</td>
<td concordion:assertEquals = "#result">9</td>
</tr>
</table>
When Concordion parses the document, it will set a temporary variable #firstNumber to be the value "2" and #secondNumber to be the value "3". Then it will execute the sum() method with parameters as #firstNumber and #secondNumber using execute command and set the result into the #result variable and check that the #result variable is equal to "5". This process is repeated for each table row element.
Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −
Here is the content of System.java file −
package com.tutorialspoint;
public class System {
public int sum(int firstNumber, int secondNumber) {
return firstNumber + secondNumber;
}
}
Following is the content of SystemFixture.java file −
package specs.tutorialspoint;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
import com.tutorialspoint.System;
@RunWith(ConcordionRunner.class)
public class SystemFixture {
System system = new System();
public int sum(int firstNumber, int secondNumber) {
return system.sum(firstNumber, secondNumber);
}
}
Following is the content of System.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type = "text/css" />
</head>
<body>
<h1>Calculator Specifications</h1>
<p>We are building online calculator support in our website.</p>
<p>Following is the requirement to add two numbers:</p>
<div class = "example">
<h3>Example</h3>
<table>
<tr>
<th>First Number</th>
<th>Second Number</th>
<th>Sum</th>
</tr>
<tr concordion:execute = "#result = sum(#firstNumber, #secondNumber)">
<td concordion:set = "#firstNumber">2</td>
<td concordion:set = "#secondNumber">3</td>
<td concordion:assertEquals = "#result">5</td>
</tr>
<tr concordion:execute = "#result = sum(#firstNumber, #secondNumber)">
<td concordion:set = "#firstNumber">4</td>
<td concordion:set = "#secondNumber">5</td>
<td concordion:assertEquals = "#result">9</td>
</tr>
</table>
</div>
</body>
</html>
Once you are done with creating the source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 2, Failures: 0
System.html is the output of Concordion test run.
Concordion execute command can be used to run the operation of concordion fixture in a repeating manner. For example, it will be useful if we want to illustrate a requirement with multiple examples in the form of a list.
Consider the following requirement −
<ul>
<li>The full name Robert De is to be split as
<ul>
<li>Robert</li>
<li>De</li>
</ul>
</li>
<li>The full name John Diere is to be split as
<ul>
<li>John</li>
<li>Diere</li>
</ul>
</li>
</ul>
If we want write a specification for a split function which will split a name into its first name and last name, then the specification would be as follows −
<ul>
<li>The full name <span concordion:execute = "#result = split(#TEXT)">
Robert De</span> is to be splited as
<ul>
<li><span concordion:assertEquals = "#result.firstName">Robert</span></li>
<li><span concordion:assertEquals = "#result.lastName">De</span></li>
</ul>
</li>
<li>The full name <span concordion:execute = "#result = split(#TEXT)">
John Diere</span> is to be splited as
<ul>
<li><span concordion:assertEquals = "#result.firstName">John</span></li>
<li><span concordion:assertEquals = "#result.lastName">Diere</span></li>
</ul>
</li>
</ul>
When Concordion parses the document, it will set the value of the special variable #TEXT to be the value of the current element as "Robert De" and pass it to the split function. Then it will execute the split() method with parameters as #TEXT using execute command and set the result into #result variable and using result, print the firstName and lastName values as the output.
Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −
Here is the content of System.java file −
package com.tutorialspoint;
import org.concordion.api.MultiValueResult;
public class System {
public MultiValueResult split(String userName){
MultiValueResult result = new MultiValueResult();
String[] words = userName.split(" ");
result.with("firstName", words[0]).with("lastName", words[1]);
return result;
}
}
Following is the content of SystemFixture.java file −
package specs.tutorialspoint;
import org.concordion.api.MultiValueResult;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
import com.tutorialspoint.System;
@RunWith(ConcordionRunner.class)
public class SystemFixture {
System system = new System();
public MultiValueResult split(String userName){
return system.split(userName);
}
}
Following is the content of System.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type = "text/css" />
</head>
<body>
<h1>System Specifications</h1>
<p>We are building specifications for our online order tracking application.</p>
<p>Following is the requirement to split full name of a logged
in user to its constituents by splitting name by whitespace:</p>
<div class = "example">
<h3>Example</h3>
<ul>
<li>The full name <span concordion:execute = "#result = split(#TEXT)">
Robert De</span> is to be splited as
<ul>
<li><span concordion:assertEquals = "#result.firstName">
Robert</span></li>
<li><span concordion:assertEquals = "#result.lastName">
De</span></li>
</ul>
</li>
<li>The full name <span concordion:execute ="#result = split(#TEXT)">
John Diere</span> is to be splited as
<ul>
<li><span concordion:assertEquals = "#result.firstName">
John</span></li>
<li><span concordion:assertEquals = "#result.lastName">
Diere</span></li>
</ul>
</li>
</ul>
</div>
</body>
</html>
Once you are done with creating source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 4, Failures: 0
System.html is the output of Concordion test run.
Concordion verifyRows command can be used to check the content of a collection returned as a result by the system. For example, if we set up a set of users in the system and do a partial search on them, then the system should return the matching elements, otherwise our acceptance tests should fail.
Consider the following requirement −
<table>
<tr><th>Users</th></tr>
<tr><td>Robert De</td></tr>
<tr><td>John Diere</td></tr>
<tr><td>Julie Re</td></tr>
</table>
<p>Search for J should return:</p>
<table>
<tr><th>Matching Users</th></tr>
<tr><td>John Diere</td></tr>
<tr><td>Julie Re</td></tr>
</table>
If we want write a specification for such a search function which will search and return a collection, then the specification will be as follows −
<table concordion:execute = "addUser(#username)">
<tr><th concordion:set = "#username">Username</th></tr>
<tr><td>Robert De</td></tr>
<tr><td>John Diere</td></tr>
<tr><td>Julie Re</td></tr>
</table>
<p>Search for "<b concordion:set = "#searchString">J</b>" should return:</p>
<table concordion:verifyRows = "#username : search(#searchString)">
<tr><th concordion:assertEquals = "#username">Matching Usernames</th></tr>
<tr><td>John Diere</td></tr>
<tr><td>Julie Re</td></tr>
</table>
When Concordion parses the document, it will execute addUser() on each row of the first table and then set the searchString to be J. Next, Concordion will execute the search function which should return a Iterable object with a predictable iteration order, (e.g. a List, LinkedHashSet or a TreeSet), verifyRows runs for each item of the collection and runs the assertEquals command.
Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −
Here is the content of System.java file −
package com.tutorialspoint;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
public class System {
private Set<String> users = new HashSet<String>();
public void addUser(String username) {
users.add(username);
}
public Iterable<String> search(String searchString) {
SortedSet<String> matches = new TreeSet<String>();
for (String username : users) {
if (username.contains(searchString)) {
matches.add(username);
}
}
return matches;
}
}
Following is the content of SystemFixture.java file −
package specs.tutorialspoint;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
import com.tutorialspoint.System;
@RunWith(ConcordionRunner.class)
public class SystemFixture {
System system = new System();
public void addUser(String username) {
system.addUser(username);
}
public Iterable<String> search(String searchString) {
return system.search(searchString);
}
}
Following is the content of System.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type = "text/css" />
</head>
<body>
<h1>System Specifications</h1>
<p>We are building specifications for our online order tracking application.</p>
<p>Following is the requirement to add a partial search capability on user names:</p>
<div class = "example">
<h3>Example</h3>
<table concordion:execute = "addUser(#username)">
<tr><th concordion:set = "#username">Username</th></tr>
<tr><td>Robert De</td></tr>
<tr><td>John Diere</td></tr>
<tr><td>Julie Re</td></tr>
</table>
<p>Search for "<b concordion:set = "#searchString">J</b>" should return:</p>
<table concordion:verifyRows = "#username : search(#searchString)">
<tr><th concordion:assertEquals = "#username">Matching Usernames</th></tr>
<tr><td>John Diere</td></tr>
<tr><td>Julie Re</td></tr>
</table>
</div>
</body>
</html>
Once you are done with creating the source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 2, Failures: 0
System.html is the output of Concordion test run.
Concordion run command can be used to link multiple specifications together and display them at one central page. This command can run all the specifications, while displaying the link's background in green / red / gray as appropriate.
Now we are going to create two specifications and link them together. We'll be reusing the specifications created in Concordion - Execute on List and Concordion - Execute on Table chapters as System Specifications and Calculator Specifications.
Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −
Here is the content of System.java file −
package com.tutorialspoint;
import org.concordion.api.MultiValueResult;
public class System {
public MultiValueResult split(String userName){
MultiValueResult result = new MultiValueResult();
String[] words = userName.split(" ");
result.with("firstName", words[0]).with("lastName", words[1]);
return result;
}
public int sum(int firstNumber, int secondNumber) {
return firstNumber + secondNumber;
}
}
Following is the content of SystemFixture.java file −
package specs.tutorialspoint;
import org.concordion.api.MultiValueResult;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
import com.tutorialspoint.System;
@RunWith(ConcordionRunner.class)
public class SystemFixture {
System system = new System();
public MultiValueResult split(String userName){
return system.split(userName);
}
}
Following is the content of CalculatorFixture.java file −
package specs.tutorialspoint;
import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
import com.tutorialspoint.System;
@RunWith(ConcordionRunner.class)
public class CalculatorFixture {
System system = new System();
public int sum(int firstNumber, int secondNumber) {
return system.sum(firstNumber, secondNumber);
}
}
Following is the content of System.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type = "text/css" />
</head>
<body>
<h1>System Specifications</h1>
<p>We are building specifications for our online
order tracking application.</p>
<p>Following is the requirement to split full name of a
logged in user to its constituents by splitting name by whitespace:</p>
<div class = "example">
<h3>Example</h3>
<ul>
<li>The full name <span concordion:execute = "#result = split(#TEXT)">
Robert De</span> is to be splited as
<ul>
<li><span concordion:assertEquals = "#result.firstName">
Robert</span></li>
<li><span concordion:assertEquals = "#result.lastName">
De</span></li>
</ul>
</li>
<li>The full name <span concordion:execute = "#result = split(#TEXT)">
John Diere</span> is to be splited as
<ul>
<li><span concordion:assertEquals = "#result.firstName">
John</span></li>
<li><span concordion:assertEquals = "#result.lastName">
Diere</span></li>
</ul>
</li>
</ul>
</div>
<a concordion:run = "concordion" href = "Calculator.html">
Calculator Service Specifications</a>
</body>
</html>
Following is the content of Calculator.html file −
<html xmlns:concordion = "http://www.concordion.org/2007/concordion">
<head>
<link href = "../concordion.css" rel = "stylesheet" type = "text/css" />
</head>
<body>
<h1>Calculator Specifications</h1>
<p>We are building online calculator support in our website.</p>
<p>Following is the requirement to add two numbers:</p>
<div class = "example">
<h3>Example</h3>
<table>
<tr>
<th>First Number</th>
<th>Second Number</th>
<th>Sum</th>
</tr>
<tr concordion:execute = "#result = sum(#firstNumber, #secondNumber)">
<td concordion:set = "#firstNumber">2</td>
<td concordion:set = "#secondNumber">3</td>
<td concordion:assertEquals = "#result">5</td>
</tr>
<tr concordion:execute = "#result = sum(#firstNumber, #secondNumber)">
<td concordion:set = "#firstNumber">4</td>
<td concordion:set = "#secondNumber">5</td>
<td concordion:assertEquals = "#result">9</td>
</tr>
</table>
</div>
</body>
</html>
Once you are done with creating source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 2, Failures: 0
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\concordion\specs\tutorialspoint\System.html
Successes: 6, Failures: 0
System.html is the output of Concordion test run.
Click on the link Calculator Service Specifications. You will see the following output −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2269,
"s": 2024,
"text": "Concordion is a powerful tool to write and manage automated acceptance tests in Java based projects. It directly integrates with JUnit framework, making it ready to be used with all popular JAVA based IDEs like Netbeans, Eclipse, IntelliJ IDEA."
},
{
"code": null,
"e": 2479,
"s": 2269,
"text": "Active software specification is a way to specify the behaviour of a feature. It also provides a way to implement and verify the software specification by having a connection with the system under development."
},
{
"code": null,
"e": 2534,
"s": 2479,
"text": "An active specification in Concordion is of two parts:"
},
{
"code": null,
"e": 3085,
"s": 2534,
"text": "\nA cleanly written requirement document which describes the desired functionality written using XHTML. The XHTML based specifications contain descriptions of the functionality provided with acceptance test examples. Example's data is marked using simple HTML tags.\nAcceptance tests are written in Java language called fixture code. Using a Concordion extension of a standard JUnit test case, test are implemented. It is the responsiblity of Fixture Code to find the example's data marked by tag and use them to verify the software under development.\n"
},
{
"code": null,
"e": 3349,
"s": 3085,
"text": "A cleanly written requirement document which describes the desired functionality written using XHTML. The XHTML based specifications contain descriptions of the functionality provided with acceptance test examples. Example's data is marked using simple HTML tags."
},
{
"code": null,
"e": 3613,
"s": 3349,
"text": "A cleanly written requirement document which describes the desired functionality written using XHTML. The XHTML based specifications contain descriptions of the functionality provided with acceptance test examples. Example's data is marked using simple HTML tags."
},
{
"code": null,
"e": 3898,
"s": 3613,
"text": "Acceptance tests are written in Java language called fixture code. Using a Concordion extension of a standard JUnit test case, test are implemented. It is the responsiblity of Fixture Code to find the example's data marked by tag and use them to verify the software under development."
},
{
"code": null,
"e": 4183,
"s": 3898,
"text": "Acceptance tests are written in Java language called fixture code. Using a Concordion extension of a standard JUnit test case, test are implemented. It is the responsiblity of Fixture Code to find the example's data marked by tag and use them to verify the software under development."
},
{
"code": null,
"e": 4632,
"s": 4183,
"text": "When Concordion active specification tests are run, outpu XHTML files shows the original specification and test results. Successful test are highlighted using \"green\" color and failed test are highlighted using \"red\". As any change in system will result in failing the test, which helps to identify that specifiction are to be updated, Concordion terms these specifications as active specifications. Therefore specifications are always up-to-date."
},
{
"code": null,
"e": 4678,
"s": 4632,
"text": "Following are the key features of Concordion:"
},
{
"code": null,
"e": 4895,
"s": 4678,
"text": "Specifications as documentation - Concordion specification being highly readable can be used as active system documentation. As Concordion based specifications are written in HTML, these documents can be hyperlinked."
},
{
"code": null,
"e": 5112,
"s": 4895,
"text": "Specifications as documentation - Concordion specification being highly readable can be used as active system documentation. As Concordion based specifications are written in HTML, these documents can be hyperlinked."
},
{
"code": null,
"e": 5410,
"s": 5112,
"text": "Specifications are live - Concordion specification contains working examples of behavior which are executed against the system. Specifications are color coded so that any one can see whether examples are working or not. Executing Concordion specifications regularly makes documentation up-to-date."
},
{
"code": null,
"e": 5708,
"s": 5410,
"text": "Specifications are live - Concordion specification contains working examples of behavior which are executed against the system. Specifications are color coded so that any one can see whether examples are working or not. Executing Concordion specifications regularly makes documentation up-to-date."
},
{
"code": null,
"e": 5922,
"s": 5708,
"text": "Separate \"what?\" from \"how?\" - Concordion specification helps in maintaining seperation between implementation and required behaviour of system. It provides flexibility that implementation can be changed later on."
},
{
"code": null,
"e": 6136,
"s": 5922,
"text": "Separate \"what?\" from \"how?\" - Concordion specification helps in maintaining seperation between implementation and required behaviour of system. It provides flexibility that implementation can be changed later on."
},
{
"code": null,
"e": 6392,
"s": 6136,
"text": "Simple to learn - Concordion library is designed keeping learning curve short and concise. It has very few commands to learn and examples are automated using JUnit tests so that tests can be run easily and can be integrated with existing projects easily."
},
{
"code": null,
"e": 6648,
"s": 6392,
"text": "Simple to learn - Concordion library is designed keeping learning curve short and concise. It has very few commands to learn and examples are automated using JUnit tests so that tests can be run easily and can be integrated with existing projects easily."
},
{
"code": null,
"e": 6899,
"s": 6648,
"text": "Powerful Customization - Concordion provides extensions API which allows to add functionality. For example, Excel spreadsheets can be used as specifications, screenshots can be added to the output, logging information can be displayed, and much more."
},
{
"code": null,
"e": 7150,
"s": 6899,
"text": "Powerful Customization - Concordion provides extensions API which allows to add functionality. For example, Excel spreadsheets can be used as specifications, screenshots can be added to the output, logging information can be displayed, and much more."
},
{
"code": null,
"e": 7387,
"s": 7150,
"text": "This tutorial will guide you on how to prepare a development environment to start your work with Spring Framework. This tutorial will also teach you how to setup JDK, Tomcat and Eclipse on your machine before you setup Spring Framework:"
},
{
"code": null,
"e": 7782,
"s": 7387,
"text": "You can download the latest version of SDK from Oracle's Java site: Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively."
},
{
"code": null,
"e": 7921,
"s": 7782,
"text": "If you are running Windows and installed the JDK in C:\\jdk1.7.0_75, you would have to put the following line in your C:\\autoexec.bat file."
},
{
"code": null,
"e": 7985,
"s": 7921,
"text": "set PATH=C:\\jdk1.7.0_75\\bin;%PATH%\nset JAVA_HOME=C:\\jdk1.7.0_75"
},
{
"code": null,
"e": 8191,
"s": 7985,
"text": "Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button."
},
{
"code": null,
"e": 8349,
"s": 8191,
"text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.7.0_75 and you use the C shell, you would put the following into your .cshrc file."
},
{
"code": null,
"e": 8434,
"s": 8349,
"text": "setenv PATH /usr/local/jdk1.7.0_75/bin:$PATH\nsetenv JAVA_HOME /usr/local/jdk1.7.0_75"
},
{
"code": null,
"e": 8715,
"s": 8434,
"text": "Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given document of the IDE."
},
{
"code": null,
"e": 8874,
"s": 8715,
"text": "All the examples in this tutorial have been written using Eclipse IDE. So I would suggest you should have latest version of Eclipse installed on your machine."
},
{
"code": null,
"e": 9191,
"s": 8874,
"text": "To install Eclipse IDE, download the latest Eclipse binaries from http://www.eclipse.org/downloads/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately."
},
{
"code": null,
"e": 9316,
"s": 9191,
"text": "Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe"
},
{
"code": null,
"e": 9341,
"s": 9316,
"text": " %C:\\eclipse\\eclipse.exe"
},
{
"code": null,
"e": 9440,
"s": 9341,
"text": "Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:"
},
{
"code": null,
"e": 9468,
"s": 9440,
"text": "$/usr/local/eclipse/eclipse"
},
{
"code": null,
"e": 9559,
"s": 9468,
"text": "After a successful startup, if everything is fine then it should display following result:"
},
{
"code": null,
"e": 9732,
"s": 9559,
"text": "Download latest version of JUnit jar file from http://www.junit.org. At the time of writing this tutorial, I downloaded Junit-4.10.jar and copied it into C:\\>JUnit folder."
},
{
"code": null,
"e": 9949,
"s": 9732,
"text": "Set the JUNIT_HOME environment variable to point to the base directory location where JUNIT jar is stored on your machine. Assuming, we've stored junit4.10.jar in JUNIT folder on various Operating Systems as follows."
},
{
"code": null,
"e": 10118,
"s": 9949,
"text": "Set the CLASSPATH environment variable to point to the JUNIT jar location. Assuming, we've stored junit4.10.jar in JUNIT folder on various Operating Systems as follows."
},
{
"code": null,
"e": 10288,
"s": 10118,
"text": "Now if everything is fine, then you can proceed to setup your Concordion libraries. Following are the simple steps to download and install the framework on your machine."
},
{
"code": null,
"e": 10419,
"s": 10288,
"text": "Download the latest version of Concordion framework binaries from http://dl.bintray.com/concordion/downloads/concordion-1.5.1.zip."
},
{
"code": null,
"e": 10634,
"s": 10419,
"text": "At the time of writing this tutorial, I downloaded concordion-1.5.1 on my Windows machine and when you unzip the downloaded file it will give you following directory structure inside E:\\concordion-1.5.1 as follows."
},
{
"code": null,
"e": 10724,
"s": 10634,
"text": "lib - Library folder\n\nhamcrest-core-1.3.jar\njunit-4.12.jar\nognl-2.6.9.jar\nxom-1.2.5.jar\n\n"
},
{
"code": null,
"e": 10745,
"s": 10724,
"text": "lib - Library folder"
},
{
"code": null,
"e": 10767,
"s": 10745,
"text": "hamcrest-core-1.3.jar"
},
{
"code": null,
"e": 10789,
"s": 10767,
"text": "hamcrest-core-1.3.jar"
},
{
"code": null,
"e": 10804,
"s": 10789,
"text": "junit-4.12.jar"
},
{
"code": null,
"e": 10819,
"s": 10804,
"text": "junit-4.12.jar"
},
{
"code": null,
"e": 10834,
"s": 10819,
"text": "ognl-2.6.9.jar"
},
{
"code": null,
"e": 10849,
"s": 10834,
"text": "ognl-2.6.9.jar"
},
{
"code": null,
"e": 10863,
"s": 10849,
"text": "xom-1.2.5.jar"
},
{
"code": null,
"e": 10877,
"s": 10863,
"text": "xom-1.2.5.jar"
},
{
"code": null,
"e": 10928,
"s": 10877,
"text": "src - Source code folder\n\nmain\ntest\ntest-dummies\n\n"
},
{
"code": null,
"e": 10953,
"s": 10928,
"text": "src - Source code folder"
},
{
"code": null,
"e": 10958,
"s": 10953,
"text": "main"
},
{
"code": null,
"e": 10963,
"s": 10958,
"text": "main"
},
{
"code": null,
"e": 10968,
"s": 10963,
"text": "test"
},
{
"code": null,
"e": 10973,
"s": 10968,
"text": "test"
},
{
"code": null,
"e": 10986,
"s": 10973,
"text": "test-dummies"
},
{
"code": null,
"e": 10999,
"s": 10986,
"text": "test-dummies"
},
{
"code": null,
"e": 11020,
"s": 10999,
"text": "concordion-1.5.1.jar"
},
{
"code": null,
"e": 11041,
"s": 11020,
"text": "concordion-1.5.1.jar"
},
{
"code": null,
"e": 11384,
"s": 11041,
"text": "You will find all the Concordion dependency libraries in the directory E:\\concordion\\lib. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face problem while running your application. If you are using Eclipse then it is not required to set CLASSPATH because all the setting will be done through Eclipse."
},
{
"code": null,
"e": 11522,
"s": 11384,
"text": "Once you are done with this last step, you are ready to proceed for your first Concordion Example which you will see in the next chapter."
},
{
"code": null,
"e": 11839,
"s": 11522,
"text": "Let us start programming with Concordion. Before you start writing your first example using Concordion, you have to make sure that you have set up your Concordion environment properly as explained in Concordion - Environment Setup tutorial. We also assume that you have a little bit working knowledge of Eclipse IDE."
},
{
"code": null,
"e": 11947,
"s": 11839,
"text": "So let us proceed to write a simple Concordion application which will print the following acceptance test −"
},
{
"code": null,
"e": 12029,
"s": 11947,
"text": "Example\nWhen Robert logs in the system, a greeting \"Hello Robert!\" is displayed.\n"
},
{
"code": null,
"e": 12271,
"s": 12029,
"text": "The first step is to create a simple Java project using Eclipse IDE. Follow the option File → New → Project and finally select Java Project wizard from the wizard list. Now name your project as Concordion using the wizard window as follows −"
},
{
"code": null,
"e": 12377,
"s": 12271,
"text": "Once your project is created successfully, you will have the following content in your Project Explorer −"
},
{
"code": null,
"e": 12636,
"s": 12377,
"text": "Let us add concordion and its dependencies in our project. To do this, right-click on your project name concordion and then follow the options available in the context menu: Build Path → Configure Build Path to display the Java Build Path window as follows −"
},
{
"code": null,
"e": 12757,
"s": 12636,
"text": "Now use Add External JARs button available under Libraries tab to add the following core JAR from the Concordion folder."
},
{
"code": null,
"e": 12774,
"s": 12757,
"text": "concordion-1.5.1"
},
{
"code": null,
"e": 12792,
"s": 12774,
"text": "hamcrest-core-1.3"
},
{
"code": null,
"e": 12803,
"s": 12792,
"text": "junit-4.12"
},
{
"code": null,
"e": 12814,
"s": 12803,
"text": "ognl-2.6.9"
},
{
"code": null,
"e": 12824,
"s": 12814,
"text": "xom-1.2.5"
},
{
"code": null,
"e": 13056,
"s": 12824,
"text": "Now let us create actual source files under the concordion project. First, we need to create a package called com.tutorialspoint. To do this, right-click on src in the package explorer section and follow the option : New → Package."
},
{
"code": null,
"e": 13133,
"s": 13056,
"text": "Next, we will create System .java file under the com.tutorialspoint package."
},
{
"code": null,
"e": 13175,
"s": 13133,
"text": "Here is the content of System.java file −"
},
{
"code": null,
"e": 13320,
"s": 13175,
"text": "package com.tutorialspoint;\n\npublic class System {\n public String getGreeting(String userName){\n return \"Hello \" + userName + \"!\";\n }\n}"
},
{
"code": null,
"e": 13736,
"s": 13320,
"text": "Now let us create actual specification files under the concordion project. First, we need to create a new source folder named specs. This folder will contain specification files like JUnitFixture or test runner and html files which are specifications. Now we need to create a package called specs.tutorialspoint. To do this, right-click on spec in the package explorer section and follow the option : New → Package."
},
{
"code": null,
"e": 13904,
"s": 13736,
"text": "Next, we will create System.html and SystemFixture.java files under the specs.tutorialspoint package. Thereafter, we will add concordion.css under specs source folder."
},
{
"code": null,
"e": 13950,
"s": 13904,
"text": "Here is the content of the System.html file −"
},
{
"code": null,
"e": 14647,
"s": 13950,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type=\"text/css\" />\n </head>\n\n <body>\n <h1>System Specifications</h1>\n <p>We are building specifications for our online order tracking application.</p>\n <p>Following is the requirement to show greeting to logged in user:</p>\n <div class = \"example\"> \n <h3>Example</h3>\n <p>When <span concordion:set = \"#userName\">Robert</span> \n logs in the system, a greeting \"<span concordion:assertEquals = \"getGreeting(#userName)\">\n Hello Robert!</span>\" is displayed.</p>\n </div>\n </body>\n\n</html>"
},
{
"code": null,
"e": 14700,
"s": 14647,
"text": "Here is the content of the SystemFixture.java file −"
},
{
"code": null,
"e": 15054,
"s": 14700,
"text": "package specs.tutorialspoint;\n\nimport com.tutorialspoint.System;\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\n\n@RunWith(ConcordionRunner.class)\n\npublic class SystemFixture {\n\n System system = new System();\n\t\n public String getGreeting(String userName){\n return system.getGreeting(userName);\n }\n}"
},
{
"code": null,
"e": 15103,
"s": 15054,
"text": "Here is the content of the concordion.css file −"
},
{
"code": null,
"e": 16324,
"s": 15103,
"text": "* {\n font-family: Arial;\n}\n\nbody {\n padding: 32px; \n}\n\npre {\n padding: 6px 28px 6px 28px;\n background-color: #E8EEF7;\n}\n\npre, pre *, code, code *, kbd {\n font-family: Courier New, Courier;\n font-size: 10pt;\n}\n\nh1, h1 * {\n font-size: 24pt;\t\n}\n\np, td, th, li, .breadcrumbs {\n font-size: 10pt;\n}\n\np, li {\n line-height: 140%;\n}\n\ntable {\n border-collapse: collapse;\n empty-cells: show;\n margin: 8px 0px 8px 0px;\n}\n\nth, td {\n border: 1px solid black;\n padding: 3px;\n}\n\ntd {\n background-color: white;\n vertical-align: top;\n}\n\nth {\n background-color: #C3D9FF;\n}\n\nli {\n margin-top: 6px;\n margin-bottom: 6px; \n}\n\n.example {\n padding: 6px 16px 6px 16px;\n border: 1px solid #D7D7D7;\n margin: 6px 0px 28px 0px;\n background-color: #F7F7F7;\n}\n\n.example h3 {\n margin-top: 8px;\n margin-bottom: 8px;\n font-size: 12pt;\n}\n\n.special {\n font-style: italic;\n}\n\n.idea {\n font-size: 9pt;\n color: #888;\n font-style: italic;\t\n}\n\n.tight li {\n margin-top: 1px;\n margin-bottom: 1px; \n}\n\n.commentary {\n float: right;\n width: 200px;\n background-color: #ffffd0;\n padding:8px;\n border: 3px solid #eeeeb0;\t \n margin: 10px 0px 10px 10px;\t \n}\n\n.commentary, .commentary * {\n font-size: 8pt;\n}"
},
{
"code": null,
"e": 16420,
"s": 16324,
"text": "There are two important points to note about the specification html file and the Test Fixture −"
},
{
"code": null,
"e": 16499,
"s": 16420,
"text": "System.html is the specification html file that uses the concordion namespace."
},
{
"code": null,
"e": 16578,
"s": 16499,
"text": "System.html is the specification html file that uses the concordion namespace."
},
{
"code": null,
"e": 16646,
"s": 16578,
"text": "<html xmlns:concordion=\"http://www.concordion.org/2007/concordion\">"
},
{
"code": null,
"e": 16837,
"s": 16646,
"text": "System.html uses concordion:set command to set a value of temporary variables userName to be Robert. Here, userName is the parameter to be passed to the getGreeting method of System fixture."
},
{
"code": null,
"e": 17028,
"s": 16837,
"text": "System.html uses concordion:set command to set a value of temporary variables userName to be Robert. Here, userName is the parameter to be passed to the getGreeting method of System fixture."
},
{
"code": null,
"e": 17099,
"s": 17028,
"text": "When <span concordion:set=\"#userName\">Robert</span> logs in the system"
},
{
"code": null,
"e": 17223,
"s": 17099,
"text": "System.html uses concordion:assertEquals command to check the output of getGreeting(userName) function to be Hello Robert!."
},
{
"code": null,
"e": 17347,
"s": 17223,
"text": "System.html uses concordion:assertEquals command to check the output of getGreeting(userName) function to be Hello Robert!."
},
{
"code": null,
"e": 17451,
"s": 17347,
"text": "a greeting \"<span concordion:assertEquals=\"getGreeting(#userName)\">\nHello Robert!</span>\" is displayed."
},
{
"code": null,
"e": 17528,
"s": 17451,
"text": "SystemFixture is a JUnit test fixture annotated with ConcordionRunner.class."
},
{
"code": null,
"e": 17605,
"s": 17528,
"text": "SystemFixture is a JUnit test fixture annotated with ConcordionRunner.class."
},
{
"code": null,
"e": 17667,
"s": 17605,
"text": "@RunWith(ConcordionRunner.class)\npublic class SystemFixture {"
},
{
"code": null,
"e": 17742,
"s": 17667,
"text": "SystemFixture has a getGreeting method that returns greetings to the user."
},
{
"code": null,
"e": 17817,
"s": 17742,
"text": "SystemFixture has a getGreeting method that returns greetings to the user."
},
{
"code": null,
"e": 17903,
"s": 17817,
"text": "public String getGreeting(String userName){\n return system.getGreeting(userName);\n}"
},
{
"code": null,
"e": 18043,
"s": 17903,
"text": "Right-click on the content area of SystemFixture and select Run as > JUnit Test Case. You will see the following output with junit success."
},
{
"code": null,
"e": 18149,
"s": 18043,
"text": "C:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 1, Failures: 0\n"
},
{
"code": null,
"e": 18199,
"s": 18149,
"text": "System.html is the output of Concordion test run."
},
{
"code": null,
"e": 18366,
"s": 18199,
"text": "Congratulations, you have created your first Concordion Acceptance test successfully. Further, let us start doing something more interesting in the next few chapters."
},
{
"code": null,
"e": 18473,
"s": 18366,
"text": "Concordion set command is used to store temporary variables that can be used in other Concordion commands."
},
{
"code": null,
"e": 18510,
"s": 18473,
"text": "Consider the following requirement −"
},
{
"code": null,
"e": 18553,
"s": 18510,
"text": "The Sum of two numbers 2 and 3 will be 5.\n"
},
{
"code": null,
"e": 18799,
"s": 18553,
"text": "If we want the numbers 2 and 3 to be as parameters and pass them to the sum function as parameter so that they can be verified against the result returned by the system, then we can use concordion:set command within span tags around the numbers."
},
{
"code": null,
"e": 19025,
"s": 18799,
"text": "<p>The Sum of two numbers <span concordion:set = \"#firstNumber\">2</span> \n and <span concordion:set = \"#secondNumber\">3</span> will be \n <span concordion:assertEquals = \"sum(#firstNumber, #secondNumber)\">5\n </span>.</p>"
},
{
"code": null,
"e": 19290,
"s": 19025,
"text": "When Concordion parses the document, it will set a temporary variable #firstNumber to be the value \"2\" and #secondNumber to be the value \"3\" and then call the sum() method with parameters as #firstNumber and #secondNumber and check that the result is equal to \"5\"."
},
{
"code": null,
"e": 19403,
"s": 19290,
"text": "Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −"
},
{
"code": null,
"e": 19445,
"s": 19403,
"text": "Here is the content of System.java file −"
},
{
"code": null,
"e": 19598,
"s": 19445,
"text": "package com.tutorialspoint;\npublic class System {\n public int sum(int firstNumber, int secondNumber) {\n return firstNumber + secondNumber;\n }\n}"
},
{
"code": null,
"e": 19652,
"s": 19598,
"text": "Following is the content of SystemFixture.java file −"
},
{
"code": null,
"e": 20020,
"s": 19652,
"text": "package specs.tutorialspoint;\n\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\nimport com.tutorialspoint.System;\n\n@RunWith(ConcordionRunner.class)\n\npublic class SystemFixture {\n System system = new System();\n public int sum(int firstNumber, int secondNumber) {\n return system.sum(firstNumber, secondNumber);\n }\n}"
},
{
"code": null,
"e": 20067,
"s": 20020,
"text": "Following is the content of System.html file −"
},
{
"code": null,
"e": 20830,
"s": 20067,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <h1>Calculator Specifications</h1>\n <p>We are building online calculator support in our website.</p>\n <p>Following is the requirement to add two numbers:</p>\n\t\t\n <div class = \"example\">\n <h3>Example</h3>\n <p>The Sum of two numbers <span concordion:set = \"#firstNumber\">2</span> \n and <span concordion:set = \"#secondNumber\">3</span> will be \n <span concordion:execute = \"#result = sum(#firstNumber, #secondNumber)\"></span>\n <span concordion:assertEquals = \"#result\">5</span>.</p>\n </div>\n </body>\n\n</html>"
},
{
"code": null,
"e": 21020,
"s": 20830,
"text": "Once you are done with creating source and specification files, let us run the application as JUnit test. If everything is fine with your application, it will produce the following result −"
},
{
"code": null,
"e": 21126,
"s": 21020,
"text": "C:\\DOCUME>1\\ADMINI>1\\LOCALS>1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 1, Failures: 0\n"
},
{
"code": null,
"e": 21176,
"s": 21126,
"text": "System.html is the output of concordion test run."
},
{
"code": null,
"e": 21288,
"s": 21176,
"text": "Concordion assertEquals command is used to check Java bean property or method result against a specified value."
},
{
"code": null,
"e": 21325,
"s": 21288,
"text": "Consider the following requirement −"
},
{
"code": null,
"e": 21368,
"s": 21325,
"text": "The sum of two numbers 2 and 3 will be 5.\n"
},
{
"code": null,
"e": 21625,
"s": 21368,
"text": "If we want the numbers 2 and 3 to be as parameters and pass them to sum function as parameter so that it can be verified against the result as 5 returned by the system then we can use concordion:assertEquals command within span tag around the sum function."
},
{
"code": null,
"e": 21842,
"s": 21625,
"text": "<p>The Sum of two numbers <span concordion:set=\"#firstNumber\">2</span> \n and <span concordion:set=\"#secondNumber\">3</span> will be \n <span concordion:assertEquals=\"sum(#firstNumber, #secondNumber)\">5</span>.</p>"
},
{
"code": null,
"e": 22156,
"s": 21842,
"text": "When Concordion parses the document, it will set a temporary variable #firstNumber to be the value \"2\" and #secondNumber to be the value \"3\" using set command and then call the sum() method with parameters as #firstNumber and #secondNumber and check that the result is equal to \"5\" using the assertEquals command."
},
{
"code": null,
"e": 22265,
"s": 22156,
"text": "Let us have working Eclipse IDE in place and follow the following steps to create a Concordion application −"
},
{
"code": null,
"e": 22311,
"s": 22265,
"text": "Here is the content of the System.java file −"
},
{
"code": null,
"e": 22464,
"s": 22311,
"text": "package com.tutorialspoint;\npublic class System {\n public int sum(int firstNumber, int secondNumber) {\n return firstNumber + secondNumber;\n }\n}"
},
{
"code": null,
"e": 22522,
"s": 22464,
"text": "Following is the content of the SystemFixture.java file −"
},
{
"code": null,
"e": 22890,
"s": 22522,
"text": "package specs.tutorialspoint;\n\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\nimport com.tutorialspoint.System;\n\n@RunWith(ConcordionRunner.class)\n\npublic class SystemFixture {\n System system = new System();\n public int sum(int firstNumber, int secondNumber) {\n return system.sum(firstNumber, secondNumber);\n }\n}"
},
{
"code": null,
"e": 22941,
"s": 22890,
"text": "Following is the content of the System.html file −"
},
{
"code": null,
"e": 23641,
"s": 22941,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <h1>Calculator Specifications</h1>\n <p>We are building online calculator support in our website.</p>\n <p>Following is the requirement to add two numbers:</p>\n\t\t\n <div class = \"example\">\n <h3>Example</h3>\n <p>The Sum of two numbers <span concordion:set = \"#firstNumber\">2</span> \n and <span concordion:set = \"#secondNumber\">3</span> will be \n <span concordion:assertEquals = \"sum(#firstNumber, #secondNumber)\">5</span>.</p>\n </div>\n\t\t\n </body>\n\n</html>"
},
{
"code": null,
"e": 23833,
"s": 23641,
"text": "Once you are done with creating source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will show the following result −"
},
{
"code": null,
"e": 23939,
"s": 23833,
"text": "C:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 1, Failures: 0\n"
},
{
"code": null,
"e": 23989,
"s": 23939,
"text": "System.html is the output of Concordion test run."
},
{
"code": null,
"e": 24016,
"s": 23989,
"text": " Successes: 1, Failures: 0"
},
{
"code": null,
"e": 24133,
"s": 24016,
"text": "Concordion assertTrue command is used when the fixture needs to know the expected result in order to perform a test."
},
{
"code": null,
"e": 24170,
"s": 24133,
"text": "Consider the following requirement −"
},
{
"code": null,
"e": 24260,
"s": 24170,
"text": "User Name : Robert De\nThe User name starts with R.\nThe User name starts with S == false.\n"
},
{
"code": null,
"e": 24364,
"s": 24260,
"text": "If we want a test to be executed on the User Name and check whether the user name starts with R or not."
},
{
"code": null,
"e": 24721,
"s": 24364,
"text": "<p>User Name :<span concordion:set = \"#userName\">Robert De</span></p>\n<p>The User name <span concordion:assertTrue = \"#userName.startsWith(#letter)\">starts\n with <b concordion:set = \"#letter\">R</b></span>.</p>\n<p>The User name <span concordion:assertTrue = \"#userName.startsWith(#letter)\">starts\n with <b concordion:set = \"#letter\">S</b></span>.</p> "
},
{
"code": null,
"e": 24939,
"s": 24721,
"text": "When Concordion parses the document, it will set a temporary variable #userName to be the value \"Robert De\". Then it will check if the userName starts with the letter specified by #letter variable set in next command."
},
{
"code": null,
"e": 25052,
"s": 24939,
"text": "Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −"
},
{
"code": null,
"e": 25098,
"s": 25052,
"text": "Here is the content of the System.java file −"
},
{
"code": null,
"e": 25153,
"s": 25098,
"text": "package com.tutorialspoint;\npublic class System { \n}"
},
{
"code": null,
"e": 25211,
"s": 25153,
"text": "Following is the content of the SystemFixture.java file −"
},
{
"code": null,
"e": 25400,
"s": 25211,
"text": "package specs.tutorialspoint;\n\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\n\n@RunWith(ConcordionRunner.class)\n\npublic class SystemFixture {\n}"
},
{
"code": null,
"e": 25451,
"s": 25400,
"text": "Following is the content of the System.html file −"
},
{
"code": null,
"e": 26411,
"s": 25451,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <h1>System Specifications</h1>\n <p>We are building specifications for our online order tracking application.</p>\n <p>Following is the requirement to split full name of a logged in user to \n its constituents by splitting name by whitespace:</p>\n \n <div class = \"example\"> \n <h3>Example</h3>\n <p>User Name :<span concordion:set = \"#userName\">Robert De</span></p>\n <p>The User name <span concordion:assertTrue = \"#userName.startsWith(#letter)\">starts\n with <b concordion:set = \"#letter\">R</b></span>.</p>\n <p>The User name <span concordion:assertTrue = \"#userName.startsWith(#letter)\">starts\n with <b concordion:set = \"#letter\">S</b></span>.</p> \n </div>\n\t\t\n </body>\n\n</html>"
},
{
"code": null,
"e": 26606,
"s": 26411,
"text": "Once you are done with creating source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −"
},
{
"code": null,
"e": 26712,
"s": 26606,
"text": "C:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 1, Failures: 1\n"
},
{
"code": null,
"e": 26762,
"s": 26712,
"text": "System.html is the output of Concordion test run."
},
{
"code": null,
"e": 26880,
"s": 26762,
"text": "Concordion assertFalse command is used when the fixture needs to know the expected result in order to perform a test."
},
{
"code": null,
"e": 26917,
"s": 26880,
"text": "Consider the following requirement −"
},
{
"code": null,
"e": 26977,
"s": 26917,
"text": "User Name : Robert De\nThe User name does not start with S.\n"
},
{
"code": null,
"e": 27079,
"s": 26977,
"text": "If we want a test to be executed on the User Name and check that the user name does not start with S."
},
{
"code": null,
"e": 27302,
"s": 27079,
"text": "<p>User Name :<span concordion:set = \"#userName\">Robert De</span></p>\n<p>The User name <span concordion:assertFalse = \"#userName.startsWith(#letter)\">does not start\n with <b concordion:set = \"#letter\">S</b></span>.</p> "
},
{
"code": null,
"e": 27521,
"s": 27302,
"text": "When Concordion parses the document, it will set a temporary variable #userName to be the value \"Robert De\". Then, it will check if the userName starts with the letter specified by #letter variable set in next command."
},
{
"code": null,
"e": 27634,
"s": 27521,
"text": "Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −"
},
{
"code": null,
"e": 27680,
"s": 27634,
"text": "Here is the content of the System.java file −"
},
{
"code": null,
"e": 27735,
"s": 27680,
"text": "package com.tutorialspoint;\npublic class System { \n}"
},
{
"code": null,
"e": 27793,
"s": 27735,
"text": "Following is the content of the SystemFixture.java file −"
},
{
"code": null,
"e": 27982,
"s": 27793,
"text": "package specs.tutorialspoint;\n\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\n\n@RunWith(ConcordionRunner.class)\n\npublic class SystemFixture {\n}"
},
{
"code": null,
"e": 28033,
"s": 27982,
"text": "Following is the content of the System.html file −"
},
{
"code": null,
"e": 28847,
"s": 28033,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <h1>System Specifications</h1>\n <p>We are building specifications for our online order tracking application.</p>\n <p>Following is the requirement to split full name of a logged in user to its \n constituents by splitting name by whitespace:</p>\n\t\t\t\n <div class = \"example\"> \n <h3>Example</h3>\n <p>User Name :<span concordion:set = \"#userName\">Robert De</span></p>\n <p>The User name <span concordion:assertFalse = \"#userName.startsWith(#letter)\">\n does not start with <b concordion:set = \"#letter\">\n S</b></span>.</p> \n </div>\n\t\t\n </body>\n\n</html>"
},
{
"code": null,
"e": 29042,
"s": 28847,
"text": "Once you are done with creating source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −"
},
{
"code": null,
"e": 29148,
"s": 29042,
"text": "C:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 1, Failures: 0\n"
},
{
"code": null,
"e": 29198,
"s": 29148,
"text": "System.html is the output of Concordion test run."
},
{
"code": null,
"e": 29311,
"s": 29198,
"text": "Concordion execute command is used run the operation of concordion fixture. Consider the following requirement −"
},
{
"code": null,
"e": 29354,
"s": 29311,
"text": "The sum of two numbers 2 and 3 will be 5.\n"
},
{
"code": null,
"e": 29505,
"s": 29354,
"text": "If we want to write a specification for a sum function which will accept two numbers and output their sum, then the specification will be as follows −"
},
{
"code": null,
"e": 29784,
"s": 29505,
"text": "<p>The Sum of two numbers <span concordion:set = \"#firstNumber\">2</span> and \n <span concordion:set = \"#secondNumber\">3</span> will be\n <span concordion:execute = \"#result = sum(#firstNumber, #secondNumber)\">\n </span><span concordion:assertEquals = \"#result\">5</span>.</p>"
},
{
"code": null,
"e": 30129,
"s": 29784,
"text": "When Concordion parses the document, it will set a temporary variable #firstNumber to be the value \"2\" and #secondNumber to be the value \"3\" and then execute the sum() method with parameters as #firstNumber and #secondNumber using the execute command and set the result into #result variable and check that the #result variable is equal to \"5\"."
},
{
"code": null,
"e": 30242,
"s": 30129,
"text": "Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −"
},
{
"code": null,
"e": 30288,
"s": 30242,
"text": "Here is the content of the System.java file −"
},
{
"code": null,
"e": 30441,
"s": 30288,
"text": "package com.tutorialspoint;\npublic class System {\n public int sum(int firstNumber, int secondNumber) {\n return firstNumber + secondNumber;\n }\n}"
},
{
"code": null,
"e": 30499,
"s": 30441,
"text": "Following is the content of the SystemFixture.java file −"
},
{
"code": null,
"e": 30867,
"s": 30499,
"text": "package specs.tutorialspoint;\n\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\nimport com.tutorialspoint.System;\n\n@RunWith(ConcordionRunner.class)\n\npublic class SystemFixture {\n System system = new System();\n public int sum(int firstNumber, int secondNumber) {\n return system.sum(firstNumber, secondNumber);\n }\n}"
},
{
"code": null,
"e": 30918,
"s": 30867,
"text": "Following is the content of the System.html file −"
},
{
"code": null,
"e": 31684,
"s": 30918,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <h1>Calculator Specifications</h1>\n <p>We are building online calculator support in our website.</p>\n <p>Following is the requirement to add two numbers:</p>\n\t\t\n <div class = \"example\">\n <h3>Example</h3>\n <p>The Sum of two numbers <span concordion:set = \"#firstNumber\">2</span> \n and <span concordion:set = \"#secondNumber\">3</span> will be \n <span concordion:execute = \"#result = sum(#firstNumber, #secondNumber)\">\n </span><span concordion:assertEquals = \"#result\">5</span>.</p>\n </div>\n\t\t\n </body>\n\n</html>"
},
{
"code": null,
"e": 31879,
"s": 31684,
"text": "Once you are done with creating source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −"
},
{
"code": null,
"e": 31985,
"s": 31879,
"text": "C:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 1, Failures: 0\n"
},
{
"code": null,
"e": 32035,
"s": 31985,
"text": "System.html is the output of Concordion test run."
},
{
"code": null,
"e": 32233,
"s": 32035,
"text": "Concordion execute command can be used to get the result of a behavior in the form of object using which we can get multiple outputs of a behavior. For example, consider the following requirement −"
},
{
"code": null,
"e": 32315,
"s": 32233,
"text": "The full name Robert De is to be broken into first name Robert and last name De.\n"
},
{
"code": null,
"e": 32490,
"s": 32315,
"text": "Here we need to have a split function which accepts a user name and returns a result object having the first name and the last name as its properties so that we can use them."
},
{
"code": null,
"e": 32657,
"s": 32490,
"text": "If we want to write a specification for such a split function which will expect a user name and output a result object, then the following will be the specification −"
},
{
"code": null,
"e": 32933,
"s": 32657,
"text": "<p>The full name <span concordion:execute = \"#result = split(#TEXT)\">Robert \n De</span> is to be broken into first name \n <span concordion:assertEquals = \"#result.firstName\">Robert</span> and last name \n <span concordion:assertEquals = \"#result.lastName\">De</span>.</p>"
},
{
"code": null,
"e": 33336,
"s": 32933,
"text": "When Concordion parses the document, it will set the value of the special variable #TEXT as the value of the current element as \"Robert De\" and pass it to the split function. Then it will execute the split() method with parameters as #TEXT using the execute command and set the result into the #result variable and using the result object, print the firstName and the lastName properties as the output."
},
{
"code": null,
"e": 33449,
"s": 33336,
"text": "Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −"
},
{
"code": null,
"e": 33491,
"s": 33449,
"text": "Here is the content of Result.java file −"
},
{
"code": null,
"e": 33903,
"s": 33491,
"text": "package com.tutorialspoint;\npublic class Result {\n private String firstName;\n private String lastName;\n\t\n public String getFirstName() {\n return firstName;\n }\n\t\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\t\n public String getLastName() {\n return lastName;\n }\n\t\n public void setLastName(String lastName) {\n this.lastName = lastName;\n } \n}"
},
{
"code": null,
"e": 33945,
"s": 33903,
"text": "Here is the content of System.java file −"
},
{
"code": null,
"e": 34217,
"s": 33945,
"text": "package com.tutorialspoint;\npublic class System {\n public Result split(String userName){\n Result result = new Result();\n String[] words = userName.split(\" \");\n result.setFirstName(words[0]);\n result.setLastName(words[1]);\n return result;\n }\n}"
},
{
"code": null,
"e": 34270,
"s": 34217,
"text": "Following is the content of SystemFixture.java file−"
},
{
"code": null,
"e": 34645,
"s": 34270,
"text": "package specs.tutorialspoint;\n\nimport com.tutorialspoint.Result;\nimport com.tutorialspoint.System;\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\n\n@RunWith(ConcordionRunner.class)\n\npublic class SystemFixture {\n System system = new System();\n public Result split(String userName){\n return system.split(userName);\n } \n}"
},
{
"code": null,
"e": 34692,
"s": 34645,
"text": "Following is the content of System.html file −"
},
{
"code": null,
"e": 35556,
"s": 34692,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <h1>System Specifications</h1>\n <p>We are building specifications for our online order tracking application.</p>\n <p>Following is the requirement to split full name of a logged in user to its \n constituents by splitting name by whitespace:</p>\n\t\t\t\n <div class = \"example\"> \n <h3>Example</h3>\n <p>The full name <span concordion:execute = \"#result = split(#TEXT)\">Robert \n De</span> is to be broken into first name <span \n concordion:assertEquals = \"#result.firstName\">Robert</span> and last name <span \n concordion:assertEquals = \"#result.lastName\">De</span>.</p>\n </div>\n\t\t\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 35755,
"s": 35556,
"text": "Once you are done with creating the source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −"
},
{
"code": null,
"e": 35861,
"s": 35755,
"text": "C:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 1, Failures: 0\n"
},
{
"code": null,
"e": 35911,
"s": 35861,
"text": "System.html is the output of Concordion test run."
},
{
"code": null,
"e": 36108,
"s": 35911,
"text": "Concordion execute command can be used to get the result of a behavior in the form of a Map using which we can get multiple outputs of a behavior. For example, consider the following requirement −"
},
{
"code": null,
"e": 36194,
"s": 36108,
"text": "The full name Robert De is to be broken into its first name Robert and last name De.\n"
},
{
"code": null,
"e": 36386,
"s": 36194,
"text": "Here we need to have a spilt function which accepts a user name and returns a Map object having the firstName and the lastName as its keys having corresponding values so that we can use them."
},
{
"code": null,
"e": 36553,
"s": 36386,
"text": "If we want to write a specification for such a split function which will accept a user name and output a result object, then the following will be the specification −"
},
{
"code": null,
"e": 36829,
"s": 36553,
"text": "<p>The full name <span concordion:execute = \"#result = split(#TEXT)\">Robert \n De</span> is to be broken into first name <span \n concordion:assertEquals = \"#result.firstName\">Robert</span> and last name <span \n concordion:assertEquals = \"#result.lastName\">De</span>.</p>"
},
{
"code": null,
"e": 37216,
"s": 36829,
"text": "When Concordion parses the document, it will set the value of the special variable #TEXT to be the value of the current element as \"Robert De\" and pass it to the split function. Then it will execute the split() method with parameters as #TEXT using the execute command and set the result into the #result variable and using result map, print the firstName and lastName values as output."
},
{
"code": null,
"e": 37329,
"s": 37216,
"text": "Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −"
},
{
"code": null,
"e": 37371,
"s": 37329,
"text": "Here is the content of System.java file −"
},
{
"code": null,
"e": 37728,
"s": 37371,
"text": "package com.tutorialspoint;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class System {\n public Map split(String userName){\n Map<String, String> result = new HashMap<String, String>();\n String[] words = userName.split(\" \");\n result.put(\"firstName\", words[0]);\n result.put(\"lastName\", words[1]);\n return result;\n }\n}"
},
{
"code": null,
"e": 37782,
"s": 37728,
"text": "Following is the content of SystemFixture.java file −"
},
{
"code": null,
"e": 38192,
"s": 37782,
"text": "package specs.tutorialspoint;\n\nimport java.util.Map;\nimport com.tutorialspoint.Result;\nimport com.tutorialspoint.System;\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\n\n@RunWith(ConcordionRunner.class)\n\npublic class SystemFixture {\n System system = new System();\n public Map<String, String> split(String userName){\n return system.split(userName);\n } \n}"
},
{
"code": null,
"e": 38239,
"s": 38192,
"text": "Following is the content of System.html file −"
},
{
"code": null,
"e": 39102,
"s": 38239,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <h1>System Specifications</h1>\n <p>We are building specifications for our online order tracking application.</p>\n <p>Following is the requirement to split full name of a logged in user to its \n constituents by splitting name by whitespace:</p>\n\t\t\t\n <div class = \"example\"> \n <h3>Example</h3>\n <p>The full name <span concordion:execute = \"#result = split(#TEXT)\">Robert \n De</span> is to be broken into first name <span \n concordion:assertEquals = \"#result.firstName\">Robert</span> and last name \n <span concordion:assertEquals = \"#result.lastName\">De</span>.</p>\n </div>\n\t\t\n </body>\n\n</html>"
},
{
"code": null,
"e": 39301,
"s": 39102,
"text": "Once you are done with creating the source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −"
},
{
"code": null,
"e": 39407,
"s": 39301,
"text": "C:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 1, Failures: 0\n"
},
{
"code": null,
"e": 39457,
"s": 39407,
"text": "System.html is the output of Concordion test run."
},
{
"code": null,
"e": 39654,
"s": 39457,
"text": "Concordion execute command can be used to get the result of a behavior in the form of a Map using which we can get multiple outputs of a behavior. For example, consider the following requirement −"
},
{
"code": null,
"e": 39740,
"s": 39654,
"text": "The full name Robert De is to be broken into its first name Robert and last name De.\n"
},
{
"code": null,
"e": 39928,
"s": 39740,
"text": "Here we need to have a split function which accepts a user name and returns a Map object having firstName and lastName as its keys with their corresponding values so that we can use them."
},
{
"code": null,
"e": 40090,
"s": 39928,
"text": "If we want write a specification for such a split function which will accept a user name and output a result object, then the specification would be as follows −"
},
{
"code": null,
"e": 40366,
"s": 40090,
"text": "<p>The full name <span concordion:execute = \"#result = split(#TEXT)\">Robert \n De</span> is to be broken into first name \n <span concordion:assertEquals = \"#result.firstName\">Robert</span> and last name \n <span concordion:assertEquals = \"#result.lastName\">De</span>.</p>"
},
{
"code": null,
"e": 40749,
"s": 40366,
"text": "When Concordion parses the document, it will set the value of the special variable #TEXT to be the value of current element as \"Robert De\" and pass it to the split function. Then it will execute the split() method with parameters as #TEXT using execute command and set the result into the #result variable and using result map, print the firstName and lastName values as the output."
},
{
"code": null,
"e": 40862,
"s": 40749,
"text": "Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −"
},
{
"code": null,
"e": 40904,
"s": 40862,
"text": "Here is the content of System.java file −"
},
{
"code": null,
"e": 41260,
"s": 40904,
"text": "package com.tutorialspoint;\nimport org.concordion.api.MultiValueResult;\n\npublic class System { \n public MultiValueResult split(String userName){ \n MultiValueResult result = new MultiValueResult();\n String[] words = userName.split(\" \"); \n result.with(\"firstName\", words[0]).with(\"lastName\", words[1]); \n return result;\n }\n}"
},
{
"code": null,
"e": 41314,
"s": 41260,
"text": "Following is the content of SystemFixture.java file −"
},
{
"code": null,
"e": 41709,
"s": 41314,
"text": "package specs.tutorialspoint;\n\nimport org.concordion.api.MultiValueResult;\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\n\nimport com.tutorialspoint.System;\n\n@RunWith(ConcordionRunner.class)\npublic class SystemFixture {\n System system = new System();\n public MultiValueResult split(String userName){\n return system.split(userName);\n } \n}"
},
{
"code": null,
"e": 41756,
"s": 41709,
"text": "Following is the content of System.html file −"
},
{
"code": null,
"e": 42618,
"s": 41756,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <h1>System Specifications</h1>\n <p>We are building specifications for our online order tracking application.</p>\n <p>Following is the requirement to split full name of a logged in \n user to its constituents by splitting name by whitespace:</p>\n\t\t\n <div class = \"example\"> \n <h3>Example</h3>\n <p>The full name <span concordion:execute = \"#result = split(#TEXT)\">Robert De</span> \n is to be broken into first name <span \n concordion:assertEquals = \"#result.firstName\">Robert</span> and last name <span \n concordion:assertEquals = \"#result.lastName\">De</span>.</p>\n </div>\n\t\t\n </body>\n\n</html>"
},
{
"code": null,
"e": 42817,
"s": 42618,
"text": "Once you are done with creating the source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −"
},
{
"code": null,
"e": 42923,
"s": 42817,
"text": "C:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 2, Failures: 0\n"
},
{
"code": null,
"e": 42973,
"s": 42923,
"text": "System.html is the output of Concordion test run."
},
{
"code": null,
"e": 43195,
"s": 42973,
"text": "Concordion execute command can be used to run the operation of concordion fixture in a repeating manner. For example, it will be useful if we want to illustrate a requirement with multiple examples in the form of a table."
},
{
"code": null,
"e": 43232,
"s": 43195,
"text": "Consider the following requirement −"
},
{
"code": null,
"e": 43403,
"s": 43232,
"text": "<table>\n <tr><th>First Number</th><th>Second Number</th><th>Sum</th></tr>\n <tr><td>2</td><td>3</td><td>5</td></tr>\n <tr><td>4</td><td>5</td><td>9</td></tr>\n</table>"
},
{
"code": null,
"e": 43555,
"s": 43403,
"text": "If we want to write a specification for a sum function which will accept two numbers and output their sum, then the specification would be as follows −"
},
{
"code": null,
"e": 44074,
"s": 43555,
"text": "<table>\n <tr><th>First Number</th><th>Second Number</th><th>Sum</th></tr>\n <tr concordion:execute = \"#result = sum(#fullName)\">\n <td concordion:set = \"#firstNumber\">2</td>\n <td concordion:set = \"#secondNumber\">3</td>\n <td concordion:assertEquals = \"#result\">5</td>\n </tr>\n <tr concordion:execute = \"#result = sum(#fullName)\">\n <td concordion:set = \"#firstNumber\">4</td>\n <td concordion:set = \"#secondNumber\">5</td>\n <td concordion:assertEquals = \"#result\">9</td>\n </tr>\n</table>"
},
{
"code": null,
"e": 44477,
"s": 44074,
"text": "When Concordion parses the document, it will set a temporary variable #firstNumber to be the value \"2\" and #secondNumber to be the value \"3\". Then it will execute the sum() method with parameters as #firstNumber and #secondNumber using execute command and set the result into the #result variable and check that the #result variable is equal to \"5\". This process is repeated for each table row element."
},
{
"code": null,
"e": 44590,
"s": 44477,
"text": "Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −"
},
{
"code": null,
"e": 44632,
"s": 44590,
"text": "Here is the content of System.java file −"
},
{
"code": null,
"e": 44785,
"s": 44632,
"text": "package com.tutorialspoint;\npublic class System {\n public int sum(int firstNumber, int secondNumber) {\n return firstNumber + secondNumber;\n }\n}"
},
{
"code": null,
"e": 44839,
"s": 44785,
"text": "Following is the content of SystemFixture.java file −"
},
{
"code": null,
"e": 45207,
"s": 44839,
"text": "package specs.tutorialspoint;\n\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\nimport com.tutorialspoint.System;\n\n@RunWith(ConcordionRunner.class)\n\npublic class SystemFixture {\n System system = new System();\n public int sum(int firstNumber, int secondNumber) {\n return system.sum(firstNumber, secondNumber);\n }\n}"
},
{
"code": null,
"e": 45254,
"s": 45207,
"text": "Following is the content of System.html file −"
},
{
"code": null,
"e": 46437,
"s": 45254,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <h1>Calculator Specifications</h1>\n <p>We are building online calculator support in our website.</p>\n <p>Following is the requirement to add two numbers:</p>\n\t\t\n <div class = \"example\">\n <h3>Example</h3>\n <table>\n <tr>\n <th>First Number</th>\n <th>Second Number</th>\n <th>Sum</th>\n </tr>\n <tr concordion:execute = \"#result = sum(#firstNumber, #secondNumber)\">\n <td concordion:set = \"#firstNumber\">2</td>\n <td concordion:set = \"#secondNumber\">3</td>\n <td concordion:assertEquals = \"#result\">5</td>\n </tr>\n <tr concordion:execute = \"#result = sum(#firstNumber, #secondNumber)\">\n <td concordion:set = \"#firstNumber\">4</td>\n <td concordion:set = \"#secondNumber\">5</td>\n <td concordion:assertEquals = \"#result\">9</td>\n </tr>\n </table>\n </div>\n\t\t\n </body>\n\n</html>"
},
{
"code": null,
"e": 46636,
"s": 46437,
"text": "Once you are done with creating the source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −"
},
{
"code": null,
"e": 46742,
"s": 46636,
"text": "C:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 2, Failures: 0\n"
},
{
"code": null,
"e": 46792,
"s": 46742,
"text": "System.html is the output of Concordion test run."
},
{
"code": null,
"e": 47013,
"s": 46792,
"text": "Concordion execute command can be used to run the operation of concordion fixture in a repeating manner. For example, it will be useful if we want to illustrate a requirement with multiple examples in the form of a list."
},
{
"code": null,
"e": 47051,
"s": 47013,
"text": "Consider the following requirement − "
},
{
"code": null,
"e": 47322,
"s": 47051,
"text": "<ul>\n <li>The full name Robert De is to be split as\n <ul>\n <li>Robert</li>\n <li>De</li>\n </ul>\n </li>\n\t\n <li>The full name John Diere is to be split as\n <ul>\n <li>John</li>\n <li>Diere</li>\n </ul>\n </li>\n\t\n</ul>"
},
{
"code": null,
"e": 47480,
"s": 47322,
"text": "If we want write a specification for a split function which will split a name into its first name and last name, then the specification would be as follows −"
},
{
"code": null,
"e": 48119,
"s": 47480,
"text": "<ul>\n <li>The full name <span concordion:execute = \"#result = split(#TEXT)\">\n Robert De</span> is to be splited as\n <ul>\n <li><span concordion:assertEquals = \"#result.firstName\">Robert</span></li>\n <li><span concordion:assertEquals = \"#result.lastName\">De</span></li>\n </ul>\n </li>\n\t\n <li>The full name <span concordion:execute = \"#result = split(#TEXT)\">\n John Diere</span> is to be splited as\n <ul>\n <li><span concordion:assertEquals = \"#result.firstName\">John</span></li>\n <li><span concordion:assertEquals = \"#result.lastName\">Diere</span></li>\n </ul>\n </li>\n</ul>"
},
{
"code": null,
"e": 48498,
"s": 48119,
"text": "When Concordion parses the document, it will set the value of the special variable #TEXT to be the value of the current element as \"Robert De\" and pass it to the split function. Then it will execute the split() method with parameters as #TEXT using execute command and set the result into #result variable and using result, print the firstName and lastName values as the output."
},
{
"code": null,
"e": 48611,
"s": 48498,
"text": "Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −"
},
{
"code": null,
"e": 48653,
"s": 48611,
"text": "Here is the content of System.java file −"
},
{
"code": null,
"e": 49009,
"s": 48653,
"text": "package com.tutorialspoint;\nimport org.concordion.api.MultiValueResult;\n\npublic class System { \n public MultiValueResult split(String userName){ \n MultiValueResult result = new MultiValueResult();\n String[] words = userName.split(\" \"); \n result.with(\"firstName\", words[0]).with(\"lastName\", words[1]); \n return result;\n }\n}"
},
{
"code": null,
"e": 49063,
"s": 49009,
"text": "Following is the content of SystemFixture.java file −"
},
{
"code": null,
"e": 49458,
"s": 49063,
"text": "package specs.tutorialspoint;\n\nimport org.concordion.api.MultiValueResult;\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\nimport com.tutorialspoint.System;\n\n@RunWith(ConcordionRunner.class)\n\npublic class SystemFixture {\n System system = new System();\n public MultiValueResult split(String userName){\n return system.split(userName);\n } \n}"
},
{
"code": null,
"e": 49505,
"s": 49458,
"text": "Following is the content of System.html file −"
},
{
"code": null,
"e": 50926,
"s": 49505,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <h1>System Specifications</h1>\n <p>We are building specifications for our online order tracking application.</p>\n <p>Following is the requirement to split full name of a logged \n in user to its constituents by splitting name by whitespace:</p>\n\t\t\t\n <div class = \"example\"> \n <h3>Example</h3>\n <ul>\n <li>The full name <span concordion:execute = \"#result = split(#TEXT)\">\n Robert De</span> is to be splited as\n <ul>\n <li><span concordion:assertEquals = \"#result.firstName\">\n Robert</span></li>\n <li><span concordion:assertEquals = \"#result.lastName\">\n De</span></li>\n </ul>\n </li>\n\t\t\t\t\n <li>The full name <span concordion:execute =\"#result = split(#TEXT)\">\n John Diere</span> is to be splited as\n <ul>\n <li><span concordion:assertEquals = \"#result.firstName\">\n John</span></li>\n <li><span concordion:assertEquals = \"#result.lastName\">\n Diere</span></li>\n </ul>\n </li>\n </ul>\n </div>\n </body>\n\n</html>"
},
{
"code": null,
"e": 51121,
"s": 50926,
"text": "Once you are done with creating source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −"
},
{
"code": null,
"e": 51227,
"s": 51121,
"text": "C:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 4, Failures: 0\n"
},
{
"code": null,
"e": 51277,
"s": 51227,
"text": "System.html is the output of Concordion test run."
},
{
"code": null,
"e": 51577,
"s": 51277,
"text": "Concordion verifyRows command can be used to check the content of a collection returned as a result by the system. For example, if we set up a set of users in the system and do a partial search on them, then the system should return the matching elements, otherwise our acceptance tests should fail."
},
{
"code": null,
"e": 51614,
"s": 51577,
"text": "Consider the following requirement −"
},
{
"code": null,
"e": 51903,
"s": 51614,
"text": "<table>\n <tr><th>Users</th></tr>\n <tr><td>Robert De</td></tr>\n <tr><td>John Diere</td></tr>\n <tr><td>Julie Re</td></tr>\n</table>\n\n<p>Search for J should return:</p>\n\n<table>\n <tr><th>Matching Users</th></tr>\n <tr><td>John Diere</td></tr>\n <tr><td>Julie Re</td></tr>\n</table>"
},
{
"code": null,
"e": 52050,
"s": 51903,
"text": "If we want write a specification for such a search function which will search and return a collection, then the specification will be as follows −"
},
{
"code": null,
"e": 52557,
"s": 52050,
"text": "<table concordion:execute = \"addUser(#username)\">\n <tr><th concordion:set = \"#username\">Username</th></tr>\n <tr><td>Robert De</td></tr>\n <tr><td>John Diere</td></tr>\n <tr><td>Julie Re</td></tr>\n</table>\n\n<p>Search for \"<b concordion:set = \"#searchString\">J</b>\" should return:</p>\n\n<table concordion:verifyRows = \"#username : search(#searchString)\">\n <tr><th concordion:assertEquals = \"#username\">Matching Usernames</th></tr>\n <tr><td>John Diere</td></tr>\n <tr><td>Julie Re</td></tr>\n</table>"
},
{
"code": null,
"e": 52941,
"s": 52557,
"text": "When Concordion parses the document, it will execute addUser() on each row of the first table and then set the searchString to be J. Next, Concordion will execute the search function which should return a Iterable object with a predictable iteration order, (e.g. a List, LinkedHashSet or a TreeSet), verifyRows runs for each item of the collection and runs the assertEquals command. "
},
{
"code": null,
"e": 53054,
"s": 52941,
"text": "Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −"
},
{
"code": null,
"e": 53096,
"s": 53054,
"text": "Here is the content of System.java file −"
},
{
"code": null,
"e": 53672,
"s": 53096,
"text": "package com.tutorialspoint;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\n\npublic class System { \n private Set<String> users = new HashSet<String>();\n\t\n public void addUser(String username) {\n users.add(username);\n }\n\t\n public Iterable<String> search(String searchString) {\n SortedSet<String> matches = new TreeSet<String>();\n\t\t\n for (String username : users) {\n if (username.contains(searchString)) {\n matches.add(username);\n }\n }\n\t\t\n return matches;\n }\n}"
},
{
"code": null,
"e": 53726,
"s": 53672,
"text": "Following is the content of SystemFixture.java file −"
},
{
"code": null,
"e": 54167,
"s": 53726,
"text": "package specs.tutorialspoint;\n\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\nimport com.tutorialspoint.System;\n\n@RunWith(ConcordionRunner.class)\n\npublic class SystemFixture {\n System system = new System();\n public void addUser(String username) {\n system.addUser(username);\n }\n\t\n public Iterable<String> search(String searchString) {\n return system.search(searchString);\n }\n}"
},
{
"code": null,
"e": 54214,
"s": 54167,
"text": "Following is the content of System.html file −"
},
{
"code": null,
"e": 55342,
"s": 54214,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <h1>System Specifications</h1>\n <p>We are building specifications for our online order tracking application.</p>\n <p>Following is the requirement to add a partial search capability on user names:</p>\n\t\t\n <div class = \"example\"> \n <h3>Example</h3>\n\t\t\t\n <table concordion:execute = \"addUser(#username)\">\n <tr><th concordion:set = \"#username\">Username</th></tr>\n <tr><td>Robert De</td></tr>\n <tr><td>John Diere</td></tr>\n <tr><td>Julie Re</td></tr>\n </table>\n\t\t\t\n <p>Search for \"<b concordion:set = \"#searchString\">J</b>\" should return:</p>\n\t\t\t\n <table concordion:verifyRows = \"#username : search(#searchString)\">\n <tr><th concordion:assertEquals = \"#username\">Matching Usernames</th></tr>\n <tr><td>John Diere</td></tr>\n <tr><td>Julie Re</td></tr>\n </table>\n\t\t\t\n </div> \n\t\t\n </body>\n\n</html>"
},
{
"code": null,
"e": 55541,
"s": 55342,
"text": "Once you are done with creating the source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −"
},
{
"code": null,
"e": 55647,
"s": 55541,
"text": "C:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 2, Failures: 0\n"
},
{
"code": null,
"e": 55697,
"s": 55647,
"text": "System.html is the output of Concordion test run."
},
{
"code": null,
"e": 55933,
"s": 55697,
"text": "Concordion run command can be used to link multiple specifications together and display them at one central page. This command can run all the specifications, while displaying the link's background in green / red / gray as appropriate."
},
{
"code": null,
"e": 56178,
"s": 55933,
"text": "Now we are going to create two specifications and link them together. We'll be reusing the specifications created in Concordion - Execute on List and Concordion - Execute on Table chapters as System Specifications and Calculator Specifications."
},
{
"code": null,
"e": 56291,
"s": 56178,
"text": "Let us have a working Eclipse IDE in place and follow the steps given below to create a Concordion application −"
},
{
"code": null,
"e": 56333,
"s": 56291,
"text": "Here is the content of System.java file −"
},
{
"code": null,
"e": 56792,
"s": 56333,
"text": "package com.tutorialspoint;\nimport org.concordion.api.MultiValueResult;\n\npublic class System { \n public MultiValueResult split(String userName){ \n MultiValueResult result = new MultiValueResult();\n String[] words = userName.split(\" \"); \n result.with(\"firstName\", words[0]).with(\"lastName\", words[1]); \n return result;\n }\n\t\n public int sum(int firstNumber, int secondNumber) {\n return firstNumber + secondNumber;\n }\n}"
},
{
"code": null,
"e": 56846,
"s": 56792,
"text": "Following is the content of SystemFixture.java file −"
},
{
"code": null,
"e": 57241,
"s": 56846,
"text": "package specs.tutorialspoint;\n\nimport org.concordion.api.MultiValueResult;\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\nimport com.tutorialspoint.System;\n\n@RunWith(ConcordionRunner.class)\n\npublic class SystemFixture {\n System system = new System();\n public MultiValueResult split(String userName){\n return system.split(userName);\n } \n}"
},
{
"code": null,
"e": 57299,
"s": 57241,
"text": "Following is the content of CalculatorFixture.java file −"
},
{
"code": null,
"e": 57671,
"s": 57299,
"text": "package specs.tutorialspoint;\n\nimport org.concordion.integration.junit4.ConcordionRunner;\nimport org.junit.runner.RunWith;\nimport com.tutorialspoint.System;\n\n@RunWith(ConcordionRunner.class)\n\npublic class CalculatorFixture {\n System system = new System();\n public int sum(int firstNumber, int secondNumber) {\n return system.sum(firstNumber, secondNumber);\n }\n}"
},
{
"code": null,
"e": 57718,
"s": 57671,
"text": "Following is the content of System.html file −"
},
{
"code": null,
"e": 59281,
"s": 57718,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <h1>System Specifications</h1>\n <p>We are building specifications for our online \n order tracking application.</p>\n <p>Following is the requirement to split full name of a \n logged in user to its constituents by splitting name by whitespace:</p>\n\t\t\n <div class = \"example\"> \n <h3>Example</h3>\n\t\t\t\n <ul>\n <li>The full name <span concordion:execute = \"#result = split(#TEXT)\">\n Robert De</span> is to be splited as\n <ul>\n <li><span concordion:assertEquals = \"#result.firstName\">\n Robert</span></li>\n <li><span concordion:assertEquals = \"#result.lastName\">\n De</span></li>\n </ul>\n </li>\n \n <li>The full name <span concordion:execute = \"#result = split(#TEXT)\">\n John Diere</span> is to be splited as\n <ul>\n <li><span concordion:assertEquals = \"#result.firstName\">\n John</span></li>\n <li><span concordion:assertEquals = \"#result.lastName\">\n Diere</span></li>\n </ul>\n </li>\n \n </ul>\n </div>\n \n <a concordion:run = \"concordion\" href = \"Calculator.html\">\n Calculator Service Specifications</a>\n </body>\n\n</html>"
},
{
"code": null,
"e": 59332,
"s": 59281,
"text": "Following is the content of Calculator.html file −"
},
{
"code": null,
"e": 60519,
"s": 59332,
"text": "<html xmlns:concordion = \"http://www.concordion.org/2007/concordion\">\n <head>\n <link href = \"../concordion.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <h1>Calculator Specifications</h1>\n <p>We are building online calculator support in our website.</p>\n <p>Following is the requirement to add two numbers:</p>\n\t\t\n <div class = \"example\">\n <h3>Example</h3>\n\t\t\n <table>\n <tr>\n <th>First Number</th>\n <th>Second Number</th>\n <th>Sum</th>\n </tr>\n <tr concordion:execute = \"#result = sum(#firstNumber, #secondNumber)\">\n <td concordion:set = \"#firstNumber\">2</td>\n <td concordion:set = \"#secondNumber\">3</td>\n <td concordion:assertEquals = \"#result\">5</td>\n </tr>\n <tr concordion:execute = \"#result = sum(#firstNumber, #secondNumber)\">\n <td concordion:set = \"#firstNumber\">4</td>\n <td concordion:set = \"#secondNumber\">5</td>\n <td concordion:assertEquals = \"#result\">9</td>\n </tr>\n </table>\n \n </div>\n </body>\n\n</html>"
},
{
"code": null,
"e": 60714,
"s": 60519,
"text": "Once you are done with creating source and specification files, let us run the application as JUnit Test. If everything is fine with your application, then it will produce the following result −"
},
{
"code": null,
"e": 60925,
"s": 60714,
"text": "C:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 2, Failures: 0\nC:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp\\concordion\\specs\\tutorialspoint\\System.html\nSuccesses: 6, Failures: 0\n"
},
{
"code": null,
"e": 60975,
"s": 60925,
"text": "System.html is the output of Concordion test run."
},
{
"code": null,
"e": 61064,
"s": 60975,
"text": "Click on the link Calculator Service Specifications. You will see the following output −"
},
{
"code": null,
"e": 61071,
"s": 61064,
"text": " Print"
},
{
"code": null,
"e": 61082,
"s": 61071,
"text": " Add Notes"
}
]
|
How to add a vector to each row of a matrix in R? | To add a vector to reach row of a matrix, we can use addition sign (+) and create the repetition of the vector up to the number of rows in the matrix. For example, if we have a matrix called M then a vector say v can be added to each row of M by using the command −
M+rep(v,each=nrow(M))
Consider the below matrix and the vector −
Live Demo
> M1<-matrix(rpois(40,2),nrow=20)
> M1
[,1] [,2]
[1,] 3 2
[2,] 3 3
[3,] 4 2
[4,] 5 1
[5,] 3 1
[6,] 2 2
[7,] 1 2
[8,] 2 1
[9,] 3 2
[10,] 0 1
[11,] 3 4
[12,] 2 6
[13,] 3 1
[14,] 4 0
[15,] 1 3
[16,] 1 0
[17,] 1 1
[18,] 0 1
[19,] 1 3
[20,] 2 0
Adding v1 to rows in M1 −
> M1+rep(v1,each=nrow(M1))
[,1] [,2]
[1,] 4 3
[2,] 4 4
[3,] 5 3
[4,] 6 2
[5,] 4 2
[6,] 3 3
[7,] 2 3
[8,] 3 2
[9,] 4 3
[10,] 1 2
[11,] 4 5
[12,] 3 7
[13,] 4 2
[14,] 5 1
[15,] 2 4
[16,] 2 1
[17,] 2 2
[18,] 1 2
[19,] 2 4
[20,] 3 1
Live Demo
> M2<-matrix(rnorm(60),ncol=3)
> M2
[,1] [,2] [,3]
[1,] -1.16459899 0.04276452 -0.38747561
[2,] 0.50198231 1.40818681 1.34047754
[3,] -0.83571273 0.15311835 -0.66026732
[4,] -1.04751005 0.68401101 0.36614494
[5,] -0.13906013 -0.08104307 1.58938567
[6,] 0.79923477 0.13871823 1.19483957
[7,] -0.70957734 -1.22610985 0.79431236
[8,] -0.61919335 -1.67900016 0.75673298
[9,] 0.02131366 0.59198453 -0.51860397
[10,] -0.92114971 -0.94043054 -0.66674705
[11,] -0.26933585 0.61537773 1.18988144
[12,] 2.11994998 -0.62014441 -0.97012363
[13,] -0.45798423 0.92096389 0.74603167
[14,] -0.51599135 -0.01450992 -1.84365984
[15,] -0.29866554 0.99900886 -0.55598877
[16,] -0.91226758 -1.63915166 -0.20200339
[17,] 0.40107684 1.79162856 -0.02759807
[18,] 0.44712300 -0.07322323 -0.15221520
[19,] 0.15838286 -1.50611267 -0.07117655
[20,] 0.53166819 -0.99748658 -0.54070065
> v2<-c(100,100,100)
Adding v2 to rows in M2 −
> M2+rep(v2,each=nrow(M2))
[,1] [,2] [,3]
[1,] 98.83540 100.04276 99.61252
[2,] 100.50198 101.40819 101.34048
[3,] 99.16429 100.15312 99.33973
[4,] 98.95249 100.68401 100.36614
[5,] 99.86094 99.91896 101.58939
[6,] 100.79923 100.13872 101.19484
[7,] 99.29042 98.77389 100.79431
[8,] 99.38081 98.32100 100.75673
[9,] 100.02131 100.59198 99.48140
[10,] 99.07885 99.05957 99.33325
[11,] 99.73066 100.61538 101.18988
[12,] 102.11995 99.37986 99.02988
[13,] 99.54202 100.92096 100.74603
[14,] 99.48401 99.98549 98.15634
[15,] 99.70133 100.99901 99.44401
[16,] 99.08773 98.36085 99.79800
[17,] 100.40108 101.79163 99.97240
[18,] 100.44712 99.92678 99.84778
[19,] 100.15838 98.49389 99.92882
[20,] 100.53167 99.00251 99.45930 | [
{
"code": null,
"e": 1328,
"s": 1062,
"text": "To add a vector to reach row of a matrix, we can use addition sign (+) and create the repetition of the vector up to the number of rows in the matrix. For example, if we have a matrix called M then a vector say v can be added to each row of M by using the command −"
},
{
"code": null,
"e": 1350,
"s": 1328,
"text": "M+rep(v,each=nrow(M))"
},
{
"code": null,
"e": 1393,
"s": 1350,
"text": "Consider the below matrix and the vector −"
},
{
"code": null,
"e": 1403,
"s": 1393,
"text": "Live Demo"
},
{
"code": null,
"e": 1442,
"s": 1403,
"text": "> M1<-matrix(rpois(40,2),nrow=20)\n> M1"
},
{
"code": null,
"e": 1778,
"s": 1442,
"text": " [,1] [,2]\n [1,] 3 2\n [2,] 3 3\n [3,] 4 2\n [4,] 5 1\n [5,] 3 1\n [6,] 2 2\n [7,] 1 2\n [8,] 2 1\n [9,] 3 2\n[10,] 0 1\n[11,] 3 4\n[12,] 2 6\n[13,] 3 1\n[14,] 4 0\n[15,] 1 3\n[16,] 1 0\n[17,] 1 1\n[18,] 0 1\n[19,] 1 3\n[20,] 2 0"
},
{
"code": null,
"e": 1804,
"s": 1778,
"text": "Adding v1 to rows in M1 −"
},
{
"code": null,
"e": 1831,
"s": 1804,
"text": "> M1+rep(v1,each=nrow(M1))"
},
{
"code": null,
"e": 2167,
"s": 1831,
"text": " [,1] [,2]\n [1,] 4 3\n [2,] 4 4\n [3,] 5 3\n [4,] 6 2\n [5,] 4 2\n [6,] 3 3\n [7,] 2 3\n [8,] 3 2\n [9,] 4 3\n[10,] 1 2\n[11,] 4 5\n[12,] 3 7\n[13,] 4 2\n[14,] 5 1\n[15,] 2 4\n[16,] 2 1\n[17,] 2 2\n[18,] 1 2\n[19,] 2 4\n[20,] 3 1"
},
{
"code": null,
"e": 2177,
"s": 2167,
"text": "Live Demo"
},
{
"code": null,
"e": 2213,
"s": 2177,
"text": "> M2<-matrix(rnorm(60),ncol=3)\n> M2"
},
{
"code": null,
"e": 3116,
"s": 2213,
"text": " [,1] [,2] [,3]\n [1,] -1.16459899 0.04276452 -0.38747561\n [2,] 0.50198231 1.40818681 1.34047754\n [3,] -0.83571273 0.15311835 -0.66026732\n [4,] -1.04751005 0.68401101 0.36614494\n [5,] -0.13906013 -0.08104307 1.58938567\n [6,] 0.79923477 0.13871823 1.19483957\n [7,] -0.70957734 -1.22610985 0.79431236\n [8,] -0.61919335 -1.67900016 0.75673298\n [9,] 0.02131366 0.59198453 -0.51860397\n[10,] -0.92114971 -0.94043054 -0.66674705\n[11,] -0.26933585 0.61537773 1.18988144\n[12,] 2.11994998 -0.62014441 -0.97012363\n[13,] -0.45798423 0.92096389 0.74603167\n[14,] -0.51599135 -0.01450992 -1.84365984\n[15,] -0.29866554 0.99900886 -0.55598877\n[16,] -0.91226758 -1.63915166 -0.20200339\n[17,] 0.40107684 1.79162856 -0.02759807\n[18,] 0.44712300 -0.07322323 -0.15221520\n[19,] 0.15838286 -1.50611267 -0.07117655\n[20,] 0.53166819 -0.99748658 -0.54070065\n> v2<-c(100,100,100)"
},
{
"code": null,
"e": 3142,
"s": 3116,
"text": "Adding v2 to rows in M2 −"
},
{
"code": null,
"e": 3169,
"s": 3142,
"text": "> M2+rep(v2,each=nrow(M2))"
},
{
"code": null,
"e": 3925,
"s": 3169,
"text": " [,1] [,2] [,3]\n [1,] 98.83540 100.04276 99.61252\n [2,] 100.50198 101.40819 101.34048\n [3,] 99.16429 100.15312 99.33973\n [4,] 98.95249 100.68401 100.36614\n [5,] 99.86094 99.91896 101.58939\n [6,] 100.79923 100.13872 101.19484\n [7,] 99.29042 98.77389 100.79431\n [8,] 99.38081 98.32100 100.75673\n [9,] 100.02131 100.59198 99.48140\n[10,] 99.07885 99.05957 99.33325\n[11,] 99.73066 100.61538 101.18988\n[12,] 102.11995 99.37986 99.02988\n[13,] 99.54202 100.92096 100.74603\n[14,] 99.48401 99.98549 98.15634\n[15,] 99.70133 100.99901 99.44401\n[16,] 99.08773 98.36085 99.79800\n[17,] 100.40108 101.79163 99.97240\n[18,] 100.44712 99.92678 99.84778\n[19,] 100.15838 98.49389 99.92882\n[20,] 100.53167 99.00251 99.45930"
}
]
|
Count of n digit numbers whose sum of digits equals to given sum in C++ | Given a positive number as the number of digits and a sum. The goal is to find all d digit numbers that have sum of digits equal to the input sum. The numbers having leading zeros will not be considered as d digit numbers.
The ranges are digits between 1 to 100 and sum between 1 and 500.
For Example
Input - digits = 3, digi_sum = 3
Output - Count of n digit numbers whose sum of digits equals to given sum are: 6
Explanation - Three digit numbers having sum of digits as 3 are:
102, 111, 120, 201, 210, and 300.
Input - digits = 4 digi_sum = 2
Output - Count of n digit numbers whose sum of digits equals to given sum are: 4
Explanation - Four digit numbers having sum of digits as 2 are :
1001, 1010, 1100, and 2000.
In this approach we will traverse from the first d digit number and find the first number whose sum of digits is equal to the given sum. Then increment numbers by 9 until we find the sum of digits more than the given sum. Once a number having digit sum greater than input sum is found then increment the number by 1 and find the next number with sum as input sum. Repeat this process till the last d digit number.
Take the number of digits and sum of digits as input.
Function digits_sum(int digits, int digi_sum) takes both input values and returns the count of n digit numbers whose sum of digits equals a given sum.
Take the initial count as 0.
Take the first number as Left = pow(10, digits - 1). And the last number of the range as right = pow(10, digits) - 1 ( i.e 10 and 99 for digits=2 ).
Using a while loop traverse from left to right.
Take first=0 and last=i.
For each i ( last ), take the rightmost digit ( last % 10 ) and add to first. Reduce last by 10 for the next iteration.
If first becomes equal to digi_sum then increment count and update i by 9 for next iteration.
Otherwise increment i by 1.
At the end of all loops we will have count as numbers that have digit sum equal to digi_sum.
Return count as result.
Live Demo
#include <bits/stdc++.h>
using namespace std;
int digits_sum(int digits, int digi_sum) {
int count = 0;
int Left = pow(10, digits - 1);
int right = pow(10, digits) - 1;
int i = Left;
while (i <= right) {
int first = 0;
int last = i;
while (last != 0) {
first = first + last % 10;
last = last / 10;
}
if (first == digi_sum) {
count++;
i = i + 9;
} else {
i++;
}
}
return count;
}
int main() {
int digits = 5;
int digi_sum = 7;
cout << "Count of n digit numbers whose sum of digits equals to given sum are: " << digits_sum(digits, digi_sum);
return 0;
}
If we run the above code it will generate the following output −
Count of n digit numbers whose sum of digits equals to given sum are: 5 | [
{
"code": null,
"e": 1285,
"s": 1062,
"text": "Given a positive number as the number of digits and a sum. The goal is to find all d digit numbers that have sum of digits equal to the input sum. The numbers having leading zeros will not be considered as d digit numbers."
},
{
"code": null,
"e": 1351,
"s": 1285,
"text": "The ranges are digits between 1 to 100 and sum between 1 and 500."
},
{
"code": null,
"e": 1363,
"s": 1351,
"text": "For Example"
},
{
"code": null,
"e": 1396,
"s": 1363,
"text": "Input - digits = 3, digi_sum = 3"
},
{
"code": null,
"e": 1477,
"s": 1396,
"text": "Output - Count of n digit numbers whose sum of digits equals to given sum are: 6"
},
{
"code": null,
"e": 1542,
"s": 1477,
"text": "Explanation - Three digit numbers having sum of digits as 3 are:"
},
{
"code": null,
"e": 1577,
"s": 1542,
"text": "102, 111, 120, 201, 210, and 300. "
},
{
"code": null,
"e": 1611,
"s": 1577,
"text": "Input - digits = 4 digi_sum = 2"
},
{
"code": null,
"e": 1692,
"s": 1611,
"text": "Output - Count of n digit numbers whose sum of digits equals to given sum are: 4"
},
{
"code": null,
"e": 1757,
"s": 1692,
"text": "Explanation - Four digit numbers having sum of digits as 2 are :"
},
{
"code": null,
"e": 1785,
"s": 1757,
"text": "1001, 1010, 1100, and 2000."
},
{
"code": null,
"e": 2199,
"s": 1785,
"text": "In this approach we will traverse from the first d digit number and find the first number whose sum of digits is equal to the given sum. Then increment numbers by 9 until we find the sum of digits more than the given sum. Once a number having digit sum greater than input sum is found then increment the number by 1 and find the next number with sum as input sum. Repeat this process till the last d digit number."
},
{
"code": null,
"e": 2253,
"s": 2199,
"text": "Take the number of digits and sum of digits as input."
},
{
"code": null,
"e": 2404,
"s": 2253,
"text": "Function digits_sum(int digits, int digi_sum) takes both input values and returns the count of n digit numbers whose sum of digits equals a given sum."
},
{
"code": null,
"e": 2433,
"s": 2404,
"text": "Take the initial count as 0."
},
{
"code": null,
"e": 2583,
"s": 2433,
"text": "Take the first number as Left = pow(10, digits - 1). And the last number of the range as right = pow(10, digits) - 1 ( i.e 10 and 99 for digits=2 )."
},
{
"code": null,
"e": 2631,
"s": 2583,
"text": "Using a while loop traverse from left to right."
},
{
"code": null,
"e": 2656,
"s": 2631,
"text": "Take first=0 and last=i."
},
{
"code": null,
"e": 2776,
"s": 2656,
"text": "For each i ( last ), take the rightmost digit ( last % 10 ) and add to first. Reduce last by 10 for the next iteration."
},
{
"code": null,
"e": 2870,
"s": 2776,
"text": "If first becomes equal to digi_sum then increment count and update i by 9 for next iteration."
},
{
"code": null,
"e": 2898,
"s": 2870,
"text": "Otherwise increment i by 1."
},
{
"code": null,
"e": 2991,
"s": 2898,
"text": "At the end of all loops we will have count as numbers that have digit sum equal to digi_sum."
},
{
"code": null,
"e": 3015,
"s": 2991,
"text": "Return count as result."
},
{
"code": null,
"e": 3025,
"s": 3015,
"text": "Live Demo"
},
{
"code": null,
"e": 3698,
"s": 3025,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint digits_sum(int digits, int digi_sum) {\n int count = 0;\n int Left = pow(10, digits - 1);\n int right = pow(10, digits) - 1;\n int i = Left;\n while (i <= right) {\n int first = 0;\n int last = i;\n while (last != 0) {\n first = first + last % 10;\n last = last / 10;\n }\n if (first == digi_sum) {\n count++;\n i = i + 9;\n } else {\n i++;\n }\n }\n return count;\n}\nint main() {\n int digits = 5;\n int digi_sum = 7;\n cout << \"Count of n digit numbers whose sum of digits equals to given sum are: \" << digits_sum(digits, digi_sum);\n return 0;\n}"
},
{
"code": null,
"e": 3763,
"s": 3698,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3835,
"s": 3763,
"text": "Count of n digit numbers whose sum of digits equals to given sum are: 5"
}
]
|
Construct an array from XOR of all elements of array except element at same index - GeeksforGeeks | 08 Mar, 2021
Given an array A[] having n positive elements. The task to create another array B[] such as B[i] is XOR of all elements of array A[] except A[i].Examples :
Input : A[] = {2, 1, 5, 9}
Output : B[] = {13, 14, 10, 6}
Input : A[] = {2, 1, 3, 6}
Output : B[] = {4, 7, 5, 0}
Naive Approach : We can simple calculate B[i] as XOR of all elements of A[] except A[i], as
for (int i = 0; i < n; i++)
{
B[i] = 0;
for (int j = 0; j < n; j++)
if ( i != j)
B[i] ^= A[j];
}
Time complexity for this naive approach is O (n^2). Auxiliary Space for this naive approach is O (n).Optimized Approach : First calculate XOR of all elements of array A[] say ‘xor’, and for each element of array A[] calculate A[i] = xor ^ A[i] .
int xor = 0;
for (int i = 0; i < n; i++)
xor ^= A[i];
for (int i = 0; i < n; i++)
A[i] = xor ^ A[i];
Time complexity for this approach is O (n). Auxiliary Space for this approach is O (1).
C++
Java
Python3
C#
PHP
Javascript
// C++ program to construct array from// XOR of elements of given array#include <bits/stdc++.h>using namespace std; // function to construct new arrayvoid constructXOR(int A[], int n){ // calculate xor of array int XOR = 0; for (int i = 0; i < n; i++) XOR ^= A[i]; // update array for (int i = 0; i < n; i++) A[i] = XOR ^ A[i];} // Driver codeint main(){ int A[] = { 2, 4, 1, 3, 5}; int n = sizeof(A) / sizeof(A[0]); constructXOR(A, n); // print result for (int i = 0; i < n; i++) cout << A[i] << " "; return 0;}
// Java program to construct array from// XOR of elements of given arrayclass GFG{ // function to construct new array static void constructXOR(int A[], int n) { // calculate xor of array int XOR = 0; for (int i = 0; i < n; i++) XOR ^= A[i]; // update array for (int i = 0; i < n; i++) A[i] = XOR ^ A[i]; } // Driver code public static void main(String[] args) { int A[] = { 2, 4, 1, 3, 5}; int n = A.length; constructXOR(A, n); // print result for (int i = 0; i < n; i++) System.out.print(A[i] + " "); }} // This code is contributed by Anant Agarwal.
# Python 3 program to construct# array from XOR of elements# of given array # function to construct new arraydef constructXOR(A, n): # calculate xor of array XOR = 0 for i in range(0, n): XOR ^= A[i] # update array for i in range(0, n): A[i] = XOR ^ A[i] # Driver codeA = [ 2, 4, 1, 3, 5 ]n = len(A)constructXOR(A, n) # print resultfor i in range(0,n): print(A[i], end =" ") # This code is contributed by Smitha Dinesh Semwal
// C# program to construct array from// XOR of elements of given arrayusing System; class GFG{ // function to construct new array static void constructXOR(int []A, int n) { // calculate xor of array int XOR = 0; for (int i = 0; i < n; i++) XOR ^= A[i]; // update array for (int i = 0; i < n; i++) A[i] = XOR ^ A[i]; } // Driver code public static void Main() { int []A = { 2, 4, 1, 3, 5}; int n = A.Length; constructXOR(A, n); // print result for (int i = 0; i < n; i++) Console.Write(A[i] + " "); }} // This code is contributed by nitin mittal
<?php// Program to construct array from// XOR of elements of given array // function to construct new arrayfunction constructXOR(&$A, $n){ // calculate xor of array $XOR = 0; for ($i = 0; $i < $n; $i++) $XOR ^= $A[$i]; // update array for ($i = 0; $i < $n; $i++) $A[$i] = $XOR ^ $A[$i];} // Driver code$A = array( 2, 4, 1, 3, 5);$n = sizeof($A);constructXOR($A, $n); // print resultfor ($i = 0; $i < $n; $i++) echo $A[$i] ." "; // This code is contributed// by ChitraNayal?>
<script> // JavaScript program to construct array from// XOR of elements of given array // function to construct new arrayfunction constructXOR(A, n){ // calculate xor of array let XOR = 0; for (let i = 0; i < n; i++) XOR ^= A[i]; // update array for (let i = 0; i < n; i++) A[i] = XOR ^ A[i];} // Driver code let A = [ 2, 4, 1, 3, 5]; let n = A.length; constructXOR(A, n); // print result for (let i = 0; i < n; i++) document.write(A[i] + " "); // This code is contributed by Surbhi Tyagi. </script>
Output:
3 5 0 2 4
Related Problem : A Product Array PuzzleThis article is contributed by Shivam Pradhan (anuj_charm). 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
ukasp
surbhityagi15
Bitwise-XOR
Arrays
Bit Magic
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
Cyclic Redundancy Check and Modulo-2 Division | [
{
"code": null,
"e": 25362,
"s": 25334,
"text": "\n08 Mar, 2021"
},
{
"code": null,
"e": 25520,
"s": 25362,
"text": "Given an array A[] having n positive elements. The task to create another array B[] such as B[i] is XOR of all elements of array A[] except A[i].Examples : "
},
{
"code": null,
"e": 25634,
"s": 25520,
"text": "Input : A[] = {2, 1, 5, 9}\nOutput : B[] = {13, 14, 10, 6}\n\nInput : A[] = {2, 1, 3, 6}\nOutput : B[] = {4, 7, 5, 0}"
},
{
"code": null,
"e": 25730,
"s": 25636,
"text": "Naive Approach : We can simple calculate B[i] as XOR of all elements of A[] except A[i], as "
},
{
"code": null,
"e": 25855,
"s": 25730,
"text": "for (int i = 0; i < n; i++)\n{\n B[i] = 0;\n for (int j = 0; j < n; j++)\n if ( i != j)\n B[i] ^= A[j];\n}"
},
{
"code": null,
"e": 26103,
"s": 25855,
"text": "Time complexity for this naive approach is O (n^2). Auxiliary Space for this naive approach is O (n).Optimized Approach : First calculate XOR of all elements of array A[] say ‘xor’, and for each element of array A[] calculate A[i] = xor ^ A[i] . "
},
{
"code": null,
"e": 26217,
"s": 26103,
"text": "int xor = 0;\nfor (int i = 0; i < n; i++)\n xor ^= A[i];\n\nfor (int i = 0; i < n; i++)\n A[i] = xor ^ A[i];"
},
{
"code": null,
"e": 26307,
"s": 26217,
"text": "Time complexity for this approach is O (n). Auxiliary Space for this approach is O (1). "
},
{
"code": null,
"e": 26311,
"s": 26307,
"text": "C++"
},
{
"code": null,
"e": 26316,
"s": 26311,
"text": "Java"
},
{
"code": null,
"e": 26324,
"s": 26316,
"text": "Python3"
},
{
"code": null,
"e": 26327,
"s": 26324,
"text": "C#"
},
{
"code": null,
"e": 26331,
"s": 26327,
"text": "PHP"
},
{
"code": null,
"e": 26342,
"s": 26331,
"text": "Javascript"
},
{
"code": "// C++ program to construct array from// XOR of elements of given array#include <bits/stdc++.h>using namespace std; // function to construct new arrayvoid constructXOR(int A[], int n){ // calculate xor of array int XOR = 0; for (int i = 0; i < n; i++) XOR ^= A[i]; // update array for (int i = 0; i < n; i++) A[i] = XOR ^ A[i];} // Driver codeint main(){ int A[] = { 2, 4, 1, 3, 5}; int n = sizeof(A) / sizeof(A[0]); constructXOR(A, n); // print result for (int i = 0; i < n; i++) cout << A[i] << \" \"; return 0;}",
"e": 26911,
"s": 26342,
"text": null
},
{
"code": "// Java program to construct array from// XOR of elements of given arrayclass GFG{ // function to construct new array static void constructXOR(int A[], int n) { // calculate xor of array int XOR = 0; for (int i = 0; i < n; i++) XOR ^= A[i]; // update array for (int i = 0; i < n; i++) A[i] = XOR ^ A[i]; } // Driver code public static void main(String[] args) { int A[] = { 2, 4, 1, 3, 5}; int n = A.length; constructXOR(A, n); // print result for (int i = 0; i < n; i++) System.out.print(A[i] + \" \"); }} // This code is contributed by Anant Agarwal.",
"e": 27618,
"s": 26911,
"text": null
},
{
"code": "# Python 3 program to construct# array from XOR of elements# of given array # function to construct new arraydef constructXOR(A, n): # calculate xor of array XOR = 0 for i in range(0, n): XOR ^= A[i] # update array for i in range(0, n): A[i] = XOR ^ A[i] # Driver codeA = [ 2, 4, 1, 3, 5 ]n = len(A)constructXOR(A, n) # print resultfor i in range(0,n): print(A[i], end =\" \") # This code is contributed by Smitha Dinesh Semwal",
"e": 28082,
"s": 27618,
"text": null
},
{
"code": "// C# program to construct array from// XOR of elements of given arrayusing System; class GFG{ // function to construct new array static void constructXOR(int []A, int n) { // calculate xor of array int XOR = 0; for (int i = 0; i < n; i++) XOR ^= A[i]; // update array for (int i = 0; i < n; i++) A[i] = XOR ^ A[i]; } // Driver code public static void Main() { int []A = { 2, 4, 1, 3, 5}; int n = A.Length; constructXOR(A, n); // print result for (int i = 0; i < n; i++) Console.Write(A[i] + \" \"); }} // This code is contributed by nitin mittal",
"e": 28779,
"s": 28082,
"text": null
},
{
"code": "<?php// Program to construct array from// XOR of elements of given array // function to construct new arrayfunction constructXOR(&$A, $n){ // calculate xor of array $XOR = 0; for ($i = 0; $i < $n; $i++) $XOR ^= $A[$i]; // update array for ($i = 0; $i < $n; $i++) $A[$i] = $XOR ^ $A[$i];} // Driver code$A = array( 2, 4, 1, 3, 5);$n = sizeof($A);constructXOR($A, $n); // print resultfor ($i = 0; $i < $n; $i++) echo $A[$i] .\" \"; // This code is contributed// by ChitraNayal?>",
"e": 29287,
"s": 28779,
"text": null
},
{
"code": "<script> // JavaScript program to construct array from// XOR of elements of given array // function to construct new arrayfunction constructXOR(A, n){ // calculate xor of array let XOR = 0; for (let i = 0; i < n; i++) XOR ^= A[i]; // update array for (let i = 0; i < n; i++) A[i] = XOR ^ A[i];} // Driver code let A = [ 2, 4, 1, 3, 5]; let n = A.length; constructXOR(A, n); // print result for (let i = 0; i < n; i++) document.write(A[i] + \" \"); // This code is contributed by Surbhi Tyagi. </script>",
"e": 29841,
"s": 29287,
"text": null
},
{
"code": null,
"e": 29850,
"s": 29841,
"text": "Output: "
},
{
"code": null,
"e": 29860,
"s": 29850,
"text": "3 5 0 2 4"
},
{
"code": null,
"e": 30336,
"s": 29860,
"text": "Related Problem : A Product Array PuzzleThis article is contributed by Shivam Pradhan (anuj_charm). 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": 30349,
"s": 30336,
"text": "nitin mittal"
},
{
"code": null,
"e": 30355,
"s": 30349,
"text": "ukasp"
},
{
"code": null,
"e": 30369,
"s": 30355,
"text": "surbhityagi15"
},
{
"code": null,
"e": 30381,
"s": 30369,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 30388,
"s": 30381,
"text": "Arrays"
},
{
"code": null,
"e": 30398,
"s": 30388,
"text": "Bit Magic"
},
{
"code": null,
"e": 30405,
"s": 30398,
"text": "Arrays"
},
{
"code": null,
"e": 30415,
"s": 30405,
"text": "Bit Magic"
},
{
"code": null,
"e": 30513,
"s": 30415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30581,
"s": 30513,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 30625,
"s": 30581,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 30657,
"s": 30625,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30680,
"s": 30657,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 30694,
"s": 30680,
"text": "Linear Search"
},
{
"code": null,
"e": 30721,
"s": 30694,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 30767,
"s": 30721,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 30835,
"s": 30767,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 30864,
"s": 30835,
"text": "Count set bits in an integer"
}
]
|
Rows or Columns — where should I put my index on? | by Nikola Ilic | Towards Data Science | Choosing the optimal indexing strategy for your SQL Server workloads is one of the most challenging tasks. As you probably know, indexes can dramatically improve the performance of your queries, but at the same time, they can cause additional overhead when it comes to maintenance.
In complete honesty, I would never call myself an expert on indexing. However, I wanted to share my experience from the recent project, as it opened a whole new perspective to me and I thought that it can be beneficial to others also.
First of all, up until a few months ago, I have never used Columnstore indexes, since the working environment in my company was based on SQL Server 2008R2. I’ve had theoretical knowledge about Columnstore indexes and I was aware of the difference between them and traditional B-Tree indexes, but I’ve never tried them in reality.
But, first things first...
As opposed to a rowstore type of data storage, which physically stores data in a row-wise format, columnstore operates on a columnar level of the table. It was first introduced with SQL Server 2012 and later improved with every newer version of SQL Server. While traditional rowstore indexes (I will refer them as B-tree indexes) store the key value of each row, so that the SQL Server engine can use this key to retrieve the row data, columnstore indexes store each table column separately!
The main reason for using the Columnstore index is its high compression! That brings significant gains in terms of memory footprint and, consequentially, better performance when used in a proper way.
There are really a lot of great resources on the web for learning about Columnstore indexes architecture, and Microsoft’s documentation is also quite comprehensive on this topic, but I wanted to show some real examples when the usage of Columnstore indexes makes sense.
Just to emphasize that I will use clustered columnstore indexes exclusively (non-clustered columnstore indexes are out of the scope of this article).
For all examples, I’m using the Stack Overflow database.
Let’s first run a few simple queries on our Posts table, which has slightly more than 17 million records, just to get a feeling about the data. At the very beginning, I don’t have any indexes on this table, except the clustered index on the primary key column.
My goal is to find all posts from the 1st half of the year 2010, with more than 3000 views:
SELECT * FROM dbo.Posts PWHERE CreationDate >= '20100101' AND CreationDate < '20100701' AND ViewCount > 3000
This query returned 88.547 rows and it took more than a minute to execute!
Since no index exists on this table, SQL Server had to scan a whole table to satisfy our request, performing around 4.2 million logical reads. Let’s help a little bit our poor SQL Server, and create a nonclustered index on the CreationDate column:
CREATE NONCLUSTERED INDEX [ix_creationDate] ON [dbo].[Posts]( [CreationDate] ASC)
Now, when I ran again exactly the same query, I’ve got back my results in 9 seconds, but the number of logical reads (5.6 million) suggests that this query is still far from being good. SQL Server is thankful for our new index since it was used to narrow down the scope for the initial search. However, selecting all columns is obviously not a good idea, as SQL Server had to pick up all other columns from the clustered index, performing an enormous number of random readings.
Now, the first question I would ask myself is: what data do I really need? Do I need Body, ClosedDate, LastEditDate, etc.? Ok, so I will rewrite the query to include only necessary columns:
SELECT P.Id AS PostId ,P.CreationDate ,P.OwnerUserId AS UserId ,P.Score ,P.ViewCountFROM dbo.Posts PWHERE P.CreationDate >= '20100101' AND P.CreationDate < '20100701' AND P.ViewCount > 3000
We are getting exactly the same execution plan, with less logical reads (4 million), since the amount of data that’s being returned was decreased.
SQL Server suggests creating an index on our predicate columns (columns in WHERE clause), and including remaining columns in the index. Let’s obey SQL Server’s wish and modify our index:
CREATE NONCLUSTERED INDEX [ix_creationDate_viewCount] ON [dbo].[Posts]( [CreationDate], [ViewCount])INCLUDE ([OwnerUserId],[Score])
Now, when I run my query, it executes in less than a second, performing only 3626 logical reads! Wow! So, we’ve created a nice “covering” index, which works perfectly for this query. I’ve intentionally bolded the part “for this query”, since we can’t create a covering index for every single query that runs against our database. Here, it’s fine for the demo purposes.
Ok, we couldn’t optimize the previous query more than we did. Let’s now see how will columnstore index performs.
The first step is to create a copy of dbo.Posts table, but instead of using the B-tree index, I will create a clustered columnstore index on this new table (dbo.Posts_CS).
CREATE CLUSTERED COLUMNSTORE INDEX cix_PostsON dbo.Posts_CS
First thing you may notice is the huuge difference in the memory footprint of these two identical tables:
So, a table with a clustered columnstore index on it consumes almost 4x less memory comparing to an original one with a B-tree index! If we also take non-clustered indexes into consideration, the difference only gets bigger. As I’ve already mentioned, data is much better compressed on the column level.
Now, let’s run exactly the same query on our newly created columnstore indexed table.
SELECT P.Id AS PostId ,P.CreationDate ,P.OwnerUserId AS UserId ,P.Score ,P.ViewCountFROM dbo.Posts_CS PWHERE P.CreationDate >= '20100101' AND P.CreationDate < '20100701' AND P.ViewCount > 3000
Data in columnstore index is stored in segments. So, depending on the data distribution within the table, SQL Server has to read more or fewer segments in order to retrieve the requested data.
As you can see in the above illustration, to return my 88.547 records, SQL Server went through 26 segments and skipped 72. That’s because the data in our columnstore index is not sorted in any specific order. We could sort it by, let’s say, CreationDate (assuming that most of our queries will use CreationDate as a predicate), and in that case performance should be even better, since SQL Server would exactly know in which segments to look for the data, and which could be skipped.
Now, let’s run both queries together and compare the query costs:
Traditional B-tree index seek has a cost of 3.7, while columnstore scan costs 10.7. Quite obvious, since we have a perfectly matching non-clustered index that covers all columns we need. Still, the difference is not so big.
But, let’s say that after some time we need to expand our output list and retrieve data for LastActivityDate. Let’s check what will happen:
Oops!!! By adding just one column, results completely changed in the favor of columnstore index. Now, B-tree non-clustered index doesn’t have all the necessary data and it needs to pick up LastActivityDate from the clustered index — that makes the cost of this query rise up to 236! On the other hand, columnstore index became slightly more expensive and now costs 14!
Of course, as you can notice in the picture above, SQL Server asks for another index (or existing ones to be expanded), but that’s what I stressed above — you shouldn’t blindly obey all of SQL Server wishes, or you will finish with “over-indexed” tables!
By definition, the area where columnstore indexes should excel is when running analytical queries. So, let’s check this on the following scenario: I want to retrieve the users who registered in the first half of the year 2010, posted in the years 2010 and 2011, and the user’s overall Reputation is greater than 3000 and respective posts have more than 3000 views...I also need to see the user’s Location and DisplayName. Sounds complicated, but it really isn’t:)
Here is the query:
SELECT U.Id ,U.Location ,U.DisplayName ,P.CreationDate ,P.Score ,P.ViewCountFROM dbo.Users U INNER JOIN dbo.Posts P ON U.Id = P.OwnerUserId WHERE U.CreationDate >= '20100101' AND U.CreationDate < '20100701' AND U.Reputation > 3000 AND P.ViewCount > 3000 AND P.CreationDate >= '20100101' AND P.CreationDate < '20120101'
The query returns 37.332 rows and we want to help SQL Server a little bit, by creating a non-clustered index on the CreationDate column in the Users table.
CREATE NONCLUSTERED INDEX [ix_creationDate] ON [dbo].[Users]( [CreationDate])
When I run the query, SQL Server comes with the following execution plan:
Since our index doesn’t cover all the necessary columns, SQL Server assumes that it’s cheaper to perform a scan on the Users table, instead of doing Index Seek and then expensive key lookups. This query costs 58.4.
Now, I will create a copy of the Users table (Users_CS) and create a clustered columnstore index on it:
CREATE CLUSTERED COLUMNSTORE INDEX cix_UsersON dbo.Users_CS
Let’s now run bot of our queries at the same time and compare the performance:
Again, the table with columnstore index on it easily outperforms the original one with the B-tree index. The cost of the second query is 9.2! And keep in mind that we didn’t even optimize the columnstore index itself (we were not sorting the data during the insertion)!
One last example comes from my real project, where we were comparing performance between columnstore and B-tree indexes on our actual workload. The query itself is so simple: I want to summarize total deposits per every single customer between January 1st and end of July this year:
SELECT customerID ,SUM(amount) totalFROM factDepositWHERE isSuccessful = 1 AND datetm >='20200101' AND datetm < '20200801'GROUP BY customerIDSELECT customerID ,SUM(amount) totalFROM factDeposit_csWHERE isSuccessful = 1 AND datetm >='20200101' AND datetm < '20200801'GROUP BY customerID
And here are the results:
Again, columnstore index convincingly “wins” with 4.6 vs 26 query cost!
Before you fall into the trap of concluding that traditional B-tree indexes aren’t needed anymore, you should ask yourself: where is the catch? And the catch is obviously there since B-tree indexes are still heavily used in most of the databases.
The biggest downside of the columnstore indexes is UPDATE/DELETE operations. Deleted records are not really deleted — they are just flagged as deleted, but they still remain part of the columnstore index, until the index is rebuilt. Updates perform even worse since they are being executed as two consecutive actions: delete and then insert...Inserts “per se” are not an issue, because SQL Server keeps them in the structure called Deltastore (which, by the way, has B-tree structure), and performs a bulk load into the columnstore index.
Therefore, if you are often performing updates and/or deletes, be aware that you will not extract maximum benefit from the columnstore index.
So, the right question should be:
The answer is, as in 99% cases within SQL Server debates — IT DEPENDS!
The key challenge is to identify the scenario, or better say the workload, that suits best to the usage of columnstore vs rowstore indexes.
Here are some recommendations for best practice usage for each of the index types:
Use columnstore indexes on large tables (with at least a few million records), that are not being updated/deleted frequently
Columnstore indexes perform best on static data, such as in OLAP workloads, with a lot of queries that simply reads the data from the tables, or bulk loading new data periodically
Columnstore indexes excel in scanning and performing aggregations on big data ranges (doing SUM, AVG, COUNT, etc), because they are able to process around 900 rows in one batch, while traditional B-tree index process one-by-one (up until SQL Server 2019, which added a batch mode for row-based workload)
Use B-tree indexes on highly transactional workloads, when your table is being frequently modified (updates, deletes, inserts)
B-tree indexes will usually perform better in queries with high selectivity, for example, when you are returning a single value or small number of values, or if you are querying a small range of values (SEEKing for a value)
To say that you should use columnstore indexes in OLAP workloads while using B-tree indexes in OLTP environment, will be huge oversimplifying. In order to get the proper answer to this question, you should ask yourself: what kind of queries are mostly used for the specific table? As soon as you get the answer to this question, you will be able to define the proper indexing strategy for your own workload.
And, finally, in case you wonder if you can take the best from both worlds: the answer is — YES! Starting from SQL Server 2016, you can combine columnstore and traditional B-tree indexes on the same table!
That’s, however, a separate and complex topic that requires serious planning and various considerations, which is out of the scope of this article.
Thanks for reading! | [
{
"code": null,
"e": 454,
"s": 172,
"text": "Choosing the optimal indexing strategy for your SQL Server workloads is one of the most challenging tasks. As you probably know, indexes can dramatically improve the performance of your queries, but at the same time, they can cause additional overhead when it comes to maintenance."
},
{
"code": null,
"e": 689,
"s": 454,
"text": "In complete honesty, I would never call myself an expert on indexing. However, I wanted to share my experience from the recent project, as it opened a whole new perspective to me and I thought that it can be beneficial to others also."
},
{
"code": null,
"e": 1019,
"s": 689,
"text": "First of all, up until a few months ago, I have never used Columnstore indexes, since the working environment in my company was based on SQL Server 2008R2. I’ve had theoretical knowledge about Columnstore indexes and I was aware of the difference between them and traditional B-Tree indexes, but I’ve never tried them in reality."
},
{
"code": null,
"e": 1046,
"s": 1019,
"text": "But, first things first..."
},
{
"code": null,
"e": 1538,
"s": 1046,
"text": "As opposed to a rowstore type of data storage, which physically stores data in a row-wise format, columnstore operates on a columnar level of the table. It was first introduced with SQL Server 2012 and later improved with every newer version of SQL Server. While traditional rowstore indexes (I will refer them as B-tree indexes) store the key value of each row, so that the SQL Server engine can use this key to retrieve the row data, columnstore indexes store each table column separately!"
},
{
"code": null,
"e": 1738,
"s": 1538,
"text": "The main reason for using the Columnstore index is its high compression! That brings significant gains in terms of memory footprint and, consequentially, better performance when used in a proper way."
},
{
"code": null,
"e": 2008,
"s": 1738,
"text": "There are really a lot of great resources on the web for learning about Columnstore indexes architecture, and Microsoft’s documentation is also quite comprehensive on this topic, but I wanted to show some real examples when the usage of Columnstore indexes makes sense."
},
{
"code": null,
"e": 2158,
"s": 2008,
"text": "Just to emphasize that I will use clustered columnstore indexes exclusively (non-clustered columnstore indexes are out of the scope of this article)."
},
{
"code": null,
"e": 2215,
"s": 2158,
"text": "For all examples, I’m using the Stack Overflow database."
},
{
"code": null,
"e": 2476,
"s": 2215,
"text": "Let’s first run a few simple queries on our Posts table, which has slightly more than 17 million records, just to get a feeling about the data. At the very beginning, I don’t have any indexes on this table, except the clustered index on the primary key column."
},
{
"code": null,
"e": 2568,
"s": 2476,
"text": "My goal is to find all posts from the 1st half of the year 2010, with more than 3000 views:"
},
{
"code": null,
"e": 2683,
"s": 2568,
"text": "SELECT * FROM dbo.Posts PWHERE CreationDate >= '20100101' AND CreationDate < '20100701' AND ViewCount > 3000"
},
{
"code": null,
"e": 2758,
"s": 2683,
"text": "This query returned 88.547 rows and it took more than a minute to execute!"
},
{
"code": null,
"e": 3006,
"s": 2758,
"text": "Since no index exists on this table, SQL Server had to scan a whole table to satisfy our request, performing around 4.2 million logical reads. Let’s help a little bit our poor SQL Server, and create a nonclustered index on the CreationDate column:"
},
{
"code": null,
"e": 3091,
"s": 3006,
"text": "CREATE NONCLUSTERED INDEX [ix_creationDate] ON [dbo].[Posts]( [CreationDate] ASC)"
},
{
"code": null,
"e": 3569,
"s": 3091,
"text": "Now, when I ran again exactly the same query, I’ve got back my results in 9 seconds, but the number of logical reads (5.6 million) suggests that this query is still far from being good. SQL Server is thankful for our new index since it was used to narrow down the scope for the initial search. However, selecting all columns is obviously not a good idea, as SQL Server had to pick up all other columns from the clustered index, performing an enormous number of random readings."
},
{
"code": null,
"e": 3759,
"s": 3569,
"text": "Now, the first question I would ask myself is: what data do I really need? Do I need Body, ClosedDate, LastEditDate, etc.? Ok, so I will rewrite the query to include only necessary columns:"
},
{
"code": null,
"e": 3967,
"s": 3759,
"text": "SELECT P.Id AS PostId ,P.CreationDate ,P.OwnerUserId AS UserId ,P.Score ,P.ViewCountFROM dbo.Posts PWHERE P.CreationDate >= '20100101' AND P.CreationDate < '20100701' AND P.ViewCount > 3000"
},
{
"code": null,
"e": 4114,
"s": 3967,
"text": "We are getting exactly the same execution plan, with less logical reads (4 million), since the amount of data that’s being returned was decreased."
},
{
"code": null,
"e": 4301,
"s": 4114,
"text": "SQL Server suggests creating an index on our predicate columns (columns in WHERE clause), and including remaining columns in the index. Let’s obey SQL Server’s wish and modify our index:"
},
{
"code": null,
"e": 4439,
"s": 4301,
"text": "CREATE NONCLUSTERED INDEX [ix_creationDate_viewCount] ON [dbo].[Posts]( [CreationDate], [ViewCount])INCLUDE ([OwnerUserId],[Score])"
},
{
"code": null,
"e": 4808,
"s": 4439,
"text": "Now, when I run my query, it executes in less than a second, performing only 3626 logical reads! Wow! So, we’ve created a nice “covering” index, which works perfectly for this query. I’ve intentionally bolded the part “for this query”, since we can’t create a covering index for every single query that runs against our database. Here, it’s fine for the demo purposes."
},
{
"code": null,
"e": 4921,
"s": 4808,
"text": "Ok, we couldn’t optimize the previous query more than we did. Let’s now see how will columnstore index performs."
},
{
"code": null,
"e": 5093,
"s": 4921,
"text": "The first step is to create a copy of dbo.Posts table, but instead of using the B-tree index, I will create a clustered columnstore index on this new table (dbo.Posts_CS)."
},
{
"code": null,
"e": 5153,
"s": 5093,
"text": "CREATE CLUSTERED COLUMNSTORE INDEX cix_PostsON dbo.Posts_CS"
},
{
"code": null,
"e": 5259,
"s": 5153,
"text": "First thing you may notice is the huuge difference in the memory footprint of these two identical tables:"
},
{
"code": null,
"e": 5563,
"s": 5259,
"text": "So, a table with a clustered columnstore index on it consumes almost 4x less memory comparing to an original one with a B-tree index! If we also take non-clustered indexes into consideration, the difference only gets bigger. As I’ve already mentioned, data is much better compressed on the column level."
},
{
"code": null,
"e": 5649,
"s": 5563,
"text": "Now, let’s run exactly the same query on our newly created columnstore indexed table."
},
{
"code": null,
"e": 5860,
"s": 5649,
"text": "SELECT P.Id AS PostId ,P.CreationDate ,P.OwnerUserId AS UserId ,P.Score ,P.ViewCountFROM dbo.Posts_CS PWHERE P.CreationDate >= '20100101' AND P.CreationDate < '20100701' AND P.ViewCount > 3000"
},
{
"code": null,
"e": 6053,
"s": 5860,
"text": "Data in columnstore index is stored in segments. So, depending on the data distribution within the table, SQL Server has to read more or fewer segments in order to retrieve the requested data."
},
{
"code": null,
"e": 6537,
"s": 6053,
"text": "As you can see in the above illustration, to return my 88.547 records, SQL Server went through 26 segments and skipped 72. That’s because the data in our columnstore index is not sorted in any specific order. We could sort it by, let’s say, CreationDate (assuming that most of our queries will use CreationDate as a predicate), and in that case performance should be even better, since SQL Server would exactly know in which segments to look for the data, and which could be skipped."
},
{
"code": null,
"e": 6603,
"s": 6537,
"text": "Now, let’s run both queries together and compare the query costs:"
},
{
"code": null,
"e": 6827,
"s": 6603,
"text": "Traditional B-tree index seek has a cost of 3.7, while columnstore scan costs 10.7. Quite obvious, since we have a perfectly matching non-clustered index that covers all columns we need. Still, the difference is not so big."
},
{
"code": null,
"e": 6967,
"s": 6827,
"text": "But, let’s say that after some time we need to expand our output list and retrieve data for LastActivityDate. Let’s check what will happen:"
},
{
"code": null,
"e": 7336,
"s": 6967,
"text": "Oops!!! By adding just one column, results completely changed in the favor of columnstore index. Now, B-tree non-clustered index doesn’t have all the necessary data and it needs to pick up LastActivityDate from the clustered index — that makes the cost of this query rise up to 236! On the other hand, columnstore index became slightly more expensive and now costs 14!"
},
{
"code": null,
"e": 7591,
"s": 7336,
"text": "Of course, as you can notice in the picture above, SQL Server asks for another index (or existing ones to be expanded), but that’s what I stressed above — you shouldn’t blindly obey all of SQL Server wishes, or you will finish with “over-indexed” tables!"
},
{
"code": null,
"e": 8055,
"s": 7591,
"text": "By definition, the area where columnstore indexes should excel is when running analytical queries. So, let’s check this on the following scenario: I want to retrieve the users who registered in the first half of the year 2010, posted in the years 2010 and 2011, and the user’s overall Reputation is greater than 3000 and respective posts have more than 3000 views...I also need to see the user’s Location and DisplayName. Sounds complicated, but it really isn’t:)"
},
{
"code": null,
"e": 8074,
"s": 8055,
"text": "Here is the query:"
},
{
"code": null,
"e": 8426,
"s": 8074,
"text": "SELECT U.Id ,U.Location ,U.DisplayName ,P.CreationDate ,P.Score ,P.ViewCountFROM dbo.Users U INNER JOIN dbo.Posts P ON U.Id = P.OwnerUserId WHERE U.CreationDate >= '20100101' AND U.CreationDate < '20100701' AND U.Reputation > 3000 AND P.ViewCount > 3000 AND P.CreationDate >= '20100101' AND P.CreationDate < '20120101'"
},
{
"code": null,
"e": 8582,
"s": 8426,
"text": "The query returns 37.332 rows and we want to help SQL Server a little bit, by creating a non-clustered index on the CreationDate column in the Users table."
},
{
"code": null,
"e": 8663,
"s": 8582,
"text": "CREATE NONCLUSTERED INDEX [ix_creationDate] ON [dbo].[Users]( [CreationDate])"
},
{
"code": null,
"e": 8737,
"s": 8663,
"text": "When I run the query, SQL Server comes with the following execution plan:"
},
{
"code": null,
"e": 8952,
"s": 8737,
"text": "Since our index doesn’t cover all the necessary columns, SQL Server assumes that it’s cheaper to perform a scan on the Users table, instead of doing Index Seek and then expensive key lookups. This query costs 58.4."
},
{
"code": null,
"e": 9056,
"s": 8952,
"text": "Now, I will create a copy of the Users table (Users_CS) and create a clustered columnstore index on it:"
},
{
"code": null,
"e": 9116,
"s": 9056,
"text": "CREATE CLUSTERED COLUMNSTORE INDEX cix_UsersON dbo.Users_CS"
},
{
"code": null,
"e": 9195,
"s": 9116,
"text": "Let’s now run bot of our queries at the same time and compare the performance:"
},
{
"code": null,
"e": 9465,
"s": 9195,
"text": "Again, the table with columnstore index on it easily outperforms the original one with the B-tree index. The cost of the second query is 9.2! And keep in mind that we didn’t even optimize the columnstore index itself (we were not sorting the data during the insertion)!"
},
{
"code": null,
"e": 9748,
"s": 9465,
"text": "One last example comes from my real project, where we were comparing performance between columnstore and B-tree indexes on our actual workload. The query itself is so simple: I want to summarize total deposits per every single customer between January 1st and end of July this year:"
},
{
"code": null,
"e": 10052,
"s": 9748,
"text": "SELECT customerID ,SUM(amount) totalFROM factDepositWHERE isSuccessful = 1 AND datetm >='20200101' AND datetm < '20200801'GROUP BY customerIDSELECT customerID ,SUM(amount) totalFROM factDeposit_csWHERE isSuccessful = 1 AND datetm >='20200101' AND datetm < '20200801'GROUP BY customerID"
},
{
"code": null,
"e": 10078,
"s": 10052,
"text": "And here are the results:"
},
{
"code": null,
"e": 10150,
"s": 10078,
"text": "Again, columnstore index convincingly “wins” with 4.6 vs 26 query cost!"
},
{
"code": null,
"e": 10397,
"s": 10150,
"text": "Before you fall into the trap of concluding that traditional B-tree indexes aren’t needed anymore, you should ask yourself: where is the catch? And the catch is obviously there since B-tree indexes are still heavily used in most of the databases."
},
{
"code": null,
"e": 10936,
"s": 10397,
"text": "The biggest downside of the columnstore indexes is UPDATE/DELETE operations. Deleted records are not really deleted — they are just flagged as deleted, but they still remain part of the columnstore index, until the index is rebuilt. Updates perform even worse since they are being executed as two consecutive actions: delete and then insert...Inserts “per se” are not an issue, because SQL Server keeps them in the structure called Deltastore (which, by the way, has B-tree structure), and performs a bulk load into the columnstore index."
},
{
"code": null,
"e": 11078,
"s": 10936,
"text": "Therefore, if you are often performing updates and/or deletes, be aware that you will not extract maximum benefit from the columnstore index."
},
{
"code": null,
"e": 11112,
"s": 11078,
"text": "So, the right question should be:"
},
{
"code": null,
"e": 11183,
"s": 11112,
"text": "The answer is, as in 99% cases within SQL Server debates — IT DEPENDS!"
},
{
"code": null,
"e": 11323,
"s": 11183,
"text": "The key challenge is to identify the scenario, or better say the workload, that suits best to the usage of columnstore vs rowstore indexes."
},
{
"code": null,
"e": 11406,
"s": 11323,
"text": "Here are some recommendations for best practice usage for each of the index types:"
},
{
"code": null,
"e": 11531,
"s": 11406,
"text": "Use columnstore indexes on large tables (with at least a few million records), that are not being updated/deleted frequently"
},
{
"code": null,
"e": 11711,
"s": 11531,
"text": "Columnstore indexes perform best on static data, such as in OLAP workloads, with a lot of queries that simply reads the data from the tables, or bulk loading new data periodically"
},
{
"code": null,
"e": 12015,
"s": 11711,
"text": "Columnstore indexes excel in scanning and performing aggregations on big data ranges (doing SUM, AVG, COUNT, etc), because they are able to process around 900 rows in one batch, while traditional B-tree index process one-by-one (up until SQL Server 2019, which added a batch mode for row-based workload)"
},
{
"code": null,
"e": 12142,
"s": 12015,
"text": "Use B-tree indexes on highly transactional workloads, when your table is being frequently modified (updates, deletes, inserts)"
},
{
"code": null,
"e": 12366,
"s": 12142,
"text": "B-tree indexes will usually perform better in queries with high selectivity, for example, when you are returning a single value or small number of values, or if you are querying a small range of values (SEEKing for a value)"
},
{
"code": null,
"e": 12774,
"s": 12366,
"text": "To say that you should use columnstore indexes in OLAP workloads while using B-tree indexes in OLTP environment, will be huge oversimplifying. In order to get the proper answer to this question, you should ask yourself: what kind of queries are mostly used for the specific table? As soon as you get the answer to this question, you will be able to define the proper indexing strategy for your own workload."
},
{
"code": null,
"e": 12980,
"s": 12774,
"text": "And, finally, in case you wonder if you can take the best from both worlds: the answer is — YES! Starting from SQL Server 2016, you can combine columnstore and traditional B-tree indexes on the same table!"
},
{
"code": null,
"e": 13128,
"s": 12980,
"text": "That’s, however, a separate and complex topic that requires serious planning and various considerations, which is out of the scope of this article."
}
]
|
Clojure - contains? | Finds out whether the set contains a certain element or not.
Following is the syntax.
(contains? setofelements searchelement)
Parameters − ‘setofelements’ is the set of elements. ‘Searchelement’ is the element which needs to be searched for in the list.
Return Value − Returns true if the element exists in the set or false if it dosen’t.
Following is an example of contains? in Clojure.
(ns clojure.examples.example
(:gen-class))
(defn example []
(println (contains? (set '(3 2 1)) 2))
(println (contains? (set '(3 2 1)) 5)))
(example)
The above code produces the following output.
true
false
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2435,
"s": 2374,
"text": "Finds out whether the set contains a certain element or not."
},
{
"code": null,
"e": 2460,
"s": 2435,
"text": "Following is the syntax."
},
{
"code": null,
"e": 2501,
"s": 2460,
"text": "(contains? setofelements searchelement)\n"
},
{
"code": null,
"e": 2629,
"s": 2501,
"text": "Parameters − ‘setofelements’ is the set of elements. ‘Searchelement’ is the element which needs to be searched for in the list."
},
{
"code": null,
"e": 2714,
"s": 2629,
"text": "Return Value − Returns true if the element exists in the set or false if it dosen’t."
},
{
"code": null,
"e": 2763,
"s": 2714,
"text": "Following is an example of contains? in Clojure."
},
{
"code": null,
"e": 2921,
"s": 2763,
"text": "(ns clojure.examples.example\n (:gen-class))\n(defn example []\n (println (contains? (set '(3 2 1)) 2))\n (println (contains? (set '(3 2 1)) 5)))\n(example)"
},
{
"code": null,
"e": 2967,
"s": 2921,
"text": "The above code produces the following output."
},
{
"code": null,
"e": 2979,
"s": 2967,
"text": "true\nfalse\n"
},
{
"code": null,
"e": 2986,
"s": 2979,
"text": " Print"
},
{
"code": null,
"e": 2997,
"s": 2986,
"text": " Add Notes"
}
]
|
All about Feature Scaling. Scale data for better performance of... | by Baijayanta Roy | Towards Data Science | Machine learning is like making a mixed fruit juice. If we want to get the best-mixed juice, we need to mix all fruit not by their size but based on their right proportion. We just need to remember apple and strawberry are not the same unless we make them similar in some context to compare their attribute. Similarly, in many machine learning algorithms, to bring all features in the same standing, we need to do scaling so that one significant number doesn’t impact the model just because of their large magnitude.
Feature scaling in machine learning is one of the most critical steps during the pre-processing of data before creating a machine learning model. Scaling can make a difference between a weak machine learning model and a better one.
The most common techniques of feature scaling are Normalization and Standardization.
Normalization is used when we want to bound our values between two numbers, typically, between [0,1] or [-1,1]. While Standardization transforms the data to have zero mean and a variance of 1, they make our data unitless. Refer to the below diagram, which shows how data looks after scaling in the X-Y plane.
Machine learning algorithm just sees number — if there is a vast difference in the range say few ranging in thousands and few ranging in the tens, and it makes the underlying assumption that higher ranging numbers have superiority of some sort. So these more significant number starts playing a more decisive role while training the model.
The machine learning algorithm works on numbers and does not know what that number represents. A weight of 10 grams and a price of 10 dollars represents completely two different things — which is a no brainer for humans, but for a model as a feature, it treats both as same.
Suppose we have two features of weight and price, as in the below table. The “Weight” cannot have a meaningful comparison with the “Price.” So the assumption algorithm makes that since “Weight” > “Price,” thus “Weight,” is more important than “Price.”
So these more significant number starts playing a more decisive role while training the model. Thus feature scaling is needed to bring every feature in the same footing without any upfront importance. Interestingly, if we convert the weight to “Kg,” then “Price” becomes dominant.
Another reason why feature scaling is applied is that few algorithms like Neural network gradient descent converge much faster with feature scaling than without it.
One more reason is saturation, like in the case of sigmoid activation in Neural Network, scaling would help not to saturate too fast.
Feature scaling is essential for machine learning algorithms that calculate distances between data. If not scale, the feature with a higher value range starts dominating when calculating distances, as explained intuitively in the “why?” section.
The ML algorithm is sensitive to the “relative scales of features,” which usually happens when it uses the numeric values of the features rather than say their rank.
In many algorithms, when we desire faster convergence, scaling is a MUST like in Neural Network.
Since the range of values of raw data varies widely, in some machine learning algorithms, objective functions do not work correctly without normalization. For example, the majority of classifiers calculate the distance between two points by the distance. If one of the features has a broad range of values, the distance governs this particular feature. Therefore, the range of all features should be normalized so that each feature contributes approximately proportionately to the final distance.
Even when the conditions, as mentioned above, are not satisfied, you may still need to rescale your features if the ML algorithm expects some scale or a saturation phenomenon can happen. Again, a neural network with saturating activation functions (e.g., sigmoid) is a good example.
Rule of thumb we may follow here is an algorithm that computes distance or assumes normality, scales your features.
Some examples of algorithms where feature scaling matters are:
K-nearest neighbors (KNN) with a Euclidean distance measure is sensitive to magnitudes and hence should be scaled for all features to weigh in equally.
K-Means uses the Euclidean distance measure here feature scaling matters.
Scaling is critical while performing Principal Component Analysis(PCA). PCA tries to get the features with maximum variance, and the variance is high for high magnitude features and skews the PCA towards high magnitude features.
We can speed up gradient descent by scaling because θ descends quickly on small ranges and slowly on large ranges, and oscillates inefficiently down to the optimum when the variables are very uneven.
Algorithms that do not require normalization/scaling are the ones that rely on rules. They would not be affected by any monotonic transformations of the variables. Scaling is a monotonic transformation. Examples of algorithms in this category are all the tree-based algorithms — CART, Random Forests, Gradient Boosted Decision Trees. These algorithms utilize rules (series of inequalities) and do not require normalization.
Algorithms like Linear Discriminant Analysis(LDA), Naive Bayes is by design equipped to handle this and give weights to the features accordingly. Performing features scaling in these algorithms may not have much effect.
Few key points to note :
Mean centering does not affect the covariance matrix
Scaling of variables does affect the covariance matrix
Standardizing affects the covariance
Below are the few ways we can do feature scaling.
1) Min Max Scaler2) Standard Scaler3) Max Abs Scaler4) Robust Scaler5) Quantile Transformer Scaler6) Power Transformer Scaler7) Unit Vector Scaler
For the explanation, we will use the table shown in the top and form the data frame to show different scaling methods.
import pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinedf = pd.DataFrame({'WEIGHT': [15, 18, 12,10], 'PRICE': [1,3,2,5]}, index = ['Orange','Apple','Banana','Grape'])print(df)WEIGHT PRICEOrange 15 1Apple 18 3Banana 12 2Grape 10 5
Transform features by scaling each feature to a given range. This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g., between zero and one. This Scaler shrinks the data within the range of -1 to 1 if there are negative values. We can set the range like [0,1] or [0,5] or [-1,1].
This Scaler responds well if the standard deviation is small and when a distribution is not Gaussian. This Scaler is sensitive to outliers.
from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()df1 = pd.DataFrame(scaler.fit_transform(df), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape'])ax = df.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow'], marker = '*',s=80, label='BREFORE SCALING');df1.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow'], marker = 'o',s=60,label='AFTER SCALING', ax = ax);plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);
The Standard Scaler assumes data is normally distributed within each feature and scales them such that the distribution centered around 0, with a standard deviation of 1.
Centering and scaling happen independently on each feature by computing the relevant statistics on the samples in the training set. If data is not normally distributed, this is not the best Scaler to use.
from sklearn.preprocessing import StandardScalerscaler = StandardScaler()df2 = pd.DataFrame(scaler.fit_transform(df), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape'])ax = df.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow'], marker = '*',s=80, label='BREFORE SCALING');df2.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow'], marker = 'o',s=60,label='AFTER SCALING', ax = ax)plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);
Scale each feature by its maximum absolute value. This estimator scales and translates each feature individually such that the maximal absolute value of each feature in the training set is 1.0. It does not shift/center the data and thus does not destroy any sparsity.
On positive-only data, this Scaler behaves similarly to Min Max Scaler and, therefore, also suffers from the presence of significant outliers.
from sklearn.preprocessing import MaxAbsScalerscaler = MaxAbsScaler()df4 = pd.DataFrame(scaler.fit_transform(df), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape'])ax = df.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow'], marker = '*',s=80, label='BREFORE SCALING');df4.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow'], marker = 'o',s=60,label='AFTER SCALING', ax = ax)plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);
As the name suggests, this Scaler is robust to outliers. If our data contains many outliers, scaling using the mean and standard deviation of the data won’t work well.
This Scaler removes the median and scales the data according to the quantile range (defaults to IQR: Interquartile Range). The IQR is the range between the 1st quartile (25th quantile) and the 3rd quartile (75th quantile). The centering and scaling statistics of this Scaler are based on percentiles and are therefore not influenced by a few numbers of huge marginal outliers. Note that the outliers themselves are still present in the transformed data. If a separate outlier clipping is desirable, a non-linear transformation is required.
from sklearn.preprocessing import RobustScalerscaler = RobustScaler()df3 = pd.DataFrame(scaler.fit_transform(df), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape'])ax = df.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow'], marker = '*',s=80, label='BREFORE SCALING');df3.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow'], marker = 'o',s=60,label='AFTER SCALING', ax = ax)plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);
Let’s now see what happens if we introduce an outlier and see the effect of scaling using Standard Scaler and Robust Scaler (a circle shows outlier).
dfr = pd.DataFrame({'WEIGHT': [15, 18, 12,10,50], 'PRICE': [1,3,2,5,20]}, index = ['Orange','Apple','Banana','Grape','Jackfruit'])print(dfr)from sklearn.preprocessing import StandardScalerscaler = StandardScaler()df21 = pd.DataFrame(scaler.fit_transform(dfr), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape','Jackfruit'])ax = dfr.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow','black'], marker = '*',s=80, label='BREFORE SCALING');df21.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow','black'], marker = 'o',s=60,label='STANDARD', ax = ax,figsize=(12,6))from sklearn.preprocessing import RobustScalerscaler = RobustScaler()df31 = pd.DataFrame(scaler.fit_transform(dfr), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape','Jackfruit'])df31.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow','black'], marker = 'v',s=60,label='ROBUST', ax = ax,figsize=(12,6))plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);WEIGHT PRICEOrange 15 1Apple 18 3Banana 12 2Grape 10 5Jackfruit 50 20
Transform features using quantiles information.
This method transforms the features to follow a uniform or a normal distribution. Therefore, for a given feature, this transformation tends to spread out the most frequent values. It also reduces the impact of (marginal) outliers: this is, therefore, a robust pre-processing scheme.
The cumulative distribution function of a feature is used to project the original values. Note that this transform is non-linear and may distort linear correlations between variables measured at the same scale but renders variables measured at different scales more directly comparable. This is also sometimes called as Rank scaler.
from sklearn.preprocessing import QuantileTransformerscaler = QuantileTransformer()df6 = pd.DataFrame(scaler.fit_transform(df), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape'])ax = df.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow'], marker = '*',s=80, label='BREFORE SCALING');df6.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow'], marker = 'o',s=60,label='AFTER SCALING', ax = ax,figsize=(6,4))plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);
The above example is just for illustration as Quantile transformer is useful when we have a large dataset with many data points usually more than 1000.
The power transformer is a family of parametric, monotonic transformations that are applied to make data more Gaussian-like. This is useful for modeling issues related to the variability of a variable that is unequal across the range (heteroscedasticity) or situations where normality is desired.
The power transform finds the optimal scaling factor in stabilizing variance and minimizing skewness through maximum likelihood estimation. Currently, Sklearn implementation of PowerTransformer supports the Box-Cox transform and the Yeo-Johnson transform. The optimal parameter for stabilizing variance and minimizing skewness is estimated through maximum likelihood. Box-Cox requires input data to be strictly positive, while Yeo-Johnson supports both positive or negative data.
from sklearn.preprocessing import PowerTransformerscaler = PowerTransformer(method='yeo-johnson')df5 = pd.DataFrame(scaler.fit_transform(df), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape'])ax = df.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow'], marker = '*',s=80, label='BREFORE SCALING');df5.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow'], marker = 'o',s=60,label='AFTER SCALING', ax = ax)plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);
Scaling is done considering the whole feature vector to be of unit length. This usually means dividing each component by the Euclidean length of the vector (L2 Norm). In some applications (e.g., histogram features), it can be more practical to use the L1 norm of the feature vector.
Like Min-Max Scaling, the Unit Vector technique produces values of range [0,1]. When dealing with features with hard boundaries, this is quite useful. For example, when dealing with image data, the colors can range from only 0 to 255.
If we plot, then it would look as below for L1 and L2 norm, respectively.
The below diagram shows how data spread for all different scaling techniques, and as we can see, a few points are overlapping, thus not visible separately.
Feature scaling is an essential step in Machine Learning pre-processing. Deep learning requires feature scaling for faster convergence, and thus it is vital to decide which feature scaling to use. There are many comparison surveys of scaling methods for various algorithms. Still, like most other machine learning steps, feature scaling too is a trial and error process, not a single silver bullet.
I look forward to your comment and share if you have any unique experience related to feature scaling. Thanks for reading. You can connect me @LinkedIn. | [
{
"code": null,
"e": 688,
"s": 171,
"text": "Machine learning is like making a mixed fruit juice. If we want to get the best-mixed juice, we need to mix all fruit not by their size but based on their right proportion. We just need to remember apple and strawberry are not the same unless we make them similar in some context to compare their attribute. Similarly, in many machine learning algorithms, to bring all features in the same standing, we need to do scaling so that one significant number doesn’t impact the model just because of their large magnitude."
},
{
"code": null,
"e": 920,
"s": 688,
"text": "Feature scaling in machine learning is one of the most critical steps during the pre-processing of data before creating a machine learning model. Scaling can make a difference between a weak machine learning model and a better one."
},
{
"code": null,
"e": 1005,
"s": 920,
"text": "The most common techniques of feature scaling are Normalization and Standardization."
},
{
"code": null,
"e": 1314,
"s": 1005,
"text": "Normalization is used when we want to bound our values between two numbers, typically, between [0,1] or [-1,1]. While Standardization transforms the data to have zero mean and a variance of 1, they make our data unitless. Refer to the below diagram, which shows how data looks after scaling in the X-Y plane."
},
{
"code": null,
"e": 1654,
"s": 1314,
"text": "Machine learning algorithm just sees number — if there is a vast difference in the range say few ranging in thousands and few ranging in the tens, and it makes the underlying assumption that higher ranging numbers have superiority of some sort. So these more significant number starts playing a more decisive role while training the model."
},
{
"code": null,
"e": 1929,
"s": 1654,
"text": "The machine learning algorithm works on numbers and does not know what that number represents. A weight of 10 grams and a price of 10 dollars represents completely two different things — which is a no brainer for humans, but for a model as a feature, it treats both as same."
},
{
"code": null,
"e": 2181,
"s": 1929,
"text": "Suppose we have two features of weight and price, as in the below table. The “Weight” cannot have a meaningful comparison with the “Price.” So the assumption algorithm makes that since “Weight” > “Price,” thus “Weight,” is more important than “Price.”"
},
{
"code": null,
"e": 2462,
"s": 2181,
"text": "So these more significant number starts playing a more decisive role while training the model. Thus feature scaling is needed to bring every feature in the same footing without any upfront importance. Interestingly, if we convert the weight to “Kg,” then “Price” becomes dominant."
},
{
"code": null,
"e": 2627,
"s": 2462,
"text": "Another reason why feature scaling is applied is that few algorithms like Neural network gradient descent converge much faster with feature scaling than without it."
},
{
"code": null,
"e": 2761,
"s": 2627,
"text": "One more reason is saturation, like in the case of sigmoid activation in Neural Network, scaling would help not to saturate too fast."
},
{
"code": null,
"e": 3007,
"s": 2761,
"text": "Feature scaling is essential for machine learning algorithms that calculate distances between data. If not scale, the feature with a higher value range starts dominating when calculating distances, as explained intuitively in the “why?” section."
},
{
"code": null,
"e": 3173,
"s": 3007,
"text": "The ML algorithm is sensitive to the “relative scales of features,” which usually happens when it uses the numeric values of the features rather than say their rank."
},
{
"code": null,
"e": 3270,
"s": 3173,
"text": "In many algorithms, when we desire faster convergence, scaling is a MUST like in Neural Network."
},
{
"code": null,
"e": 3767,
"s": 3270,
"text": "Since the range of values of raw data varies widely, in some machine learning algorithms, objective functions do not work correctly without normalization. For example, the majority of classifiers calculate the distance between two points by the distance. If one of the features has a broad range of values, the distance governs this particular feature. Therefore, the range of all features should be normalized so that each feature contributes approximately proportionately to the final distance."
},
{
"code": null,
"e": 4050,
"s": 3767,
"text": "Even when the conditions, as mentioned above, are not satisfied, you may still need to rescale your features if the ML algorithm expects some scale or a saturation phenomenon can happen. Again, a neural network with saturating activation functions (e.g., sigmoid) is a good example."
},
{
"code": null,
"e": 4166,
"s": 4050,
"text": "Rule of thumb we may follow here is an algorithm that computes distance or assumes normality, scales your features."
},
{
"code": null,
"e": 4229,
"s": 4166,
"text": "Some examples of algorithms where feature scaling matters are:"
},
{
"code": null,
"e": 4381,
"s": 4229,
"text": "K-nearest neighbors (KNN) with a Euclidean distance measure is sensitive to magnitudes and hence should be scaled for all features to weigh in equally."
},
{
"code": null,
"e": 4455,
"s": 4381,
"text": "K-Means uses the Euclidean distance measure here feature scaling matters."
},
{
"code": null,
"e": 4684,
"s": 4455,
"text": "Scaling is critical while performing Principal Component Analysis(PCA). PCA tries to get the features with maximum variance, and the variance is high for high magnitude features and skews the PCA towards high magnitude features."
},
{
"code": null,
"e": 4884,
"s": 4684,
"text": "We can speed up gradient descent by scaling because θ descends quickly on small ranges and slowly on large ranges, and oscillates inefficiently down to the optimum when the variables are very uneven."
},
{
"code": null,
"e": 5308,
"s": 4884,
"text": "Algorithms that do not require normalization/scaling are the ones that rely on rules. They would not be affected by any monotonic transformations of the variables. Scaling is a monotonic transformation. Examples of algorithms in this category are all the tree-based algorithms — CART, Random Forests, Gradient Boosted Decision Trees. These algorithms utilize rules (series of inequalities) and do not require normalization."
},
{
"code": null,
"e": 5528,
"s": 5308,
"text": "Algorithms like Linear Discriminant Analysis(LDA), Naive Bayes is by design equipped to handle this and give weights to the features accordingly. Performing features scaling in these algorithms may not have much effect."
},
{
"code": null,
"e": 5553,
"s": 5528,
"text": "Few key points to note :"
},
{
"code": null,
"e": 5606,
"s": 5553,
"text": "Mean centering does not affect the covariance matrix"
},
{
"code": null,
"e": 5661,
"s": 5606,
"text": "Scaling of variables does affect the covariance matrix"
},
{
"code": null,
"e": 5698,
"s": 5661,
"text": "Standardizing affects the covariance"
},
{
"code": null,
"e": 5748,
"s": 5698,
"text": "Below are the few ways we can do feature scaling."
},
{
"code": null,
"e": 5895,
"s": 5748,
"text": "1) Min Max Scaler2) Standard Scaler3) Max Abs Scaler4) Robust Scaler5) Quantile Transformer Scaler6) Power Transformer Scaler7) Unit Vector Scaler"
},
{
"code": null,
"e": 6014,
"s": 5895,
"text": "For the explanation, we will use the table shown in the top and form the data frame to show different scaling methods."
},
{
"code": null,
"e": 6354,
"s": 6014,
"text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinedf = pd.DataFrame({'WEIGHT': [15, 18, 12,10], 'PRICE': [1,3,2,5]}, index = ['Orange','Apple','Banana','Grape'])print(df)WEIGHT PRICEOrange 15 1Apple 18 3Banana 12 2Grape 10 5"
},
{
"code": null,
"e": 6701,
"s": 6354,
"text": "Transform features by scaling each feature to a given range. This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g., between zero and one. This Scaler shrinks the data within the range of -1 to 1 if there are negative values. We can set the range like [0,1] or [0,5] or [-1,1]."
},
{
"code": null,
"e": 6841,
"s": 6701,
"text": "This Scaler responds well if the standard deviation is small and when a distribution is not Gaussian. This Scaler is sensitive to outliers."
},
{
"code": null,
"e": 7431,
"s": 6841,
"text": "from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()df1 = pd.DataFrame(scaler.fit_transform(df), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape'])ax = df.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow'], marker = '*',s=80, label='BREFORE SCALING');df1.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow'], marker = 'o',s=60,label='AFTER SCALING', ax = ax);plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);"
},
{
"code": null,
"e": 7602,
"s": 7431,
"text": "The Standard Scaler assumes data is normally distributed within each feature and scales them such that the distribution centered around 0, with a standard deviation of 1."
},
{
"code": null,
"e": 7807,
"s": 7602,
"text": "Centering and scaling happen independently on each feature by computing the relevant statistics on the samples in the training set. If data is not normally distributed, this is not the best Scaler to use."
},
{
"code": null,
"e": 8400,
"s": 7807,
"text": "from sklearn.preprocessing import StandardScalerscaler = StandardScaler()df2 = pd.DataFrame(scaler.fit_transform(df), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape'])ax = df.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow'], marker = '*',s=80, label='BREFORE SCALING');df2.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow'], marker = 'o',s=60,label='AFTER SCALING', ax = ax)plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);"
},
{
"code": null,
"e": 8668,
"s": 8400,
"text": "Scale each feature by its maximum absolute value. This estimator scales and translates each feature individually such that the maximal absolute value of each feature in the training set is 1.0. It does not shift/center the data and thus does not destroy any sparsity."
},
{
"code": null,
"e": 8811,
"s": 8668,
"text": "On positive-only data, this Scaler behaves similarly to Min Max Scaler and, therefore, also suffers from the presence of significant outliers."
},
{
"code": null,
"e": 9400,
"s": 8811,
"text": "from sklearn.preprocessing import MaxAbsScalerscaler = MaxAbsScaler()df4 = pd.DataFrame(scaler.fit_transform(df), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape'])ax = df.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow'], marker = '*',s=80, label='BREFORE SCALING');df4.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow'], marker = 'o',s=60,label='AFTER SCALING', ax = ax)plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);"
},
{
"code": null,
"e": 9568,
"s": 9400,
"text": "As the name suggests, this Scaler is robust to outliers. If our data contains many outliers, scaling using the mean and standard deviation of the data won’t work well."
},
{
"code": null,
"e": 10108,
"s": 9568,
"text": "This Scaler removes the median and scales the data according to the quantile range (defaults to IQR: Interquartile Range). The IQR is the range between the 1st quartile (25th quantile) and the 3rd quartile (75th quantile). The centering and scaling statistics of this Scaler are based on percentiles and are therefore not influenced by a few numbers of huge marginal outliers. Note that the outliers themselves are still present in the transformed data. If a separate outlier clipping is desirable, a non-linear transformation is required."
},
{
"code": null,
"e": 10697,
"s": 10108,
"text": "from sklearn.preprocessing import RobustScalerscaler = RobustScaler()df3 = pd.DataFrame(scaler.fit_transform(df), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape'])ax = df.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow'], marker = '*',s=80, label='BREFORE SCALING');df3.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow'], marker = 'o',s=60,label='AFTER SCALING', ax = ax)plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);"
},
{
"code": null,
"e": 10847,
"s": 10697,
"text": "Let’s now see what happens if we introduce an outlier and see the effect of scaling using Standard Scaler and Robust Scaler (a circle shows outlier)."
},
{
"code": null,
"e": 12188,
"s": 10847,
"text": "dfr = pd.DataFrame({'WEIGHT': [15, 18, 12,10,50], 'PRICE': [1,3,2,5,20]}, index = ['Orange','Apple','Banana','Grape','Jackfruit'])print(dfr)from sklearn.preprocessing import StandardScalerscaler = StandardScaler()df21 = pd.DataFrame(scaler.fit_transform(dfr), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape','Jackfruit'])ax = dfr.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow','black'], marker = '*',s=80, label='BREFORE SCALING');df21.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow','black'], marker = 'o',s=60,label='STANDARD', ax = ax,figsize=(12,6))from sklearn.preprocessing import RobustScalerscaler = RobustScaler()df31 = pd.DataFrame(scaler.fit_transform(dfr), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape','Jackfruit'])df31.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow','black'], marker = 'v',s=60,label='ROBUST', ax = ax,figsize=(12,6))plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);WEIGHT PRICEOrange 15 1Apple 18 3Banana 12 2Grape 10 5Jackfruit 50 20"
},
{
"code": null,
"e": 12236,
"s": 12188,
"text": "Transform features using quantiles information."
},
{
"code": null,
"e": 12519,
"s": 12236,
"text": "This method transforms the features to follow a uniform or a normal distribution. Therefore, for a given feature, this transformation tends to spread out the most frequent values. It also reduces the impact of (marginal) outliers: this is, therefore, a robust pre-processing scheme."
},
{
"code": null,
"e": 12852,
"s": 12519,
"text": "The cumulative distribution function of a feature is used to project the original values. Note that this transform is non-linear and may distort linear correlations between variables measured at the same scale but renders variables measured at different scales more directly comparable. This is also sometimes called as Rank scaler."
},
{
"code": null,
"e": 13469,
"s": 12852,
"text": "from sklearn.preprocessing import QuantileTransformerscaler = QuantileTransformer()df6 = pd.DataFrame(scaler.fit_transform(df), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape'])ax = df.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow'], marker = '*',s=80, label='BREFORE SCALING');df6.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow'], marker = 'o',s=60,label='AFTER SCALING', ax = ax,figsize=(6,4))plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);"
},
{
"code": null,
"e": 13621,
"s": 13469,
"text": "The above example is just for illustration as Quantile transformer is useful when we have a large dataset with many data points usually more than 1000."
},
{
"code": null,
"e": 13918,
"s": 13621,
"text": "The power transformer is a family of parametric, monotonic transformations that are applied to make data more Gaussian-like. This is useful for modeling issues related to the variability of a variable that is unequal across the range (heteroscedasticity) or situations where normality is desired."
},
{
"code": null,
"e": 14398,
"s": 13918,
"text": "The power transform finds the optimal scaling factor in stabilizing variance and minimizing skewness through maximum likelihood estimation. Currently, Sklearn implementation of PowerTransformer supports the Box-Cox transform and the Yeo-Johnson transform. The optimal parameter for stabilizing variance and minimizing skewness is estimated through maximum likelihood. Box-Cox requires input data to be strictly positive, while Yeo-Johnson supports both positive or negative data."
},
{
"code": null,
"e": 15015,
"s": 14398,
"text": "from sklearn.preprocessing import PowerTransformerscaler = PowerTransformer(method='yeo-johnson')df5 = pd.DataFrame(scaler.fit_transform(df), columns=['WEIGHT','PRICE'], index = ['Orange','Apple','Banana','Grape'])ax = df.plot.scatter(x='WEIGHT', y='PRICE',color=['red','green','blue','yellow'], marker = '*',s=80, label='BREFORE SCALING');df5.plot.scatter(x='WEIGHT', y='PRICE', color=['red','green','blue','yellow'], marker = 'o',s=60,label='AFTER SCALING', ax = ax)plt.axhline(0, color='red',alpha=0.2)plt.axvline(0, color='red',alpha=0.2);"
},
{
"code": null,
"e": 15298,
"s": 15015,
"text": "Scaling is done considering the whole feature vector to be of unit length. This usually means dividing each component by the Euclidean length of the vector (L2 Norm). In some applications (e.g., histogram features), it can be more practical to use the L1 norm of the feature vector."
},
{
"code": null,
"e": 15533,
"s": 15298,
"text": "Like Min-Max Scaling, the Unit Vector technique produces values of range [0,1]. When dealing with features with hard boundaries, this is quite useful. For example, when dealing with image data, the colors can range from only 0 to 255."
},
{
"code": null,
"e": 15607,
"s": 15533,
"text": "If we plot, then it would look as below for L1 and L2 norm, respectively."
},
{
"code": null,
"e": 15763,
"s": 15607,
"text": "The below diagram shows how data spread for all different scaling techniques, and as we can see, a few points are overlapping, thus not visible separately."
},
{
"code": null,
"e": 16162,
"s": 15763,
"text": "Feature scaling is an essential step in Machine Learning pre-processing. Deep learning requires feature scaling for faster convergence, and thus it is vital to decide which feature scaling to use. There are many comparison surveys of scaling methods for various algorithms. Still, like most other machine learning steps, feature scaling too is a trial and error process, not a single silver bullet."
}
]
|
192.168.0.1 Admin Login - GeeksforGeeks | 28 Mar, 2020
Before even beginning the discussion, one needs to be clear about the concept of IP Address. The IP address or the Internet Protocol address is defined a s a numerical tag that is assigned to each and every computer which is a part of a computer network. The reason of reserving few IP addresses not for the public, has everything to do with the new version of Internet Protocol version 4 (IPv4).There are two main functions of an IP address, which are as follows:
Location Addressing or defining the location of the device connected, and,Identifying the network interface.
Location Addressing or defining the location of the device connected, and,
Identifying the network interface.
As far as the address 192.168.0.1 is concerned, the same is used to obtain the router configuration details. The address is preferred by the manufacturers to define the LAN or Local Area Network IP Address.
About 192.168.0.1 IP AddressNot all the destinations on the internet have a public address. 192.168.0.1 is one of the private addresses that is used by most of the ADSL modems to get the configuration details of a particular router system. This is a default host address of the version 4 of IP (IPv4).
Nonetheless, it is important that the user type the address correctly on the address bar to avoid any kind of fatal errors. Secondly, the address gives us the information about the management of the router console of the network your device is connected to.
How to Login 192.168.0.1 IP Address:To access your router admin portal, you need to follow the following steps :
Check the network connectivity of your device. It should be connected either through Ethernet or wireless.Open your preferred browser that you normally use to access the internet. Type any one of the following in the address bar:(a) http://192.168.0.1
(b) 192.168.0.1 By pressing enter, you will be sent to a login page of your router or modem.Enter the username and password of your router. You may also check your password if you have forgotten the same.After clicking enter, you will be passed into a configuration page where you can change the settings.
Check the network connectivity of your device. It should be connected either through Ethernet or wireless.
Open your preferred browser that you normally use to access the internet. Type any one of the following in the address bar:(a) http://192.168.0.1
(b) 192.168.0.1
(a) http://192.168.0.1
(b) 192.168.0.1
By pressing enter, you will be sent to a login page of your router or modem.
Enter the username and password of your router. You may also check your password if you have forgotten the same.
After clicking enter, you will be passed into a configuration page where you can change the settings.
How to Find Router’s IP Address ?It is not necessary that the IP address of your router is 192.168.0.1, it is a possibility that the address can be 192.168.1.1 or some other. All you have to do is, to find your default address. You can do this by going through the list of default router IP addresses and find the same. We have mentioned the router’s default username and password list below.
Router’s Default Username and Password List:The username and the password of your router can be obtained from the router manual which comes along with the router at the time of installation. If you have misplaced the manual, no need to worry, you can visit this website in order to retrieve the default username or password.
Many manufacturers have router models that have different passwords and usernames. The list in the link will tell you the default passwords and usernames of the routers of your router.
What to do if I Forget Router Username And Password?It is not a possible at a human level to remember the passwords. One can very easily get the passwords and usernames by following few steps. There are two ways of dealing with this problem. One, you can refer to the manual of router credentials as presented in the above link, the other and the preferred one, by resetting the router. This can be done by following steps:
Look for the reset button at the back of the router.Take a pointy object and prepare to press the button.Press and hold the button for at least 10-15 seconds.
Look for the reset button at the back of the router.
Take a pointy object and prepare to press the button.
Press and hold the button for at least 10-15 seconds.
By doing this, you will reset the router credentials to the default settings. Now, you can easily put the default username and passwords in the login tab and find the router details on the screen.
How to Troubleshoot Router Errors ?There maybe times when your router might not agree with your commands or might not be actively participating in the process of IP transfer. This can happen due to few Router Errors. The router errors can very easily be resolved and can be solved by troubleshooting. There are few things that need to be kept in mind before approaching with the process of troubleshooting.The following are discussed as follows:
Check Power Supply
The majorly found error is generated through the most basic problem of power supply. This problem can be solved very easily by checking the connection of the router to the problem. This is a common problem and does not require any professional knowledge to troubleshoot. The power supply is usually indicated by a lighting up small LED in the router.
Use Proper Quality Cables
This depends upon your Internet Service Provider. A user should always prefer the best transmission cables while dealing with high speed networks. The role of the connecting wires cannot be overlooked. The quality of wire is necessary to be kept in mind to ensure smooth functioning of the network protocols.
Check the Router Signals:
The router signals are the responses of the router. If the router is unable to perform a function, it might be the role of poor routing signals. The router supports few LED lights that determine the status of the router signals. If such a problem occurs, one can look for the correctness in the working of these LEDs.
Conclusion:In conclusion, a user can do wonders by changing the router settings. All he or she has to do is to understand the working of the 198.162.0.1 IP Address and they are good to go. The internet provides so many sources from where you can gather your router credentials. By following the aforementioned processes, you can ensure that the network you use for surfing the network works as per your commands. The problems in your routers can also be troubleshooted while following the simple steps. This way, you can also increase the security of your network-router connection. The user, at last, has the entire control of the process.
Computer Networks
GBlog
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Secure Socket Layer (SSL)
GSM in Wireless Communication
Stop and Wait ARQ
Roadmap to Become a Web Developer in 2022
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Socket Programming in C/C++
DSA Sheet by Love Babbar
GET and POST requests using Python | [
{
"code": null,
"e": 24510,
"s": 24482,
"text": "\n28 Mar, 2020"
},
{
"code": null,
"e": 24975,
"s": 24510,
"text": "Before even beginning the discussion, one needs to be clear about the concept of IP Address. The IP address or the Internet Protocol address is defined a s a numerical tag that is assigned to each and every computer which is a part of a computer network. The reason of reserving few IP addresses not for the public, has everything to do with the new version of Internet Protocol version 4 (IPv4).There are two main functions of an IP address, which are as follows:"
},
{
"code": null,
"e": 25084,
"s": 24975,
"text": "Location Addressing or defining the location of the device connected, and,Identifying the network interface."
},
{
"code": null,
"e": 25159,
"s": 25084,
"text": "Location Addressing or defining the location of the device connected, and,"
},
{
"code": null,
"e": 25194,
"s": 25159,
"text": "Identifying the network interface."
},
{
"code": null,
"e": 25401,
"s": 25194,
"text": "As far as the address 192.168.0.1 is concerned, the same is used to obtain the router configuration details. The address is preferred by the manufacturers to define the LAN or Local Area Network IP Address."
},
{
"code": null,
"e": 25703,
"s": 25401,
"text": "About 192.168.0.1 IP AddressNot all the destinations on the internet have a public address. 192.168.0.1 is one of the private addresses that is used by most of the ADSL modems to get the configuration details of a particular router system. This is a default host address of the version 4 of IP (IPv4)."
},
{
"code": null,
"e": 25961,
"s": 25703,
"text": "Nonetheless, it is important that the user type the address correctly on the address bar to avoid any kind of fatal errors. Secondly, the address gives us the information about the management of the router console of the network your device is connected to."
},
{
"code": null,
"e": 26074,
"s": 25961,
"text": "How to Login 192.168.0.1 IP Address:To access your router admin portal, you need to follow the following steps :"
},
{
"code": null,
"e": 26634,
"s": 26074,
"text": "Check the network connectivity of your device. It should be connected either through Ethernet or wireless.Open your preferred browser that you normally use to access the internet. Type any one of the following in the address bar:(a) http://192.168.0.1\n(b) 192.168.0.1 By pressing enter, you will be sent to a login page of your router or modem.Enter the username and password of your router. You may also check your password if you have forgotten the same.After clicking enter, you will be passed into a configuration page where you can change the settings."
},
{
"code": null,
"e": 26741,
"s": 26634,
"text": "Check the network connectivity of your device. It should be connected either through Ethernet or wireless."
},
{
"code": null,
"e": 26906,
"s": 26741,
"text": "Open your preferred browser that you normally use to access the internet. Type any one of the following in the address bar:(a) http://192.168.0.1\n(b) 192.168.0.1 "
},
{
"code": null,
"e": 26948,
"s": 26906,
"text": "(a) http://192.168.0.1\n(b) 192.168.0.1 "
},
{
"code": null,
"e": 27025,
"s": 26948,
"text": "By pressing enter, you will be sent to a login page of your router or modem."
},
{
"code": null,
"e": 27138,
"s": 27025,
"text": "Enter the username and password of your router. You may also check your password if you have forgotten the same."
},
{
"code": null,
"e": 27240,
"s": 27138,
"text": "After clicking enter, you will be passed into a configuration page where you can change the settings."
},
{
"code": null,
"e": 27633,
"s": 27240,
"text": "How to Find Router’s IP Address ?It is not necessary that the IP address of your router is 192.168.0.1, it is a possibility that the address can be 192.168.1.1 or some other. All you have to do is, to find your default address. You can do this by going through the list of default router IP addresses and find the same. We have mentioned the router’s default username and password list below."
},
{
"code": null,
"e": 27958,
"s": 27633,
"text": "Router’s Default Username and Password List:The username and the password of your router can be obtained from the router manual which comes along with the router at the time of installation. If you have misplaced the manual, no need to worry, you can visit this website in order to retrieve the default username or password."
},
{
"code": null,
"e": 28143,
"s": 27958,
"text": "Many manufacturers have router models that have different passwords and usernames. The list in the link will tell you the default passwords and usernames of the routers of your router."
},
{
"code": null,
"e": 28567,
"s": 28143,
"text": "What to do if I Forget Router Username And Password?It is not a possible at a human level to remember the passwords. One can very easily get the passwords and usernames by following few steps. There are two ways of dealing with this problem. One, you can refer to the manual of router credentials as presented in the above link, the other and the preferred one, by resetting the router. This can be done by following steps:"
},
{
"code": null,
"e": 28726,
"s": 28567,
"text": "Look for the reset button at the back of the router.Take a pointy object and prepare to press the button.Press and hold the button for at least 10-15 seconds."
},
{
"code": null,
"e": 28779,
"s": 28726,
"text": "Look for the reset button at the back of the router."
},
{
"code": null,
"e": 28833,
"s": 28779,
"text": "Take a pointy object and prepare to press the button."
},
{
"code": null,
"e": 28887,
"s": 28833,
"text": "Press and hold the button for at least 10-15 seconds."
},
{
"code": null,
"e": 29084,
"s": 28887,
"text": "By doing this, you will reset the router credentials to the default settings. Now, you can easily put the default username and passwords in the login tab and find the router details on the screen."
},
{
"code": null,
"e": 29530,
"s": 29084,
"text": "How to Troubleshoot Router Errors ?There maybe times when your router might not agree with your commands or might not be actively participating in the process of IP transfer. This can happen due to few Router Errors. The router errors can very easily be resolved and can be solved by troubleshooting. There are few things that need to be kept in mind before approaching with the process of troubleshooting.The following are discussed as follows:"
},
{
"code": null,
"e": 29550,
"s": 29530,
"text": "Check Power Supply "
},
{
"code": null,
"e": 29901,
"s": 29550,
"text": "The majorly found error is generated through the most basic problem of power supply. This problem can be solved very easily by checking the connection of the router to the problem. This is a common problem and does not require any professional knowledge to troubleshoot. The power supply is usually indicated by a lighting up small LED in the router."
},
{
"code": null,
"e": 29928,
"s": 29901,
"text": "Use Proper Quality Cables "
},
{
"code": null,
"e": 30237,
"s": 29928,
"text": "This depends upon your Internet Service Provider. A user should always prefer the best transmission cables while dealing with high speed networks. The role of the connecting wires cannot be overlooked. The quality of wire is necessary to be kept in mind to ensure smooth functioning of the network protocols."
},
{
"code": null,
"e": 30263,
"s": 30237,
"text": "Check the Router Signals:"
},
{
"code": null,
"e": 30581,
"s": 30263,
"text": "The router signals are the responses of the router. If the router is unable to perform a function, it might be the role of poor routing signals. The router supports few LED lights that determine the status of the router signals. If such a problem occurs, one can look for the correctness in the working of these LEDs."
},
{
"code": null,
"e": 31222,
"s": 30581,
"text": "Conclusion:In conclusion, a user can do wonders by changing the router settings. All he or she has to do is to understand the working of the 198.162.0.1 IP Address and they are good to go. The internet provides so many sources from where you can gather your router credentials. By following the aforementioned processes, you can ensure that the network you use for surfing the network works as per your commands. The problems in your routers can also be troubleshooted while following the simple steps. This way, you can also increase the security of your network-router connection. The user, at last, has the entire control of the process."
},
{
"code": null,
"e": 31240,
"s": 31222,
"text": "Computer Networks"
},
{
"code": null,
"e": 31246,
"s": 31240,
"text": "GBlog"
},
{
"code": null,
"e": 31264,
"s": 31246,
"text": "Computer Networks"
},
{
"code": null,
"e": 31362,
"s": 31264,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31371,
"s": 31362,
"text": "Comments"
},
{
"code": null,
"e": 31384,
"s": 31371,
"text": "Old Comments"
},
{
"code": null,
"e": 31419,
"s": 31384,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 31452,
"s": 31419,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 31478,
"s": 31452,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 31508,
"s": 31478,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 31526,
"s": 31508,
"text": "Stop and Wait ARQ"
},
{
"code": null,
"e": 31568,
"s": 31526,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 31642,
"s": 31568,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 31670,
"s": 31642,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 31695,
"s": 31670,
"text": "DSA Sheet by Love Babbar"
}
]
|
Matplotlib Cheat Sheet. Basic plots, include code samples. | by XuanKhanh Nguyen | Towards Data Science | Matplotlib is a plotting library for the Python programming language. The most used module of Matplotib is Pyplot which provides an interface like Matlab but instead, it uses Python and it is open source.
In this note, we will focus on basic Matplotlib to help visualize our data. This is not a comprehensive list but contains common types of data visualization formats. Let’s hop to it!
The structure of this note:
Anatomy of Matplotlib FigureStart with PyplotChart Types
Anatomy of Matplotlib Figure
Start with Pyplot
Chart Types
A figure contains the overall window where plotting happens.
Axes: It is what we generally think of as a plot. Each Axes has a title, an x-label, and a y-label.
Note: We can have more than one Axes in a figure which helps in building multiple plots.
Axis are the number line like objects and help to generate the graph limits. Every axes has an x-axis and y-axis for plotting.
Ticks are the markers denoting data points on axes, that is, the values used to show specific points on the coordinate axis. These values can be a number or a string. Whenever we plot a graph, the axes adjust and take the default ticks. Matplotlib’s default ticks are generally sufficient in common situations but are in no way optimal for every plot.
A spine to a graph is the edge of the graph. It connects the axis tick marks and noting the boundaries of the data area.
Pyplot is a module of Matplotlib which provides simple functions to add plot elements like lines, images, text, etc. to the current axes in the current figure.
At first, we set up the notebook for plotting and importing the packages we will use:
import numpy as npimport matplotlib.pyplot as pltplt.style.use('seaborn-whitegrid') # Set the aesthetic style of the plots
A figure and axes can be created as follows:
fig, ax = plt.subplots()print(type(fig))print(type(ax))
We commonly use the variable name fig to refer to a figure instance, and ax to refer to an axes instance or group of axes instances.
Once we have created an axes, we can use the plt.plot function to plot some data. Let’s start with a simple plot. Perhaps the simplest of all plots is the visualization of a single function y = 2x.
fig, ax = plt.subplots()x = np.random.randint(1,10, size=10)y = 2*x plt.plot(x,y) # same as ax.plot(x,y)plt.show()
If we want to create a single figure with multiple lines, we can simply call the plot function multiple times:
# Multiple linesfig, ax = plt.subplots()x = np.random.randint(1,10, size=10)y = 2*x plt.plot(x,y)plt.plot(x,x+3)plt.show()
The plt.plot() function takes additional arguments that can be used to specify the line color and style. To adjust, we can use the color linestyle keyword, which accepts a string argument representing virtually any imaginable color/style. Colors and styles can be specified in a variety of ways:
fig, ax = plt.subplots()x = np.linspace(0,10,1000)y = 2*x# set of default color and styleplt.plot(x, np.cos(x))# RGB tuple, values 0 to 1, solid styleplt.plot(x, np.sin(x), color=(1.0,0.2,0.3),linestyle='-')# specify color by name, dashed styleplt.plot(x, y, color='blue', linestyle='--')# short color code (rgbcmyk), dotted style plt.plot(x, x+3, color='g',linestyle=':')# Grayscale between 0 and 1, dashdot style plt.plot(x, np.log(x), color='0.75',linestyle='-.')# Hex code (RRGGBB from 00 to FF), dashed style plt.plot(x, x, color='#FFDD44',linestyle='--')
Matplotlib does a decent job of choosing default axes limits for our plot, but sometimes it’s nice to have finer control. The most basic way to adjust axis limits is to use the plt.xlim() and plt.ylim() methods:
plt.xlim(0, 11)plt.ylim(-1.5, 10)
As the last piece of this section, we will briefly look at the labeling of plots: titles, axis labels, and simple legends.
plt.plot(x, np.sin(x), label='y=sin(x)')plt.plot(x,np.cos(x), label='y=cos(x)')plt.title('Sine and Cosine Functions ')plt.xlabel("x-axis")plt.ylabel("y-axis")plt.legend() # Describing the element of the graphplt.show()
There are various plots which can be created using python Matplotlib. We will discuss the most used plots for data visualization in this section.
We use the World Happiness Report dataset from Kaggle. I cleaned the data and combined all files in happiness_rank.csv file. You can download and clean the data or just simply download the final result here. I recommend you check out my data cleaning codes on Github.
A scatter plot is a type of chart that is often used in statistics and data science. It consists of multiple data points plotted across two axes. Each variable depicted in a scatter plot would have multiple observations. This can be a very useful chart type whenever we would like to see if there is any relationship between two sets of data.
We use a scatter plot to identify the relationship of the data with each variable (i.e, correlation, or trend patterns.) It also helps in detecting outliers in the plot.
In machine learning, scatter plots are often used in regression, where x and y are continuous variables. They are also used in clustering scatters or outlier detection.
Scatter plots are not suitable if we are interested in observing time patterns.
A scatter plot is used with numerical data or numbers. So, if we have categories such as three divisions, five products, etc, a scatter plot would not reveal much.
fig, ax = plt.subplots(figsize = (12,6))x = df['GDP']y = df['Score']plt.scatter(x,y)plt.title('GDP vs Happiness Score')plt.xlabel('GDP')plt.ylabel('Score')
3D Scatterplot
3D Scatterplot helps in visualizing three numerical variables in a three- dimensional plot.
from mpl_toolkits.mplot3d import Axes3Dfig = plt.figure(figsize=(10,6))ax = fig.add_subplot(111, projection='3d')ax.scatter(df['Year'],df['GDP'],df['Score'], s=30)ax.set( xlabel='Year', ylabel='GDP',zlabel='Score')plt.xticks(np.arange(2015,2020,step =1))plt.show()
Scatter plot with a linear regression line of best fit
We will implement linear regression with Scikit-learn using the LinearRegression. After creating a linear regression object, we can obtain the line that best fits our data by calling the fit method.
x = df['GDP'].values.reshape(-1,1).astype('float32')y = df['Score'].values.reshape(-1,1).astype('float32')# Split the data to train and test dataX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)# Apply Linear Regression Algorithmsh = LinearRegression() h.fit(X_train,y_train)y_pred = h.predict(X_test)fig,(ax1) = plt.subplots(1, figsize = (12,6))ax1.scatter (X_test, y_test, s = 8)plt.plot(X_test,y_pred, color = 'black', linewidth = 2)plt.show()
A diverging bar chart is a bar chart that has the marks for some dimension members pointing up or right, and the marks for other dimension members pointing in the opposite direction (down or left, respectively).
Note:
The marks flowing down or left does not necessarily represent negative values.
The divergent line can represent zero, but it can also be used to simply separate the marks for two-dimension members.
We use diverging bars to see how the items are varying based on a single metric and visualize the order and amount of this variance. If our primary objective is to compare the trend of each dimension member, a divergent bar chart is a good option.
The drawback to using diverging bar charts is that it’s not as easy to compare the values across dimension members as it is with a grouped bar chart.
We only use 2019 data as an example.
# Data processingtop_economies = ['United States', 'China','Japan', 'Germany','United Kingdom','India', 'France','Brazil', 'Canada']df_top = df_19[(df_19['Country'].isin(top_economies))].sort_values(['Country'])df_top.reset_index(drop=True)x = df_top.loc[:, ['Score']]df_top['Score_z'] = (x - x.mean())/x.std()df_top['colors'] = ['red' if x < 0 else 'blue' for x in df_top['Score_z']]df_top.sort_values('Score_z', inplace=True)df_top.reset_index(inplace=True)# Draw plotplt.figure(figsize=(8,6), dpi= 50)plt.hlines(y=df_top.index, xmin=0, xmax=df_top.Score_z, color=df_top.colors, alpha=0.5, linewidth=20)# Decorationsplt.gca().set(ylabel='Country', xlabel='Happiness_Score')plt.yticks(df_top.index, df_top.Country, fontsize=15)plt.title('Happiness Score for Top Economies in 2019', fontdict={'size':20})plt.grid(linestyle='--', alpha=0.5)plt.show()
The idea of an area chart is based on the line chart. Colored regions (areas) show us the development of each variable over time.
There are three types of area charts: regular area chart, stacked area chart, and 100% stacked area chart.
We use area charts to show how the parts of a complete change over time. For example, the happiness score has six generating divisions; we would like to see each of these divisions’ contributions.
Moreover, if we are interested in the portion generated by each division and not that much of the total amount of the division self, we can use a 100% stacked area chart. This will show each division’s percentage contribution over time.
Area charts are not the best choice if we want to compare the size of different shares with each other. If you want to show that one share overtook another one; or if the differences between our values are very small, consider a line chart instead.
Python Implementation
# Regular Area Chart# Create datax = df_top['Score']y = df_top['GDP']# Change the color and its transparencyplt.fill_between( x, y, color="skyblue", alpha=0.2)plt.xlabel('Score')plt.ylabel('GDP')plt.plot(x, y, color="Slateblue", alpha=0.6)
# Stacked Area Chartplt.stackplot(df_top.index, [df_top['GDP'], df_top['Health'], df_top['Support'], df_top['Freedom']], df_top['Generosity'], df_top['Corruption'], labels=['GDP', 'Health', 'Support', 'Freedom','Generosity','Corruption'], alpha=0.8)plt.legend(loc=2, fontsize='large')plt.show()
# 100% Stacked Area Chartdata_perc = df_top[['GDP', 'Health', 'Support', 'Freedom','Generosity','Corruption']]data_perc = data_perc.divide(data_perc.sum(axis=1), axis=0)plt.stackplot(data_perc.index, [data_perc['GDP'], data_perc['Health'], data_perc['Support'], data_perc['Freedom']], data_perc['Generosity'], data_perc['Corruption'], labels=['GDP', 'Health', 'Support', 'Freedom','Generosity','Corruption'], alpha=0.8)plt.legend(loc=2, fontsize='large')plt.show()
Bar charts are among the most frequently used chart types. As the name suggests, a bar chart is composed of a series of bars illustrating a variable’s development.
There are four types of bar charts: regular bar chart, horizontal bar chart, group bar chart, and stacked bar chart.
Bar charts are great when we want to track the development of one or two variables over time. One axis of the chart shows the specific categories being compared, and the other axis represents a measured value.
A simple bar chart isn’t suitable when we have a single period breakdown of a variable. For example, if I want to portray the main business lines that contributed to a company’s revenues, I wouldn’t use a bar chart. Instead, I would create a pie chart or one of its variations.
# Bar Chartcountries = ['United States','Japan', 'Germany','Brazil', 'India']y_pos = np.arange(len(countries))data = df_19[(df_19['Country'].isin(countries))].sort_values(['Country'])data.sort_values('GDP', inplace=True)data.reset_index(drop=True)plt.bar(y_pos, data['GDP'], align='center', alpha=0.5)plt.xticks(y_pos, data['Country'])plt.ylabel('GDP')plt.title('Bar Chart')plt.show()
# Horizontal bar chartdf_19[(df_19['Country'].isin(countries))].sort_values(['Country'])data.sort_values('Score', inplace=True)data.reset_index(drop=True)plt.barh(y_pos, data['Score'], align='center', alpha=0.5)plt.yticks(y_pos, data['Country'])plt.xlabel('Score')plt.title('Horizontal Bar Chart')plt.show()
# Group bar chartindex = np.arange(5)width = 0.35fig, ax = plt.subplots(figsize=(9, 6))rects1 = ax.bar(index - width / 2, data['GDP'], width, color='#1f77b4', alpha=0.5)rects2 = ax.bar(index + width / 2, data['Health'], width, color='#1f77b4')plt.xticks(index, gdp['Country'])plt.legend((rects1[0], rects2[0]), ('GDP', 'Health'))plt.show()
# Stacked bar chartfig = plt.figure(figsize=(14,10))rect1 = plt.bar(np.arange(5), data['Support'], width=0.5, color='lightblue')rect2 = plt.bar(np.arange(5), data['Freedom'], width=0.5, color='#1f77b4')plt.xticks(index, data['Country'])plt.legend((rect1[0], rect2[0]), ('Support', 'Freedom'))plt.show()
Lollipop chart serves a similar purpose as an ordered bar chart in a visually pleasing way. We use lollipop charts to show the relationship between a numerical variable and another numerical or categorical variable.
The lollipop chart is often claimed to be useful compared to a normal bar chart, if we are dealing with a large number of values and when the values are all high, such as in the 80–90% range (out of 100%). Then a large set of tall columns can be visually aggressive.
If our data has unsorted bars of very similar length — it is harder to compare the lengths of two very similar lollipops than standard bars.
Python Implementation
(markerline, stemlines, baseline) = plt.stem(data['Country'], data['GDP'])plt.setp(markerline, marker='o', markersize=15, markeredgewidth=2, color='lightblue')plt.setp(stemlines, color='lightblue')plt.setp(baseline, visible=False)plt.tick_params(labelsize=12)plt.ylabel('GDP', size=12)plt.ylim(bottom=0)plt.show()
A histogram is a vertical bar chart that depicts the distribution of a set of data. Histograms are used to show distributions of variables while bar charts are used to compare variables. Histograms plot quantitative data with ranges of the data grouped into bins or intervals while bar charts plot categorical data.
Note: Bar graphs have space between the columns, while histograms do not.
Histograms are great when we would like to show the distribution of the data we are working with. This allows us to group continuous data into bins and hence, provide a useful representation of where observations are concentrated.
Python Implementation
# Histogramfig = plt.figure(figsize=(8,6))plt.hist(df_19['Corruption'], bins=6, density=True)plt.grid(alpha=0.2)plt.show()
A box plot or whisker plot is a way of summarizing a set of data measured on an interval scale. This type of graph is used to show the shape of the distribution, its central value, and its variability.
We use box plots in explanatory data analysis, indicating whether a distribution is skewed and whether there are potential unusual observations (outliers) in the data set.
Box plots are also very useful when large numbers of observations are involved and when two or more data sets are being compared.
Box plots do not show the distribution in as much detail as a stem and leaf plot or histogram does.
Suppose we have a dataset containing the number of articles Medium members read in 2020’s first six months.
# Create datasetuser_1 = [10, 3, 15, 21, 17, 14]user_2 = [5, 13, 10, 7, 9, 12]data = [user_1, user_2]fig = plt.figure(figsize =(8, 6)) # Create axes instance ax = fig.add_axes([0, 0, 1, 1]) # Create plot bp = ax.boxplot(data) # Show plot plt.xticks([1,2],['user_1','user_2'])plt.show()
Pie charts are a classic way to show the composition of groups. A pie chart is a circular graph divided into slices. The larger a slice is the bigger portion of the total quantity it represents.
However, it is not generally advisable to use nowadays because the area of the pie portions can sometimes become misleading. So, while using pie charts, it is highly recommended to explicitly write down the percentage or numbers for each portion of the pie.
Pie charts are best suited to depict sections of a whole.
We can’t use a pie chart in situations when we would like to show how one or more variables develop over time.
Suppose we have a dataset containing information about Medium members. We want to see the percentage of articles read in 2020’s first six months.
# Pie Chartfig = plt.figure(figsize=(8,8))labels = 'Jan', 'Feb', 'March', 'April', 'May', 'June'user_1 = [10, 3, 15, 21, 17, 14]p = plt.pie(user_1, labels=labels, explode=(0.07, 0, 0, 0, 0, 0), autopct='%1.1f%%', startangle=130, shadow=True)plt.axis('equal')for i, (Jan, Feb, March, April, May, June) in enumerate(p): if i > 0: Jan.set_fontsize(12) Feb.set_fontsize(12) March.set_fontsize(12) April.set_fontsize(12) May.set_fontsize(12) June.set_fontsize(12)plt.show()
A treemap chart is similar to a pie chart and it does better work without misleading the contributions of each group. Treemap chart allows us to split the sum of the whole into hierarchies and then show an internal breakdown of each of these hierarchies.
Treemaps are often used for sales data, as they capture relative sizes of data categories, allowing for a quick, high-level summary of the similarities and anomalies within one category as well as between multiple categories.
Treemap charts are not suitable when our data is not divisible into categories and sub-categories.
Moreover, when we’re encoding data with area and intensity of color, our eyes aren’t great a detecting relatively minor differences in either of these dimensions. If our data is such that our audience needs to make precise comparisons between categories, it’s even more cumbersome when the categories aren’t aligned to a common baseline. We should never make our audience do more work than necessary to understand a graph!
For example, we use a treemap chart to present new users and view of articles this month.
import squarifyfig = plt.figure(figsize=(10,10))articles = [17, 22, 35, 41, 5, 12, 47]labels = ['User_1:\n 17 articles', 'User_2:\n 22 articles', 'User_3:\n 35 articles', 'User_4:\n 41 articles', 'User_5:\n 5 articles', 'User_6:\n 12 articles', 'User_7:\n 47 articles']color_list = ['#0f7216', '#b2790c', '#ffe9a3', '#f9d4d4', '#d35158', '#ea3033']plt.rc('font', size=14) squarify.plot(sizes=articles, label=labels, color=color_list, alpha=0.7)plt.axis('off')plt.show()
Time-series graphs can be used to visualize trends in counts or numerical values over time. Because date and time information is continuous categorical data (expressed as a range of values), points are plotted along the x-axis and connected by a continuous line.
The goal of time series analysis is to find patterns in the data and use the data for predictions. Time-series graphs can answer questions about our data, such as: How does the trend change over time?
# Time Series Plotplt.figure(figsize=(8,6))ts = pd.Series(np.random.randn(100), index = pd.date_range( '1/1/2020', periods = 100)) # Return the cumulative sum of the elements.ts = ts.cumsum() ts.plot() plt.show()
The code in this note is available on Github.
In this note, we learned how to build data visualization plots using Matplotlib. We can now easily build plots for understanding our data intuitively through visualizations.
Happy studying!
My note just covered all of what I consider to be the basic necessities for Matplotlib. It takes months, sometimes years to master a skill, so, don’t stop learning! If you are eager to learn more about Matplotlib, starting with the great links below.
Customize ticksMatplotlib tutorialMatplotlib galleryMatplotlib user’s guide
Customize ticks
Matplotlib tutorial
Matplotlib gallery
Matplotlib user’s guide | [
{
"code": null,
"e": 252,
"s": 47,
"text": "Matplotlib is a plotting library for the Python programming language. The most used module of Matplotib is Pyplot which provides an interface like Matlab but instead, it uses Python and it is open source."
},
{
"code": null,
"e": 435,
"s": 252,
"text": "In this note, we will focus on basic Matplotlib to help visualize our data. This is not a comprehensive list but contains common types of data visualization formats. Let’s hop to it!"
},
{
"code": null,
"e": 463,
"s": 435,
"text": "The structure of this note:"
},
{
"code": null,
"e": 520,
"s": 463,
"text": "Anatomy of Matplotlib FigureStart with PyplotChart Types"
},
{
"code": null,
"e": 549,
"s": 520,
"text": "Anatomy of Matplotlib Figure"
},
{
"code": null,
"e": 567,
"s": 549,
"text": "Start with Pyplot"
},
{
"code": null,
"e": 579,
"s": 567,
"text": "Chart Types"
},
{
"code": null,
"e": 640,
"s": 579,
"text": "A figure contains the overall window where plotting happens."
},
{
"code": null,
"e": 740,
"s": 640,
"text": "Axes: It is what we generally think of as a plot. Each Axes has a title, an x-label, and a y-label."
},
{
"code": null,
"e": 829,
"s": 740,
"text": "Note: We can have more than one Axes in a figure which helps in building multiple plots."
},
{
"code": null,
"e": 956,
"s": 829,
"text": "Axis are the number line like objects and help to generate the graph limits. Every axes has an x-axis and y-axis for plotting."
},
{
"code": null,
"e": 1308,
"s": 956,
"text": "Ticks are the markers denoting data points on axes, that is, the values used to show specific points on the coordinate axis. These values can be a number or a string. Whenever we plot a graph, the axes adjust and take the default ticks. Matplotlib’s default ticks are generally sufficient in common situations but are in no way optimal for every plot."
},
{
"code": null,
"e": 1429,
"s": 1308,
"text": "A spine to a graph is the edge of the graph. It connects the axis tick marks and noting the boundaries of the data area."
},
{
"code": null,
"e": 1589,
"s": 1429,
"text": "Pyplot is a module of Matplotlib which provides simple functions to add plot elements like lines, images, text, etc. to the current axes in the current figure."
},
{
"code": null,
"e": 1675,
"s": 1589,
"text": "At first, we set up the notebook for plotting and importing the packages we will use:"
},
{
"code": null,
"e": 1798,
"s": 1675,
"text": "import numpy as npimport matplotlib.pyplot as pltplt.style.use('seaborn-whitegrid') # Set the aesthetic style of the plots"
},
{
"code": null,
"e": 1843,
"s": 1798,
"text": "A figure and axes can be created as follows:"
},
{
"code": null,
"e": 1899,
"s": 1843,
"text": "fig, ax = plt.subplots()print(type(fig))print(type(ax))"
},
{
"code": null,
"e": 2032,
"s": 1899,
"text": "We commonly use the variable name fig to refer to a figure instance, and ax to refer to an axes instance or group of axes instances."
},
{
"code": null,
"e": 2230,
"s": 2032,
"text": "Once we have created an axes, we can use the plt.plot function to plot some data. Let’s start with a simple plot. Perhaps the simplest of all plots is the visualization of a single function y = 2x."
},
{
"code": null,
"e": 2345,
"s": 2230,
"text": "fig, ax = plt.subplots()x = np.random.randint(1,10, size=10)y = 2*x plt.plot(x,y) # same as ax.plot(x,y)plt.show()"
},
{
"code": null,
"e": 2456,
"s": 2345,
"text": "If we want to create a single figure with multiple lines, we can simply call the plot function multiple times:"
},
{
"code": null,
"e": 2579,
"s": 2456,
"text": "# Multiple linesfig, ax = plt.subplots()x = np.random.randint(1,10, size=10)y = 2*x plt.plot(x,y)plt.plot(x,x+3)plt.show()"
},
{
"code": null,
"e": 2875,
"s": 2579,
"text": "The plt.plot() function takes additional arguments that can be used to specify the line color and style. To adjust, we can use the color linestyle keyword, which accepts a string argument representing virtually any imaginable color/style. Colors and styles can be specified in a variety of ways:"
},
{
"code": null,
"e": 3442,
"s": 2875,
"text": "fig, ax = plt.subplots()x = np.linspace(0,10,1000)y = 2*x# set of default color and styleplt.plot(x, np.cos(x))# RGB tuple, values 0 to 1, solid styleplt.plot(x, np.sin(x), color=(1.0,0.2,0.3),linestyle='-')# specify color by name, dashed styleplt.plot(x, y, color='blue', linestyle='--')# short color code (rgbcmyk), dotted style plt.plot(x, x+3, color='g',linestyle=':')# Grayscale between 0 and 1, dashdot style plt.plot(x, np.log(x), color='0.75',linestyle='-.')# Hex code (RRGGBB from 00 to FF), dashed style plt.plot(x, x, color='#FFDD44',linestyle='--')"
},
{
"code": null,
"e": 3654,
"s": 3442,
"text": "Matplotlib does a decent job of choosing default axes limits for our plot, but sometimes it’s nice to have finer control. The most basic way to adjust axis limits is to use the plt.xlim() and plt.ylim() methods:"
},
{
"code": null,
"e": 3688,
"s": 3654,
"text": "plt.xlim(0, 11)plt.ylim(-1.5, 10)"
},
{
"code": null,
"e": 3811,
"s": 3688,
"text": "As the last piece of this section, we will briefly look at the labeling of plots: titles, axis labels, and simple legends."
},
{
"code": null,
"e": 4030,
"s": 3811,
"text": "plt.plot(x, np.sin(x), label='y=sin(x)')plt.plot(x,np.cos(x), label='y=cos(x)')plt.title('Sine and Cosine Functions ')plt.xlabel(\"x-axis\")plt.ylabel(\"y-axis\")plt.legend() # Describing the element of the graphplt.show()"
},
{
"code": null,
"e": 4176,
"s": 4030,
"text": "There are various plots which can be created using python Matplotlib. We will discuss the most used plots for data visualization in this section."
},
{
"code": null,
"e": 4444,
"s": 4176,
"text": "We use the World Happiness Report dataset from Kaggle. I cleaned the data and combined all files in happiness_rank.csv file. You can download and clean the data or just simply download the final result here. I recommend you check out my data cleaning codes on Github."
},
{
"code": null,
"e": 4787,
"s": 4444,
"text": "A scatter plot is a type of chart that is often used in statistics and data science. It consists of multiple data points plotted across two axes. Each variable depicted in a scatter plot would have multiple observations. This can be a very useful chart type whenever we would like to see if there is any relationship between two sets of data."
},
{
"code": null,
"e": 4957,
"s": 4787,
"text": "We use a scatter plot to identify the relationship of the data with each variable (i.e, correlation, or trend patterns.) It also helps in detecting outliers in the plot."
},
{
"code": null,
"e": 5126,
"s": 4957,
"text": "In machine learning, scatter plots are often used in regression, where x and y are continuous variables. They are also used in clustering scatters or outlier detection."
},
{
"code": null,
"e": 5206,
"s": 5126,
"text": "Scatter plots are not suitable if we are interested in observing time patterns."
},
{
"code": null,
"e": 5370,
"s": 5206,
"text": "A scatter plot is used with numerical data or numbers. So, if we have categories such as three divisions, five products, etc, a scatter plot would not reveal much."
},
{
"code": null,
"e": 5526,
"s": 5370,
"text": "fig, ax = plt.subplots(figsize = (12,6))x = df['GDP']y = df['Score']plt.scatter(x,y)plt.title('GDP vs Happiness Score')plt.xlabel('GDP')plt.ylabel('Score')"
},
{
"code": null,
"e": 5541,
"s": 5526,
"text": "3D Scatterplot"
},
{
"code": null,
"e": 5633,
"s": 5541,
"text": "3D Scatterplot helps in visualizing three numerical variables in a three- dimensional plot."
},
{
"code": null,
"e": 5898,
"s": 5633,
"text": "from mpl_toolkits.mplot3d import Axes3Dfig = plt.figure(figsize=(10,6))ax = fig.add_subplot(111, projection='3d')ax.scatter(df['Year'],df['GDP'],df['Score'], s=30)ax.set( xlabel='Year', ylabel='GDP',zlabel='Score')plt.xticks(np.arange(2015,2020,step =1))plt.show()"
},
{
"code": null,
"e": 5953,
"s": 5898,
"text": "Scatter plot with a linear regression line of best fit"
},
{
"code": null,
"e": 6152,
"s": 5953,
"text": "We will implement linear regression with Scikit-learn using the LinearRegression. After creating a linear regression object, we can obtain the line that best fits our data by calling the fit method."
},
{
"code": null,
"e": 6639,
"s": 6152,
"text": "x = df['GDP'].values.reshape(-1,1).astype('float32')y = df['Score'].values.reshape(-1,1).astype('float32')# Split the data to train and test dataX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)# Apply Linear Regression Algorithmsh = LinearRegression() h.fit(X_train,y_train)y_pred = h.predict(X_test)fig,(ax1) = plt.subplots(1, figsize = (12,6))ax1.scatter (X_test, y_test, s = 8)plt.plot(X_test,y_pred, color = 'black', linewidth = 2)plt.show()"
},
{
"code": null,
"e": 6851,
"s": 6639,
"text": "A diverging bar chart is a bar chart that has the marks for some dimension members pointing up or right, and the marks for other dimension members pointing in the opposite direction (down or left, respectively)."
},
{
"code": null,
"e": 6857,
"s": 6851,
"text": "Note:"
},
{
"code": null,
"e": 6936,
"s": 6857,
"text": "The marks flowing down or left does not necessarily represent negative values."
},
{
"code": null,
"e": 7055,
"s": 6936,
"text": "The divergent line can represent zero, but it can also be used to simply separate the marks for two-dimension members."
},
{
"code": null,
"e": 7303,
"s": 7055,
"text": "We use diverging bars to see how the items are varying based on a single metric and visualize the order and amount of this variance. If our primary objective is to compare the trend of each dimension member, a divergent bar chart is a good option."
},
{
"code": null,
"e": 7453,
"s": 7303,
"text": "The drawback to using diverging bar charts is that it’s not as easy to compare the values across dimension members as it is with a grouped bar chart."
},
{
"code": null,
"e": 7490,
"s": 7453,
"text": "We only use 2019 data as an example."
},
{
"code": null,
"e": 8340,
"s": 7490,
"text": "# Data processingtop_economies = ['United States', 'China','Japan', 'Germany','United Kingdom','India', 'France','Brazil', 'Canada']df_top = df_19[(df_19['Country'].isin(top_economies))].sort_values(['Country'])df_top.reset_index(drop=True)x = df_top.loc[:, ['Score']]df_top['Score_z'] = (x - x.mean())/x.std()df_top['colors'] = ['red' if x < 0 else 'blue' for x in df_top['Score_z']]df_top.sort_values('Score_z', inplace=True)df_top.reset_index(inplace=True)# Draw plotplt.figure(figsize=(8,6), dpi= 50)plt.hlines(y=df_top.index, xmin=0, xmax=df_top.Score_z, color=df_top.colors, alpha=0.5, linewidth=20)# Decorationsplt.gca().set(ylabel='Country', xlabel='Happiness_Score')plt.yticks(df_top.index, df_top.Country, fontsize=15)plt.title('Happiness Score for Top Economies in 2019', fontdict={'size':20})plt.grid(linestyle='--', alpha=0.5)plt.show()"
},
{
"code": null,
"e": 8470,
"s": 8340,
"text": "The idea of an area chart is based on the line chart. Colored regions (areas) show us the development of each variable over time."
},
{
"code": null,
"e": 8577,
"s": 8470,
"text": "There are three types of area charts: regular area chart, stacked area chart, and 100% stacked area chart."
},
{
"code": null,
"e": 8774,
"s": 8577,
"text": "We use area charts to show how the parts of a complete change over time. For example, the happiness score has six generating divisions; we would like to see each of these divisions’ contributions."
},
{
"code": null,
"e": 9011,
"s": 8774,
"text": "Moreover, if we are interested in the portion generated by each division and not that much of the total amount of the division self, we can use a 100% stacked area chart. This will show each division’s percentage contribution over time."
},
{
"code": null,
"e": 9260,
"s": 9011,
"text": "Area charts are not the best choice if we want to compare the size of different shares with each other. If you want to show that one share overtook another one; or if the differences between our values are very small, consider a line chart instead."
},
{
"code": null,
"e": 9282,
"s": 9260,
"text": "Python Implementation"
},
{
"code": null,
"e": 9522,
"s": 9282,
"text": "# Regular Area Chart# Create datax = df_top['Score']y = df_top['GDP']# Change the color and its transparencyplt.fill_between( x, y, color=\"skyblue\", alpha=0.2)plt.xlabel('Score')plt.ylabel('GDP')plt.plot(x, y, color=\"Slateblue\", alpha=0.6)"
},
{
"code": null,
"e": 9883,
"s": 9522,
"text": "# Stacked Area Chartplt.stackplot(df_top.index, [df_top['GDP'], df_top['Health'], df_top['Support'], df_top['Freedom']], df_top['Generosity'], df_top['Corruption'], labels=['GDP', 'Health', 'Support', 'Freedom','Generosity','Corruption'], alpha=0.8)plt.legend(loc=2, fontsize='large')plt.show()"
},
{
"code": null,
"e": 10414,
"s": 9883,
"text": "# 100% Stacked Area Chartdata_perc = df_top[['GDP', 'Health', 'Support', 'Freedom','Generosity','Corruption']]data_perc = data_perc.divide(data_perc.sum(axis=1), axis=0)plt.stackplot(data_perc.index, [data_perc['GDP'], data_perc['Health'], data_perc['Support'], data_perc['Freedom']], data_perc['Generosity'], data_perc['Corruption'], labels=['GDP', 'Health', 'Support', 'Freedom','Generosity','Corruption'], alpha=0.8)plt.legend(loc=2, fontsize='large')plt.show()"
},
{
"code": null,
"e": 10578,
"s": 10414,
"text": "Bar charts are among the most frequently used chart types. As the name suggests, a bar chart is composed of a series of bars illustrating a variable’s development."
},
{
"code": null,
"e": 10695,
"s": 10578,
"text": "There are four types of bar charts: regular bar chart, horizontal bar chart, group bar chart, and stacked bar chart."
},
{
"code": null,
"e": 10905,
"s": 10695,
"text": "Bar charts are great when we want to track the development of one or two variables over time. One axis of the chart shows the specific categories being compared, and the other axis represents a measured value."
},
{
"code": null,
"e": 11183,
"s": 10905,
"text": "A simple bar chart isn’t suitable when we have a single period breakdown of a variable. For example, if I want to portray the main business lines that contributed to a company’s revenues, I wouldn’t use a bar chart. Instead, I would create a pie chart or one of its variations."
},
{
"code": null,
"e": 11568,
"s": 11183,
"text": "# Bar Chartcountries = ['United States','Japan', 'Germany','Brazil', 'India']y_pos = np.arange(len(countries))data = df_19[(df_19['Country'].isin(countries))].sort_values(['Country'])data.sort_values('GDP', inplace=True)data.reset_index(drop=True)plt.bar(y_pos, data['GDP'], align='center', alpha=0.5)plt.xticks(y_pos, data['Country'])plt.ylabel('GDP')plt.title('Bar Chart')plt.show()"
},
{
"code": null,
"e": 11876,
"s": 11568,
"text": "# Horizontal bar chartdf_19[(df_19['Country'].isin(countries))].sort_values(['Country'])data.sort_values('Score', inplace=True)data.reset_index(drop=True)plt.barh(y_pos, data['Score'], align='center', alpha=0.5)plt.yticks(y_pos, data['Country'])plt.xlabel('Score')plt.title('Horizontal Bar Chart')plt.show()"
},
{
"code": null,
"e": 12246,
"s": 11876,
"text": "# Group bar chartindex = np.arange(5)width = 0.35fig, ax = plt.subplots(figsize=(9, 6))rects1 = ax.bar(index - width / 2, data['GDP'], width, color='#1f77b4', alpha=0.5)rects2 = ax.bar(index + width / 2, data['Health'], width, color='#1f77b4')plt.xticks(index, gdp['Country'])plt.legend((rects1[0], rects2[0]), ('GDP', 'Health'))plt.show()"
},
{
"code": null,
"e": 12579,
"s": 12246,
"text": "# Stacked bar chartfig = plt.figure(figsize=(14,10))rect1 = plt.bar(np.arange(5), data['Support'], width=0.5, color='lightblue')rect2 = plt.bar(np.arange(5), data['Freedom'], width=0.5, color='#1f77b4')plt.xticks(index, data['Country'])plt.legend((rect1[0], rect2[0]), ('Support', 'Freedom'))plt.show()"
},
{
"code": null,
"e": 12795,
"s": 12579,
"text": "Lollipop chart serves a similar purpose as an ordered bar chart in a visually pleasing way. We use lollipop charts to show the relationship between a numerical variable and another numerical or categorical variable."
},
{
"code": null,
"e": 13062,
"s": 12795,
"text": "The lollipop chart is often claimed to be useful compared to a normal bar chart, if we are dealing with a large number of values and when the values are all high, such as in the 80–90% range (out of 100%). Then a large set of tall columns can be visually aggressive."
},
{
"code": null,
"e": 13203,
"s": 13062,
"text": "If our data has unsorted bars of very similar length — it is harder to compare the lengths of two very similar lollipops than standard bars."
},
{
"code": null,
"e": 13225,
"s": 13203,
"text": "Python Implementation"
},
{
"code": null,
"e": 13591,
"s": 13225,
"text": "(markerline, stemlines, baseline) = plt.stem(data['Country'], data['GDP'])plt.setp(markerline, marker='o', markersize=15, markeredgewidth=2, color='lightblue')plt.setp(stemlines, color='lightblue')plt.setp(baseline, visible=False)plt.tick_params(labelsize=12)plt.ylabel('GDP', size=12)plt.ylim(bottom=0)plt.show()"
},
{
"code": null,
"e": 13907,
"s": 13591,
"text": "A histogram is a vertical bar chart that depicts the distribution of a set of data. Histograms are used to show distributions of variables while bar charts are used to compare variables. Histograms plot quantitative data with ranges of the data grouped into bins or intervals while bar charts plot categorical data."
},
{
"code": null,
"e": 13981,
"s": 13907,
"text": "Note: Bar graphs have space between the columns, while histograms do not."
},
{
"code": null,
"e": 14212,
"s": 13981,
"text": "Histograms are great when we would like to show the distribution of the data we are working with. This allows us to group continuous data into bins and hence, provide a useful representation of where observations are concentrated."
},
{
"code": null,
"e": 14234,
"s": 14212,
"text": "Python Implementation"
},
{
"code": null,
"e": 14357,
"s": 14234,
"text": "# Histogramfig = plt.figure(figsize=(8,6))plt.hist(df_19['Corruption'], bins=6, density=True)plt.grid(alpha=0.2)plt.show()"
},
{
"code": null,
"e": 14559,
"s": 14357,
"text": "A box plot or whisker plot is a way of summarizing a set of data measured on an interval scale. This type of graph is used to show the shape of the distribution, its central value, and its variability."
},
{
"code": null,
"e": 14731,
"s": 14559,
"text": "We use box plots in explanatory data analysis, indicating whether a distribution is skewed and whether there are potential unusual observations (outliers) in the data set."
},
{
"code": null,
"e": 14861,
"s": 14731,
"text": "Box plots are also very useful when large numbers of observations are involved and when two or more data sets are being compared."
},
{
"code": null,
"e": 14961,
"s": 14861,
"text": "Box plots do not show the distribution in as much detail as a stem and leaf plot or histogram does."
},
{
"code": null,
"e": 15069,
"s": 14961,
"text": "Suppose we have a dataset containing the number of articles Medium members read in 2020’s first six months."
},
{
"code": null,
"e": 15361,
"s": 15069,
"text": "# Create datasetuser_1 = [10, 3, 15, 21, 17, 14]user_2 = [5, 13, 10, 7, 9, 12]data = [user_1, user_2]fig = plt.figure(figsize =(8, 6)) # Create axes instance ax = fig.add_axes([0, 0, 1, 1]) # Create plot bp = ax.boxplot(data) # Show plot plt.xticks([1,2],['user_1','user_2'])plt.show()"
},
{
"code": null,
"e": 15556,
"s": 15361,
"text": "Pie charts are a classic way to show the composition of groups. A pie chart is a circular graph divided into slices. The larger a slice is the bigger portion of the total quantity it represents."
},
{
"code": null,
"e": 15814,
"s": 15556,
"text": "However, it is not generally advisable to use nowadays because the area of the pie portions can sometimes become misleading. So, while using pie charts, it is highly recommended to explicitly write down the percentage or numbers for each portion of the pie."
},
{
"code": null,
"e": 15872,
"s": 15814,
"text": "Pie charts are best suited to depict sections of a whole."
},
{
"code": null,
"e": 15983,
"s": 15872,
"text": "We can’t use a pie chart in situations when we would like to show how one or more variables develop over time."
},
{
"code": null,
"e": 16129,
"s": 15983,
"text": "Suppose we have a dataset containing information about Medium members. We want to see the percentage of articles read in 2020’s first six months."
},
{
"code": null,
"e": 16654,
"s": 16129,
"text": "# Pie Chartfig = plt.figure(figsize=(8,8))labels = 'Jan', 'Feb', 'March', 'April', 'May', 'June'user_1 = [10, 3, 15, 21, 17, 14]p = plt.pie(user_1, labels=labels, explode=(0.07, 0, 0, 0, 0, 0), autopct='%1.1f%%', startangle=130, shadow=True)plt.axis('equal')for i, (Jan, Feb, March, April, May, June) in enumerate(p): if i > 0: Jan.set_fontsize(12) Feb.set_fontsize(12) March.set_fontsize(12) April.set_fontsize(12) May.set_fontsize(12) June.set_fontsize(12)plt.show()"
},
{
"code": null,
"e": 16909,
"s": 16654,
"text": "A treemap chart is similar to a pie chart and it does better work without misleading the contributions of each group. Treemap chart allows us to split the sum of the whole into hierarchies and then show an internal breakdown of each of these hierarchies."
},
{
"code": null,
"e": 17135,
"s": 16909,
"text": "Treemaps are often used for sales data, as they capture relative sizes of data categories, allowing for a quick, high-level summary of the similarities and anomalies within one category as well as between multiple categories."
},
{
"code": null,
"e": 17234,
"s": 17135,
"text": "Treemap charts are not suitable when our data is not divisible into categories and sub-categories."
},
{
"code": null,
"e": 17657,
"s": 17234,
"text": "Moreover, when we’re encoding data with area and intensity of color, our eyes aren’t great a detecting relatively minor differences in either of these dimensions. If our data is such that our audience needs to make precise comparisons between categories, it’s even more cumbersome when the categories aren’t aligned to a common baseline. We should never make our audience do more work than necessary to understand a graph!"
},
{
"code": null,
"e": 17747,
"s": 17657,
"text": "For example, we use a treemap chart to present new users and view of articles this month."
},
{
"code": null,
"e": 18304,
"s": 17747,
"text": "import squarifyfig = plt.figure(figsize=(10,10))articles = [17, 22, 35, 41, 5, 12, 47]labels = ['User_1:\\n 17 articles', 'User_2:\\n 22 articles', 'User_3:\\n 35 articles', 'User_4:\\n 41 articles', 'User_5:\\n 5 articles', 'User_6:\\n 12 articles', 'User_7:\\n 47 articles']color_list = ['#0f7216', '#b2790c', '#ffe9a3', '#f9d4d4', '#d35158', '#ea3033']plt.rc('font', size=14) squarify.plot(sizes=articles, label=labels, color=color_list, alpha=0.7)plt.axis('off')plt.show()"
},
{
"code": null,
"e": 18567,
"s": 18304,
"text": "Time-series graphs can be used to visualize trends in counts or numerical values over time. Because date and time information is continuous categorical data (expressed as a range of values), points are plotted along the x-axis and connected by a continuous line."
},
{
"code": null,
"e": 18768,
"s": 18567,
"text": "The goal of time series analysis is to find patterns in the data and use the data for predictions. Time-series graphs can answer questions about our data, such as: How does the trend change over time?"
},
{
"code": null,
"e": 19013,
"s": 18768,
"text": "# Time Series Plotplt.figure(figsize=(8,6))ts = pd.Series(np.random.randn(100), index = pd.date_range( '1/1/2020', periods = 100)) # Return the cumulative sum of the elements.ts = ts.cumsum() ts.plot() plt.show()"
},
{
"code": null,
"e": 19059,
"s": 19013,
"text": "The code in this note is available on Github."
},
{
"code": null,
"e": 19233,
"s": 19059,
"text": "In this note, we learned how to build data visualization plots using Matplotlib. We can now easily build plots for understanding our data intuitively through visualizations."
},
{
"code": null,
"e": 19249,
"s": 19233,
"text": "Happy studying!"
},
{
"code": null,
"e": 19500,
"s": 19249,
"text": "My note just covered all of what I consider to be the basic necessities for Matplotlib. It takes months, sometimes years to master a skill, so, don’t stop learning! If you are eager to learn more about Matplotlib, starting with the great links below."
},
{
"code": null,
"e": 19576,
"s": 19500,
"text": "Customize ticksMatplotlib tutorialMatplotlib galleryMatplotlib user’s guide"
},
{
"code": null,
"e": 19592,
"s": 19576,
"text": "Customize ticks"
},
{
"code": null,
"e": 19612,
"s": 19592,
"text": "Matplotlib tutorial"
},
{
"code": null,
"e": 19631,
"s": 19612,
"text": "Matplotlib gallery"
}
]
|
C++ Program to Implement Rolling Hash | Rolling hash is a hash function in which the input is hashed in a window that moves through the input.
Rabin-Karp is popular application of rolling hash. The rolling hash function proposed by Rabin and Karp calculates an integer value. For a string the integer value is numeric value of a string.
The Rabin–Karp string search algorithm is often explained using a very simple rolling hash function that only uses multiplications and additions −
H=c1ak-1+c2ak-2+....+ cka0.
Where, a is a constant, and c1, c2....ck are the input characters. In order to manipulate Huge value of H, mod n is done.
Begin
Declare a constant variable P_B of the integer datatype.
Initialize P_B= 227.
Declare a constant variable P_M of the integer datatype.
Initialize P_M= 1000005.
Declare a hash() function
Pass a string s as parameter.
Declare r of the integer datatype.
Initialize r = 0.
for (int i = 0; i < s.size(); i++)
r = r* P_B + s[i]
r %= P_M
return r
Declare function rabin_karp(const string& n, const string& hstack)
Declare h1 of the integer datatype.
Initialize h1 = hash(n).
Declare h2 of the integer datatype.
Initialize h2 = 0.
Declare power of the integer datatype.
Initialize power = 1.
for (int i = 0; i < n.size(); i++)
power = (power * P_B) % P_M
for (int i = 0; i < hstack.size(); i++)
h2 = h2*P_B + hstack[i]
h2 %= P_M
if (i >= n.size())
h2 -= power * hstack[i-n.size()] % P_M
if (h2 < 0)
h2 += P_M
if (i >= n.size()-1 && h1 == h2)
return i - (n.size()-1);
return -1;
Declare s1 and s2 to the string type.
Print “Enter Input String:”
Call getline(line, s1) to enter the string.
Print “Enter string to find:”
Take input for s2.
if(rabin_karp(s2, s1) == -1)
print” String not found”
else
print the string.
End.
Live Demo
#include <iostream>
#include <string>
using namespace std;
const int P_B= 227;
const int P_M = 1000005;
int hash(const string& s) {
int r = 0;
for (int i = 0; i < s.size(); i++) {
r = r* P_B + s[i];
r %= P_M;
}
return r;
}
int rabin_karp(const string& n, const string& hstack) {
int h1 = hash(n);
int h2 = 0;
int power = 1;
for (int i = 0; i < n.size(); i++)
power = (power * P_B) % P_M;
for (int i = 0; i < hstack.size(); i++) {
h2 = h2*P_B + hstack[i];
h2 %= P_M;
if (i >= n.size()) {
h2 -= power * hstack[i-n.size()] % P_M;
if (h2 < 0)
h2 += P_M;
}
if (i >= n.size()-1 && h1 == h2)
return i - (n.size()-1);
}
return -1;
}
int main() {
string s1, s2;
cout<<"Enter Input String: ";
getline(cin, s1);
cout<<"Enter String to find: ";
cin>>s2;
if(rabin_karp(s2, s1) == -1)
cout<<"String not found"<<endl;
else
cout<<"String"<<" "<<s2<<” “<<"found at position "<<rabin_karp(s2, s1)<<endl;
return 0;
}
Enter Input String: Tutorialspoint
Enter String to find: a
String a found at position 6
Enter Input String: Tutorialspoint
Enter String to find: b
String not found | [
{
"code": null,
"e": 1165,
"s": 1062,
"text": "Rolling hash is a hash function in which the input is hashed in a window that moves through the input."
},
{
"code": null,
"e": 1359,
"s": 1165,
"text": "Rabin-Karp is popular application of rolling hash. The rolling hash function proposed by Rabin and Karp calculates an integer value. For a string the integer value is numeric value of a string."
},
{
"code": null,
"e": 1506,
"s": 1359,
"text": "The Rabin–Karp string search algorithm is often explained using a very simple rolling hash function that only uses multiplications and additions −"
},
{
"code": null,
"e": 1534,
"s": 1506,
"text": "H=c1ak-1+c2ak-2+....+ cka0."
},
{
"code": null,
"e": 1656,
"s": 1534,
"text": "Where, a is a constant, and c1, c2....ck are the input characters. In order to manipulate Huge value of H, mod n is done."
},
{
"code": null,
"e": 3040,
"s": 1656,
"text": "Begin\n Declare a constant variable P_B of the integer datatype.\n Initialize P_B= 227.\n Declare a constant variable P_M of the integer datatype.\n Initialize P_M= 1000005.\n Declare a hash() function\n Pass a string s as parameter.\n Declare r of the integer datatype.\n Initialize r = 0.\n for (int i = 0; i < s.size(); i++)\n r = r* P_B + s[i]\n r %= P_M\n return r\n Declare function rabin_karp(const string& n, const string& hstack)\n Declare h1 of the integer datatype.\n Initialize h1 = hash(n).\n Declare h2 of the integer datatype.\n Initialize h2 = 0.\n Declare power of the integer datatype.\n Initialize power = 1.\n for (int i = 0; i < n.size(); i++)\n power = (power * P_B) % P_M\n for (int i = 0; i < hstack.size(); i++)\n h2 = h2*P_B + hstack[i]\n h2 %= P_M\n if (i >= n.size())\n h2 -= power * hstack[i-n.size()] % P_M\n if (h2 < 0)\n h2 += P_M\n if (i >= n.size()-1 && h1 == h2)\n return i - (n.size()-1);\n return -1;\n Declare s1 and s2 to the string type.\n Print “Enter Input String:”\n Call getline(line, s1) to enter the string.\n Print “Enter string to find:”\n Take input for s2.\n if(rabin_karp(s2, s1) == -1)\n print” String not found”\n else\n print the string.\nEnd."
},
{
"code": null,
"e": 3051,
"s": 3040,
"text": " Live Demo"
},
{
"code": null,
"e": 4105,
"s": 3051,
"text": "#include <iostream>\n#include <string>\nusing namespace std;\nconst int P_B= 227;\nconst int P_M = 1000005;\nint hash(const string& s) {\n int r = 0;\n for (int i = 0; i < s.size(); i++) {\n r = r* P_B + s[i];\n r %= P_M;\n }\n return r;\n}\nint rabin_karp(const string& n, const string& hstack) {\n int h1 = hash(n);\n int h2 = 0;\n int power = 1;\n for (int i = 0; i < n.size(); i++)\n power = (power * P_B) % P_M;\n for (int i = 0; i < hstack.size(); i++) {\n h2 = h2*P_B + hstack[i];\n h2 %= P_M;\n if (i >= n.size()) {\n h2 -= power * hstack[i-n.size()] % P_M;\n if (h2 < 0)\n h2 += P_M;\n }\n if (i >= n.size()-1 && h1 == h2)\n return i - (n.size()-1);\n }\n return -1;\n}\nint main() {\n string s1, s2;\n cout<<\"Enter Input String: \";\n getline(cin, s1);\n cout<<\"Enter String to find: \";\n cin>>s2;\n if(rabin_karp(s2, s1) == -1)\n cout<<\"String not found\"<<endl;\n else\n cout<<\"String\"<<\" \"<<s2<<” “<<\"found at position \"<<rabin_karp(s2, s1)<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 4269,
"s": 4105,
"text": "Enter Input String: Tutorialspoint\nEnter String to find: a\nString a found at position 6\nEnter Input String: Tutorialspoint\nEnter String to find: b\nString not found"
}
]
|
Adobe RoboHelp - Quick Guide | Adobe RoboHelp is a popular Help Authoring Tool (HAT) from Adobe. It is used by industry professionals to deliver engaging help content, e-learning resources, organizational policies and knowledge base articles to a wide audience irrespective of device form factor. The latest version of RoboHelp (2017 release) helps you to easily create next-gen Responsive HTML5 layouts, which enable seamless navigation and rich interactivity.
RoboHelp was first created by Gen Kiyooka and released by Blue Sky Software in 1992. Blue Sky Software was acquired by Macromedia, which was subsequently acquired by Adobe in 2005. Adobe RoboHelp 2017 is versioned as 13.0 although technically it is version 21 taking into account the previous versions released under Macromedia.
RoboHelp has evolved from being just a HAT to a versatile tool, which can help you create eBooks and even web sites. RoboHelp can output to a variety of help formats using the following Single Source Layouts (SSLs) −
Responsive HTML5
eBook
Microsoft HTML Help
JavaHelp
Oracle Help
Eclipse Help
Adobe AIR Help
Standard Word and PDF documentation
One of the biggest challenges faced in content delivery is ensuring that the intended audience is able to view it. RoboHelp allows content creators to create native apps for Android and iOS without the need for any extra software.
With a plethora of new features in the latest release, Adobe RoboHelp remains the industry standard HAT for creating engaging help, e-learning and technical content which addresses the varied needs of the target audience in a dynamic way. It is easy to use – both by seasoned authors as well as by novices.
The 2017 release of RoboHelp packs in many new features. These include −
Next-generation HTML5 layouts
Auto-complete
Thumbnail support
Favorites in Responsive HTML5 layouts
Baggage file folder import
Variable views
Let us understand them in detail.
The 2017 release of RoboHelp promises to help you create visually engaging borderless HTML5 layouts. These layouts offer a superior search and navigation experience and are preloaded with many features like topic sliders, show/hide widgets, etc. The responsive design enables the content to scale well across screens of different sizes.
Now you can get predictive search results in the search field of the responsive HTML5 output after typing the first few characters. The results appear instantaneously and are contextual without the user having to enter the full search string. The results are ranked based on the frequency of the keyword in the content.
You can now publish thumbnails of images, which can reduce page loading times, saving bandwidth, while also being mobile friendly. If needed, the user can simply load the larger image by clicking on the thumbnail. It is possible to maintain a standard thumbnail size in order to maintain consistency throughout the content.
It is now possible to mark topics as favorites and add custom links with the new Indigo themed Responsive HTML5 layout.
You can now add multiple baggage files stored in a folder in a single click by adding the folder to the project thereby making it easy to import folders containing support information.
You can now easily toggle between the variable name and its value by a keyboard shortcut or from the context menu. You can toggle a single variable or all variables to view content exactly as your audience would view it.
Adobe RoboHelp Server is a server based help solution. You can upload your help content on a server, which can then provide real-time end user feedback. It can log data on the queries, which is asked by the users. RoboHelp Server can graphically show how users are navigating around the help system.
You can use an authoring tool to author the content, which can include multiple projects and upload the entire project onto the RoboHelp Server. The RoboHelp Server includes automatic project merging, which allows authors to work on different projects at different schedules and publish all of them to the same server. Authors can also publish projects written in various languages on the same server.
The RoboHelp Server can also interface with database servers such as Oracle or MS SQL Server and generate reports and logs. The response to the user query is relayed back via an Apache HTTP Server.
The typical RoboHelp workspace comprises of elements called Pods, Panes, Bars and Windows. Let us have a look at some of the components of the workspace.
The Quick Access Toolbar provides access to frequently used commands. It can be customized to access the commands you access the most.
The default commands include: Save All, Copy, Paste, Undo, and Redo.
Tabs are logical groups of commands put together. A tab contains commands of related functionality. Tabs are contextual and change depending on the type of content and formatting.
The document pane generally comprises of three rows of tabs as shown in the following screenshot.
These tabs are explained below.
The first row is the Tabbed Document Pane. Each tab comprises of one project. You can work on multiple projects at once and copy paste assets between these projects.
The first row is the Tabbed Document Pane. Each tab comprises of one project. You can work on multiple projects at once and copy paste assets between these projects.
The second row is the Design and HTML View Panes. For any given document, you can toggle between the design you are working on and the HTML code of your design. You can edit the HTML for even finer control. The HTML code is auto-generated as you keep working on the design.
The second row is the Design and HTML View Panes. For any given document, you can toggle between the design you are working on and the HTML code of your design. You can edit the HTML for even finer control. The HTML code is auto-generated as you keep working on the design.
The third row shows the Document Area Selectors. These help you to jump to various sections of the document such as Paragraphs, Headings and Hyperlinks.
The third row shows the Document Area Selectors. These help you to jump to various sections of the document such as Paragraphs, Headings and Hyperlinks.
Pods are panes that you can dock anywhere in the workspace to get access to all features, which are logically grouped. For example, the Project Manager pod shows all the components of the project. Pods can be grouped together or can be free floating on the workspace.
You can also make them auto-hide or move them to a different monitor.
RoboHelp makes it easy to locate and identify commands associated with a particular function by organizing them into tabs. The tabs are organized in a ribbon similar to the Microsoft Office suite of programs.
The ribbon comprises several tabs, which include −
File
Project
Edit
Insert
Review
Collaborate
Output
Tools
Let us understand each of these in detail.
Create new projects, open, save the existing project, view recent projects and change program settings.
Create, import, edit, and delete project components such as topics, snippets, tags, and variables. You can save the currently unsaved changes across the project.
Creating and editing stylesheets, text formatting and content tagging.
Insert objects such as tables, images, Adobe Captivate content and snippets.
Track changes, accept and reject changes in a document review.
Share project resources across users and enable version control.
Create, search, setup, generate, view and open RoboHelp outputs.
You can create and view reports. RoboHelp ships with a number of scripts, which you can use to perform certain commands. Select and execute scripts from the Scripts list in this tab.
A pod is a floating or docked window of the workflow or associated functions organized in a logical manner. To open a pod, go to the Project tab, then in the Open section, click on the Pods icon to reveal a list of pods. Select a pod from the list. You can either dock the pod or keep it floating on your desktop. You can also auto-hide the pod or open it as a tabbed document.
RoboHelp includes many types of pods. Some of them include −
Starter Pod
Project Manager Pod
Output Setup Pod
Let us discuss each of these in detail.
The Starter Pod usually appears as a tabbed document but just like any other pod, you can make it float or even dock it. It usually the starting point in the RoboHelp workflow.
The Starter Pod comprises of four sections, which are −
Recent Projects − Shows a list of recently opened projects.
Recent Projects − Shows a list of recently opened projects.
Create − Lets you choose the type of help file you want to create.
Create − Lets you choose the type of help file you want to create.
Import − Import content from Microsoft Word, Adobe FrameMaker, Adobe PDF files, HTML or other supported formats.
Import − Import content from Microsoft Word, Adobe FrameMaker, Adobe PDF files, HTML or other supported formats.
Resources − Contains links to help resources, seminars and knowledge base articles to help you get the most out of RoboHelp.
Resources − Contains links to help resources, seminars and knowledge base articles to help you get the most out of RoboHelp.
The Project Manager pod contains all the various folders in which you store and edit your project files. The Project Manager pod has default folders for each content type.
For example, all images in the project are stored under the Images folder, videos and sounds are stored under the Multimedia folder, etc.
The Project Manager Pod also contains the Baggage Files folder, which contains the indirectly linked files that are part of the project. The baggage files might include –PDF files, PowerPoint presentations, etc. Double-clicking on files within the Baggage Files folder opens the file in its associated application.
The Output Setup Pod helps you to view and modify the output of the content based on the targeted device. It contains a hierarchical organization of the different output components such as the Window, Master Pages, Skins, Device Profiles, Screen Layouts, etc.
Right-click on any container to change its properties.
For example – If you want to alter the dimensions of the MS_HTML output window, right-click on the MS_HTML container in the Windows folder and select how you want the window to be displayed on the screen.
The arrangement of workspace elements such windows, pods and other elements is called an environment. Environments can be customized as desired by the user. There can be specific arrangements of windows and pods, which can be saved as an environment.
Environments can then be recalled by selecting the environment from the Workspace menu on the upper right hand corner of the window. Environments are saved in an ‘.rhs file’, which can be exchanged with other authors.
Arrange all the pods in the workspace. Click on the dropdown arrow next to the Workspace in the upper right hand corner of the RoboHelp window. Click on Save... and select a location and name for the workspace.
Click on the dropdown arrow next to the Workspace in the upper right hand corner of the RoboHelp window and select Load....
Browse to the file location of the .rhs file and click on Open to load the environment.
To delete an environment, navigate to the location on the disk, where the .rhs file was stored and simply delete the .rhs file pertaining to that environment.
Keyboard shortcuts help in quickly completing tasks and RoboHelp has many keyboard shortcuts to enable you to get your work done faster. You can also customize your own keyboard shortcuts.
The following points will explain how to create keyboard shortcuts in RoboHelp.
In the dropdown menu, next to the Quick Access Toolbar select the More Commands option.
In the dropdown menu, next to the Quick Access Toolbar select the More Commands option.
In the General section, under User Interface Options, click on Customize Keyboard Shortcuts.
In the General section, under User Interface Options, click on Customize Keyboard Shortcuts.
Choose a tab category in the Category dropdown and select a command for which you want to assign a keyboard shortcut.
Choose a tab category in the Category dropdown and select a command for which you want to assign a keyboard shortcut.
In the Press new shortcut key box, enter the keyboard shortcut or combination and click on Assign. If keyboard shortcuts are already assigned, it will show up in the Key assignments: box.
In the Press new shortcut key box, enter the keyboard shortcut or combination and click on Assign. If keyboard shortcuts are already assigned, it will show up in the Key assignments: box.
Once you have done assigning all keyboard shortcuts, click on Close to close the dialog box.
Once you have done assigning all keyboard shortcuts, click on Close to close the dialog box.
You can also export the list of keyboard shortcuts as a CSV file by selecting Export.
You can also export the list of keyboard shortcuts as a CSV file by selecting Export.
The following points will explain how to remove the keyboard shortcuts in RoboHelp.
To remove an assigned shortcut, navigate to the Customize Keyboard Shortcuts... dialog box and click on the command of which you want the keyboard shortcut to be removed.
To remove an assigned shortcut, navigate to the Customize Keyboard Shortcuts... dialog box and click on the command of which you want the keyboard shortcut to be removed.
Then click on Remove to remove the keyboard shortcut assigned to that command.
Then click on Remove to remove the keyboard shortcut assigned to that command.
To restore the keyboard shortcuts to their default settings, select Reset All.
To restore the keyboard shortcuts to their default settings, select Reset All.
To configure general program options, go to the File tab, then go to Options and select the General section to change the settings.
An overview of some of the important settings is given in the following screenshot −
Following are the preferences for general setting in RoboHelp.
Use underscores in filenames − Topic file names are saved with underscores between words, which are required for HTML projects.
Use underscores in filenames − Topic file names are saved with underscores between words, which are required for HTML projects.
Automatically check for updates − Checks for updates upon exit. You can also enable this option by selecting File → Help → Accounts and updates → Updates...
Automatically check for updates − Checks for updates upon exit. You can also enable this option by selecting File → Help → Accounts and updates → Updates...
Allow editing of multiple topics − Opens topics in different tabs in Design Editor and allows editing.
Allow editing of multiple topics − Opens topics in different tabs in Design Editor and allows editing.
Clear project cache (.cpd file) before opening any project − This helps to Delete the old <ProjectName>.cpd file every time. While opening a project and a new <ProjectName>.cpd is created from the project files.
Clear project cache (.cpd file) before opening any project − This helps to Delete the old <ProjectName>.cpd file every time. While opening a project and a new <ProjectName>.cpd is created from the project files.
Remember project state − Ensures that RoboHelp remembers the location of the opened files and pods, so that the project will open in the same state, the next time you open the program.
Remember project state − Ensures that RoboHelp remembers the location of the opened files and pods, so that the project will open in the same state, the next time you open the program.
Following are the list of commands in RoboHelp.
Auto-compile outdated files − Automatically generates your primary layout, when the output files are out of date.
Auto-compile outdated files − Automatically generates your primary layout, when the output files are out of date.
Auto-display output view − Shows the Output View at the bottom of the program window, when a project is generating.
Auto-display output view − Shows the Output View at the bottom of the program window, when a project is generating.
Convert RoboHelp-edited topics to HTML − Converts XHTML topics into HTML in the output. Topics created or edited with third-party editors are not converted.
Convert RoboHelp-edited topics to HTML − Converts XHTML topics into HTML in the output. Topics created or edited with third-party editors are not converted.
Show learning resources on Starter page − Show or hide the area that has a stream of learning resources on the Starter page.
Show learning resources on Starter page − Show or hide the area that has a stream of learning resources on the Starter page.
A project is a collection of source files that becomes the help system, which the end user sees. Project files are stored in the .xpj format and contain the information and properties of the project.
A project file comprises of the following components −
Content
Properties
Navigation
Let us discuss each of these in detail.
The project content includes the topics and information about the location of topics, images, index, ToC, etc.
On a new project, default properties are used. These properties include settings such as – Title, Language, Windows, etc., which can be modified based on the requirement.
Projects include a ToC, Index and full text search to enable the user to navigate the content.
A RoboHelp project comprises of the following files −
Main project file (XPJ)
Folder files (FPJ)
Single-source layout files (SSL)
Auxiliary project files (APJ) and
Other types of files
Let us discuss each of these files in detail below.
The project file (.xpj) is XML-based. Older .mpj files convert to XPJ files in the latest version of RoboHelp.
The FPJ file lists the folder contents. Only those subfolders and topics that are listed in the FPJ file of a folder are displayed.
Stores properties of the single-source layout and is modified when you edit the properties.
Components such as windows, baggage files, map files, font sets, etc., have corresponding APJ files, which get modified or edited.
Other types of files in a project include the following −
Browse sequences (BRS)
Topics (HTM)
TOC (HHC)
Index (HHK)
Glossary (GLO)
Image and multimedia files (filename extension varies)
Style sheets (CSS)
You can create a project from scratch or by importing data from an external file such as FrameMaker, Word or PDF.
The following points describe how to create a new project in RoboHelp.
A new project can be created either by selecting File → New Project or using the ‘More’ option in the Starter pod under Create New.
A new project can be created either by selecting File → New Project or using the ‘More’ option in the Starter pod under Create New.
In the New Project dialog box, double-click a project type. You can change the project type after your project is created.
In the New Project dialog box, double-click a project type. You can change the project type after your project is created.
In the New Project Wizard dialog box, specify the options such as Project Title, File Name, Location on Disk and the title of first topic and click on Finish to create the project.
In the New Project Wizard dialog box, specify the options such as Project Title, File Name, Location on Disk and the title of first topic and click on Finish to create the project.
The following steps explain how to create a project by importing documents in RoboHelp.
You can create new projects by importing content from external sources such as FrameMaker or Word documents.
You can create new projects by importing content from external sources such as FrameMaker or Word documents.
Go to the New Project dialog box File → New Project or by using the ‘More’ option in the Starter pod under Create New. Select the Import tab.
Go to the New Project dialog box File → New Project or by using the ‘More’ option in the Starter pod under Create New. Select the Import tab.
Choose the type of document that you need to import and click OK.
Choose the type of document that you need to import and click OK.
In the New Project Wizard dialog box, specify the options such as Project Title, File Name, Location on Disk and the title of the first topic and click on Finish to create the project.
In the New Project Wizard dialog box, specify the options such as Project Title, File Name, Location on Disk and the title of the first topic and click on Finish to create the project.
You can open a project when starting RoboHelp using the Starter pod or traditionally by using the File menu.
The Starter pod shows a list of recently opened projects. Click on the project name, which has to be opened. If you do not see the needed project, click Open Project and navigate to the location of the project on disk.
Click on the File tab and select Open Project. Click on the Local or Network Path and select a project from disk.
If you are opening projects created in an older version of RoboHelp, you will be asked to convert the project into the new format.
To change settings for a project, in the Project tab, click on Project Settings in the File section.
You can change settings such as the title of the project, the primary output, and localization. You can also manage a To Do List by clicking on the Manage... button and adding the required to do actions.
In the Index section, you can choose to either add new keywords to the project index file (HHK) or save as individual topic files (HTM). Select the Binary Index option if you want to combine indexes from multiple CHM files.
You order topics and folders logically in the Project Manager pod to define a chapter layout. This chapter layout forms the basis for the Table of Contents creation by RoboHelp.
A few important points to note here are as follows −
If you rename a folder or a topic, the topics and folders retain their order.
If you rename a folder or a topic, the topics and folders retain their order.
If you delete a topic or a folder, the remaining topics retain their order.
If you delete a topic or a folder, the remaining topics retain their order.
If you add a new topic or a folder, it is added at the top inside the parent folder.
If you add a new topic or a folder, it is added at the top inside the parent folder.
If you drop a topic or a folder on a non-topic/folder item (such as CSS, image, or baggage), it moves to the last position inside the parent folder of the target.
If you drop a topic or a folder on a non-topic/folder item (such as CSS, image, or baggage), it moves to the last position inside the parent folder of the target.
To order topics, simply drag a topic or folder above or below another topic or folder. A green arrow is shown to indicate the placement of the topic or folder.
RoboHelp provides many ways to organize and work with project files. We will look at some of the common operations below −
Open a project, and in the Project tab, go to the View section → Display Topics and select to display topics By Topic Title or By File Name.
Project tasks can be tracked by using To Do Lists, which can be customized. To Do Lists are retained when converting projects from an older RoboHelp version. To edit a To Do List go to Project Settings, click on the General tab and then click Manage...
To add a task to the list, click Add. Type the name of the task item. To edit or remove a task, select the task and click Edit or Delete.
The RoboHelp Starter pod lists recently opened projects. To edit this list, go to the File menu and click on Options. Click the Recent Projects tab. If you want to change the number of files listed, specify a number in the Max Projects box. To remove a file from the list, select it and click on Remove. You can pin frequently used files by selecting it and clicking on Pin.
Sometimes, you might have to add files to the Baggage Files folder, so the external elements appear correctly in the output. You can add individual files or even folders. To add files or a folder to the Baggage Files folder, right-click on Project Files, go to Import Baggage and select File or Folder.
You can map file types to associate them with the applications for editing and viewing. To associate a file extension with an application, go to the File menu and click on Options. Click on the File Association tab. You can associate programs as well as HTML Editors.
To associate programs, click Add in the Associated Programs section and enter a filename extension. Select an editor to edit documents with the specified filename extension and then select a program to view the file.
To add an HTML editor, click Add in the HTML Editors section and select from the recommended or other programs registered to edit or view .html or .htm files and click OK.
It is recommended to back up all project files, view and print reports before removing project files. This is especially important if your project is not under version control. In order to avoid broken links, do not remove files in Windows Explorer or version control software.
Select one or more files and press Delete on the keyboard. As a precaution, it is recommended not to remove references to removed topics, so that they can be shown in the Broken Links folder for later review. To remove multiple topics, use the Topic List Pod.
Similar to project file management, RoboHelp also provides ways to manage project files. We will look at some of the common folder operations below −
There are default folders that you can use to create folders and subfolders in the Project Manager. These folders include −
HTML Files (Topics)
Images
Multimedia
Style Sheets and
Baggage Files
To create a folder, right click on the Project Files folder in the Project Manager pod, go to New and select Folder. Enter a name and press Enter.
To rename folders, expand the Project Files folder in the Project Manager pod. Right-click the folder you want to rename and click on Rename. Type the new name and press Enter.
To move a folder, select the folder in Project Files in the Project Manager pod and drag the subfolder to its new location.
To remove a folder, right-click the folder in the Project Manager pod and click Delete.
RoboHelp allows for authoring content in multiple languages. The language applies to the text, dictionary and the index of the project. However, keep in mind that the end user’s OS must be in the same language for HTML Help systems as the project language otherwise it will be overridden by the OS language.
You can compare content in different languages or select a different language for translation.
To compare content in different languages, open the topics created in different languages. Drag the tab of one of the topics a little below on to the Design button (second row on the Document Pane) and choose if you want to compare them vertically or horizontally.
In the Output tab, select Stop Words as shown in the following screenshot.
You can change the following settings in the respective tabs in the Advanced Settings for Localization dialog box.
Stop List − Add words that must be ignored during a text search.
Stop List − Add words that must be ignored during a text search.
Phrases − Add a phrase for the Smart Index Wizard to include when searching topic content for keywords.
Phrases − Add a phrase for the Smart Index Wizard to include when searching topic content for keywords.
Labels − Modify the text for each user interface element listed.
Labels − Modify the text for each user interface element listed.
"Always Ignore" Words − Add a word or phrase that the Smart Index Wizard ignores when generating the index.
"Always Ignore" Words − Add a word or phrase that the Smart Index Wizard ignores when generating the index.
Synonyms − Add a synonym for a word. The results are always returned for the searched words even when searched for the synonym.
Synonyms − Add a synonym for a word. The results are always returned for the searched words even when searched for the synonym.
In the next chapter, we will understand how to import PDF files in RoboHelp.
RoboHelp allows you to import content from PDF files. The ToCs are carried over into the help file. However, keep in mind that encrypted PDF files or files containing SWFs will not import. You can either create a project by importing a PDF or import a PDF into a project.
To create a project from a PDF file, we would need to follow the steps given below.
Step 1 − Go to the File menu, click on New Project and click on the Import tab. Select PDF document in the list of file types and click OK.
Step 2 − In the Import PDF Wizard, browse to the location of the PDF file you want to import and click on Next. Enter details of the project and click on Next. Select the desired conversion options and click on Finish to import the PDF as a HTML help file.
Step 3 − When you choose to create new topic(s) based on style(s), RoboHelp will analyze the PDF for paragraph styles and headings and splits the topics for you.
To import PDF files into a project, we have to follow the steps given below.
Step 1 − You can import PDF files into an existing project. Make sure the Project Manager Pod is open, then right-click on the Project Files folder. Click on Import Topics... and browse to the location of the PDF file on disk.
Note − You can also select multiple PDF files at once by holding down the Ctrl key and clicking on each file.
Step 2 − In the Import PDF Wizard, browse to the location of the PDF file you want to import and click on Next. Enter details of the project and click on Next.
Step 3 − Select the desired conversion options and click on Finish to import the PDF as a HTML help file. When you choose to create new topic(s) based on style(s), RoboHelp will analyze the PDF for paragraph styles and headings and splits the topics for you.
Just like PDF files, you can import and link Microsoft Word Documents in RoboHelp. You can create new help files by importing Word documents or import Word documents into existing help files. Before importing Word documents, it is important that they be optimized for online output. You have the option of either importing or linking Word documents. It is important to choose the one that suits your needs.
Importing allows you to integrate the Word document in the help file and customize filenames from the Project Manager. Linking allows you to dynamically-update the source document including ToC, index and glossary.
You can also regenerate deleted topics and preserve changes in generated topics. You cannot however, change the filenames and topic titles from the Project Manager.
To optimize word documents for online output, we should consider the following points.
Heading hierarchies − Apply hierarchical headings before conversion to achieve automatic pagination. For example, you can apply Heading 1 style in your Word document, map this style to a similar RoboHelp style, and define pagination to create an HTML topic for each Heading 1 style.
Heading hierarchies − Apply hierarchical headings before conversion to achieve automatic pagination. For example, you can apply Heading 1 style in your Word document, map this style to a similar RoboHelp style, and define pagination to create an HTML topic for each Heading 1 style.
Inline styles and style overrides − You can convert inline styles to CSS styles in RoboHelp.
Inline styles and style overrides − You can convert inline styles to CSS styles in RoboHelp.
Header and footer information − RoboHelp can convert headers and footers. To ensure consistency across your topics, you can define a master page that contains the required header and footer information.
Header and footer information − RoboHelp can convert headers and footers. To ensure consistency across your topics, you can define a master page that contains the required header and footer information.
Chapter versus topic − In online Help, the organizational unit is the topic, and users see topics one at a time. Provide comprehensive information without adding redundancy by grouping related topics.
Chapter versus topic − In online Help, the organizational unit is the topic, and users see topics one at a time. Provide comprehensive information without adding redundancy by grouping related topics.
ToCs − You can also import the Word ToC into the RoboHelp ToC by defining the topic hierarchy and representing it in RoboHelp TOC.
ToCs − You can also import the Word ToC into the RoboHelp ToC by defining the topic hierarchy and representing it in RoboHelp TOC.
Context sensitivity − You can assign context-sensitive Help markers in Word documents using custom footnote entries. RoboHelp reads these footnote entries and assigns the map IDs to the generated topics.
Context sensitivity − You can assign context-sensitive Help markers in Word documents using custom footnote entries. RoboHelp reads these footnote entries and assigns the map IDs to the generated topics.
Unlike PDFs, which do not require you to have Acrobat or Acrobat Reader installed, you need to have Microsoft Word installed to be able to import Word documents into RoboHelp.
To import a Word document, in the Starter pod, go to the Import tab and select the icon representing Word documents (*.docx, *.doc) and select the Word document you want to import. Enter the details of the project and click on Finish.
To Link a Word document to a RoboHelp project, we should follow the steps given below.
Step 1 − In the Project Manager Pod, right-click on the Project Files folder and select Word Document from the Link submenu. Select one or more Word documents and click Open.
Step 2 − Right-click on the linked Word document in the Project Files folder and click on Properties.
Step 3 − In the Word Document Settings dialog box, specify settings for the ToC, index and glossary.
Step 4 − To generate a ToC from the Word document, click on the Convert Table of Contents checkbox and choose to either append to an existing ToC or create a new associated ToC.
Step 5 − To generate an index from the Word document, click on the Convert Index checkbox and choose to either append to an existing index or create a new associated index.
Step 6 − To generate a glossary from the Word document, click on the Convert Glossary checkbox and choose to either append to an existing glossary or create a new associated glossary.
Word styles are mapped to RoboHelp styles using Cascading Style Sheets (CSS). The default CSS used by RoboHelp is called RHStyleMapping.css. You can change this to a file of your choice or edit this CSS file in your preferred CSS editor.
To select the CSS for style mapping, we should follow the points given below.
Link or import the Word document whose style needs to be mapped to RoboHelp.
Link or import the Word document whose style needs to be mapped to RoboHelp.
Open the Project Settings dialog box from the Project tab and click on the Import tab.
Open the Project Settings dialog box from the Project tab and click on the Import tab.
Select the CSS from the CSS for Style Mapping dropdown menu. You can also select a custom CSS by selecting the <BrowseCSS> in the dropdown menu.
Select the CSS from the CSS for Style Mapping dropdown menu. You can also select a custom CSS by selecting the <BrowseCSS> in the dropdown menu.
For converting Word paragraphs and character styles to RoboHelp styles, we should consider the following steps.
Step 1 − Import or link the Word document and go to Project Settings. Select the Import tab and click on Edit... in the Word Document section.
Step 2 − In the Conversion Settings dialog box, select the Word style from the Paragraph group. You can choose to map a RoboHelp style to the Word style from the RoboHelp Style dropdown menu. Select [Source] to retain the appearance of Word text in your online Help format. To edit the selected RoboHelp style, click Edit Style.
Step 3 − To mark a style for the glossary, select the Glossary Definition checkbox to consider the style for the glossary definition. Select Glossary Term checkbox to consider the style for the glossary term.
Step 4 − To create a Help topic at each occurrence of the selected Word paragraph style, select the Pagination (Split into topics based on this style) checkbox.
Step 5 − You can also select or enter a User Defined HTML Tag for the selected paragraph style.
Step 6 − You can similarly also map and edit the Word character formats to character styles in RoboHelp. Select the Word character style from the Character group and select the RoboHelp character style from the dropdown menu.
Step 7 − To import the Word character style, select [Source] from the pop-up menu. You can edit the character style in RoboHelp by clicking on Edit Style.
A Darwin Information Typing Architecture (DITA) map is like a table of contents listing and linking the topics for a specific output. They assemble topics into sequence and hierarchy tailored to specific delivery requirements. A DITA map file has the extension .ditamap. You can import both DITA map and XML files to generate an XHTML output.
To import DITA map files, we should follow the steps given below.
Step 1 − Go to the File menu, click on New Project and click on the Import tab. Select the PDF document in the list of file types and click OK to open the DITA Open Toolkit Processing Options dialog box.
Step 2 − Review the following settings that are available in the dialog box and then click on Finish.
Replace default XSLT file for conversion − Select an XSL file to use for transforming the DITA files to XHTML instead of the default XSL file used by the DITA Open Toolkit.
Replace default XSLT file for conversion − Select an XSL file to use for transforming the DITA files to XHTML instead of the default XSL file used by the DITA Open Toolkit.
Use DITA val for conditional processing − The XHTML is generated based on the Val file. A DITA Val file contains filter, flagging, and revision information. Specify a DITA Val file to use for conditional processing of the DITA files.
Use DITA val for conditional processing − The XHTML is generated based on the Val file. A DITA Val file contains filter, flagging, and revision information. Specify a DITA Val file to use for conditional processing of the DITA files.
Show Index entries in Topics − Select to show the index entries in RoboHelp topics.
Show Index entries in Topics − Select to show the index entries in RoboHelp topics.
Show image filename in Annotation − Select to add annotations to images showing the filename of the image or the full path to include in the topics.
Show image filename in Annotation − Select to add annotations to images showing the filename of the image or the full path to include in the topics.
Include Draft and Cleanup content − Select to include draft and required cleanup content (items identified as left to do before publishing).
Include Draft and Cleanup content − Select to include draft and required cleanup content (items identified as left to do before publishing).
Select XHTML file to be placed in the header area (hdf) − Select the location of the file containing XHTML to place in the header area of the output file.
Select XHTML file to be placed in the header area (hdf) − Select the location of the file containing XHTML to place in the header area of the output file.
Select XHTML file to be placed in the body running-header area (hdr) − Select the location of the file containing the XHTML to place in the body running-header area of the output file.
Select XHTML file to be placed in the body running-header area (hdr) − Select the location of the file containing the XHTML to place in the body running-header area of the output file.
Select XHTML file to be placed in the body running-footer Area (ftr) − Select the location of the file containing XHTML to place in the body running-footer area of the output file.
Select XHTML file to be placed in the body running-footer Area (ftr) − Select the location of the file containing XHTML to place in the body running-footer area of the output file.
DITA Open Tool Kit Home Directory − Select the absolute location of the home folder of the DITA Open Toolkit. You specify this location only once. It is stored in the registry.
DITA Open Tool Kit Home Directory − Select the absolute location of the home folder of the DITA Open Toolkit. You specify this location only once. It is stored in the registry.
To import XML files into a project in RoboHelp, we should follow the steps given below.
Step 1 − RoboHelp creates a topic for the XML file when imported in to the existing project. To import an XML file, in the Project Manager pod, select the file to import.
Step 2 − Go to the Import section of the Project tab and in the dropdown menu, select, the XML File. Select one or more XML files and the click on Open.
Step 3 − In the Select XML Import Handler dialog box, click on Options. You can also select Import XML (CSS/XSL) to set advanced options.
The following options are available −
Treat as text flow − Import the XML file as HTML text without formatting.
Treat as text flow − Import the XML file as HTML text without formatting.
Treat as XML tree view − Import the XML file in HTML tree view. HTML imports as code.
Treat as XML tree view − Import the XML file in HTML tree view. HTML imports as code.
Use customized CSS/XSL file − Select a file from the pop-up menu.
Use customized CSS/XSL file − Select a file from the pop-up menu.
Step 4 − Click OK to import the XML file into the project.
RoboHelp can import compiled WinHelp 4.0 (HLP) or WinHelp Project File (HPJ) into your project. Although you cannot output a WinHelp file from RoboHelp HTML, you can import the HPJ file, which is the main organizational file containing the set of the entire source files.
From the Starter pod, select either the WinHelp (*.hlp) or WinHelp Project (*.hlp) and proceed to browse the location of the file on disk. Click Finish to convert and import the file as a RoboHelp file.
There are some limitations when converting HLP files to HTML. All these limitations are explained in brief as follows −
Bullets − WinHelp topics should not use bitmap references as bullets. You can however choose to keep bulleted lists.
Bullets − WinHelp topics should not use bitmap references as bullets. You can however choose to keep bulleted lists.
HTML Jumps − Jumps to HTML pages that are not converted, but you can easily re-create the links in the Design Editor after the HTML topics are created.
HTML Jumps − Jumps to HTML pages that are not converted, but you can easily re-create the links in the Design Editor after the HTML topics are created.
Jumps to external WinHelp topics − Jumps to external WinHelp topics that are stripped out of the HTML topics.
Jumps to external WinHelp topics − Jumps to external WinHelp topics that are stripped out of the HTML topics.
Macros, buttons, and shortcuts − Macros that convert include Jump Context, JumpId, and PopupId. Other macros are not converted.
Macros, buttons, and shortcuts − Macros that convert include Jump Context, JumpId, and PopupId. Other macros are not converted.
Microsoft Word HTML styles − Microsoft Word HTML styles are not used to format the HTML topics.
Microsoft Word HTML styles − Microsoft Word HTML styles are not used to format the HTML topics.
Microsoft Word templates − Word templates that are used to format RTF files in WinHelp are not converted to HTML style sheets.
Microsoft Word templates − Word templates that are used to format RTF files in WinHelp are not converted to HTML style sheets.
Mid-Topic jumps − Mid-topic jumps are converted to bookmarks.
Mid-Topic jumps − Mid-topic jumps are converted to bookmarks.
Multimedia files (AVI and WAV) − These files cannot be converted with HLP files. However, you can add sound and video to HTML topics in the Design Editor.
Multimedia files (AVI and WAV) − These files cannot be converted with HLP files. However, you can add sound and video to HTML topics in the Design Editor.
Non-scrolling regions − HTML-based output does not support non-scrolling regions.
Non-scrolling regions − HTML-based output does not support non-scrolling regions.
Numbered lists − Numbered lists use a 12-point serif font by default. To change the style, you need to create a new numbered list style and reformat it in RoboHelp.
Numbered lists − Numbered lists use a 12-point serif font by default. To change the style, you need to create a new numbered list style and reformat it in RoboHelp.
Related Topics buttons − Related Topics keywords are translated into Related Topics terms.
Related Topics buttons − Related Topics keywords are translated into Related Topics terms.
Secondary windows − WinHelp secondary windows are not translated. Unlike WinHelp topics, HTML topics do not support links that display information in secondary windows.
Secondary windows − WinHelp secondary windows are not translated. Unlike WinHelp topics, HTML topics do not support links that display information in secondary windows.
Table of contents − The HTML TOC file (HHC) does not support WinHelp pages that link to external WinHelp topics or reference macros or that contain link statements.
Table of contents − The HTML TOC file (HHC) does not support WinHelp pages that link to external WinHelp topics or reference macros or that contain link statements.
What's This? Help − Context-sensitive Help is not converted. What's This? Help-style topics or dialog topics are converted into regular HTML Help topics.
What's This? Help − Context-sensitive Help is not converted. What's This? Help-style topics or dialog topics are converted into regular HTML Help topics.
Microsoft Word formatting − The following formatting is converted in the HTML topics – underlining, paragraph spacing, indents, alignments, table borders, spreadsheets, background colors, and watermarks.
Microsoft Word formatting − The following formatting is converted in the HTML topics – underlining, paragraph spacing, indents, alignments, table borders, spreadsheets, background colors, and watermarks.
In the next chapter, we will understand what version control is and how it benefits RoboHelp.
Version control is an important enterprise feature, which saves every version of the document on a server. Multiple people can therefore, simultaneously make changes to a document without fear of disturbing the original document. Since all versions of a document are saved, users can revert to any version as needed.
RoboHelp supports native Microsoft SharePoint 2010 and above integration. Support for Microsoft SharePoint is installed during program setup itself. The setup also installs the .NET Framework 4.0 and SQL Server Compact 3.5 SP2, which is required for SharePoint integration.
To configure SharePoint settings, go to the File menu, click on Options and select Version Control. To enable file comparisons between your computer and the server, you need to have a file comparison program installed.
You can download a free program called Winmerge from http://winmerge.org/ and enter the program path in the Path parameter in the SharePoint Settings area. You can also enter any program specific arguments.
You can also configure the following options −
Notify before overwriting writable files − Notifies the user before overwriting any writable files that are not checked out.
Notify before overwriting writable files − Notifies the user before overwriting any writable files that are not checked out.
Replace local file even if server version is same − Fetch the latest files from the server, even if the local file version and the server version is the same.
Replace local file even if server version is same − Fetch the latest files from the server, even if the local file version and the server version is the same.
Default Check-in Option − Select to check in the files as a major version or as a minor version. The default is to check in as a major version.
Default Check-in Option − Select to check in the files as a major version or as a minor version. The default is to check in as a major version.
In the next chapter, we will learn how to work with reports in RoboHelp.
RoboHelp makes it easy to get reports about a project. You can export, print and send reports from the Reports Dialog Box.
Click on the Tools tab and select a report type. Customize the report as needed. Click on ‘Save As...’ and save the report as an RTF or TXT file.
In the Reports dialog box, customize the report as needed. Click on Print... to print the report. You can print the ToC or index from the ToC pod or Index pod by going to the File menu and clicking on Print.
In the Reports dialog box, customize the report and click on ‘Mail To...’ You need to have an email program configured in your system before you can use this function. The report will appear in the body of the message, which you can edit before sending.
With RoboHelp, you can generate and customize a wide variety of reports. We will look at an example of a non-customizable and a customizable report. All reports can be accessed from the Tools tab.
This report can be accessed by clicking on the Map ID icon in the Tools tab and selecting Broken Links. It finds files that contain broken links. This report is not customizable.
Click on the ToC icon in the Tools tab and select Index from the dropdown menu. The following options can be customized in this report.
Keywords − Includes all keywords from the index.
Keywords − Includes all keywords from the index.
Keywords and Topics − Contains a list of keywords. Each keyword lists the topics that use it.
Keywords and Topics − Contains a list of keywords. Each keyword lists the topics that use it.
Topics and Keywords − Contains a list of topics. Each topic lists the keywords associated with the topic.
Topics and Keywords − Contains a list of topics. Each topic lists the keywords associated with the topic.
Select Index − Select an Index from the list to generate a report for the index selected.
Select Index − Select an Index from the list to generate a report for the index selected.
The Project Manager pod makes it easy to create, save or open topics.
For creating a topic in RoboHelp, we should follow the steps given below.
Step 1 − To start with, create a project, right-click on the XHTML Files (Topics) folder, go to the ‘New’ menu and select Topic... to open the New Topic dialog box.
Step 2 − In the New Topic dialog box, specify a topic title and select a variable from the Variables list, then click on Insert. Variables help manage changes and ensure consistency.
Step 3 − As per the HTML file naming protocol, use underscores rather than spaces. Select a Master Page if required and specify a language for the new topic. If you do not specify a language, RoboHelp uses the default language setting of the project.
Step 4 − You can add keywords to tag the contents of the topic. Keywords can be separated by comma, space or semicolon. If you prefer not to include this topic in search results, check the Exclude this topic from Search checkbox.
To save a topic, simply press Ctrl+S on the keyboard or click the Save All icon in the Project tab.
To open a topic, double-click on the topic name in the Project Manager Pod or Topic List pod to open the topic in the Design Editor. To open the topic in an editor of your choice, right-click on the topic, go to the Edit With menu and select the editor.
RoboHelp can create topic files in XHTML. XHTML allows for structured authoring that ensures well-written code. All old RoboHelp for HTML topics are upgraded to XHTML. The XHTML topics conform to the XHTML 1.0 Transitional specification from the World Wide Web Consortium (W3C).
The topics have the XHTML Transitional 1.0 doc type − <DOCTYPE html PUBLIC “-//W3C3DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
The XHTML files generated by RoboHelp can be edited by third-party editors such as Notepad or Adobe Dreamweaver. To view the XHTML source, open the topic and click on the HTML View beside the Design Editor.
You can convert the XHTML topics into HTML in the SSL output. To do this, go to the File menu, then go to Options and click on General. In the Generation section, check the box Convert RoboHelp edited topics to HTML and click OK.
The RoboHelp generated XHTML code can be validated for compliance with the XHTML Transition 1.0 W3C specifications. To validate a topic, right-click the topic, and select Validate W3C Compliance to validate the topic. This will generate an Output View in the Document Pane showing the results.
Some features such as marquees in Topics, Border Color in Framesets and Background Sound in topic properties are not supported in XHTML. These will result in a non-compliant code. You will need to remove these features to pass the validation.
Master pages are a form of templates, which help in separating layout and styling from the content. The layout information of a master page is associated with a CSS file. The master page template defines the placement of Headers, Footers and Placeholders for the Body, Breadcrumbs and Topic ToC.
To create a master page, go to the Output tab and from the Master Page menu and select New Master Page.
In the New Master Page dialog box, enter a name for the master page. Go to the Appearance tab and select a style sheet to apply to the new master page and click OK. This can also be changed later in the master page properties.
To edit a master page, simply double-click on the master page in the Output Setup Pod or right-click on the master page and click on Edit. Make the desired changes.
You can insert placeholders for Topic ToCs, Breadcrumbs and Topics in Master Pages. A new master page has a body placeholder by default.
To insert a new placeholder, place the cursor below or after the body placeholder. Go to the Insert tab and in the Page Design section, click the Topic ToC button to select the desired placeholder from the dropdown menu.
From the topic list in the Project Manager, select one or more topics to which you want to assign the master page. Right-click on the topic(s) and select Properties.
In the General tab, select the list of master pages available in the Master Page dropdown menu and then click on OK. You can also choose to have a preview by clicking the Spectacles Icon beside the Master Page menu or browse to a master page on the disk.
RoboHelp makes it easy to manage topics. You can rename topics, update the topic references and even track the status of a topic.
To rename a topic, Right-click on a topic in the Project Manager and select Properties.
In the General tab, type the new title in the Topic Title box and click OK to update the title. You can also click the Rename button in the File section of the Project tab.
It is important to update the topic references when renaming the topic title. Topic references include the following aspects −
Text links − The path of the link is updated, but the link text that is visible to a user is not. If the link text in any topic includes the topic title, then we have to update each topic.
Text links − The path of the link is updated, but the link text that is visible to a user is not. If the link text in any topic includes the topic title, then we have to update each topic.
Topic heading − To change the topic heading to match the topic title, change it in the Design Editor.
Topic heading − To change the topic heading to match the topic title, change it in the Design Editor.
Table of Contents − In the Table of Contents pod, right-click on the book or page and select Rename. Enter the new title.
Table of Contents − In the Table of Contents pod, right-click on the book or page and select Rename. Enter the new title.
Index − If the topic title is an index keyword, update the keyword in the Index pod. Right-click on the keyword in the upper pane and select Rename. Type the new title.
Index − If the topic title is an index keyword, update the keyword in the Index pod. Right-click on the keyword in the upper pane and select Rename. Type the new title.
The default status of new topics is, In Progress. The status information is shown in the Project Report. To change the topic status or to set priorities, open the Properties of the topic from the File section of the Project tab and click on the Status tab. You can change the development stage of the topic from the Status dropdown menu.
Enter a number to assign a priority in the Priority field. You can also set the estimated or actual hours of development in the Hours field. You can check off items in the To Do List as you complete them. Any other description can be entered in the Comment field.
RoboHelp can do spell check across the Content, ToC, Index and Glossary of the project. You can spell check a topic or an entire project.
To spell check a topic, open the topic in the Design Editor and in the Review tab, click on either Spell Check or Spell Check All Topics in the Proofing section.
RoboHelp scans the document and recommends corrections for words. You can also add words to the current dictionary.
You can also spell check the entire project including the glossary, index and ToC. To do this, in the Review tab, click on Spell Check Project. This will open up a similar Spelling dialog box as before. You can skip to different parts of the project by clicking on Skip.
You can add extra words to the dictionary using the Dictionary Editor. Words in the Dictionary Editor are case-sensitive. In the Review tab, click Spelling Options. In the Options tab, in the Spelling Options dialog box, click on Modify... to open the Dictionary Editor.
Enter a word that you want to add to the dictionary. Then click on the Add button and click OK.
With the Find and Replace feature, you can search and replace text, HTML, attributes, etc., in the current topic or project or even across files and folders in a specified path. To open the Find and Replace pod, press Ctrl+Shift+F on the keyboard or click on Find and Replace in the Project tab.
Type the text, tag, or attribute that you want to search in the Find box. You can enable Show Advanced Filters to select the filters and specify the text, tag or attribute for RoboHelp to build a regular expression.
The following advanced filters can be applied −
Begins With − Specify phrases, words, or characters that should occur in the beginning of found instances.
Begins With − Specify phrases, words, or characters that should occur in the beginning of found instances.
Ends With − Specify phrases, words, or characters that should occur in the end of found instances.
Ends With − Specify phrases, words, or characters that should occur in the end of found instances.
Contains − Specify phrases, words, or characters that found instances should contain.
Contains − Specify phrases, words, or characters that found instances should contain.
Does Not Contain − Specify phrases, words, or characters that found instances should not contain.
Does Not Contain − Specify phrases, words, or characters that found instances should not contain.
Type the text, tag, or attribute that you want to replace in the Replace With box. If you want to search without replacing, leave the Replace With box empty.
You can choose where to look for the text by using the Look In option to search in the following
Current Project − Search within the current project.
Current Project − Search within the current project.
Current Window − Search in the current topic.
Current Window − Search in the current topic.
Opened Files − Search all files currently opened in RoboHelp.
Opened Files − Search all files currently opened in RoboHelp.
Path − Search all files in the selected folder path.
Path − Search all files in the selected folder path.
In the next chapter, we will learn how to ensure W3C compliance in RoboHelp.
You can validate both topics and projects for W3C compliance. RoboHelp validates all content and shows warnings or error messages for any non-compliance. To validate a topic, right-click on the topic in the Project Manager pod and click on Validate W3C Compliance.
To validate a project, right-click on the Project Files folder in the Project Manager pod and select Validate W3C Compliance. Depending on the situation, the following messages are seen in the Output View Pod and Error List pod.
Errors − incorrect or unclosed tags
Errors − incorrect or unclosed tags
Warnings − invalid XHTML tag
Warnings − invalid XHTML tag
Information − all topics are validated
Information − all topics are validated
The Error List pod shows the line and column in the HTML, where the error has occurred. You can directly navigate to this line by double-clicking on the error.
RoboHelp includes a Design Editor and a HTML Editor by default. You can also use third party editors such as Microsoft Word or Adobe Dreamweaver for editing.
Select a topic file from the Project Manager pod, to open it in the Design Editor. You can use the RoboHelp Design Editor to perform word-processing tasks and to insert online elements, such as links, multimedia and Dynamic HTML.
You can also add index keywords to topics, apply conditional text, create browse sequences, map IDs, and edit master pages. You can edit any standard XHTML or HTML file in the Design Editor.
You can directly author XHTML code in the RoboHelp HTML Editor. To switch to the HTML Editor, click on the HTML tab in the Document Pane. You enter HTML tags and text.
You can use keyword expansions to auto-suggest keywords or tags as you type. When you start typing a keyword, you can select it from the keyword expansion list to insert the keyword or tag. In addition to the existing keywords and tags, you can also specify your own keywords by right clicking in the HTML Editor and selecting Edit Expansions....
You can use third-party HTML editors, while RoboHelp is open, but RoboHelp specific features such as text-only pop-ups or link controls are not available. Insert the images and the JavaScript based special effects into the Baggage Files folder. If you are inserting them using a third-party editor.
To add a HTML editor, click on Options in the File tab and click on File Associations. In the HTML Editors section, click on Add and choose from the list of recommended programs or browse to the location of the program on disk.
The Edit tab provides options for working with characters and fonts. You can create inline styles using the Edit tab, which overrides an existing style sheet.
To add or remove font formatting, select the required text and in the Edit tab, go to the Character section, click on Character Formatting and then choose Font.
A font set is a collection of fonts that you can apply in a style sheet. For example, you can create a font set with Calibri as the first font and then Cambria and Segoe UI (in order) as substitute fonts. If the viewer does not have Calibri installed, it will use Cambria and then Segoe UI.
To create a font set, click on Font Sets in the Character Formatting menu in the Edit tab. You can modify an existing font set by selecting the font and clicking Modify... or create a new set by clicking New and typing a name for the font set.
In the Modify Font Set dialog box, select the first font and click on Add. Select the remaining fonts in the order of preference and then add them and click on the OK button. Font sets are saved and then associated with projects.
The Edit tab provides options for working with paragraphs. You can create inline styles using the Edit tab, which overrides an existing style sheet.
Select the paragraph to align and click on one of the four alignment buttons in the Paragraph section of the Edit tab. To set an indent, click on the Increase Indent or Decrease Indent button in the same section.
To adjust line spacing, click on Paragraph in the Paragraph Formatting menu in the Edit tab.
Set the Spacing options of the Paragraph dialog box; specify the amount of space above and after each paragraph and the spacing between the lines and click on OK.
RoboHelp allows you to edit border and backgrounds in your content easily. The applied formatting creates inline styles, which override style sheets.
Select a paragraph in the topic and in the Paragraph Formatting menu in the Edit tab, click on Borders and Shading. Click on the Borders tab or shading tab, specify the desired options, and click OK.
Double-click on the image in the Design Editor. In the Image dialog box, click Borders to open the Borders dialog box and set the options as required. Click on OK.
Right-click on a topic in the Project Manager and click on Properties. In the Appearance tab, enter the sound file in the Background Sound box. The supported sound formats include – .au, .mid, .rmi and .wav. Enter the number of times to play in the Sound Loop Count box.
RoboHelp allows for organization of data into tables. Tables in RoboHelp are fully customizable with the option of applying styles, which can be used across multiple topics. Table styles from Word or FrameMaker documents can be imported and mapped to RoboHelp table styles.
Go to the Insert tab and click on the Table icon to select the number of rows and columns to add. Click to insert the table.
You can also insert custom tables by clicking on Insert Table... This will open a dialog box where you can specify the number of rows and columns and choose predefined table styles.
To edit a table, click on the table to enable the Table tab in the ribbon. From this tab, you can add or remove rows and columns and merge or split cells. You can also change the table properties such as alignment and column width.
RoboHelp offers several options for working with lists. You can indent lists and apply bullet styles and numbering formats.
Select the list in the topic that you want to indent and from the Edit toolbar choose either Decrease Indent or Increase Indent as needed.
You can match the color of the bullets with that of the list simply by changing the font color. Select the list you want to change the color and in the Edit tab, click on the Character Formatting menu and select Font or simply press Ctrl+D. In the dialog box that appears, select the desired font color. The bullet color and the list color will become one as an inline style.
Select the list you wish to number, right-click the list and click on Bullets and Numbering... Select the desired numbering style. In the Numbered tab, select the desired numbering pattern.
To add a paragraph within a list, insert the cursor at the end of the paragraph and press Shift+Enter to create a line break. To end the line break and restart bullets or numbering, press Enter.
You can store static global information that can be used repeatedly in your project in the form of User-Defined Variables (UDVs). When you modify a variable or value, every occurrence of that variable or value is updated across the project.
The User Defined Variables pod lists all the user-defined variables in a project.
To create a UDV, right-click a word in the topic, go to the Add to menu and select User Defined Variable. In the dialog box that appears, specify the Variable Name and click on OK.
Variable sets enable you to modify values of various user-defined variables and use them in different outputs. The Default Variable Set is the master variable set. When you insert a variable, the variable is taken from the Default Variable Set.
To use a variable set other than the Default Variable Set, Click on the Add/Edit Variable Set icon in the UDV pod and click Add to specify a name for the new variable set and then click on OK.
To edit a user-defined variable, right-click on the variable name and click on Edit.... In the user-defined Variable Properties dialog box, you can edit the different properties of the variable such as variable name, the set it belongs to, the value and an optional description.
Media rules help in defining the appearance of the document on different screen sizes.
To define a media-specific style, right-click on the style sheet in the Project Manager Pod, and click on Edit. In the Styles Dialog Box, select a style to modify for a specific media. Select the media type from the Media list.
The (none) style is used to define generic styles and the Print style is used for printers.
The (none) style is used to define generic styles and the Print style is used for printers.
Modify the style as required and click OK.
Modify the style as required and click OK.
If you want to define different media rules for a style in the style sheet that is currently linked to a topic, go to the Project tab and in the Pods dropdown menu, click the Style and Formatting pod. In the Styles and Formatting pod, select a style to modify for a specific media, right-click and choose Edit.
Select the media or screen profile name from the Media list.
Select the media or screen profile name from the Media list.
Modify the style as required and click OK.
Modify the style as required and click OK.
A style sheet can be associated with any number of HTML topics or a new topic. If you create a style sheet in a project and apply it to a new topic, all topics you create later use the new style sheet. You can link a topic to another style sheet, if necessary.
To link a style sheet, select one or more topics from the topic list, right-click, select Properties, and click on the Appearance tab.
Select a style sheet in the list or navigate to a new style sheet on your computer. You can click New to create a style sheet or edit the style sheet in the Styles Dialog Box.
The default.css is the default style sheet until you create a style sheet or link another style sheet to a new topic. To create a style sheet, go to the Edit tab and in the CSS section, click on the New Stylesheet.
In the Name field, type a filename including the .css extension and select a folder location. If you would like to base your new style sheet on an existing one, select an existing style in the Copy Styles From dropdown menu. Click Create to open the Styles dialog box to create a new style and then click on OK.
In this chapter, we will understand how to style the style sheets.
To create a style, right-click on the style sheet where you want the style in the Project Manager Pod and click on Edit. Click New and select a style type. By default, the new style is created with a default name such as Style1.
In the Styles dialog box, change the default name of the style without using any special characters or spaces in the name. In the Formatting section of the Styles dialog box, change the required options. You can preview the changes in the Paragraph Preview section.
For additional options, click Format and select from the following options −
Font − Select font families, size, and attributes, such as bold or italics.
Font − Select font families, size, and attributes, such as bold or italics.
Paragraph − Set up indents, line spacing and alignment.
Paragraph − Set up indents, line spacing and alignment.
Borders and Shading − Use the Borders tab to set border types, color, line thickness, and spacing. Use the Shading tab to set background color and image options.
Borders and Shading − Use the Borders tab to set border types, color, line thickness, and spacing. Use the Shading tab to set background color and image options.
DHTML Effects − Select which dynamic HTML effect to include and when to include it.
DHTML Effects − Select which dynamic HTML effect to include and when to include it.
You create styles on the fly using the Design Editor. To do so, select some text in the topic and apply some formatting. With the text still highlighted, type a style name in the Style list in the Edit tab and press Enter. In the dialog box that appears, click Create.
The Style Editor allows you to create and customize table styles according to your requirements. Modifications to a table style affects all tables using that style.
To apply a table style on an existing table, right-click an existing table in a topic and select Table Style.... Select Clean Table Inline Formatting in the Select Table Style dialog box to remove any inline styles used in the table. Select a style from the Available Table Styles list or select a Global Table Style (Table Templates) and then click OK.
Open the Style and Formatting pod from the Project tab. In the Style and Formatting tab, click on Create New Style and select Table Style. Name the new table style and then click on OK.
You can apply formatting to the whole table, first or last column or row, or a group of rows or columns. From the Apply Formatting To list, select the columns or rows to format.
Select font, size, and color. Select border and border color and click on Apply. The new style appears in the CSS Styles list of the Table Styles dialog box. Select this style to create tables with the same style later.
<Start here> With RoboHelp, you can create both HTML lists and advanced lists. Advanced lists can be either single level or multilevel lists.
HTML lists − All the ordered <ol> and unordered <ul> lists come under the HTML lists.
HTML lists − All the ordered <ol> and unordered <ul> lists come under the HTML lists.
Advanced lists − Creates a hierarchical or outline list, such as numbered heading styles, with numbering such as 1, 1.1, 1.1.1, and so on.
Advanced lists − Creates a hierarchical or outline list, such as numbered heading styles, with numbering such as 1, 1.1, 1.1.1, and so on.
In the Styles and Formatting pod, choose List Styles. Right-click on the pod, go to the New Menu and select List Style. Name the new list, select the font, font size and color for the new list style.
You can click on the Create an numbered List or the Create a bulleted list button to create a numbered or bulleted list.
In the Style and Formatting pod, click Create New Style, and select Multilevel List Style. Type a name for the new multilevel list and click on OK. Select a list level from the Apply Formatting To menu and select the paragraph style to apply to the current list level. You can select a predefined list style from the List Style dropdown menu, or click New to create a list style.
In the Edit Style dialog box, enter text or numbers to prefix a sequence or a multilevel list. To specify the level to prefix, select the level from the Insert Level menu. You can add a prefix to the level in the Edit Style box by separating the level and prefix with a separator such as a dot (.) or an angle bracket (>).
Apply formatting to the list style and then click on OK.
You can edit the Div, Hyperlink and Image styles using the Styles editor or from the Styles and Formatting pod.
Div is used for text boxes and positioned text boxes.
Div is used for text boxes and positioned text boxes.
Hyperlink is used for hyperlinks, dropdown hotspots, expanding hotspot and glossary terms.
Hyperlink is used for hyperlinks, dropdown hotspots, expanding hotspot and glossary terms.
Image is used to place an image.
Image is used to place an image.
To create a style based on Div, Hyperlink or Image styles, double-click a CSS file in the Project Manager pod to open the Styles editor. Right-click on a style category from the Styles list and select New. Name the style and set the properties as desired.
We can edit the properties of Div and Image styles from the Styles editor or from the Styles and Formatting pod. You can edit the Size, Margin, Float, and Border attributes of a division or a section of text or an image.
Use the Float attribute to position text to the left or to the right of a division. If you set the Float attribute to Left, the text is placed to the right. The Overflow property (for Div styles) can be used to specify what happens if text overflows in a division. If you specify Overflow as Scroll, a scroll bar is added to display the content that overflows.
When you edit styles in a CSS file, all topics that are linked to the file are updated.
To edit a style, right-click on the CSS file in the Project Manager pod and click on Edit. Deselect the Hide Inherited Styles checkbox and select a style sheet from the Available In dropdown menu.
Select a style in the Styles box, click Format, and select the attributes and click OK.
Right-click on the CSS file in the Project Manager Pod and click Edit with Code Editor to open the style sheet in a new topic window. You can now edit the styles according to your requirement.
The Table of Contents (ToC) is a hierarchy of the folders and topics in the Project Manager. In this chapter, we will see how to create and print ToCs in RoboHelp.
To create a ToC, right-click on the Table of Contents folder in the Project Manager and select ‘New Table of Contents’. Specify a name for the ToC. You can also browse for an existing ToC file (.hhc) by selecting the Copy Existing Table of Contents checkbox to create the ToC from an available ToC.
Click OK to open the Table of Contents pod. In the Table of Contents pod, click the AutoCreate TOC button. You have the option of deleting the current ToC before creating a new one or creating a new one using bookmarks in the topics.
To print a ToC, click the Table of Contents pod, go to the File tab and click on Print TOC. In the dialog box that appears, select the one of the following options to print −
Overview − Print all book and page titles.
Overview − Print all book and page titles.
Detailed − Print all book and page titles, the topic titles linked to each, and the folders in which the topics are located.
Detailed − Print all book and page titles, the topic titles linked to each, and the folders in which the topics are located.
You can modify the print options by clicking on Properties or Page Setup.
You can rename ToC books and pages without affecting the topic title linked to it. You can also change the topic title without affecting the ToC. In RoboHelp, you can rename, reorder or change properties of ToC books or pages.
To rename a ToC book or page, right-click a book or page in the Table of Contents pod and select Rename. Type the new name and press Enter.
Select a book or page in the Table of Contents pod and drag the item to a different location.
To rename a book or page or edit a window frame, right-click on the book or the page in the Table of Contents pod. Click on Properties to open the TOC Book Properties dialog box. Make the desired changes in the General and Advanced tabs and then click OK.
RoboHelp provides several options for managing ToCs and resolving errors and broken links.
We can get different forms of ToC reports, which we can print, copy and email. To access these reports, go to the Tools tab and in the Reports section, select the type of report needed.
The TOC Report displays the hierarchy of books and pages in a table of contents. If you change topic titles or filenames, you can compare them with the titles used in the books and pages.
You can choose from the following report formats −
Detailed − Includes titles of books and pages, names of topics that are linked to them and names of folders in which the files are located.
Detailed − Includes titles of books and pages, names of topics that are linked to them and names of folders in which the files are located.
Overview − Includes titles of books and pages and names of topics linked to them.
Overview − Includes titles of books and pages and names of topics linked to them.
You can identify broken links when they appear in the Table of Contents pod with a red X. In the Project tab, click on Broken Links in the Navigation section.
Shows all references to the missing topic. The Open Book icon indicates broken TOC references.
Displays topics missing from the project. To remove a TOC item, select it under References to Selected Topic, and then click on Delete.
We can create multiple ToCs for a single project, which can be used for a single-source publishing such as separate tables of contents for a project that contains multiple languages or outputs for different audiences.
Double-click on the table of contents in the Table of Contents folder in the Project Manager pod. Drag books and pages from one Table of Contents pod to the other.
A project can have multiple ToCs. Right-click on the Table of Contents folder in the Project Manager pod and select New Table of Contents. In the New Table of Contents dialog box, type a name for the ToC and click OK. An empty table of contents is created in the Table of Contents folder.
It is also possible to merge multiple ToCs in the project into a single ToC. To do this, select the book or page where you want to merge the table of contents in the Table of Contents pod and click on the Insert TOC Placeholder button. In the Insert TOC Placeholder dialog box, select the table of contents to merge in the Select Table of Contents menu and then click on OK.
You create an index by adding keywords and associating them with topics. You can spellcheck an index, and you can use topic To Do lists to track your work while indexing.
Open the Index pod by going to the Pods menu in the Project tab. To add a keyword, click the New Index Keyword button in the Index pod toolbar. Type the keyword in the text box and press Enter. The new keyword appears in bold, indicating that it is not yet linked to topics.
Open the Topic List pod from the Pods menu in the Project tab. To link the keyword to topics, drag topics from the Topic List pod to the lower panel in the Index pod. The linked keyword changes from bold to plain text.
Index keywords can be copied between topics. After copying, you can customize them to work with individual topics. Right-click on a topic in the Topic List pod and click Properties. In the Index tab, click Add Existing. On the left, a list of all keywords in the project appears. On the right, a list of all keywords for the current topic appears. If the topic is not yet indexed, no keywords appear.
To copy a single keyword, select it on the left and click the single arrow button or click the double arrow button to copy all keywords. Click OK to link the keywords to the topic.
Index keywords can be cross-referenced so that when users select the cross-referenced keyword in the index, an alternate keyword appears which the user can select to display the topic.
Add a keyword to cross-reference in the Index pod. Right-click a keyword and select Properties. In the Index Keyword Properties dialog box, select the Cross-References checkbox and from the dropdown menu, select an alternate keyword. The cross-reference appears in the lower panel of the Index Designer.
RoboHelp allows you to edit and sort index keywords. Other layouts have sorted indexes but changing the sorting of keywords is available only in the HTML Help layout. Moving an index keyword moves its sub keywords as well.
You can sort index keywords in three ways −
Select a keyword and click an arrow button in the toolbar.
Select a keyword and click an arrow button in the toolbar.
Drag the keyword.
Drag the keyword.
Right-click a keyword. In the Sort menu, select either Current Level or Current Level and Below.
Right-click a keyword. In the Sort menu, select either Current Level or Current Level and Below.
Sorting is available only if the action is allowed for the index.
To rename a topic keyword referenced by a specific topic, change the topic properties. If other topics use the same keyword, the original keyword remains in the index. Only the topic you change is updated.
In the Topic List pod, right-click a topic and click Properties. Select a keyword in the Index tab. Type the new keyword in the text box and click Replace.
Removing a keyword from a topic only affects the current topic. Other topics that reference the keyword are still linked to it. In the Topic Properties dialog box, select a keyword in the Index tab and click Delete.
You can use reports to manage indexes. There are two types of reports for indexes – Index report and Unused Index Keywords reports.
The Index report lets you display all the keywords, a list of keywords with their related topics, or a list of topics and their related keywords. The Unused Index Keywords report lists keywords that topics do not reference. These keywords reside in the index file.
From the Tools tab, select Index in the Reports section. View the report and click Close to close the report. You can also print, copy or email the report.
Open the Broken Links folder in the Project Manager pod. Missing topics if any will be listed with a red X. Right-click a missing topic and click on Properties. Keywords that reference the missing topic appear with a key icon, which can be removed or relinked in the Index pod.
RoboHelp can automatically build an index based on the topic contents. You can select from suggested keywords or use your own.
The Smart Index wizard can search the content of topics and suggest keywords. In the Tools tab, click on Smart Index Wizard. In the Smart Index Wizard dialog box, select from the following search criteria −
Find new and existing index keywords − Add keywords based on topic content and existing index entries.
Find new and existing index keywords − Add keywords based on topic content and existing index entries.
Add existing index keywords to topic(s) − Search topics for keywords already used and link the keywords to the topics.
Add existing index keywords to topic(s) − Search topics for keywords already used and link the keywords to the topics.
Use custom search settings − Select Settings, and set custom search options. In the Smart Index Settings dialog box, you can define an effective language to find index keywords.
Use custom search settings − Select Settings, and set custom search options. In the Smart Index Settings dialog box, you can define an effective language to find index keywords.
In the next screen, specify the following options −
Folder − Search topics in a specified folder.
Folder − Search topics in a specified folder.
Status − Search topics by status.
Status − Search topics by status.
Check only new topics (that have not been Smart Indexed) − Search only non-indexed topics.
Check only new topics (that have not been Smart Indexed) − Search only non-indexed topics.
Click on Next to see suggested keywords for the first topic. Select, deselect, rename or remove keywords. Then, click on Next, and click Close in the Results dialog box. The new keywords appear in the Index pod.
Open the Smart Index Wizard and click on Next twice. Select a keyword in the list, click on Options, and select Synonyms...
The keyword appears in the Word box. You can also click on Antonyms to see antonyms for the keyword. You can look up synonyms and antonyms for additional words by typing the word in the Word box and clicking Look Up.
Select the best match for the word in the Categories section and under Synonyms select a word to add as a keyword. Click Add to Topic and click Close to close the dialog box.
Multiple indexes can be created in the same project, which are added to the Index folder. You can right-click on any index and select Set as Default to set that index as the default index.
To merge the indexes within a project, open the Index folder in the Project Manager pod, and double-click on an index. In the Index pod, select a keyword where you want to insert the merged index and click the Insert Index Placeholder button. Select the index to insert and click OK.
The merged index appears with the New Index icon. Double-click on the icon and then click on View.
You can select a custom font for displaying book and page titles and can create a 3D look for the ToC. You can also add ToC and index controls for better navigation.
Right-click on a layout for HTML Help output in the Single Source Layouts pod and select Properties. Click Edit next to Advanced Settings and click on the TOC Styles tab. Set the style options as needed and then click on OK.
Open a topic in the Design view. Click where you want to add the table of contents. In the HTML section of the Insert tab, select Table of Contents from the Javascript menu. The Contents control appears in the Design Editor.
To test the control, generate the project. The Table of Contents control displays the same table of contents as in the final output.
If your project does not support a tri-pane design, you can add an index control to a topic to make the index file available. The index appears when the topic is opened with the index control. In the Design Editor, open the topic with the control and click where you want to add the index.
In the HTML section of the Insert tab, select Index from the JavaScript menu. The Index control appears in the Design Editor. To test the index control, compile the project. The index control displays the same index as in the final output.
To create a Glossary, Double-click a glossary in the Glossary folder, in the Project Manager Pod. In the Glossary pod, type a term in the Term box. Click on the Add Term button (plus sign) or press Enter. The term appears in bold, indicating that it does not have a definition. In the Definition For panel, type a definition.
For terms and definitions to appear within topics, add expanding glossary hotspots.
Before importing or changing glossaries, it is always helpful to print a detailed report of the glossary to determine the terms that exists and to compare definitions
Select a glossary in the Glossary folder in the Project Manager pod. In the Project tab, select Glossary from the dropdown menu in the Import section. Click on the Browse button to navigate to a GLO file. For definitions in the external glossary to overwrite matching terms, select Replace Existing Glossary Definitions.
Select one or more terms in the Terms in Imported glossary list, click on Add or Add All button and then click OK.
To change the glossary definitions, select the term to change in the Glossary pod and edit the definition text.
You can create multiple glossaries in the same project. New glossaries are added to the Glossary folder.
Note − You cannot delete the default glossary.
To create multiple glossary, we should follow the steps given below.
In the Project Manager Pod, right-click on the Glossary folder and select New Glossary.
In the Project Manager Pod, right-click on the Glossary folder and select New Glossary.
You can also click on the Create/View Glossary File button and click on New.
You can also click on the Create/View Glossary File button and click on New.
Type a name in the text box.
Type a name in the text box.
To copy an existing glossary, select Copy Existing Glossary and click the browse button to navigate to the glossary.
To copy an existing glossary, select Copy Existing Glossary and click the browse button to navigate to the glossary.
The Glossary Hotspot wizard finds glossary terms within topics and marks them in the topics. You can mark all terms to convert to expanding hotspot when you generate or preview output.
Note − Glossary panel is not supported in Oracle Help.
To add expanding glossary hotspots, drag a term from the Glossary pod into a topic. You can also click the Glossary Hotspot Wizard button in the Glossary pod.
The Glossary Hotspot Wizard finds glossary terms within topics and marks them in the topics. You can mark all the terms to convert to expanding hotspot, when you generate or preview the output. Preview a hotspot by double-clicking it in the Design Editor.
Open the Glossary Hotspot Wizard as discussed above. Select the Confirm marking Terms for each topic checkbox. Select a folder and status to search. From the Select Term menu, select the term to remove and then click on Next.
We can create links with most items you see in the Project Manager and TOC Composer including Topics, Bookmarks, URLs, Baggage Files, Newsgroups, FTP Sites, Files (such as PDF) associated with other programs and remote topics.
Select the insertion point for the link in the Design Editor and click the Insert Hyperlink button from the Links section of the Insert tab. Select an option from the Link To menu and specify the source location in the box.
Select from one of the following options −
Display in Frame − This option defines the frameset for displaying the destination content. You can select the frame type or enter custom frame information.
Display in Frame − This option defines the frameset for displaying the destination content. You can select the frame type or enter custom frame information.
Display in auto-sizing popup − Displays the destination topic in a pop-up window rather than in the viewer or browser.
Display in auto-sizing popup − Displays the destination topic in a pop-up window rather than in the viewer or browser.
Display in custom-sized popup − Displays the destination topic in a pop-up window. For sizing the window manually, type a number in the Width and Height fields.
Display in custom-sized popup − Displays the destination topic in a pop-up window. For sizing the window manually, type a number in the Width and Height fields.
Add tool tip text to appear when you hover over the link. Select a local topic, bookmark, frame, or URL in the Select destination (file or URL) dropdown menu and then click on OK.
Bookmarks can be used to create incremental links within a topic. The Bookmark icon appears next to the bookmarked objects. To view bookmarks from the Project.
Manager, click on the plus sign next to a topic.
Click on the left of the desired location for the bookmark in the Design Editor. Then click the Insert Bookmark icon from the Links section of the Insert tab. Enter a name, without spaces, using any combination of letters and numbers.
After you save the topic, bookmark icons appear indented under topics listed in the Project Manager pod and next to topics in the Topics List pod.
Open the topic with a bookmark. Double-click the bookmark next to the topic, edit the name, and then click OK.
We can link images, sounds, videos and other multimedia files in RoboHelp.
Place the cursor where you want to link in the Design Editor or select text or an image to create a hotspot for the link. Click on the Insert Hyperlink button from the Links section of the Insert tab.
In Link To section, click on the triangle button and select Multimedia... Select the file to link and click Open.
You can also add links from images and multimedia. In the Design Editor, click on the multimedia object or the image to link and then follow the steps given below.
Click on the Insert Hyperlink button from the Links section of the Insert tab.
Click on the Insert Hyperlink button from the Links section of the Insert tab.
To link from multimedia, in the Link To section, click on the triangle button and select Multimedia...
To link from multimedia, in the Link To section, click on the triangle button and select Multimedia...
To link from images, select the destination. Images can contain only one link.
To link from images, select the destination. Images can contain only one link.
In this chapter, we will learn how to link external sources in RoboHelp.
External topics can be Microsoft HTML Help Projects or other such related projects. Click on the Insert Hyperlink button from the Links section of the Insert tab. In the Link To section, click on the triangle dropdown menu to select Remote Topic.
Select a link location in the Design Editor and enter text. Highlight the text, click on the Insert Hyperlink button from the Links section of the Insert tab. Click on the triangle button next to Link To and then select File....
Browse to a file, open it, and copy it into the project folder. Generate the file to test links to external topics. For WebHelp projects, the external file must be distributed in the WebHelp folder. For Microsoft HTML Help Projects, the external file must the distributed with the CHM file.
Choose a location for the link in the Design Editor or select text or an image to define a hotspot. Click the Insert Hyperlink button from the Links section of the Insert tab.
In the Link To section, click the triangle button and then select from the following −
To link to e-mail or select Email.
To link to e-mail or select Email.
To link to FTP sites or newsgroups, select FTP or Usenet News.
To link to FTP sites or newsgroups, select FTP or Usenet News.
To link to intranets or websites, select Web Address.
To link to intranets or websites, select Web Address.
In the next chapter, we will discuss how to maintain and repair links in RoboHelp.
Maintaining and repairing links is a very important component of RoboHelp. Let us learn how this is done and what its advantages are.
To update and remove links, we should follow the steps given below.
Open the topic containing the desired link.
Open the topic containing the desired link.
To update the link, right-click on the link, select Hyperlink Properties and make changes.
To update the link, right-click on the link, select Hyperlink Properties and make changes.
To remove a link, right-click the link and select Remove Hyperlink.
To remove a link, right-click the link and select Remove Hyperlink.
To remove the link and the text, select the text and press Delete.
To remove the link and the text, select the text and press Delete.
To fix broken links, we should follow the steps given below.
Click on the Topic References button in the Navigation section of the Project tab to open the Topic References dialog box. To fix a link, first select a link in the References to the Selected Topic and then click on Edit or Delete to edit or remove the hyperlink.
Click on the Topic References button in the Navigation section of the Project tab to open the Topic References dialog box. To fix a link, first select a link in the References to the Selected Topic and then click on Edit or Delete to edit or remove the hyperlink.
To fix a TOC item, index keyword, or image map, first select the item and then click Edit and select a valid destination to repair the broken link.
To fix a TOC item, index keyword, or image map, first select the item and then click Edit and select a valid destination to repair the broken link.
To remove TOC entries, select the TOC item and then click on Delete.
To remove TOC entries, select the TOC item and then click on Delete.
Link controls are navigational alternatives to the TOC and index. A link control works like a link and can appear as text, a button, or an image. Link controls can direct users to related topics and information. They save the user’s time spent in searching for topics. They also help to organize information for different kinds of users.
Link controls manage topic content by keeping information needed by multiple topics in a single topic and providing access to it from several places with link controls. You can manage topic layout by inserting link controls as objects rather than as long lines of links.
Click on a location for the control in the Design Editor. In the Links section of the Insert tab, click on Related Topics. In the Related Topic Wizard – Link Options dialog box, choose an option to show related topics as a button, which can be a label or an image, or to show related topics as text and then click on Next.
From the Topics in the project section, select a topic and click on Add. Continue to add all the topics you want to appear as related topics. Click on Change to update the topic name in Related Topics if needed and then click on Next.
Choose whether options should be displayed in a Topics Found dialog or in a Popup menu. Select an option to display the selected topic in a frame or new window and then click on Next.
Select display and font options.
Click on Finish and then click on the View button to test.
DoubleTo create and assign ‘See Also’ keywords, click on the See Also Folder in the Project Manager pod to open the See Also pod. You can also type the See Also keyword in the text box and click the plus sign. The keyword appears in bold, indicating that no topics are associated with it.
Let us now consider the following steps for adding topics, keywords, etc.
To assign topics to the See Also keyword, click on the Topic List pod.
To assign topics to the See Also keyword, click on the Topic List pod.
To add a keyword to multiple topics, select a topic, drag it into the lower pod, and repeat for all the topics you want to assign.
To add a keyword to multiple topics, select a topic, drag it into the lower pod, and repeat for all the topics you want to assign.
To add the keyword to individual topics, click on the Topic List pod, select a topic, click the Properties button and select See Also. Type the keyword to assign to the topic and click on Add.
To add the keyword to individual topics, click on the Topic List pod, select a topic, click the Properties button and select See Also. Type the keyword to assign to the topic and click on Add.
Add a See Also control to the new keyword.
Add a See Also control to the new keyword.
To change, reuse or remove link controls, we should follow the steps given below.
Open a topic containing the link control In the Design Editor.
Open a topic containing the link control In the Design Editor.
To change a control, double-click the control and change its properties.
To change a control, double-click the control and change its properties.
To reuse a control, right-click on the control and select Copy. Right-click in the destination topic and select Paste.
To reuse a control, right-click on the control and select Copy. Right-click in the destination topic and select Paste.
To remove a control, select the control and click on Delete.
To remove a control, select the control and click on Delete.
In the next chapter, we will learn how to work with text-only pop-ups.
We can create short text passages called text-only pop-up messages that appear when a user clicks a linked term.
Select the text in the Design Editor and from the Insert tab, click on the Text Popup icon. Type the pop-up text directly into the window.
To edit text-only pop-ups, Right-click on the text, which has been assigned the text-only pop-up. Then we should select the Text Popup Properties...
The next step is to type or edit the text in the Popup Text box. You can also change the size, background color, fonts and margins. Future text-only pop-ups will carry forward these options.
Browse sequences help readers in navigating through a series of topics. A single topic can belong to multiple browse sequences but HTML files or external topics from other help systems cannot be included in browse sequences.
To create browse sequences automatically, create the table of contents. From the Navigation section of the Project tab, click on Browse Sequences. In the Browse Sequence Editor dialog box, click on Auto-create using TOC... to open the Auto-create Browse Sequences using TOC dialog box.
Enter the number of levels from the TOC hierarchy that you want to include in the browse sequence, and then click on OK. Click OK again. Click on Yes, if you see the Enable Browse Sequence dialog box.
To create browse sequences manually, from the Navigation section of the Project tab, click on Browse Sequences to open the Browse Sequence Editor dialog box. Click on New and then name the browse sequence. From the Available Topics list, select the folder containing the topics you are adding and add topics to the Browse Sequences Pane and click on OK. Click on Yes, if you see the Enable Browse Sequence dialog box.
RoboHelp supports many features for search. For example, we can have a multi-language search, which users can use to search for terms in other languages (if they are embedded in the topic). We can also search for Chinese/Japanese/Korean (CJK) search terms with WebHelp, FlashHelp and AIRHelp outputs. You can also use Boolean operators such as AND, OR and NOT to perform searches.
You can add or edit search metadata by going to Project Settings in the File section of the Project tab. Click on the ‘Advanced’ button next to the Language dropdown menu to open the Advanced Settings for the Localization dialog box.
Set the following metadata components as needed.
Used to define synonyms in search terms. For example, if the synonymous terms are, ‘Processor’ and ‘CPU’, RoboHelp returns topics containing ‘Intel’ with the term highlighted. Remember that we can specify only words in the Synonyms tab and not phrases.
Used to associate specific words or phrases with the current topic. You can choose words or phrases that are relevant but not generally found in the contents. For example, if ‘Adobe Systems’ is associated with a topic, when the user searches for ‘Adobe Systems’, the topic is displayed even though if it actually doesn’t contain this keyword.
Use the Phrases tab to add the keywords.
Used to ignore words to display relevant search results. Common words such as ‘a’, ‘an’, ‘the’ etc., can be ignored to ensure that RoboHelp displays only the results for the keywords needed.
In this chapter, we will understand how to optimize and configure search in RoboHelp.
RoboHelp supports many ways to optimize the content for search −
Make Office and PDF files searchable (WebHelp/Pro, FlashHelp/Pro) − When baggage files are referenced in a topic through a hyperlink, users can search for them in the published output.
Make Office and PDF files searchable (WebHelp/Pro, FlashHelp/Pro) − When baggage files are referenced in a topic through a hyperlink, users can search for them in the published output.
Exclude specified baggage file types from search (Multiscreen HTML5, WebHelp, FlashHelp, and AIR Help) − The Exclude Baggage File Types from Search option lets you exclude baggage files of specified types from search. For example, you can exclude all PDF files in your projects from search.
Exclude specified baggage file types from search (Multiscreen HTML5, WebHelp, FlashHelp, and AIR Help) − The Exclude Baggage File Types from Search option lets you exclude baggage files of specified types from search. For example, you can exclude all PDF files in your projects from search.
You can configure the search experience of end users in the following ways −
Show Total Number Of Search Results (WebHelp and AIRHelp) − This option enables display of the total number of results for a search string entered by users in the output.
Show Total Number Of Search Results (WebHelp and AIRHelp) − This option enables display of the total number of results for a search string entered by users in the output.
Hide Rank column in search results (WebHelp and WebHelp Pro) − The Rank column in search results can be hidden to provide more space for displaying search results.
Hide Rank column in search results (WebHelp and WebHelp Pro) − The Rank column in search results can be hidden to provide more space for displaying search results.
You can display content from specified URLs based on user search terms using external content search. When a user performs a search using any of these search terms, RoboHelp returns the title and description of the corresponding URL in the search results.
From the Open section of the Project tab, click on the Pods icon and select External Content Search to open the External Content Search pod. The pod allows the following options −
Add − Click Add and specify search terms (separated by a comma, space, or semicolon) and the URL for the external content.
Add − Click Add and specify search terms (separated by a comma, space, or semicolon) and the URL for the external content.
Edit − Select the entry you want to edit and click on Edit. Modify the details and then click OK.
Edit − Select the entry you want to edit and click on Edit. Modify the details and then click OK.
Import − Allows you to select the SearchOptions.xml file from a project to import the external content search settings of that project into the current project.
Import − Allows you to select the SearchOptions.xml file from a project to import the external content search settings of that project into the current project.
Export − Select a folder to export the SearchOptions.xml file.
Export − Select a folder to export the SearchOptions.xml file.
Search − Allows you to specify a string to search for a particular entry.
Search − Allows you to specify a string to search for a particular entry.
RoboHelp supports standard image formats such as GIF, JPEG, BMP, MRB, WMF, PNG, etc.
You can use the Graphics Locator to scan hard drives and folders for image files, view thumbnails, and copy files. Double-click on the Graphics Locator in the Toolbox pod and select the graphic file format that we have to search. Enter the path for the search or browse to a new location and click on Search.
To add an image to a topic in RoboHelp, we should follow the steps given below.
Select a location for the image in the Design Editor. In the Media section of the Insert tab, click on Image.
Select a location for the image in the Design Editor. In the Media section of the Insert tab, click on Image.
You can either browse to a file or insert image from a project. You can also drag images from the Images folder of the Project Manager into the topic.
You can either browse to a file or insert image from a project. You can also drag images from the Images folder of the Project Manager into the topic.
Click OK to close the Image dialog box.
Click OK to close the Image dialog box.
Select the image to edit In the Design Editor, right-click the image and choose Image Properties to set the following options −
Text Wrapping − Align the image with the surrounding text.
Text Wrapping − Align the image with the surrounding text.
Screen Tip − Text to display when the user hovers the cursor over the image.
Screen Tip − Text to display when the user hovers the cursor over the image.
ALT Text − Text to display when the image cannot be displayed.
ALT Text − Text to display when the image cannot be displayed.
Size − Set the dimensions of the image in pixels. Select Maintain aspect ratio to maintain the height to width proportion.
Size − Set the dimensions of the image in pixels. Select Maintain aspect ratio to maintain the height to width proportion.
Margins − Specify the space between the image and the text.
Margins − Specify the space between the image and the text.
Borders − Add a border to the image and specify a style.
Borders − Add a border to the image and specify a style.
It is possible to launch Adobe Captivate from RoboHelp and create demo topics. You can also insert SWF and HTML5 output of Adobe Captivate demos in the existing topics. The demo source can be opened from RoboHelp and edited.
Click on the Document icon in the Import section of the Project tab and select Adobe Captivate Demo to open the Select Adobe Captivate Demo dialog box. Specify a title, path for HTML output and path for SWF output for the new topic that you want to create for the demo.
If you have skipped specifying the corresponding SWF output path, RoboHelp adds a non-editable placeholder SWF for use in the Design Editor.
RoboHelp allows you to add a wide variety of multimedia content to your help projects. You can add both online and offline content. Depending on the output and the target browser, RoboHelp allows you to incorporate MPEG4, QuickTime and Ogg files along with a host of other compatible formats such as Real Media and Windows Media files.
To add a multimedia object, select a location in the topic where you would like to insert the multimedia and select Multimedia from the Media section of the Insert tab.
Select the Local File to insert multimedia from disk or select Web URL to link to a multimedia file online. Click on the Browse icon next to the Source field to browse to the location on disk. If you have already added files earlier, they will be seen in the Multimedia section in the Project Folders Section.
For online sources, input the Source URL rather than the HTTP URL. The Source URL can be found in the embed code of the online multimedia content beginning with ‘src=’ in the code. You can however use HTTP URLs, if you are inserting YouTube, Vimeo or DailyMotion links
To remove a multimedia object, simply click the object and press the Delete key on the keyboard.
Dynamic HTML or DHTML is used to create interactive web pages using a combination of HTML, JavaScript, CSS and DOM. With DHTML, it is possible to add effects to HTML pages that are often difficult to achieve. RoboHelp allows you to add DHTML to your help projects.
Select an element in the Design Editor and from the DHTML section of the Insert tab, click on the Effects dropdown menu and select Effects.
Select event for initiating the effect from the When list and from the ‘What’ list, select the effect you want to apply. Adjust the relevant properties in the Settings section. DHTML effects are indicated with light grey hash marks.
With the topic open in the Design Editor, go the DHTML section of the Insert tab, click on the Effects dropdown menu and select Remove Effects.
The light grey hash marks are no longer associated with the text or paragraph.
You can open DHTML effects using triggers. When you click a text or an image that is associated with a trigger, a target appears. It is important that triggers and targets reside.
Select a text or image in the Design Editor and from the DHTML section of the Insert tab, click on the Trigger dropdown menu and select Trigger.
A cable drum icon is seen on the content to which the trigger is applied. Hash marks indicate application of the DHTML effect. The next step is to connect the trigger to an image or a text.
To connect the trigger to a text or an image, select the text or image to use as a target and from the DHTML section of the Insert tab, click on the Effects dropdown menu and select Effects. In the ‘When’ section, select the 1st Trigger Activation and under ‘What’ select the effect that occurs when the user clicks the trigger. Set the required properties under Settings. Repeat for the 2nd Trigger Activation.
A plug icon appears to indicate that it is a target. For images, you can drag the cable icon onto any image and select the required DHTML effect as the target.
To remove a DHTML trigger, select the item associated with the trigger and from the DHTML section of the Insert tab, click on the Trigger dropdown menu and select Remove Trigger.
Marquees are moving text messages.
To insert a marquee, select a text in the topic and from the HTML section of the Insert tab click on the Text Box dropdown menu and select Marquee. To change properties of the marquee, right-click on the marquee and click on Marquee Properties to change the marquee settings.
Click OK to apply the settings to the marquee and close the Marquee dialog box.
To delete a marquee, click on the boundary of the marquee and press the Delete key on the keyboard.
RoboHelp makes it easy to insert HTML comments in topics.
To insert an HTML comment, open a topic in the Design Editor and place the cursor where you wish to insert the comment. From the HTML section of the Insert tab, click on the Text Box dropdown menu and select Comment.
Type your comment in the Comment Editor in the following format - <!--a comment -> and click OK.
You can insert inline frames (iframes) to show PDFs or URLs within a HTML page. To insert an iframe, open a topic in the Design Editor and place the cursor where you wish to insert the iframe. From the HTML section of the Insert tab, click on the Text Box dropdown menu and select Iframe.
Enter a name in the Name field and click on the Browse button to select a URL, HTML file, or PDF file to link and then click OK.
You can optionally set border options in the Border tab.
Conditional texts allow you to create subsets of a content within a content to suit the target audience. For example, you can choose to tag certain parts of the content and choose to exclude them in the final output via a conditional build tag.
In the New section of the Project tab, click on Tag. Type a name for the tag in the New Conditional Build Tag dialog box. You can also select a color for the tag by clicking on the Build Tag Color button.
By default, RoboHelp provides two tags – Online and Print in all new projects.
Open the Topic List pod and select a topic or multiple topics. From the Edit tab, in the Tags section, click on the Apply dropdown menu and click on New/Multiple...
Select the conditional tag that you wish to apply. When the conditional tag is applied, the content is overlaid with the color of the tag defined.
To apply tags to folders, indexes and ToCs, click on the corresponding folder in the Project Manager pod and from the Edit tab, in the Tags section, click on the Apply dropdown menu and click on New/Multiple... Select the conditional tag(s) that you wish to apply.
Sometimes, you might feel the need to create help files relative to the action performed by the user. Such help is called Context-Sensitive Help (CSH). For example, you can provide help information when a user hovers over a dialog box or other objects. The process of creating a CSH involves specifying map IDs and map files. The help engine receives the map number and help file name whenever the user accesses a CSH. The Help engine then matches the map number to a topic ID and HTM file and displays the correct help topic.
RoboHelp supports three types of CSH −
Window-level − This level of CSH provides topics for windows, dialog boxes and other fields. Users can access window-level CSH by calling the Help function within the application or pressing F1.
Window-level − This level of CSH provides topics for windows, dialog boxes and other fields. Users can access window-level CSH by calling the Help function within the application or pressing F1.
Field-level (What's This?) − This CSH describes information when a user clicks on a question mark icon and then clicks a field or function. “What’s This?” topics are supported only by WinHelp and MS HTML Help projects.
Field-level (What's This?) − This CSH describes information when a user clicks on a question mark icon and then clicks a field or function. “What’s This?” topics are supported only by WinHelp and MS HTML Help projects.
Airplane Help − This usually refers to offline help that is called when there is no access to the internet. Using Airplane Help requires associating the offline Help system with the RH_AssociateOfflineHelp program function.
Airplane Help − This usually refers to offline help that is called when there is no access to the internet. Using Airplane Help requires associating the offline Help system with the RH_AssociateOfflineHelp program function.
Before looking at creating and managing map IDs, it is important to acquaint ourselves with map numbers, map files and map IDs.
Map Number − A map number is a number associated with a topic ID. Map numbers and topics IDs are stored in map files, which are called upon when CSH is invoked.
Map Number − A map number is a number associated with a topic ID. Map numbers and topics IDs are stored in map files, which are called upon when CSH is invoked.
Map File − A map file contains the map number and topic IDs. A project can contain multiple map files. Map files have the extension .h, .hh or .hm.
Map File − A map file contains the map number and topic IDs. A project can contain multiple map files. Map files have the extension .h, .hh or .hm.
Map ID − A map ID pairs the map number with a topic ID.
Map ID − A map ID pairs the map number with a topic ID.
A map file can be created by either authors or developers. Open the Output Setup Pod and expand the Context-Sensitive Help folder.
Right click on the Map Files folder and click on New Map File... Enter a name for the new map file and then click on OK.
For creating a Map ID, we should follow the steps given below.
Expand the Map Files folder in the Context-Sensitive Help folder in the Output Setup pod and double click on All Map IDs.
Expand the Map Files folder in the Context-Sensitive Help folder in the Output Setup pod and double click on All Map IDs.
In the Map File dropdown menu, select a map file to store the map ID.
In the Map File dropdown menu, select a map file to store the map ID.
Then, click on the Create Map ID or Edit Map ID button.
Then, click on the Create Map ID or Edit Map ID button.
Type a word or phrase to identify the topic in Topic ID and type a number in Map Number.
Type a word or phrase to identify the topic in Topic ID and type a number in Map Number.
We can dynamically edit a context-sensitive help topic (CST) associated with an application dialog box. Technical authors can open the application and associate the Help topic dynamically.
RoboHelp makes it easy to map a Help project with an application. Open the Help project that belongs to the application for which a CSH needs to be created. In the CSH section of the Tools tab, click on Open CSH Help, browse to the path of the executable for which the CSH needs to be mapped. Then click on the Open button.
When the application launches, select a dialog box in the application, which needs CSH mapping and press F1 or click on Help. Select a map file from the Project Map File popup menu in the CSH Options dialog box.
From here, we can either map the application to an existing topic (Map to selected topic) or map it to a new topic (Map to New Topic) and then click OK. We can also edit the topic contents (Edit Mapped Topic) or remove the mapping altogether (Remove Mapping).
Developers can use RoboHelp APIs to create custom dialog boxes based on their requirements. RH_ShowHelp is the program function that calls the Help files in the project. Supported languages include Visual Basic, C/C++, JavaScript and Java.
The files for respective languages are located in Install Directory\Adobe\Adobe RoboHelp (version)\CSH API. The RoboHelp documentation lists the parameters contained in RH_ShowHelp. They following table describes all these parameters −
hParent
This parameter closes the Help dialog, when the calling window is closed.
a_pszHelpFile
This parameter specifies the Help Source depending on the Output type.
For Webhelp/FlashHelp: "Path to project start page"
For Webhelp Pro: "http://<ServerName>/roboapi.asp"
For HTML Help: "Path to .CHM file".
uCommand
This parameter contains the following constants −
HH_DISPLAY_INDEX − Displays Index pane and default topic.
HH_DISPLAY_SEARCH − Displays Search pane and default topic.
HH_DISPLAY_TOC − Displays Contents pane and default topic.
HH_HELP_CONTEXT − Opens topic associated with map ID in dwData parameter.
dwData
This parameter is used to obtain the map ID and export the map file for the programming language. Use the HH_HELP_CONTEXT in the uCommand parameter.
For more information or to further connect CSH topics to the languages listed above, refer to the Adobe RoboHelp documentation available on the following link – https://helpx.adobe.com/support/robohelp.html.
The ‘What’s This?’ Help can be used to add CSH to controls and fields in dialog boxes. For MS HTML Help files, the composer supports .exe, .dll and .ocx files. The Help files are created in a Context.txt file, which is then attached to the project.
To create a What’s This? Help file, expand the Context-Sensitive Help folder in the Output Setup pod. Right click on the What’s This? Help Files folder and click on Create/Import What’s This? Help File...
In the Create/Import What’s This? Help File dialog box, select the text file containing the What’s This? Help content. Alternatively, you can type a name for the What’s This? Help file and RoboHelp will create a .txt file for you.
When you create a new What’s This? Help file, you will be given the option to link the topic IDs with the corresponding map numbers. We should now follow the steps given below to complete the process −
Enter the topic ID and the corresponding map numbers.
In the Topic Text field, enter the content of the topic.
Click on Add/Update to link the topic and the map number.
Click Close when done.
Single-source layouts (SSLs) are templates for different output types of the project. For example, you can create an SSL that has different settings for different types of outputs such as eBooks, WebHelp, Responsive HTML5, etc. SSLs allows us to define output settings and enable batch publishing.
Primary layouts lets us set the default layout for our work. Additional options can then be specified to the primary layout. To specify a primary layout, right click a layout in the Outputs (SSL) pod and click on Set as Primary Output. Additional windows created are based on this primary layout.
To create an SSL, click on the Create Output in the Outputs (SSL) pod. You can also duplicate an existing layout by clicking on the Duplicate Output icon.
Then, type a name in the Output Name box and select an output type in the Output Type dropdown menu and then click OK.
The Dynamic User Centric Content (DUCC) helps users to toggle between different types of layouts, which cater to different products. Each layout will contain its own ToC, Index and Glossary.
DUCC works best with Adobe AIR and WebHelp outputs. For example, you can create content categories in an Adobe AIR layout, which can be then selected in the output.
From the Outputs (SSL) pod, click on the Create Output button in the toolbar and select the output type as Adobe AIR.
Then, right click on the Adobe AIR output in the Outputs (SSL) pod and click on Properties. In the Content Categories tab, select the categories that you want the user to dynamically change. You can also create, edit, change the order or remove existing categories.
Each content category has its own ToC, Index, Browse Sequences, etc.
It is possible to publish native ASPX or HTML outputs directly to a Microsoft SharePoint server from RoboHelp. SharePoint acts as a single resource for multiple web applications and content management. Hence, it makes it easy for users in SMEs to access centralized information.
The Multiscreen HTML5 SSL enables direct publishing of native (ASPX) outputs to a SharePoint 2010 library or SharePoint 2007 folder. The topics appear as a single HTML page when viewed in the browser.
In the Outputs (SSL) pod, right click on the Multiscreen HTML5 output and click on Properties. In the Multiscreen HTML5 Settings dialog box, click on SharePoint (Native) and specify the SharePoint version on the server.
You can also create custom master pages for each of the device profiles by clicking on the device profile name and selecting the type of master page.
Similar to ASPX multiscreen output, you can publish WebHelp, FlashHelp as well as Adobe AIR output directly to SharePoint. To publish a WebHelp output, double click on the WebHelp output in the Outputs(SSL) pod to open the WebHelp settings dialog box.
Then, click on Publish and select the SharePoint server to which we would like the output to be published. We can also add new SharePoint servers by clicking on the New... button.
Most modern browsers are available on multiple platforms and are optimized to scale content dynamically based on screen size. However, this might not be always sufficient and sometimes you might need to target content to a specific screen size or form factor. Using Multiscreen HTML5 SSL enables us to optimize our content for the specific screen size, so that the users are automatically presented the most optimized content.
You can also publish content to HTTPS sites.
You can also publish content to HTTPS sites.
While using Multiscreen HTML5 outputs, make sure to specify the default screen profile, screen resolution and browser agent to ensure that the content renders as intended on the chosen device.
While using Multiscreen HTML5 outputs, make sure to specify the default screen profile, screen resolution and browser agent to ensure that the content renders as intended on the chosen device.
The Adobe RoboHelp documentation lists the following supported browsers for HTML5 output −
RoboHelp can also publish outputs in MS HTML, JavaHelp and Oracle Help layouts. Each layout is designed to work with applications written in their respective programming languages.
The MS HTML projects include HTM files for the topics along with Index, ToC, Related topics, etc. The MS HTML files can be generated at any point during the project.
We can also extract topics from the CHM files using RoboHelp. To do so, open the Toolbox pod and double click on the HTML Help Studio icon. Go to the File menu and click on Open to select a CHM file. Select All Files or individual files and click on Extract to extract to a specified destination.
JavaHelp projects include compressed output files that work with Java applications that run on various platforms. JavaHelp can also be created from existing WinHelp or HTML projects. RoboHelp can output directly to the JavaHelp format along with HTML features such as hyperlinks.
We will need Sun Java 2 SDK (or later) and JavaHelp 1.1.3 (or later) to author JavaHelp content. The user needs to have Java Runtime Environment (JRE) 1.2.1 (or later) and JavaHelp 1.1.3 (or later) to view JavaHelp JAR files. JavaHelp does not support text animations or special effects.
Similar to JavaHelp, Oracle Help projects also work with applications written in Java or other programming languages. The Oracle Help file is stored as a compressed JAR file. To author or view Oracle Help files, Oracle Help components 3.2.2 or 4.1.2 (or later), Sun Java 2 SDK (or later) and the Java Runtime Environment (JRE) 1.2.1 (or later) are required.
Oracle Help uses a default window for displaying topics. If we want the topic to be displayed in its own window, open the topic in the HTML Editor and edit the following Meta tag −
meta name = “window-type” content = [“window name”]
Help content can be distributed in the EPUB or Kindle Book formats, so that it can be read on eBook readers, tablets and other mobile devices.
To generate eBook outputs, double click on the eBook in the Outputs (SSL) pod to open the eBook Settings page. In the General Page under the eBook Formats, select EPUB 3 or Kindle Book or both.
For EPUB 3, RoboHelp generates .epub files. For Kindle Book, RoboHelp generates a Kindle Format 8 and Mobi file using the KindleGen converter. The link to download the KindleGen converter is available in the Kindle Book Generation dialog box.
The EPUB output can be validated by clicking on the Validate EPUB 3 Output under Options. This requires downloading a Java EpubCheck file, which is available in the link shown in the dialog box.
To add a cover image to the eBook, click Meta Information on the left hand side pane and under Cover Image, select the path to the image that you wish to be the cover image.
We can also embed fonts used in the project along with the EPUB, so that users need not have the fonts installed natively on their reader. To do so, click on Content in the left hand side pane and tick the Embed Fonts checkbox. Click on Manage... to select the fonts you wish to embed in the eBook.
RoboHelp makes it easy for effective collaboration among all stakeholders involved in the project. We will look at some of the review and collaboration features below −
We can directly insert our comments in the Design Editor. The Review tab contains all the tools we need to add/edit reviews and track changes. To track changes in the Design Editor, click on Track Changes in the Tracking section of the Review toolbar.
Note − RoboHelp cannot track formatting and structure changes.
You can also create a PDF that can be sent to the reviewers. The PDF uses the same-tagged structure as the RoboHelp project, so that we can directly import those reviews into RoboHelp.
To create a PDF for review, in the PDF section of the Review tab, click on Create PDF to open the Create PDF for Review dialog box. Here, you can select the topics to be included for review and define Conditional Build Tag Expressions as well.
We can import a reviewed PDF by clicking on the Import Comments in the PDF section of the Review tab. However, for the import to be successful, the PDF should have been created from within RoboHelp.
Comments made by you or stakeholders can be accepted or rejected from the Design Editor. All the comments in the project can be viewed as a list in the Review Pane pod. The Review Pane pod allows you to filter comments and accept/reject them. Each comment can also have a status.
Often, teams work on big projects are distributed and work simultaneously. Whereas, the content is hosted on different servers such as −
Dropbox
OneDrive
Google Drive
SharePoint, etc.
RoboHelp can help you add resources from across cloud and file-system based locations into the project. To add a shared location, in the Open section of the Review tab, click on Pods and click on Resource Manager. In the Resource Manager pod, click on Add Shared Location and specify the type of shared location you want to add.
The Resource Manager pod also allows you to order your resources as categories. To add a category, click on the Add/Edit Categories icon and add the corresponding file types to a category such as .avi and .flv files for Video.
ActiveX controls are small programs that run in Windows applications such as Internet Explorer and HTML Help Viewer to enable additional functionality to the HTML page. RoboHelp comes with several ActiveX controls that you can use for HTML Help. By default, ActiveX controls such as HHCTRL.OCX are included to provide ToC, index and full text search.
The most common types of HTML ActiveX controls include −
Calendar Control
Custom Buttons
Banner
Chart
Calculations, etc.
You might need to distribute the ActiveX controls located in the Redist directory of your Adobe RoboHelp installation to users who require them.
To insert an ActiveX control, place the cursor in the topic where the control is desired and from the HTML section of the Insert tab, click on the JavaScript dropdown menu and click on ActiveX Control.
Select the desired ActiveX control from the list and click on OK to add the control to your topic. You can double click on the added ActiveX control to view its properties.
Note − Not all ActiveX controls have properties dialog boxes.
RoboHelp allows you to add forms to topics where the user can fill in information and create frames and framesets to help in navigation.
To insert a form, place the cursor in the topic where the form is desired and from the HTML section of the Insert tab, click on the HTML Form dropdown menu and click on Form.
A placeholder will be inserted in the text. Double click on the placeholder to edit the form’s properties.
Frames divide the help viewer into different regions for each topic. Framesets allow the topics to change, while keeping some topics stationary. Though you can create multiple frames in a frameset, creating too many frames can clutter the interface and even cause increased load times.
In the Project Manger tab (click on Toggle Project Manager View if required), right click on the Project Files folder and in the ‘New’ menu click on Frameset.
Select a frameset template from the options given. Enter a title and click on Next.
The framesets can be seen in the HTML Files folder in the Project Manager and can be edited.
HTML Help controls help in navigating the content. They are portable and be copied into multiple topics.
To reuse a HTML Help control, open the topic that contains the control in the Design Editor, right click the control and click Copy. Paste it in the topic that needs the control.
To add WinHelp topic controls, select a desired location for the WinHelp topic control and from the HTML section of the Insert tab, click on the JavaScript dropdown menu and click on WinHelp Topic.
Follow the prompts in the wizard to insert the WinHelp topic control.
Index controls can be useful when the project does not support a tri-pane design containing an index tab. To insert an index control, place the cursor in the topic where the index control is desired and from the HTML section of the Insert tab, click on the JavaScript dropdown menu and click on Index.
To add a ToC control, place the cursor in the topic where the ToC control is desired. Then from the HTML section of the Insert tab, click on the JavaScript dropdown menu and click on Table of Contents.
Compile the project to test the index and ToC controls.
Splash screens can be displayed when the topic opens in the viewer. Bitmap and GIF images can be used for splash screens. To add a splash screen, open the topic for which the splash screen is desired and from the HTML section of the Insert tab, click on the JavaScript dropdown menu and click on Splash Screen.
Select the image file to use for the splash screen. You can also set the duration for which the splash screen is to be displayed by setting the amount of time in the Duration of splash display (Seconds) field.
Click on Finish. Preview the topic to test the splash screen.
30 Lectures
3.5 hours
Abhilash Nelson
36 Lectures
8 hours
Eduonix Learning Solutions
15 Lectures
15 hours
Sanjeev
14 Lectures
48 mins
Ermin Dedic
127 Lectures
11.5 hours
Aleksandar Cucukovic
103 Lectures
11.5 hours
Aleksandar Cucukovic
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 4177,
"s": 3746,
"text": "Adobe RoboHelp is a popular Help Authoring Tool (HAT) from Adobe. It is used by industry professionals to deliver engaging help content, e-learning resources, organizational policies and knowledge base articles to a wide audience irrespective of device form factor. The latest version of RoboHelp (2017 release) helps you to easily create next-gen Responsive HTML5 layouts, which enable seamless navigation and rich interactivity."
},
{
"code": null,
"e": 4506,
"s": 4177,
"text": "RoboHelp was first created by Gen Kiyooka and released by Blue Sky Software in 1992. Blue Sky Software was acquired by Macromedia, which was subsequently acquired by Adobe in 2005. Adobe RoboHelp 2017 is versioned as 13.0 although technically it is version 21 taking into account the previous versions released under Macromedia."
},
{
"code": null,
"e": 4723,
"s": 4506,
"text": "RoboHelp has evolved from being just a HAT to a versatile tool, which can help you create eBooks and even web sites. RoboHelp can output to a variety of help formats using the following Single Source Layouts (SSLs) −"
},
{
"code": null,
"e": 4740,
"s": 4723,
"text": "Responsive HTML5"
},
{
"code": null,
"e": 4746,
"s": 4740,
"text": "eBook"
},
{
"code": null,
"e": 4766,
"s": 4746,
"text": "Microsoft HTML Help"
},
{
"code": null,
"e": 4775,
"s": 4766,
"text": "JavaHelp"
},
{
"code": null,
"e": 4787,
"s": 4775,
"text": "Oracle Help"
},
{
"code": null,
"e": 4800,
"s": 4787,
"text": "Eclipse Help"
},
{
"code": null,
"e": 4815,
"s": 4800,
"text": "Adobe AIR Help"
},
{
"code": null,
"e": 4851,
"s": 4815,
"text": "Standard Word and PDF documentation"
},
{
"code": null,
"e": 5082,
"s": 4851,
"text": "One of the biggest challenges faced in content delivery is ensuring that the intended audience is able to view it. RoboHelp allows content creators to create native apps for Android and iOS without the need for any extra software."
},
{
"code": null,
"e": 5389,
"s": 5082,
"text": "With a plethora of new features in the latest release, Adobe RoboHelp remains the industry standard HAT for creating engaging help, e-learning and technical content which addresses the varied needs of the target audience in a dynamic way. It is easy to use – both by seasoned authors as well as by novices."
},
{
"code": null,
"e": 5462,
"s": 5389,
"text": "The 2017 release of RoboHelp packs in many new features. These include −"
},
{
"code": null,
"e": 5492,
"s": 5462,
"text": "Next-generation HTML5 layouts"
},
{
"code": null,
"e": 5506,
"s": 5492,
"text": "Auto-complete"
},
{
"code": null,
"e": 5524,
"s": 5506,
"text": "Thumbnail support"
},
{
"code": null,
"e": 5562,
"s": 5524,
"text": "Favorites in Responsive HTML5 layouts"
},
{
"code": null,
"e": 5589,
"s": 5562,
"text": "Baggage file folder import"
},
{
"code": null,
"e": 5604,
"s": 5589,
"text": "Variable views"
},
{
"code": null,
"e": 5638,
"s": 5604,
"text": "Let us understand them in detail."
},
{
"code": null,
"e": 5975,
"s": 5638,
"text": "The 2017 release of RoboHelp promises to help you create visually engaging borderless HTML5 layouts. These layouts offer a superior search and navigation experience and are preloaded with many features like topic sliders, show/hide widgets, etc. The responsive design enables the content to scale well across screens of different sizes."
},
{
"code": null,
"e": 6295,
"s": 5975,
"text": "Now you can get predictive search results in the search field of the responsive HTML5 output after typing the first few characters. The results appear instantaneously and are contextual without the user having to enter the full search string. The results are ranked based on the frequency of the keyword in the content."
},
{
"code": null,
"e": 6619,
"s": 6295,
"text": "You can now publish thumbnails of images, which can reduce page loading times, saving bandwidth, while also being mobile friendly. If needed, the user can simply load the larger image by clicking on the thumbnail. It is possible to maintain a standard thumbnail size in order to maintain consistency throughout the content."
},
{
"code": null,
"e": 6739,
"s": 6619,
"text": "It is now possible to mark topics as favorites and add custom links with the new Indigo themed Responsive HTML5 layout."
},
{
"code": null,
"e": 6924,
"s": 6739,
"text": "You can now add multiple baggage files stored in a folder in a single click by adding the folder to the project thereby making it easy to import folders containing support information."
},
{
"code": null,
"e": 7145,
"s": 6924,
"text": "You can now easily toggle between the variable name and its value by a keyboard shortcut or from the context menu. You can toggle a single variable or all variables to view content exactly as your audience would view it."
},
{
"code": null,
"e": 7445,
"s": 7145,
"text": "Adobe RoboHelp Server is a server based help solution. You can upload your help content on a server, which can then provide real-time end user feedback. It can log data on the queries, which is asked by the users. RoboHelp Server can graphically show how users are navigating around the help system."
},
{
"code": null,
"e": 7847,
"s": 7445,
"text": "You can use an authoring tool to author the content, which can include multiple projects and upload the entire project onto the RoboHelp Server. The RoboHelp Server includes automatic project merging, which allows authors to work on different projects at different schedules and publish all of them to the same server. Authors can also publish projects written in various languages on the same server."
},
{
"code": null,
"e": 8045,
"s": 7847,
"text": "The RoboHelp Server can also interface with database servers such as Oracle or MS SQL Server and generate reports and logs. The response to the user query is relayed back via an Apache HTTP Server."
},
{
"code": null,
"e": 8199,
"s": 8045,
"text": "The typical RoboHelp workspace comprises of elements called Pods, Panes, Bars and Windows. Let us have a look at some of the components of the workspace."
},
{
"code": null,
"e": 8334,
"s": 8199,
"text": "The Quick Access Toolbar provides access to frequently used commands. It can be customized to access the commands you access the most."
},
{
"code": null,
"e": 8403,
"s": 8334,
"text": "The default commands include: Save All, Copy, Paste, Undo, and Redo."
},
{
"code": null,
"e": 8583,
"s": 8403,
"text": "Tabs are logical groups of commands put together. A tab contains commands of related functionality. Tabs are contextual and change depending on the type of content and formatting."
},
{
"code": null,
"e": 8681,
"s": 8583,
"text": "The document pane generally comprises of three rows of tabs as shown in the following screenshot."
},
{
"code": null,
"e": 8713,
"s": 8681,
"text": "These tabs are explained below."
},
{
"code": null,
"e": 8879,
"s": 8713,
"text": "The first row is the Tabbed Document Pane. Each tab comprises of one project. You can work on multiple projects at once and copy paste assets between these projects."
},
{
"code": null,
"e": 9045,
"s": 8879,
"text": "The first row is the Tabbed Document Pane. Each tab comprises of one project. You can work on multiple projects at once and copy paste assets between these projects."
},
{
"code": null,
"e": 9319,
"s": 9045,
"text": "The second row is the Design and HTML View Panes. For any given document, you can toggle between the design you are working on and the HTML code of your design. You can edit the HTML for even finer control. The HTML code is auto-generated as you keep working on the design."
},
{
"code": null,
"e": 9593,
"s": 9319,
"text": "The second row is the Design and HTML View Panes. For any given document, you can toggle between the design you are working on and the HTML code of your design. You can edit the HTML for even finer control. The HTML code is auto-generated as you keep working on the design."
},
{
"code": null,
"e": 9746,
"s": 9593,
"text": "The third row shows the Document Area Selectors. These help you to jump to various sections of the document such as Paragraphs, Headings and Hyperlinks."
},
{
"code": null,
"e": 9899,
"s": 9746,
"text": "The third row shows the Document Area Selectors. These help you to jump to various sections of the document such as Paragraphs, Headings and Hyperlinks."
},
{
"code": null,
"e": 10167,
"s": 9899,
"text": "Pods are panes that you can dock anywhere in the workspace to get access to all features, which are logically grouped. For example, the Project Manager pod shows all the components of the project. Pods can be grouped together or can be free floating on the workspace."
},
{
"code": null,
"e": 10237,
"s": 10167,
"text": "You can also make them auto-hide or move them to a different monitor."
},
{
"code": null,
"e": 10446,
"s": 10237,
"text": "RoboHelp makes it easy to locate and identify commands associated with a particular function by organizing them into tabs. The tabs are organized in a ribbon similar to the Microsoft Office suite of programs."
},
{
"code": null,
"e": 10497,
"s": 10446,
"text": "The ribbon comprises several tabs, which include −"
},
{
"code": null,
"e": 10502,
"s": 10497,
"text": "File"
},
{
"code": null,
"e": 10510,
"s": 10502,
"text": "Project"
},
{
"code": null,
"e": 10515,
"s": 10510,
"text": "Edit"
},
{
"code": null,
"e": 10522,
"s": 10515,
"text": "Insert"
},
{
"code": null,
"e": 10529,
"s": 10522,
"text": "Review"
},
{
"code": null,
"e": 10541,
"s": 10529,
"text": "Collaborate"
},
{
"code": null,
"e": 10548,
"s": 10541,
"text": "Output"
},
{
"code": null,
"e": 10554,
"s": 10548,
"text": "Tools"
},
{
"code": null,
"e": 10597,
"s": 10554,
"text": "Let us understand each of these in detail."
},
{
"code": null,
"e": 10701,
"s": 10597,
"text": "Create new projects, open, save the existing project, view recent projects and change program settings."
},
{
"code": null,
"e": 10863,
"s": 10701,
"text": "Create, import, edit, and delete project components such as topics, snippets, tags, and variables. You can save the currently unsaved changes across the project."
},
{
"code": null,
"e": 10934,
"s": 10863,
"text": "Creating and editing stylesheets, text formatting and content tagging."
},
{
"code": null,
"e": 11011,
"s": 10934,
"text": "Insert objects such as tables, images, Adobe Captivate content and snippets."
},
{
"code": null,
"e": 11074,
"s": 11011,
"text": "Track changes, accept and reject changes in a document review."
},
{
"code": null,
"e": 11139,
"s": 11074,
"text": "Share project resources across users and enable version control."
},
{
"code": null,
"e": 11204,
"s": 11139,
"text": "Create, search, setup, generate, view and open RoboHelp outputs."
},
{
"code": null,
"e": 11387,
"s": 11204,
"text": "You can create and view reports. RoboHelp ships with a number of scripts, which you can use to perform certain commands. Select and execute scripts from the Scripts list in this tab."
},
{
"code": null,
"e": 11765,
"s": 11387,
"text": "A pod is a floating or docked window of the workflow or associated functions organized in a logical manner. To open a pod, go to the Project tab, then in the Open section, click on the Pods icon to reveal a list of pods. Select a pod from the list. You can either dock the pod or keep it floating on your desktop. You can also auto-hide the pod or open it as a tabbed document."
},
{
"code": null,
"e": 11826,
"s": 11765,
"text": "RoboHelp includes many types of pods. Some of them include −"
},
{
"code": null,
"e": 11838,
"s": 11826,
"text": "Starter Pod"
},
{
"code": null,
"e": 11858,
"s": 11838,
"text": "Project Manager Pod"
},
{
"code": null,
"e": 11875,
"s": 11858,
"text": "Output Setup Pod"
},
{
"code": null,
"e": 11915,
"s": 11875,
"text": "Let us discuss each of these in detail."
},
{
"code": null,
"e": 12092,
"s": 11915,
"text": "The Starter Pod usually appears as a tabbed document but just like any other pod, you can make it float or even dock it. It usually the starting point in the RoboHelp workflow."
},
{
"code": null,
"e": 12148,
"s": 12092,
"text": "The Starter Pod comprises of four sections, which are −"
},
{
"code": null,
"e": 12208,
"s": 12148,
"text": "Recent Projects − Shows a list of recently opened projects."
},
{
"code": null,
"e": 12268,
"s": 12208,
"text": "Recent Projects − Shows a list of recently opened projects."
},
{
"code": null,
"e": 12335,
"s": 12268,
"text": "Create − Lets you choose the type of help file you want to create."
},
{
"code": null,
"e": 12402,
"s": 12335,
"text": "Create − Lets you choose the type of help file you want to create."
},
{
"code": null,
"e": 12515,
"s": 12402,
"text": "Import − Import content from Microsoft Word, Adobe FrameMaker, Adobe PDF files, HTML or other supported formats."
},
{
"code": null,
"e": 12628,
"s": 12515,
"text": "Import − Import content from Microsoft Word, Adobe FrameMaker, Adobe PDF files, HTML or other supported formats."
},
{
"code": null,
"e": 12753,
"s": 12628,
"text": "Resources − Contains links to help resources, seminars and knowledge base articles to help you get the most out of RoboHelp."
},
{
"code": null,
"e": 12878,
"s": 12753,
"text": "Resources − Contains links to help resources, seminars and knowledge base articles to help you get the most out of RoboHelp."
},
{
"code": null,
"e": 13050,
"s": 12878,
"text": "The Project Manager pod contains all the various folders in which you store and edit your project files. The Project Manager pod has default folders for each content type."
},
{
"code": null,
"e": 13188,
"s": 13050,
"text": "For example, all images in the project are stored under the Images folder, videos and sounds are stored under the Multimedia folder, etc."
},
{
"code": null,
"e": 13503,
"s": 13188,
"text": "The Project Manager Pod also contains the Baggage Files folder, which contains the indirectly linked files that are part of the project. The baggage files might include –PDF files, PowerPoint presentations, etc. Double-clicking on files within the Baggage Files folder opens the file in its associated application."
},
{
"code": null,
"e": 13763,
"s": 13503,
"text": "The Output Setup Pod helps you to view and modify the output of the content based on the targeted device. It contains a hierarchical organization of the different output components such as the Window, Master Pages, Skins, Device Profiles, Screen Layouts, etc."
},
{
"code": null,
"e": 13818,
"s": 13763,
"text": "Right-click on any container to change its properties."
},
{
"code": null,
"e": 14023,
"s": 13818,
"text": "For example – If you want to alter the dimensions of the MS_HTML output window, right-click on the MS_HTML container in the Windows folder and select how you want the window to be displayed on the screen."
},
{
"code": null,
"e": 14274,
"s": 14023,
"text": "The arrangement of workspace elements such windows, pods and other elements is called an environment. Environments can be customized as desired by the user. There can be specific arrangements of windows and pods, which can be saved as an environment."
},
{
"code": null,
"e": 14492,
"s": 14274,
"text": "Environments can then be recalled by selecting the environment from the Workspace menu on the upper right hand corner of the window. Environments are saved in an ‘.rhs file’, which can be exchanged with other authors."
},
{
"code": null,
"e": 14703,
"s": 14492,
"text": "Arrange all the pods in the workspace. Click on the dropdown arrow next to the Workspace in the upper right hand corner of the RoboHelp window. Click on Save... and select a location and name for the workspace."
},
{
"code": null,
"e": 14827,
"s": 14703,
"text": "Click on the dropdown arrow next to the Workspace in the upper right hand corner of the RoboHelp window and select Load...."
},
{
"code": null,
"e": 14915,
"s": 14827,
"text": "Browse to the file location of the .rhs file and click on Open to load the environment."
},
{
"code": null,
"e": 15074,
"s": 14915,
"text": "To delete an environment, navigate to the location on the disk, where the .rhs file was stored and simply delete the .rhs file pertaining to that environment."
},
{
"code": null,
"e": 15263,
"s": 15074,
"text": "Keyboard shortcuts help in quickly completing tasks and RoboHelp has many keyboard shortcuts to enable you to get your work done faster. You can also customize your own keyboard shortcuts."
},
{
"code": null,
"e": 15343,
"s": 15263,
"text": "The following points will explain how to create keyboard shortcuts in RoboHelp."
},
{
"code": null,
"e": 15431,
"s": 15343,
"text": "In the dropdown menu, next to the Quick Access Toolbar select the More Commands option."
},
{
"code": null,
"e": 15519,
"s": 15431,
"text": "In the dropdown menu, next to the Quick Access Toolbar select the More Commands option."
},
{
"code": null,
"e": 15612,
"s": 15519,
"text": "In the General section, under User Interface Options, click on Customize Keyboard Shortcuts."
},
{
"code": null,
"e": 15705,
"s": 15612,
"text": "In the General section, under User Interface Options, click on Customize Keyboard Shortcuts."
},
{
"code": null,
"e": 15823,
"s": 15705,
"text": "Choose a tab category in the Category dropdown and select a command for which you want to assign a keyboard shortcut."
},
{
"code": null,
"e": 15941,
"s": 15823,
"text": "Choose a tab category in the Category dropdown and select a command for which you want to assign a keyboard shortcut."
},
{
"code": null,
"e": 16129,
"s": 15941,
"text": "In the Press new shortcut key box, enter the keyboard shortcut or combination and click on Assign. If keyboard shortcuts are already assigned, it will show up in the Key assignments: box."
},
{
"code": null,
"e": 16317,
"s": 16129,
"text": "In the Press new shortcut key box, enter the keyboard shortcut or combination and click on Assign. If keyboard shortcuts are already assigned, it will show up in the Key assignments: box."
},
{
"code": null,
"e": 16410,
"s": 16317,
"text": "Once you have done assigning all keyboard shortcuts, click on Close to close the dialog box."
},
{
"code": null,
"e": 16503,
"s": 16410,
"text": "Once you have done assigning all keyboard shortcuts, click on Close to close the dialog box."
},
{
"code": null,
"e": 16589,
"s": 16503,
"text": "You can also export the list of keyboard shortcuts as a CSV file by selecting Export."
},
{
"code": null,
"e": 16675,
"s": 16589,
"text": "You can also export the list of keyboard shortcuts as a CSV file by selecting Export."
},
{
"code": null,
"e": 16759,
"s": 16675,
"text": "The following points will explain how to remove the keyboard shortcuts in RoboHelp."
},
{
"code": null,
"e": 16930,
"s": 16759,
"text": "To remove an assigned shortcut, navigate to the Customize Keyboard Shortcuts... dialog box and click on the command of which you want the keyboard shortcut to be removed."
},
{
"code": null,
"e": 17101,
"s": 16930,
"text": "To remove an assigned shortcut, navigate to the Customize Keyboard Shortcuts... dialog box and click on the command of which you want the keyboard shortcut to be removed."
},
{
"code": null,
"e": 17180,
"s": 17101,
"text": "Then click on Remove to remove the keyboard shortcut assigned to that command."
},
{
"code": null,
"e": 17259,
"s": 17180,
"text": "Then click on Remove to remove the keyboard shortcut assigned to that command."
},
{
"code": null,
"e": 17338,
"s": 17259,
"text": "To restore the keyboard shortcuts to their default settings, select Reset All."
},
{
"code": null,
"e": 17417,
"s": 17338,
"text": "To restore the keyboard shortcuts to their default settings, select Reset All."
},
{
"code": null,
"e": 17549,
"s": 17417,
"text": "To configure general program options, go to the File tab, then go to Options and select the General section to change the settings."
},
{
"code": null,
"e": 17634,
"s": 17549,
"text": "An overview of some of the important settings is given in the following screenshot −"
},
{
"code": null,
"e": 17697,
"s": 17634,
"text": "Following are the preferences for general setting in RoboHelp."
},
{
"code": null,
"e": 17825,
"s": 17697,
"text": "Use underscores in filenames − Topic file names are saved with underscores between words, which are required for HTML projects."
},
{
"code": null,
"e": 17953,
"s": 17825,
"text": "Use underscores in filenames − Topic file names are saved with underscores between words, which are required for HTML projects."
},
{
"code": null,
"e": 18110,
"s": 17953,
"text": "Automatically check for updates − Checks for updates upon exit. You can also enable this option by selecting File → Help → Accounts and updates → Updates..."
},
{
"code": null,
"e": 18267,
"s": 18110,
"text": "Automatically check for updates − Checks for updates upon exit. You can also enable this option by selecting File → Help → Accounts and updates → Updates..."
},
{
"code": null,
"e": 18370,
"s": 18267,
"text": "Allow editing of multiple topics − Opens topics in different tabs in Design Editor and allows editing."
},
{
"code": null,
"e": 18473,
"s": 18370,
"text": "Allow editing of multiple topics − Opens topics in different tabs in Design Editor and allows editing."
},
{
"code": null,
"e": 18685,
"s": 18473,
"text": "Clear project cache (.cpd file) before opening any project − This helps to Delete the old <ProjectName>.cpd file every time. While opening a project and a new <ProjectName>.cpd is created from the project files."
},
{
"code": null,
"e": 18897,
"s": 18685,
"text": "Clear project cache (.cpd file) before opening any project − This helps to Delete the old <ProjectName>.cpd file every time. While opening a project and a new <ProjectName>.cpd is created from the project files."
},
{
"code": null,
"e": 19082,
"s": 18897,
"text": "Remember project state − Ensures that RoboHelp remembers the location of the opened files and pods, so that the project will open in the same state, the next time you open the program."
},
{
"code": null,
"e": 19267,
"s": 19082,
"text": "Remember project state − Ensures that RoboHelp remembers the location of the opened files and pods, so that the project will open in the same state, the next time you open the program."
},
{
"code": null,
"e": 19315,
"s": 19267,
"text": "Following are the list of commands in RoboHelp."
},
{
"code": null,
"e": 19429,
"s": 19315,
"text": "Auto-compile outdated files − Automatically generates your primary layout, when the output files are out of date."
},
{
"code": null,
"e": 19543,
"s": 19429,
"text": "Auto-compile outdated files − Automatically generates your primary layout, when the output files are out of date."
},
{
"code": null,
"e": 19659,
"s": 19543,
"text": "Auto-display output view − Shows the Output View at the bottom of the program window, when a project is generating."
},
{
"code": null,
"e": 19775,
"s": 19659,
"text": "Auto-display output view − Shows the Output View at the bottom of the program window, when a project is generating."
},
{
"code": null,
"e": 19932,
"s": 19775,
"text": "Convert RoboHelp-edited topics to HTML − Converts XHTML topics into HTML in the output. Topics created or edited with third-party editors are not converted."
},
{
"code": null,
"e": 20089,
"s": 19932,
"text": "Convert RoboHelp-edited topics to HTML − Converts XHTML topics into HTML in the output. Topics created or edited with third-party editors are not converted."
},
{
"code": null,
"e": 20214,
"s": 20089,
"text": "Show learning resources on Starter page − Show or hide the area that has a stream of learning resources on the Starter page."
},
{
"code": null,
"e": 20339,
"s": 20214,
"text": "Show learning resources on Starter page − Show or hide the area that has a stream of learning resources on the Starter page."
},
{
"code": null,
"e": 20539,
"s": 20339,
"text": "A project is a collection of source files that becomes the help system, which the end user sees. Project files are stored in the .xpj format and contain the information and properties of the project."
},
{
"code": null,
"e": 20594,
"s": 20539,
"text": "A project file comprises of the following components −"
},
{
"code": null,
"e": 20602,
"s": 20594,
"text": "Content"
},
{
"code": null,
"e": 20613,
"s": 20602,
"text": "Properties"
},
{
"code": null,
"e": 20624,
"s": 20613,
"text": "Navigation"
},
{
"code": null,
"e": 20664,
"s": 20624,
"text": "Let us discuss each of these in detail."
},
{
"code": null,
"e": 20775,
"s": 20664,
"text": "The project content includes the topics and information about the location of topics, images, index, ToC, etc."
},
{
"code": null,
"e": 20946,
"s": 20775,
"text": "On a new project, default properties are used. These properties include settings such as – Title, Language, Windows, etc., which can be modified based on the requirement."
},
{
"code": null,
"e": 21041,
"s": 20946,
"text": "Projects include a ToC, Index and full text search to enable the user to navigate the content."
},
{
"code": null,
"e": 21095,
"s": 21041,
"text": "A RoboHelp project comprises of the following files −"
},
{
"code": null,
"e": 21119,
"s": 21095,
"text": "Main project file (XPJ)"
},
{
"code": null,
"e": 21138,
"s": 21119,
"text": "Folder files (FPJ)"
},
{
"code": null,
"e": 21171,
"s": 21138,
"text": "Single-source layout files (SSL)"
},
{
"code": null,
"e": 21205,
"s": 21171,
"text": "Auxiliary project files (APJ) and"
},
{
"code": null,
"e": 21226,
"s": 21205,
"text": "Other types of files"
},
{
"code": null,
"e": 21278,
"s": 21226,
"text": "Let us discuss each of these files in detail below."
},
{
"code": null,
"e": 21389,
"s": 21278,
"text": "The project file (.xpj) is XML-based. Older .mpj files convert to XPJ files in the latest version of RoboHelp."
},
{
"code": null,
"e": 21521,
"s": 21389,
"text": "The FPJ file lists the folder contents. Only those subfolders and topics that are listed in the FPJ file of a folder are displayed."
},
{
"code": null,
"e": 21613,
"s": 21521,
"text": "Stores properties of the single-source layout and is modified when you edit the properties."
},
{
"code": null,
"e": 21744,
"s": 21613,
"text": "Components such as windows, baggage files, map files, font sets, etc., have corresponding APJ files, which get modified or edited."
},
{
"code": null,
"e": 21802,
"s": 21744,
"text": "Other types of files in a project include the following −"
},
{
"code": null,
"e": 21825,
"s": 21802,
"text": "Browse sequences (BRS)"
},
{
"code": null,
"e": 21838,
"s": 21825,
"text": "Topics (HTM)"
},
{
"code": null,
"e": 21848,
"s": 21838,
"text": "TOC (HHC)"
},
{
"code": null,
"e": 21860,
"s": 21848,
"text": "Index (HHK)"
},
{
"code": null,
"e": 21875,
"s": 21860,
"text": "Glossary (GLO)"
},
{
"code": null,
"e": 21930,
"s": 21875,
"text": "Image and multimedia files (filename extension varies)"
},
{
"code": null,
"e": 21949,
"s": 21930,
"text": "Style sheets (CSS)"
},
{
"code": null,
"e": 22063,
"s": 21949,
"text": "You can create a project from scratch or by importing data from an external file such as FrameMaker, Word or PDF."
},
{
"code": null,
"e": 22134,
"s": 22063,
"text": "The following points describe how to create a new project in RoboHelp."
},
{
"code": null,
"e": 22266,
"s": 22134,
"text": "A new project can be created either by selecting File → New Project or using the ‘More’ option in the Starter pod under Create New."
},
{
"code": null,
"e": 22398,
"s": 22266,
"text": "A new project can be created either by selecting File → New Project or using the ‘More’ option in the Starter pod under Create New."
},
{
"code": null,
"e": 22521,
"s": 22398,
"text": "In the New Project dialog box, double-click a project type. You can change the project type after your project is created."
},
{
"code": null,
"e": 22644,
"s": 22521,
"text": "In the New Project dialog box, double-click a project type. You can change the project type after your project is created."
},
{
"code": null,
"e": 22825,
"s": 22644,
"text": "In the New Project Wizard dialog box, specify the options such as Project Title, File Name, Location on Disk and the title of first topic and click on Finish to create the project."
},
{
"code": null,
"e": 23006,
"s": 22825,
"text": "In the New Project Wizard dialog box, specify the options such as Project Title, File Name, Location on Disk and the title of first topic and click on Finish to create the project."
},
{
"code": null,
"e": 23094,
"s": 23006,
"text": "The following steps explain how to create a project by importing documents in RoboHelp."
},
{
"code": null,
"e": 23203,
"s": 23094,
"text": "You can create new projects by importing content from external sources such as FrameMaker or Word documents."
},
{
"code": null,
"e": 23312,
"s": 23203,
"text": "You can create new projects by importing content from external sources such as FrameMaker or Word documents."
},
{
"code": null,
"e": 23454,
"s": 23312,
"text": "Go to the New Project dialog box File → New Project or by using the ‘More’ option in the Starter pod under Create New. Select the Import tab."
},
{
"code": null,
"e": 23596,
"s": 23454,
"text": "Go to the New Project dialog box File → New Project or by using the ‘More’ option in the Starter pod under Create New. Select the Import tab."
},
{
"code": null,
"e": 23662,
"s": 23596,
"text": "Choose the type of document that you need to import and click OK."
},
{
"code": null,
"e": 23728,
"s": 23662,
"text": "Choose the type of document that you need to import and click OK."
},
{
"code": null,
"e": 23913,
"s": 23728,
"text": "In the New Project Wizard dialog box, specify the options such as Project Title, File Name, Location on Disk and the title of the first topic and click on Finish to create the project."
},
{
"code": null,
"e": 24098,
"s": 23913,
"text": "In the New Project Wizard dialog box, specify the options such as Project Title, File Name, Location on Disk and the title of the first topic and click on Finish to create the project."
},
{
"code": null,
"e": 24207,
"s": 24098,
"text": "You can open a project when starting RoboHelp using the Starter pod or traditionally by using the File menu."
},
{
"code": null,
"e": 24427,
"s": 24207,
"text": "The Starter pod shows a list of recently opened projects. Click on the project name, which has to be opened. If you do not see the needed project, click Open Project and navigate to the location of the project on disk."
},
{
"code": null,
"e": 24541,
"s": 24427,
"text": "Click on the File tab and select Open Project. Click on the Local or Network Path and select a project from disk."
},
{
"code": null,
"e": 24672,
"s": 24541,
"text": "If you are opening projects created in an older version of RoboHelp, you will be asked to convert the project into the new format."
},
{
"code": null,
"e": 24773,
"s": 24672,
"text": "To change settings for a project, in the Project tab, click on Project Settings in the File section."
},
{
"code": null,
"e": 24977,
"s": 24773,
"text": "You can change settings such as the title of the project, the primary output, and localization. You can also manage a To Do List by clicking on the Manage... button and adding the required to do actions."
},
{
"code": null,
"e": 25201,
"s": 24977,
"text": "In the Index section, you can choose to either add new keywords to the project index file (HHK) or save as individual topic files (HTM). Select the Binary Index option if you want to combine indexes from multiple CHM files."
},
{
"code": null,
"e": 25379,
"s": 25201,
"text": "You order topics and folders logically in the Project Manager pod to define a chapter layout. This chapter layout forms the basis for the Table of Contents creation by RoboHelp."
},
{
"code": null,
"e": 25432,
"s": 25379,
"text": "A few important points to note here are as follows −"
},
{
"code": null,
"e": 25510,
"s": 25432,
"text": "If you rename a folder or a topic, the topics and folders retain their order."
},
{
"code": null,
"e": 25588,
"s": 25510,
"text": "If you rename a folder or a topic, the topics and folders retain their order."
},
{
"code": null,
"e": 25664,
"s": 25588,
"text": "If you delete a topic or a folder, the remaining topics retain their order."
},
{
"code": null,
"e": 25740,
"s": 25664,
"text": "If you delete a topic or a folder, the remaining topics retain their order."
},
{
"code": null,
"e": 25825,
"s": 25740,
"text": "If you add a new topic or a folder, it is added at the top inside the parent folder."
},
{
"code": null,
"e": 25910,
"s": 25825,
"text": "If you add a new topic or a folder, it is added at the top inside the parent folder."
},
{
"code": null,
"e": 26073,
"s": 25910,
"text": "If you drop a topic or a folder on a non-topic/folder item (such as CSS, image, or baggage), it moves to the last position inside the parent folder of the target."
},
{
"code": null,
"e": 26236,
"s": 26073,
"text": "If you drop a topic or a folder on a non-topic/folder item (such as CSS, image, or baggage), it moves to the last position inside the parent folder of the target."
},
{
"code": null,
"e": 26396,
"s": 26236,
"text": "To order topics, simply drag a topic or folder above or below another topic or folder. A green arrow is shown to indicate the placement of the topic or folder."
},
{
"code": null,
"e": 26519,
"s": 26396,
"text": "RoboHelp provides many ways to organize and work with project files. We will look at some of the common operations below −"
},
{
"code": null,
"e": 26660,
"s": 26519,
"text": "Open a project, and in the Project tab, go to the View section → Display Topics and select to display topics By Topic Title or By File Name."
},
{
"code": null,
"e": 26913,
"s": 26660,
"text": "Project tasks can be tracked by using To Do Lists, which can be customized. To Do Lists are retained when converting projects from an older RoboHelp version. To edit a To Do List go to Project Settings, click on the General tab and then click Manage..."
},
{
"code": null,
"e": 27051,
"s": 26913,
"text": "To add a task to the list, click Add. Type the name of the task item. To edit or remove a task, select the task and click Edit or Delete."
},
{
"code": null,
"e": 27426,
"s": 27051,
"text": "The RoboHelp Starter pod lists recently opened projects. To edit this list, go to the File menu and click on Options. Click the Recent Projects tab. If you want to change the number of files listed, specify a number in the Max Projects box. To remove a file from the list, select it and click on Remove. You can pin frequently used files by selecting it and clicking on Pin."
},
{
"code": null,
"e": 27729,
"s": 27426,
"text": "Sometimes, you might have to add files to the Baggage Files folder, so the external elements appear correctly in the output. You can add individual files or even folders. To add files or a folder to the Baggage Files folder, right-click on Project Files, go to Import Baggage and select File or Folder."
},
{
"code": null,
"e": 27997,
"s": 27729,
"text": "You can map file types to associate them with the applications for editing and viewing. To associate a file extension with an application, go to the File menu and click on Options. Click on the File Association tab. You can associate programs as well as HTML Editors."
},
{
"code": null,
"e": 28214,
"s": 27997,
"text": "To associate programs, click Add in the Associated Programs section and enter a filename extension. Select an editor to edit documents with the specified filename extension and then select a program to view the file."
},
{
"code": null,
"e": 28386,
"s": 28214,
"text": "To add an HTML editor, click Add in the HTML Editors section and select from the recommended or other programs registered to edit or view .html or .htm files and click OK."
},
{
"code": null,
"e": 28664,
"s": 28386,
"text": "It is recommended to back up all project files, view and print reports before removing project files. This is especially important if your project is not under version control. In order to avoid broken links, do not remove files in Windows Explorer or version control software."
},
{
"code": null,
"e": 28924,
"s": 28664,
"text": "Select one or more files and press Delete on the keyboard. As a precaution, it is recommended not to remove references to removed topics, so that they can be shown in the Broken Links folder for later review. To remove multiple topics, use the Topic List Pod."
},
{
"code": null,
"e": 29074,
"s": 28924,
"text": "Similar to project file management, RoboHelp also provides ways to manage project files. We will look at some of the common folder operations below −"
},
{
"code": null,
"e": 29198,
"s": 29074,
"text": "There are default folders that you can use to create folders and subfolders in the Project Manager. These folders include −"
},
{
"code": null,
"e": 29218,
"s": 29198,
"text": "HTML Files (Topics)"
},
{
"code": null,
"e": 29225,
"s": 29218,
"text": "Images"
},
{
"code": null,
"e": 29236,
"s": 29225,
"text": "Multimedia"
},
{
"code": null,
"e": 29254,
"s": 29236,
"text": "Style Sheets and "
},
{
"code": null,
"e": 29268,
"s": 29254,
"text": "Baggage Files"
},
{
"code": null,
"e": 29415,
"s": 29268,
"text": "To create a folder, right click on the Project Files folder in the Project Manager pod, go to New and select Folder. Enter a name and press Enter."
},
{
"code": null,
"e": 29592,
"s": 29415,
"text": "To rename folders, expand the Project Files folder in the Project Manager pod. Right-click the folder you want to rename and click on Rename. Type the new name and press Enter."
},
{
"code": null,
"e": 29716,
"s": 29592,
"text": "To move a folder, select the folder in Project Files in the Project Manager pod and drag the subfolder to its new location."
},
{
"code": null,
"e": 29804,
"s": 29716,
"text": "To remove a folder, right-click the folder in the Project Manager pod and click Delete."
},
{
"code": null,
"e": 30112,
"s": 29804,
"text": "RoboHelp allows for authoring content in multiple languages. The language applies to the text, dictionary and the index of the project. However, keep in mind that the end user’s OS must be in the same language for HTML Help systems as the project language otherwise it will be overridden by the OS language."
},
{
"code": null,
"e": 30207,
"s": 30112,
"text": "You can compare content in different languages or select a different language for translation."
},
{
"code": null,
"e": 30472,
"s": 30207,
"text": "To compare content in different languages, open the topics created in different languages. Drag the tab of one of the topics a little below on to the Design button (second row on the Document Pane) and choose if you want to compare them vertically or horizontally."
},
{
"code": null,
"e": 30547,
"s": 30472,
"text": "In the Output tab, select Stop Words as shown in the following screenshot."
},
{
"code": null,
"e": 30662,
"s": 30547,
"text": "You can change the following settings in the respective tabs in the Advanced Settings for Localization dialog box."
},
{
"code": null,
"e": 30727,
"s": 30662,
"text": "Stop List − Add words that must be ignored during a text search."
},
{
"code": null,
"e": 30792,
"s": 30727,
"text": "Stop List − Add words that must be ignored during a text search."
},
{
"code": null,
"e": 30896,
"s": 30792,
"text": "Phrases − Add a phrase for the Smart Index Wizard to include when searching topic content for keywords."
},
{
"code": null,
"e": 31000,
"s": 30896,
"text": "Phrases − Add a phrase for the Smart Index Wizard to include when searching topic content for keywords."
},
{
"code": null,
"e": 31065,
"s": 31000,
"text": "Labels − Modify the text for each user interface element listed."
},
{
"code": null,
"e": 31130,
"s": 31065,
"text": "Labels − Modify the text for each user interface element listed."
},
{
"code": null,
"e": 31238,
"s": 31130,
"text": "\"Always Ignore\" Words − Add a word or phrase that the Smart Index Wizard ignores when generating the index."
},
{
"code": null,
"e": 31346,
"s": 31238,
"text": "\"Always Ignore\" Words − Add a word or phrase that the Smart Index Wizard ignores when generating the index."
},
{
"code": null,
"e": 31474,
"s": 31346,
"text": "Synonyms − Add a synonym for a word. The results are always returned for the searched words even when searched for the synonym."
},
{
"code": null,
"e": 31602,
"s": 31474,
"text": "Synonyms − Add a synonym for a word. The results are always returned for the searched words even when searched for the synonym."
},
{
"code": null,
"e": 31679,
"s": 31602,
"text": "In the next chapter, we will understand how to import PDF files in RoboHelp."
},
{
"code": null,
"e": 31951,
"s": 31679,
"text": "RoboHelp allows you to import content from PDF files. The ToCs are carried over into the help file. However, keep in mind that encrypted PDF files or files containing SWFs will not import. You can either create a project by importing a PDF or import a PDF into a project."
},
{
"code": null,
"e": 32035,
"s": 31951,
"text": "To create a project from a PDF file, we would need to follow the steps given below."
},
{
"code": null,
"e": 32175,
"s": 32035,
"text": "Step 1 − Go to the File menu, click on New Project and click on the Import tab. Select PDF document in the list of file types and click OK."
},
{
"code": null,
"e": 32432,
"s": 32175,
"text": "Step 2 − In the Import PDF Wizard, browse to the location of the PDF file you want to import and click on Next. Enter details of the project and click on Next. Select the desired conversion options and click on Finish to import the PDF as a HTML help file."
},
{
"code": null,
"e": 32594,
"s": 32432,
"text": "Step 3 − When you choose to create new topic(s) based on style(s), RoboHelp will analyze the PDF for paragraph styles and headings and splits the topics for you."
},
{
"code": null,
"e": 32671,
"s": 32594,
"text": "To import PDF files into a project, we have to follow the steps given below."
},
{
"code": null,
"e": 32898,
"s": 32671,
"text": "Step 1 − You can import PDF files into an existing project. Make sure the Project Manager Pod is open, then right-click on the Project Files folder. Click on Import Topics... and browse to the location of the PDF file on disk."
},
{
"code": null,
"e": 33008,
"s": 32898,
"text": "Note − You can also select multiple PDF files at once by holding down the Ctrl key and clicking on each file."
},
{
"code": null,
"e": 33168,
"s": 33008,
"text": "Step 2 − In the Import PDF Wizard, browse to the location of the PDF file you want to import and click on Next. Enter details of the project and click on Next."
},
{
"code": null,
"e": 33427,
"s": 33168,
"text": "Step 3 − Select the desired conversion options and click on Finish to import the PDF as a HTML help file. When you choose to create new topic(s) based on style(s), RoboHelp will analyze the PDF for paragraph styles and headings and splits the topics for you."
},
{
"code": null,
"e": 33834,
"s": 33427,
"text": "Just like PDF files, you can import and link Microsoft Word Documents in RoboHelp. You can create new help files by importing Word documents or import Word documents into existing help files. Before importing Word documents, it is important that they be optimized for online output. You have the option of either importing or linking Word documents. It is important to choose the one that suits your needs."
},
{
"code": null,
"e": 34049,
"s": 33834,
"text": "Importing allows you to integrate the Word document in the help file and customize filenames from the Project Manager. Linking allows you to dynamically-update the source document including ToC, index and glossary."
},
{
"code": null,
"e": 34214,
"s": 34049,
"text": "You can also regenerate deleted topics and preserve changes in generated topics. You cannot however, change the filenames and topic titles from the Project Manager."
},
{
"code": null,
"e": 34301,
"s": 34214,
"text": "To optimize word documents for online output, we should consider the following points."
},
{
"code": null,
"e": 34584,
"s": 34301,
"text": "Heading hierarchies − Apply hierarchical headings before conversion to achieve automatic pagination. For example, you can apply Heading 1 style in your Word document, map this style to a similar RoboHelp style, and define pagination to create an HTML topic for each Heading 1 style."
},
{
"code": null,
"e": 34867,
"s": 34584,
"text": "Heading hierarchies − Apply hierarchical headings before conversion to achieve automatic pagination. For example, you can apply Heading 1 style in your Word document, map this style to a similar RoboHelp style, and define pagination to create an HTML topic for each Heading 1 style."
},
{
"code": null,
"e": 34960,
"s": 34867,
"text": "Inline styles and style overrides − You can convert inline styles to CSS styles in RoboHelp."
},
{
"code": null,
"e": 35053,
"s": 34960,
"text": "Inline styles and style overrides − You can convert inline styles to CSS styles in RoboHelp."
},
{
"code": null,
"e": 35256,
"s": 35053,
"text": "Header and footer information − RoboHelp can convert headers and footers. To ensure consistency across your topics, you can define a master page that contains the required header and footer information."
},
{
"code": null,
"e": 35459,
"s": 35256,
"text": "Header and footer information − RoboHelp can convert headers and footers. To ensure consistency across your topics, you can define a master page that contains the required header and footer information."
},
{
"code": null,
"e": 35660,
"s": 35459,
"text": "Chapter versus topic − In online Help, the organizational unit is the topic, and users see topics one at a time. Provide comprehensive information without adding redundancy by grouping related topics."
},
{
"code": null,
"e": 35861,
"s": 35660,
"text": "Chapter versus topic − In online Help, the organizational unit is the topic, and users see topics one at a time. Provide comprehensive information without adding redundancy by grouping related topics."
},
{
"code": null,
"e": 35992,
"s": 35861,
"text": "ToCs − You can also import the Word ToC into the RoboHelp ToC by defining the topic hierarchy and representing it in RoboHelp TOC."
},
{
"code": null,
"e": 36123,
"s": 35992,
"text": "ToCs − You can also import the Word ToC into the RoboHelp ToC by defining the topic hierarchy and representing it in RoboHelp TOC."
},
{
"code": null,
"e": 36327,
"s": 36123,
"text": "Context sensitivity − You can assign context-sensitive Help markers in Word documents using custom footnote entries. RoboHelp reads these footnote entries and assigns the map IDs to the generated topics."
},
{
"code": null,
"e": 36531,
"s": 36327,
"text": "Context sensitivity − You can assign context-sensitive Help markers in Word documents using custom footnote entries. RoboHelp reads these footnote entries and assigns the map IDs to the generated topics."
},
{
"code": null,
"e": 36707,
"s": 36531,
"text": "Unlike PDFs, which do not require you to have Acrobat or Acrobat Reader installed, you need to have Microsoft Word installed to be able to import Word documents into RoboHelp."
},
{
"code": null,
"e": 36942,
"s": 36707,
"text": "To import a Word document, in the Starter pod, go to the Import tab and select the icon representing Word documents (*.docx, *.doc) and select the Word document you want to import. Enter the details of the project and click on Finish."
},
{
"code": null,
"e": 37029,
"s": 36942,
"text": "To Link a Word document to a RoboHelp project, we should follow the steps given below."
},
{
"code": null,
"e": 37204,
"s": 37029,
"text": "Step 1 − In the Project Manager Pod, right-click on the Project Files folder and select Word Document from the Link submenu. Select one or more Word documents and click Open."
},
{
"code": null,
"e": 37306,
"s": 37204,
"text": "Step 2 − Right-click on the linked Word document in the Project Files folder and click on Properties."
},
{
"code": null,
"e": 37407,
"s": 37306,
"text": "Step 3 − In the Word Document Settings dialog box, specify settings for the ToC, index and glossary."
},
{
"code": null,
"e": 37585,
"s": 37407,
"text": "Step 4 − To generate a ToC from the Word document, click on the Convert Table of Contents checkbox and choose to either append to an existing ToC or create a new associated ToC."
},
{
"code": null,
"e": 37758,
"s": 37585,
"text": "Step 5 − To generate an index from the Word document, click on the Convert Index checkbox and choose to either append to an existing index or create a new associated index."
},
{
"code": null,
"e": 37942,
"s": 37758,
"text": "Step 6 − To generate a glossary from the Word document, click on the Convert Glossary checkbox and choose to either append to an existing glossary or create a new associated glossary."
},
{
"code": null,
"e": 38180,
"s": 37942,
"text": "Word styles are mapped to RoboHelp styles using Cascading Style Sheets (CSS). The default CSS used by RoboHelp is called RHStyleMapping.css. You can change this to a file of your choice or edit this CSS file in your preferred CSS editor."
},
{
"code": null,
"e": 38258,
"s": 38180,
"text": "To select the CSS for style mapping, we should follow the points given below."
},
{
"code": null,
"e": 38335,
"s": 38258,
"text": "Link or import the Word document whose style needs to be mapped to RoboHelp."
},
{
"code": null,
"e": 38412,
"s": 38335,
"text": "Link or import the Word document whose style needs to be mapped to RoboHelp."
},
{
"code": null,
"e": 38499,
"s": 38412,
"text": "Open the Project Settings dialog box from the Project tab and click on the Import tab."
},
{
"code": null,
"e": 38586,
"s": 38499,
"text": "Open the Project Settings dialog box from the Project tab and click on the Import tab."
},
{
"code": null,
"e": 38731,
"s": 38586,
"text": "Select the CSS from the CSS for Style Mapping dropdown menu. You can also select a custom CSS by selecting the <BrowseCSS> in the dropdown menu."
},
{
"code": null,
"e": 38876,
"s": 38731,
"text": "Select the CSS from the CSS for Style Mapping dropdown menu. You can also select a custom CSS by selecting the <BrowseCSS> in the dropdown menu."
},
{
"code": null,
"e": 38988,
"s": 38876,
"text": "For converting Word paragraphs and character styles to RoboHelp styles, we should consider the following steps."
},
{
"code": null,
"e": 39131,
"s": 38988,
"text": "Step 1 − Import or link the Word document and go to Project Settings. Select the Import tab and click on Edit... in the Word Document section."
},
{
"code": null,
"e": 39460,
"s": 39131,
"text": "Step 2 − In the Conversion Settings dialog box, select the Word style from the Paragraph group. You can choose to map a RoboHelp style to the Word style from the RoboHelp Style dropdown menu. Select [Source] to retain the appearance of Word text in your online Help format. To edit the selected RoboHelp style, click Edit Style."
},
{
"code": null,
"e": 39669,
"s": 39460,
"text": "Step 3 − To mark a style for the glossary, select the Glossary Definition checkbox to consider the style for the glossary definition. Select Glossary Term checkbox to consider the style for the glossary term."
},
{
"code": null,
"e": 39830,
"s": 39669,
"text": "Step 4 − To create a Help topic at each occurrence of the selected Word paragraph style, select the Pagination (Split into topics based on this style) checkbox."
},
{
"code": null,
"e": 39926,
"s": 39830,
"text": "Step 5 − You can also select or enter a User Defined HTML Tag for the selected paragraph style."
},
{
"code": null,
"e": 40152,
"s": 39926,
"text": "Step 6 − You can similarly also map and edit the Word character formats to character styles in RoboHelp. Select the Word character style from the Character group and select the RoboHelp character style from the dropdown menu."
},
{
"code": null,
"e": 40307,
"s": 40152,
"text": "Step 7 − To import the Word character style, select [Source] from the pop-up menu. You can edit the character style in RoboHelp by clicking on Edit Style."
},
{
"code": null,
"e": 40650,
"s": 40307,
"text": "A Darwin Information Typing Architecture (DITA) map is like a table of contents listing and linking the topics for a specific output. They assemble topics into sequence and hierarchy tailored to specific delivery requirements. A DITA map file has the extension .ditamap. You can import both DITA map and XML files to generate an XHTML output."
},
{
"code": null,
"e": 40716,
"s": 40650,
"text": "To import DITA map files, we should follow the steps given below."
},
{
"code": null,
"e": 40920,
"s": 40716,
"text": "Step 1 − Go to the File menu, click on New Project and click on the Import tab. Select the PDF document in the list of file types and click OK to open the DITA Open Toolkit Processing Options dialog box."
},
{
"code": null,
"e": 41022,
"s": 40920,
"text": "Step 2 − Review the following settings that are available in the dialog box and then click on Finish."
},
{
"code": null,
"e": 41195,
"s": 41022,
"text": "Replace default XSLT file for conversion − Select an XSL file to use for transforming the DITA files to XHTML instead of the default XSL file used by the DITA Open Toolkit."
},
{
"code": null,
"e": 41368,
"s": 41195,
"text": "Replace default XSLT file for conversion − Select an XSL file to use for transforming the DITA files to XHTML instead of the default XSL file used by the DITA Open Toolkit."
},
{
"code": null,
"e": 41602,
"s": 41368,
"text": "Use DITA val for conditional processing − The XHTML is generated based on the Val file. A DITA Val file contains filter, flagging, and revision information. Specify a DITA Val file to use for conditional processing of the DITA files."
},
{
"code": null,
"e": 41836,
"s": 41602,
"text": "Use DITA val for conditional processing − The XHTML is generated based on the Val file. A DITA Val file contains filter, flagging, and revision information. Specify a DITA Val file to use for conditional processing of the DITA files."
},
{
"code": null,
"e": 41920,
"s": 41836,
"text": "Show Index entries in Topics − Select to show the index entries in RoboHelp topics."
},
{
"code": null,
"e": 42004,
"s": 41920,
"text": "Show Index entries in Topics − Select to show the index entries in RoboHelp topics."
},
{
"code": null,
"e": 42153,
"s": 42004,
"text": "Show image filename in Annotation − Select to add annotations to images showing the filename of the image or the full path to include in the topics."
},
{
"code": null,
"e": 42302,
"s": 42153,
"text": "Show image filename in Annotation − Select to add annotations to images showing the filename of the image or the full path to include in the topics."
},
{
"code": null,
"e": 42443,
"s": 42302,
"text": "Include Draft and Cleanup content − Select to include draft and required cleanup content (items identified as left to do before publishing)."
},
{
"code": null,
"e": 42584,
"s": 42443,
"text": "Include Draft and Cleanup content − Select to include draft and required cleanup content (items identified as left to do before publishing)."
},
{
"code": null,
"e": 42739,
"s": 42584,
"text": "Select XHTML file to be placed in the header area (hdf) − Select the location of the file containing XHTML to place in the header area of the output file."
},
{
"code": null,
"e": 42894,
"s": 42739,
"text": "Select XHTML file to be placed in the header area (hdf) − Select the location of the file containing XHTML to place in the header area of the output file."
},
{
"code": null,
"e": 43079,
"s": 42894,
"text": "Select XHTML file to be placed in the body running-header area (hdr) − Select the location of the file containing the XHTML to place in the body running-header area of the output file."
},
{
"code": null,
"e": 43264,
"s": 43079,
"text": "Select XHTML file to be placed in the body running-header area (hdr) − Select the location of the file containing the XHTML to place in the body running-header area of the output file."
},
{
"code": null,
"e": 43445,
"s": 43264,
"text": "Select XHTML file to be placed in the body running-footer Area (ftr) − Select the location of the file containing XHTML to place in the body running-footer area of the output file."
},
{
"code": null,
"e": 43626,
"s": 43445,
"text": "Select XHTML file to be placed in the body running-footer Area (ftr) − Select the location of the file containing XHTML to place in the body running-footer area of the output file."
},
{
"code": null,
"e": 43803,
"s": 43626,
"text": "DITA Open Tool Kit Home Directory − Select the absolute location of the home folder of the DITA Open Toolkit. You specify this location only once. It is stored in the registry."
},
{
"code": null,
"e": 43980,
"s": 43803,
"text": "DITA Open Tool Kit Home Directory − Select the absolute location of the home folder of the DITA Open Toolkit. You specify this location only once. It is stored in the registry."
},
{
"code": null,
"e": 44068,
"s": 43980,
"text": "To import XML files into a project in RoboHelp, we should follow the steps given below."
},
{
"code": null,
"e": 44239,
"s": 44068,
"text": "Step 1 − RoboHelp creates a topic for the XML file when imported in to the existing project. To import an XML file, in the Project Manager pod, select the file to import."
},
{
"code": null,
"e": 44392,
"s": 44239,
"text": "Step 2 − Go to the Import section of the Project tab and in the dropdown menu, select, the XML File. Select one or more XML files and the click on Open."
},
{
"code": null,
"e": 44530,
"s": 44392,
"text": "Step 3 − In the Select XML Import Handler dialog box, click on Options. You can also select Import XML (CSS/XSL) to set advanced options."
},
{
"code": null,
"e": 44568,
"s": 44530,
"text": "The following options are available −"
},
{
"code": null,
"e": 44642,
"s": 44568,
"text": "Treat as text flow − Import the XML file as HTML text without formatting."
},
{
"code": null,
"e": 44716,
"s": 44642,
"text": "Treat as text flow − Import the XML file as HTML text without formatting."
},
{
"code": null,
"e": 44802,
"s": 44716,
"text": "Treat as XML tree view − Import the XML file in HTML tree view. HTML imports as code."
},
{
"code": null,
"e": 44888,
"s": 44802,
"text": "Treat as XML tree view − Import the XML file in HTML tree view. HTML imports as code."
},
{
"code": null,
"e": 44954,
"s": 44888,
"text": "Use customized CSS/XSL file − Select a file from the pop-up menu."
},
{
"code": null,
"e": 45020,
"s": 44954,
"text": "Use customized CSS/XSL file − Select a file from the pop-up menu."
},
{
"code": null,
"e": 45079,
"s": 45020,
"text": "Step 4 − Click OK to import the XML file into the project."
},
{
"code": null,
"e": 45351,
"s": 45079,
"text": "RoboHelp can import compiled WinHelp 4.0 (HLP) or WinHelp Project File (HPJ) into your project. Although you cannot output a WinHelp file from RoboHelp HTML, you can import the HPJ file, which is the main organizational file containing the set of the entire source files."
},
{
"code": null,
"e": 45554,
"s": 45351,
"text": "From the Starter pod, select either the WinHelp (*.hlp) or WinHelp Project (*.hlp) and proceed to browse the location of the file on disk. Click Finish to convert and import the file as a RoboHelp file."
},
{
"code": null,
"e": 45674,
"s": 45554,
"text": "There are some limitations when converting HLP files to HTML. All these limitations are explained in brief as follows −"
},
{
"code": null,
"e": 45791,
"s": 45674,
"text": "Bullets − WinHelp topics should not use bitmap references as bullets. You can however choose to keep bulleted lists."
},
{
"code": null,
"e": 45908,
"s": 45791,
"text": "Bullets − WinHelp topics should not use bitmap references as bullets. You can however choose to keep bulleted lists."
},
{
"code": null,
"e": 46060,
"s": 45908,
"text": "HTML Jumps − Jumps to HTML pages that are not converted, but you can easily re-create the links in the Design Editor after the HTML topics are created."
},
{
"code": null,
"e": 46212,
"s": 46060,
"text": "HTML Jumps − Jumps to HTML pages that are not converted, but you can easily re-create the links in the Design Editor after the HTML topics are created."
},
{
"code": null,
"e": 46322,
"s": 46212,
"text": "Jumps to external WinHelp topics − Jumps to external WinHelp topics that are stripped out of the HTML topics."
},
{
"code": null,
"e": 46432,
"s": 46322,
"text": "Jumps to external WinHelp topics − Jumps to external WinHelp topics that are stripped out of the HTML topics."
},
{
"code": null,
"e": 46560,
"s": 46432,
"text": "Macros, buttons, and shortcuts − Macros that convert include Jump Context, JumpId, and PopupId. Other macros are not converted."
},
{
"code": null,
"e": 46688,
"s": 46560,
"text": "Macros, buttons, and shortcuts − Macros that convert include Jump Context, JumpId, and PopupId. Other macros are not converted."
},
{
"code": null,
"e": 46784,
"s": 46688,
"text": "Microsoft Word HTML styles − Microsoft Word HTML styles are not used to format the HTML topics."
},
{
"code": null,
"e": 46880,
"s": 46784,
"text": "Microsoft Word HTML styles − Microsoft Word HTML styles are not used to format the HTML topics."
},
{
"code": null,
"e": 47007,
"s": 46880,
"text": "Microsoft Word templates − Word templates that are used to format RTF files in WinHelp are not converted to HTML style sheets."
},
{
"code": null,
"e": 47134,
"s": 47007,
"text": "Microsoft Word templates − Word templates that are used to format RTF files in WinHelp are not converted to HTML style sheets."
},
{
"code": null,
"e": 47196,
"s": 47134,
"text": "Mid-Topic jumps − Mid-topic jumps are converted to bookmarks."
},
{
"code": null,
"e": 47258,
"s": 47196,
"text": "Mid-Topic jumps − Mid-topic jumps are converted to bookmarks."
},
{
"code": null,
"e": 47413,
"s": 47258,
"text": "Multimedia files (AVI and WAV) − These files cannot be converted with HLP files. However, you can add sound and video to HTML topics in the Design Editor."
},
{
"code": null,
"e": 47568,
"s": 47413,
"text": "Multimedia files (AVI and WAV) − These files cannot be converted with HLP files. However, you can add sound and video to HTML topics in the Design Editor."
},
{
"code": null,
"e": 47650,
"s": 47568,
"text": "Non-scrolling regions − HTML-based output does not support non-scrolling regions."
},
{
"code": null,
"e": 47732,
"s": 47650,
"text": "Non-scrolling regions − HTML-based output does not support non-scrolling regions."
},
{
"code": null,
"e": 47897,
"s": 47732,
"text": "Numbered lists − Numbered lists use a 12-point serif font by default. To change the style, you need to create a new numbered list style and reformat it in RoboHelp."
},
{
"code": null,
"e": 48062,
"s": 47897,
"text": "Numbered lists − Numbered lists use a 12-point serif font by default. To change the style, you need to create a new numbered list style and reformat it in RoboHelp."
},
{
"code": null,
"e": 48153,
"s": 48062,
"text": "Related Topics buttons − Related Topics keywords are translated into Related Topics terms."
},
{
"code": null,
"e": 48244,
"s": 48153,
"text": "Related Topics buttons − Related Topics keywords are translated into Related Topics terms."
},
{
"code": null,
"e": 48413,
"s": 48244,
"text": "Secondary windows − WinHelp secondary windows are not translated. Unlike WinHelp topics, HTML topics do not support links that display information in secondary windows."
},
{
"code": null,
"e": 48582,
"s": 48413,
"text": "Secondary windows − WinHelp secondary windows are not translated. Unlike WinHelp topics, HTML topics do not support links that display information in secondary windows."
},
{
"code": null,
"e": 48747,
"s": 48582,
"text": "Table of contents − The HTML TOC file (HHC) does not support WinHelp pages that link to external WinHelp topics or reference macros or that contain link statements."
},
{
"code": null,
"e": 48912,
"s": 48747,
"text": "Table of contents − The HTML TOC file (HHC) does not support WinHelp pages that link to external WinHelp topics or reference macros or that contain link statements."
},
{
"code": null,
"e": 49066,
"s": 48912,
"text": "What's This? Help − Context-sensitive Help is not converted. What's This? Help-style topics or dialog topics are converted into regular HTML Help topics."
},
{
"code": null,
"e": 49220,
"s": 49066,
"text": "What's This? Help − Context-sensitive Help is not converted. What's This? Help-style topics or dialog topics are converted into regular HTML Help topics."
},
{
"code": null,
"e": 49424,
"s": 49220,
"text": "Microsoft Word formatting − The following formatting is converted in the HTML topics – underlining, paragraph spacing, indents, alignments, table borders, spreadsheets, background colors, and watermarks."
},
{
"code": null,
"e": 49628,
"s": 49424,
"text": "Microsoft Word formatting − The following formatting is converted in the HTML topics – underlining, paragraph spacing, indents, alignments, table borders, spreadsheets, background colors, and watermarks."
},
{
"code": null,
"e": 49722,
"s": 49628,
"text": "In the next chapter, we will understand what version control is and how it benefits RoboHelp."
},
{
"code": null,
"e": 50039,
"s": 49722,
"text": "Version control is an important enterprise feature, which saves every version of the document on a server. Multiple people can therefore, simultaneously make changes to a document without fear of disturbing the original document. Since all versions of a document are saved, users can revert to any version as needed."
},
{
"code": null,
"e": 50313,
"s": 50039,
"text": "RoboHelp supports native Microsoft SharePoint 2010 and above integration. Support for Microsoft SharePoint is installed during program setup itself. The setup also installs the .NET Framework 4.0 and SQL Server Compact 3.5 SP2, which is required for SharePoint integration."
},
{
"code": null,
"e": 50532,
"s": 50313,
"text": "To configure SharePoint settings, go to the File menu, click on Options and select Version Control. To enable file comparisons between your computer and the server, you need to have a file comparison program installed."
},
{
"code": null,
"e": 50739,
"s": 50532,
"text": "You can download a free program called Winmerge from http://winmerge.org/ and enter the program path in the Path parameter in the SharePoint Settings area. You can also enter any program specific arguments."
},
{
"code": null,
"e": 50786,
"s": 50739,
"text": "You can also configure the following options −"
},
{
"code": null,
"e": 50911,
"s": 50786,
"text": "Notify before overwriting writable files − Notifies the user before overwriting any writable files that are not checked out."
},
{
"code": null,
"e": 51036,
"s": 50911,
"text": "Notify before overwriting writable files − Notifies the user before overwriting any writable files that are not checked out."
},
{
"code": null,
"e": 51195,
"s": 51036,
"text": "Replace local file even if server version is same − Fetch the latest files from the server, even if the local file version and the server version is the same."
},
{
"code": null,
"e": 51354,
"s": 51195,
"text": "Replace local file even if server version is same − Fetch the latest files from the server, even if the local file version and the server version is the same."
},
{
"code": null,
"e": 51498,
"s": 51354,
"text": "Default Check-in Option − Select to check in the files as a major version or as a minor version. The default is to check in as a major version."
},
{
"code": null,
"e": 51642,
"s": 51498,
"text": "Default Check-in Option − Select to check in the files as a major version or as a minor version. The default is to check in as a major version."
},
{
"code": null,
"e": 51715,
"s": 51642,
"text": "In the next chapter, we will learn how to work with reports in RoboHelp."
},
{
"code": null,
"e": 51838,
"s": 51715,
"text": "RoboHelp makes it easy to get reports about a project. You can export, print and send reports from the Reports Dialog Box."
},
{
"code": null,
"e": 51984,
"s": 51838,
"text": "Click on the Tools tab and select a report type. Customize the report as needed. Click on ‘Save As...’ and save the report as an RTF or TXT file."
},
{
"code": null,
"e": 52192,
"s": 51984,
"text": "In the Reports dialog box, customize the report as needed. Click on Print... to print the report. You can print the ToC or index from the ToC pod or Index pod by going to the File menu and clicking on Print."
},
{
"code": null,
"e": 52446,
"s": 52192,
"text": "In the Reports dialog box, customize the report and click on ‘Mail To...’ You need to have an email program configured in your system before you can use this function. The report will appear in the body of the message, which you can edit before sending."
},
{
"code": null,
"e": 52643,
"s": 52446,
"text": "With RoboHelp, you can generate and customize a wide variety of reports. We will look at an example of a non-customizable and a customizable report. All reports can be accessed from the Tools tab."
},
{
"code": null,
"e": 52822,
"s": 52643,
"text": "This report can be accessed by clicking on the Map ID icon in the Tools tab and selecting Broken Links. It finds files that contain broken links. This report is not customizable."
},
{
"code": null,
"e": 52958,
"s": 52822,
"text": "Click on the ToC icon in the Tools tab and select Index from the dropdown menu. The following options can be customized in this report."
},
{
"code": null,
"e": 53007,
"s": 52958,
"text": "Keywords − Includes all keywords from the index."
},
{
"code": null,
"e": 53056,
"s": 53007,
"text": "Keywords − Includes all keywords from the index."
},
{
"code": null,
"e": 53150,
"s": 53056,
"text": "Keywords and Topics − Contains a list of keywords. Each keyword lists the topics that use it."
},
{
"code": null,
"e": 53244,
"s": 53150,
"text": "Keywords and Topics − Contains a list of keywords. Each keyword lists the topics that use it."
},
{
"code": null,
"e": 53350,
"s": 53244,
"text": "Topics and Keywords − Contains a list of topics. Each topic lists the keywords associated with the topic."
},
{
"code": null,
"e": 53456,
"s": 53350,
"text": "Topics and Keywords − Contains a list of topics. Each topic lists the keywords associated with the topic."
},
{
"code": null,
"e": 53546,
"s": 53456,
"text": "Select Index − Select an Index from the list to generate a report for the index selected."
},
{
"code": null,
"e": 53636,
"s": 53546,
"text": "Select Index − Select an Index from the list to generate a report for the index selected."
},
{
"code": null,
"e": 53706,
"s": 53636,
"text": "The Project Manager pod makes it easy to create, save or open topics."
},
{
"code": null,
"e": 53780,
"s": 53706,
"text": "For creating a topic in RoboHelp, we should follow the steps given below."
},
{
"code": null,
"e": 53945,
"s": 53780,
"text": "Step 1 − To start with, create a project, right-click on the XHTML Files (Topics) folder, go to the ‘New’ menu and select Topic... to open the New Topic dialog box."
},
{
"code": null,
"e": 54128,
"s": 53945,
"text": "Step 2 − In the New Topic dialog box, specify a topic title and select a variable from the Variables list, then click on Insert. Variables help manage changes and ensure consistency."
},
{
"code": null,
"e": 54379,
"s": 54128,
"text": "Step 3 − As per the HTML file naming protocol, use underscores rather than spaces. Select a Master Page if required and specify a language for the new topic. If you do not specify a language, RoboHelp uses the default language setting of the project."
},
{
"code": null,
"e": 54609,
"s": 54379,
"text": "Step 4 − You can add keywords to tag the contents of the topic. Keywords can be separated by comma, space or semicolon. If you prefer not to include this topic in search results, check the Exclude this topic from Search checkbox."
},
{
"code": null,
"e": 54709,
"s": 54609,
"text": "To save a topic, simply press Ctrl+S on the keyboard or click the Save All icon in the Project tab."
},
{
"code": null,
"e": 54963,
"s": 54709,
"text": "To open a topic, double-click on the topic name in the Project Manager Pod or Topic List pod to open the topic in the Design Editor. To open the topic in an editor of your choice, right-click on the topic, go to the Edit With menu and select the editor."
},
{
"code": null,
"e": 55242,
"s": 54963,
"text": "RoboHelp can create topic files in XHTML. XHTML allows for structured authoring that ensures well-written code. All old RoboHelp for HTML topics are upgraded to XHTML. The XHTML topics conform to the XHTML 1.0 Transitional specification from the World Wide Web Consortium (W3C)."
},
{
"code": null,
"e": 55416,
"s": 55242,
"text": "The topics have the XHTML Transitional 1.0 doc type − <DOCTYPE html PUBLIC “-//W3C3DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>"
},
{
"code": null,
"e": 55623,
"s": 55416,
"text": "The XHTML files generated by RoboHelp can be edited by third-party editors such as Notepad or Adobe Dreamweaver. To view the XHTML source, open the topic and click on the HTML View beside the Design Editor."
},
{
"code": null,
"e": 55853,
"s": 55623,
"text": "You can convert the XHTML topics into HTML in the SSL output. To do this, go to the File menu, then go to Options and click on General. In the Generation section, check the box Convert RoboHelp edited topics to HTML and click OK."
},
{
"code": null,
"e": 56147,
"s": 55853,
"text": "The RoboHelp generated XHTML code can be validated for compliance with the XHTML Transition 1.0 W3C specifications. To validate a topic, right-click the topic, and select Validate W3C Compliance to validate the topic. This will generate an Output View in the Document Pane showing the results."
},
{
"code": null,
"e": 56390,
"s": 56147,
"text": "Some features such as marquees in Topics, Border Color in Framesets and Background Sound in topic properties are not supported in XHTML. These will result in a non-compliant code. You will need to remove these features to pass the validation."
},
{
"code": null,
"e": 56686,
"s": 56390,
"text": "Master pages are a form of templates, which help in separating layout and styling from the content. The layout information of a master page is associated with a CSS file. The master page template defines the placement of Headers, Footers and Placeholders for the Body, Breadcrumbs and Topic ToC."
},
{
"code": null,
"e": 56790,
"s": 56686,
"text": "To create a master page, go to the Output tab and from the Master Page menu and select New Master Page."
},
{
"code": null,
"e": 57017,
"s": 56790,
"text": "In the New Master Page dialog box, enter a name for the master page. Go to the Appearance tab and select a style sheet to apply to the new master page and click OK. This can also be changed later in the master page properties."
},
{
"code": null,
"e": 57182,
"s": 57017,
"text": "To edit a master page, simply double-click on the master page in the Output Setup Pod or right-click on the master page and click on Edit. Make the desired changes."
},
{
"code": null,
"e": 57319,
"s": 57182,
"text": "You can insert placeholders for Topic ToCs, Breadcrumbs and Topics in Master Pages. A new master page has a body placeholder by default."
},
{
"code": null,
"e": 57540,
"s": 57319,
"text": "To insert a new placeholder, place the cursor below or after the body placeholder. Go to the Insert tab and in the Page Design section, click the Topic ToC button to select the desired placeholder from the dropdown menu."
},
{
"code": null,
"e": 57706,
"s": 57540,
"text": "From the topic list in the Project Manager, select one or more topics to which you want to assign the master page. Right-click on the topic(s) and select Properties."
},
{
"code": null,
"e": 57961,
"s": 57706,
"text": "In the General tab, select the list of master pages available in the Master Page dropdown menu and then click on OK. You can also choose to have a preview by clicking the Spectacles Icon beside the Master Page menu or browse to a master page on the disk."
},
{
"code": null,
"e": 58091,
"s": 57961,
"text": "RoboHelp makes it easy to manage topics. You can rename topics, update the topic references and even track the status of a topic."
},
{
"code": null,
"e": 58179,
"s": 58091,
"text": "To rename a topic, Right-click on a topic in the Project Manager and select Properties."
},
{
"code": null,
"e": 58352,
"s": 58179,
"text": "In the General tab, type the new title in the Topic Title box and click OK to update the title. You can also click the Rename button in the File section of the Project tab."
},
{
"code": null,
"e": 58479,
"s": 58352,
"text": "It is important to update the topic references when renaming the topic title. Topic references include the following aspects −"
},
{
"code": null,
"e": 58668,
"s": 58479,
"text": "Text links − The path of the link is updated, but the link text that is visible to a user is not. If the link text in any topic includes the topic title, then we have to update each topic."
},
{
"code": null,
"e": 58857,
"s": 58668,
"text": "Text links − The path of the link is updated, but the link text that is visible to a user is not. If the link text in any topic includes the topic title, then we have to update each topic."
},
{
"code": null,
"e": 58959,
"s": 58857,
"text": "Topic heading − To change the topic heading to match the topic title, change it in the Design Editor."
},
{
"code": null,
"e": 59061,
"s": 58959,
"text": "Topic heading − To change the topic heading to match the topic title, change it in the Design Editor."
},
{
"code": null,
"e": 59183,
"s": 59061,
"text": "Table of Contents − In the Table of Contents pod, right-click on the book or page and select Rename. Enter the new title."
},
{
"code": null,
"e": 59305,
"s": 59183,
"text": "Table of Contents − In the Table of Contents pod, right-click on the book or page and select Rename. Enter the new title."
},
{
"code": null,
"e": 59474,
"s": 59305,
"text": "Index − If the topic title is an index keyword, update the keyword in the Index pod. Right-click on the keyword in the upper pane and select Rename. Type the new title."
},
{
"code": null,
"e": 59643,
"s": 59474,
"text": "Index − If the topic title is an index keyword, update the keyword in the Index pod. Right-click on the keyword in the upper pane and select Rename. Type the new title."
},
{
"code": null,
"e": 59981,
"s": 59643,
"text": "The default status of new topics is, In Progress. The status information is shown in the Project Report. To change the topic status or to set priorities, open the Properties of the topic from the File section of the Project tab and click on the Status tab. You can change the development stage of the topic from the Status dropdown menu."
},
{
"code": null,
"e": 60245,
"s": 59981,
"text": "Enter a number to assign a priority in the Priority field. You can also set the estimated or actual hours of development in the Hours field. You can check off items in the To Do List as you complete them. Any other description can be entered in the Comment field."
},
{
"code": null,
"e": 60383,
"s": 60245,
"text": "RoboHelp can do spell check across the Content, ToC, Index and Glossary of the project. You can spell check a topic or an entire project."
},
{
"code": null,
"e": 60545,
"s": 60383,
"text": "To spell check a topic, open the topic in the Design Editor and in the Review tab, click on either Spell Check or Spell Check All Topics in the Proofing section."
},
{
"code": null,
"e": 60661,
"s": 60545,
"text": "RoboHelp scans the document and recommends corrections for words. You can also add words to the current dictionary."
},
{
"code": null,
"e": 60932,
"s": 60661,
"text": "You can also spell check the entire project including the glossary, index and ToC. To do this, in the Review tab, click on Spell Check Project. This will open up a similar Spelling dialog box as before. You can skip to different parts of the project by clicking on Skip."
},
{
"code": null,
"e": 61203,
"s": 60932,
"text": "You can add extra words to the dictionary using the Dictionary Editor. Words in the Dictionary Editor are case-sensitive. In the Review tab, click Spelling Options. In the Options tab, in the Spelling Options dialog box, click on Modify... to open the Dictionary Editor."
},
{
"code": null,
"e": 61299,
"s": 61203,
"text": "Enter a word that you want to add to the dictionary. Then click on the Add button and click OK."
},
{
"code": null,
"e": 61595,
"s": 61299,
"text": "With the Find and Replace feature, you can search and replace text, HTML, attributes, etc., in the current topic or project or even across files and folders in a specified path. To open the Find and Replace pod, press Ctrl+Shift+F on the keyboard or click on Find and Replace in the Project tab."
},
{
"code": null,
"e": 61811,
"s": 61595,
"text": "Type the text, tag, or attribute that you want to search in the Find box. You can enable Show Advanced Filters to select the filters and specify the text, tag or attribute for RoboHelp to build a regular expression."
},
{
"code": null,
"e": 61859,
"s": 61811,
"text": "The following advanced filters can be applied −"
},
{
"code": null,
"e": 61966,
"s": 61859,
"text": "Begins With − Specify phrases, words, or characters that should occur in the beginning of found instances."
},
{
"code": null,
"e": 62073,
"s": 61966,
"text": "Begins With − Specify phrases, words, or characters that should occur in the beginning of found instances."
},
{
"code": null,
"e": 62172,
"s": 62073,
"text": "Ends With − Specify phrases, words, or characters that should occur in the end of found instances."
},
{
"code": null,
"e": 62271,
"s": 62172,
"text": "Ends With − Specify phrases, words, or characters that should occur in the end of found instances."
},
{
"code": null,
"e": 62357,
"s": 62271,
"text": "Contains − Specify phrases, words, or characters that found instances should contain."
},
{
"code": null,
"e": 62443,
"s": 62357,
"text": "Contains − Specify phrases, words, or characters that found instances should contain."
},
{
"code": null,
"e": 62541,
"s": 62443,
"text": "Does Not Contain − Specify phrases, words, or characters that found instances should not contain."
},
{
"code": null,
"e": 62639,
"s": 62541,
"text": "Does Not Contain − Specify phrases, words, or characters that found instances should not contain."
},
{
"code": null,
"e": 62797,
"s": 62639,
"text": "Type the text, tag, or attribute that you want to replace in the Replace With box. If you want to search without replacing, leave the Replace With box empty."
},
{
"code": null,
"e": 62895,
"s": 62797,
"text": "You can choose where to look for the text by using the Look In option to search in the following "
},
{
"code": null,
"e": 62948,
"s": 62895,
"text": "Current Project − Search within the current project."
},
{
"code": null,
"e": 63001,
"s": 62948,
"text": "Current Project − Search within the current project."
},
{
"code": null,
"e": 63047,
"s": 63001,
"text": "Current Window − Search in the current topic."
},
{
"code": null,
"e": 63093,
"s": 63047,
"text": "Current Window − Search in the current topic."
},
{
"code": null,
"e": 63155,
"s": 63093,
"text": "Opened Files − Search all files currently opened in RoboHelp."
},
{
"code": null,
"e": 63217,
"s": 63155,
"text": "Opened Files − Search all files currently opened in RoboHelp."
},
{
"code": null,
"e": 63270,
"s": 63217,
"text": "Path − Search all files in the selected folder path."
},
{
"code": null,
"e": 63323,
"s": 63270,
"text": "Path − Search all files in the selected folder path."
},
{
"code": null,
"e": 63400,
"s": 63323,
"text": "In the next chapter, we will learn how to ensure W3C compliance in RoboHelp."
},
{
"code": null,
"e": 63665,
"s": 63400,
"text": "You can validate both topics and projects for W3C compliance. RoboHelp validates all content and shows warnings or error messages for any non-compliance. To validate a topic, right-click on the topic in the Project Manager pod and click on Validate W3C Compliance."
},
{
"code": null,
"e": 63894,
"s": 63665,
"text": "To validate a project, right-click on the Project Files folder in the Project Manager pod and select Validate W3C Compliance. Depending on the situation, the following messages are seen in the Output View Pod and Error List pod."
},
{
"code": null,
"e": 63930,
"s": 63894,
"text": "Errors − incorrect or unclosed tags"
},
{
"code": null,
"e": 63966,
"s": 63930,
"text": "Errors − incorrect or unclosed tags"
},
{
"code": null,
"e": 63995,
"s": 63966,
"text": "Warnings − invalid XHTML tag"
},
{
"code": null,
"e": 64024,
"s": 63995,
"text": "Warnings − invalid XHTML tag"
},
{
"code": null,
"e": 64063,
"s": 64024,
"text": "Information − all topics are validated"
},
{
"code": null,
"e": 64102,
"s": 64063,
"text": "Information − all topics are validated"
},
{
"code": null,
"e": 64262,
"s": 64102,
"text": "The Error List pod shows the line and column in the HTML, where the error has occurred. You can directly navigate to this line by double-clicking on the error."
},
{
"code": null,
"e": 64420,
"s": 64262,
"text": "RoboHelp includes a Design Editor and a HTML Editor by default. You can also use third party editors such as Microsoft Word or Adobe Dreamweaver for editing."
},
{
"code": null,
"e": 64650,
"s": 64420,
"text": "Select a topic file from the Project Manager pod, to open it in the Design Editor. You can use the RoboHelp Design Editor to perform word-processing tasks and to insert online elements, such as links, multimedia and Dynamic HTML."
},
{
"code": null,
"e": 64841,
"s": 64650,
"text": "You can also add index keywords to topics, apply conditional text, create browse sequences, map IDs, and edit master pages. You can edit any standard XHTML or HTML file in the Design Editor."
},
{
"code": null,
"e": 65009,
"s": 64841,
"text": "You can directly author XHTML code in the RoboHelp HTML Editor. To switch to the HTML Editor, click on the HTML tab in the Document Pane. You enter HTML tags and text."
},
{
"code": null,
"e": 65356,
"s": 65009,
"text": "You can use keyword expansions to auto-suggest keywords or tags as you type. When you start typing a keyword, you can select it from the keyword expansion list to insert the keyword or tag. In addition to the existing keywords and tags, you can also specify your own keywords by right clicking in the HTML Editor and selecting Edit Expansions...."
},
{
"code": null,
"e": 65655,
"s": 65356,
"text": "You can use third-party HTML editors, while RoboHelp is open, but RoboHelp specific features such as text-only pop-ups or link controls are not available. Insert the images and the JavaScript based special effects into the Baggage Files folder. If you are inserting them using a third-party editor."
},
{
"code": null,
"e": 65883,
"s": 65655,
"text": "To add a HTML editor, click on Options in the File tab and click on File Associations. In the HTML Editors section, click on Add and choose from the list of recommended programs or browse to the location of the program on disk."
},
{
"code": null,
"e": 66042,
"s": 65883,
"text": "The Edit tab provides options for working with characters and fonts. You can create inline styles using the Edit tab, which overrides an existing style sheet."
},
{
"code": null,
"e": 66203,
"s": 66042,
"text": "To add or remove font formatting, select the required text and in the Edit tab, go to the Character section, click on Character Formatting and then choose Font."
},
{
"code": null,
"e": 66494,
"s": 66203,
"text": "A font set is a collection of fonts that you can apply in a style sheet. For example, you can create a font set with Calibri as the first font and then Cambria and Segoe UI (in order) as substitute fonts. If the viewer does not have Calibri installed, it will use Cambria and then Segoe UI."
},
{
"code": null,
"e": 66738,
"s": 66494,
"text": "To create a font set, click on Font Sets in the Character Formatting menu in the Edit tab. You can modify an existing font set by selecting the font and clicking Modify... or create a new set by clicking New and typing a name for the font set."
},
{
"code": null,
"e": 66968,
"s": 66738,
"text": "In the Modify Font Set dialog box, select the first font and click on Add. Select the remaining fonts in the order of preference and then add them and click on the OK button. Font sets are saved and then associated with projects."
},
{
"code": null,
"e": 67117,
"s": 66968,
"text": "The Edit tab provides options for working with paragraphs. You can create inline styles using the Edit tab, which overrides an existing style sheet."
},
{
"code": null,
"e": 67330,
"s": 67117,
"text": "Select the paragraph to align and click on one of the four alignment buttons in the Paragraph section of the Edit tab. To set an indent, click on the Increase Indent or Decrease Indent button in the same section."
},
{
"code": null,
"e": 67423,
"s": 67330,
"text": "To adjust line spacing, click on Paragraph in the Paragraph Formatting menu in the Edit tab."
},
{
"code": null,
"e": 67586,
"s": 67423,
"text": "Set the Spacing options of the Paragraph dialog box; specify the amount of space above and after each paragraph and the spacing between the lines and click on OK."
},
{
"code": null,
"e": 67736,
"s": 67586,
"text": "RoboHelp allows you to edit border and backgrounds in your content easily. The applied formatting creates inline styles, which override style sheets."
},
{
"code": null,
"e": 67936,
"s": 67736,
"text": "Select a paragraph in the topic and in the Paragraph Formatting menu in the Edit tab, click on Borders and Shading. Click on the Borders tab or shading tab, specify the desired options, and click OK."
},
{
"code": null,
"e": 68100,
"s": 67936,
"text": "Double-click on the image in the Design Editor. In the Image dialog box, click Borders to open the Borders dialog box and set the options as required. Click on OK."
},
{
"code": null,
"e": 68371,
"s": 68100,
"text": "Right-click on a topic in the Project Manager and click on Properties. In the Appearance tab, enter the sound file in the Background Sound box. The supported sound formats include – .au, .mid, .rmi and .wav. Enter the number of times to play in the Sound Loop Count box."
},
{
"code": null,
"e": 68645,
"s": 68371,
"text": "RoboHelp allows for organization of data into tables. Tables in RoboHelp are fully customizable with the option of applying styles, which can be used across multiple topics. Table styles from Word or FrameMaker documents can be imported and mapped to RoboHelp table styles."
},
{
"code": null,
"e": 68770,
"s": 68645,
"text": "Go to the Insert tab and click on the Table icon to select the number of rows and columns to add. Click to insert the table."
},
{
"code": null,
"e": 68952,
"s": 68770,
"text": "You can also insert custom tables by clicking on Insert Table... This will open a dialog box where you can specify the number of rows and columns and choose predefined table styles."
},
{
"code": null,
"e": 69184,
"s": 68952,
"text": "To edit a table, click on the table to enable the Table tab in the ribbon. From this tab, you can add or remove rows and columns and merge or split cells. You can also change the table properties such as alignment and column width."
},
{
"code": null,
"e": 69308,
"s": 69184,
"text": "RoboHelp offers several options for working with lists. You can indent lists and apply bullet styles and numbering formats."
},
{
"code": null,
"e": 69447,
"s": 69308,
"text": "Select the list in the topic that you want to indent and from the Edit toolbar choose either Decrease Indent or Increase Indent as needed."
},
{
"code": null,
"e": 69823,
"s": 69447,
"text": "You can match the color of the bullets with that of the list simply by changing the font color. Select the list you want to change the color and in the Edit tab, click on the Character Formatting menu and select Font or simply press Ctrl+D. In the dialog box that appears, select the desired font color. The bullet color and the list color will become one as an inline style."
},
{
"code": null,
"e": 70013,
"s": 69823,
"text": "Select the list you wish to number, right-click the list and click on Bullets and Numbering... Select the desired numbering style. In the Numbered tab, select the desired numbering pattern."
},
{
"code": null,
"e": 70208,
"s": 70013,
"text": "To add a paragraph within a list, insert the cursor at the end of the paragraph and press Shift+Enter to create a line break. To end the line break and restart bullets or numbering, press Enter."
},
{
"code": null,
"e": 70449,
"s": 70208,
"text": "You can store static global information that can be used repeatedly in your project in the form of User-Defined Variables (UDVs). When you modify a variable or value, every occurrence of that variable or value is updated across the project."
},
{
"code": null,
"e": 70531,
"s": 70449,
"text": "The User Defined Variables pod lists all the user-defined variables in a project."
},
{
"code": null,
"e": 70712,
"s": 70531,
"text": "To create a UDV, right-click a word in the topic, go to the Add to menu and select User Defined Variable. In the dialog box that appears, specify the Variable Name and click on OK."
},
{
"code": null,
"e": 70957,
"s": 70712,
"text": "Variable sets enable you to modify values of various user-defined variables and use them in different outputs. The Default Variable Set is the master variable set. When you insert a variable, the variable is taken from the Default Variable Set."
},
{
"code": null,
"e": 71150,
"s": 70957,
"text": "To use a variable set other than the Default Variable Set, Click on the Add/Edit Variable Set icon in the UDV pod and click Add to specify a name for the new variable set and then click on OK."
},
{
"code": null,
"e": 71429,
"s": 71150,
"text": "To edit a user-defined variable, right-click on the variable name and click on Edit.... In the user-defined Variable Properties dialog box, you can edit the different properties of the variable such as variable name, the set it belongs to, the value and an optional description."
},
{
"code": null,
"e": 71516,
"s": 71429,
"text": "Media rules help in defining the appearance of the document on different screen sizes."
},
{
"code": null,
"e": 71744,
"s": 71516,
"text": "To define a media-specific style, right-click on the style sheet in the Project Manager Pod, and click on Edit. In the Styles Dialog Box, select a style to modify for a specific media. Select the media type from the Media list."
},
{
"code": null,
"e": 71836,
"s": 71744,
"text": "The (none) style is used to define generic styles and the Print style is used for printers."
},
{
"code": null,
"e": 71928,
"s": 71836,
"text": "The (none) style is used to define generic styles and the Print style is used for printers."
},
{
"code": null,
"e": 71971,
"s": 71928,
"text": "Modify the style as required and click OK."
},
{
"code": null,
"e": 72014,
"s": 71971,
"text": "Modify the style as required and click OK."
},
{
"code": null,
"e": 72325,
"s": 72014,
"text": "If you want to define different media rules for a style in the style sheet that is currently linked to a topic, go to the Project tab and in the Pods dropdown menu, click the Style and Formatting pod. In the Styles and Formatting pod, select a style to modify for a specific media, right-click and choose Edit."
},
{
"code": null,
"e": 72386,
"s": 72325,
"text": "Select the media or screen profile name from the Media list."
},
{
"code": null,
"e": 72447,
"s": 72386,
"text": "Select the media or screen profile name from the Media list."
},
{
"code": null,
"e": 72490,
"s": 72447,
"text": "Modify the style as required and click OK."
},
{
"code": null,
"e": 72533,
"s": 72490,
"text": "Modify the style as required and click OK."
},
{
"code": null,
"e": 72794,
"s": 72533,
"text": "A style sheet can be associated with any number of HTML topics or a new topic. If you create a style sheet in a project and apply it to a new topic, all topics you create later use the new style sheet. You can link a topic to another style sheet, if necessary."
},
{
"code": null,
"e": 72929,
"s": 72794,
"text": "To link a style sheet, select one or more topics from the topic list, right-click, select Properties, and click on the Appearance tab."
},
{
"code": null,
"e": 73106,
"s": 72929,
"text": "Select a style sheet in the list or navigate to a new style sheet on your computer. You can click New to create a style sheet or edit the style sheet in the Styles Dialog Box."
},
{
"code": null,
"e": 73321,
"s": 73106,
"text": "The default.css is the default style sheet until you create a style sheet or link another style sheet to a new topic. To create a style sheet, go to the Edit tab and in the CSS section, click on the New Stylesheet."
},
{
"code": null,
"e": 73633,
"s": 73321,
"text": "In the Name field, type a filename including the .css extension and select a folder location. If you would like to base your new style sheet on an existing one, select an existing style in the Copy Styles From dropdown menu. Click Create to open the Styles dialog box to create a new style and then click on OK."
},
{
"code": null,
"e": 73700,
"s": 73633,
"text": "In this chapter, we will understand how to style the style sheets."
},
{
"code": null,
"e": 73929,
"s": 73700,
"text": "To create a style, right-click on the style sheet where you want the style in the Project Manager Pod and click on Edit. Click New and select a style type. By default, the new style is created with a default name such as Style1."
},
{
"code": null,
"e": 74195,
"s": 73929,
"text": "In the Styles dialog box, change the default name of the style without using any special characters or spaces in the name. In the Formatting section of the Styles dialog box, change the required options. You can preview the changes in the Paragraph Preview section."
},
{
"code": null,
"e": 74272,
"s": 74195,
"text": "For additional options, click Format and select from the following options −"
},
{
"code": null,
"e": 74348,
"s": 74272,
"text": "Font − Select font families, size, and attributes, such as bold or italics."
},
{
"code": null,
"e": 74424,
"s": 74348,
"text": "Font − Select font families, size, and attributes, such as bold or italics."
},
{
"code": null,
"e": 74480,
"s": 74424,
"text": "Paragraph − Set up indents, line spacing and alignment."
},
{
"code": null,
"e": 74536,
"s": 74480,
"text": "Paragraph − Set up indents, line spacing and alignment."
},
{
"code": null,
"e": 74698,
"s": 74536,
"text": "Borders and Shading − Use the Borders tab to set border types, color, line thickness, and spacing. Use the Shading tab to set background color and image options."
},
{
"code": null,
"e": 74860,
"s": 74698,
"text": "Borders and Shading − Use the Borders tab to set border types, color, line thickness, and spacing. Use the Shading tab to set background color and image options."
},
{
"code": null,
"e": 74944,
"s": 74860,
"text": "DHTML Effects − Select which dynamic HTML effect to include and when to include it."
},
{
"code": null,
"e": 75028,
"s": 74944,
"text": "DHTML Effects − Select which dynamic HTML effect to include and when to include it."
},
{
"code": null,
"e": 75297,
"s": 75028,
"text": "You create styles on the fly using the Design Editor. To do so, select some text in the topic and apply some formatting. With the text still highlighted, type a style name in the Style list in the Edit tab and press Enter. In the dialog box that appears, click Create."
},
{
"code": null,
"e": 75462,
"s": 75297,
"text": "The Style Editor allows you to create and customize table styles according to your requirements. Modifications to a table style affects all tables using that style."
},
{
"code": null,
"e": 75816,
"s": 75462,
"text": "To apply a table style on an existing table, right-click an existing table in a topic and select Table Style.... Select Clean Table Inline Formatting in the Select Table Style dialog box to remove any inline styles used in the table. Select a style from the Available Table Styles list or select a Global Table Style (Table Templates) and then click OK."
},
{
"code": null,
"e": 76002,
"s": 75816,
"text": "Open the Style and Formatting pod from the Project tab. In the Style and Formatting tab, click on Create New Style and select Table Style. Name the new table style and then click on OK."
},
{
"code": null,
"e": 76180,
"s": 76002,
"text": "You can apply formatting to the whole table, first or last column or row, or a group of rows or columns. From the Apply Formatting To list, select the columns or rows to format."
},
{
"code": null,
"e": 76400,
"s": 76180,
"text": "Select font, size, and color. Select border and border color and click on Apply. The new style appears in the CSS Styles list of the Table Styles dialog box. Select this style to create tables with the same style later."
},
{
"code": null,
"e": 76542,
"s": 76400,
"text": "<Start here> With RoboHelp, you can create both HTML lists and advanced lists. Advanced lists can be either single level or multilevel lists."
},
{
"code": null,
"e": 76628,
"s": 76542,
"text": "HTML lists − All the ordered <ol> and unordered <ul> lists come under the HTML lists."
},
{
"code": null,
"e": 76714,
"s": 76628,
"text": "HTML lists − All the ordered <ol> and unordered <ul> lists come under the HTML lists."
},
{
"code": null,
"e": 76853,
"s": 76714,
"text": "Advanced lists − Creates a hierarchical or outline list, such as numbered heading styles, with numbering such as 1, 1.1, 1.1.1, and so on."
},
{
"code": null,
"e": 76992,
"s": 76853,
"text": "Advanced lists − Creates a hierarchical or outline list, such as numbered heading styles, with numbering such as 1, 1.1, 1.1.1, and so on."
},
{
"code": null,
"e": 77192,
"s": 76992,
"text": "In the Styles and Formatting pod, choose List Styles. Right-click on the pod, go to the New Menu and select List Style. Name the new list, select the font, font size and color for the new list style."
},
{
"code": null,
"e": 77313,
"s": 77192,
"text": "You can click on the Create an numbered List or the Create a bulleted list button to create a numbered or bulleted list."
},
{
"code": null,
"e": 77693,
"s": 77313,
"text": "In the Style and Formatting pod, click Create New Style, and select Multilevel List Style. Type a name for the new multilevel list and click on OK. Select a list level from the Apply Formatting To menu and select the paragraph style to apply to the current list level. You can select a predefined list style from the List Style dropdown menu, or click New to create a list style."
},
{
"code": null,
"e": 78016,
"s": 77693,
"text": "In the Edit Style dialog box, enter text or numbers to prefix a sequence or a multilevel list. To specify the level to prefix, select the level from the Insert Level menu. You can add a prefix to the level in the Edit Style box by separating the level and prefix with a separator such as a dot (.) or an angle bracket (>)."
},
{
"code": null,
"e": 78073,
"s": 78016,
"text": "Apply formatting to the list style and then click on OK."
},
{
"code": null,
"e": 78185,
"s": 78073,
"text": "You can edit the Div, Hyperlink and Image styles using the Styles editor or from the Styles and Formatting pod."
},
{
"code": null,
"e": 78239,
"s": 78185,
"text": "Div is used for text boxes and positioned text boxes."
},
{
"code": null,
"e": 78293,
"s": 78239,
"text": "Div is used for text boxes and positioned text boxes."
},
{
"code": null,
"e": 78384,
"s": 78293,
"text": "Hyperlink is used for hyperlinks, dropdown hotspots, expanding hotspot and glossary terms."
},
{
"code": null,
"e": 78475,
"s": 78384,
"text": "Hyperlink is used for hyperlinks, dropdown hotspots, expanding hotspot and glossary terms."
},
{
"code": null,
"e": 78508,
"s": 78475,
"text": "Image is used to place an image."
},
{
"code": null,
"e": 78541,
"s": 78508,
"text": "Image is used to place an image."
},
{
"code": null,
"e": 78797,
"s": 78541,
"text": "To create a style based on Div, Hyperlink or Image styles, double-click a CSS file in the Project Manager pod to open the Styles editor. Right-click on a style category from the Styles list and select New. Name the style and set the properties as desired."
},
{
"code": null,
"e": 79018,
"s": 78797,
"text": "We can edit the properties of Div and Image styles from the Styles editor or from the Styles and Formatting pod. You can edit the Size, Margin, Float, and Border attributes of a division or a section of text or an image."
},
{
"code": null,
"e": 79379,
"s": 79018,
"text": "Use the Float attribute to position text to the left or to the right of a division. If you set the Float attribute to Left, the text is placed to the right. The Overflow property (for Div styles) can be used to specify what happens if text overflows in a division. If you specify Overflow as Scroll, a scroll bar is added to display the content that overflows."
},
{
"code": null,
"e": 79467,
"s": 79379,
"text": "When you edit styles in a CSS file, all topics that are linked to the file are updated."
},
{
"code": null,
"e": 79664,
"s": 79467,
"text": "To edit a style, right-click on the CSS file in the Project Manager pod and click on Edit. Deselect the Hide Inherited Styles checkbox and select a style sheet from the Available In dropdown menu."
},
{
"code": null,
"e": 79752,
"s": 79664,
"text": "Select a style in the Styles box, click Format, and select the attributes and click OK."
},
{
"code": null,
"e": 79945,
"s": 79752,
"text": "Right-click on the CSS file in the Project Manager Pod and click Edit with Code Editor to open the style sheet in a new topic window. You can now edit the styles according to your requirement."
},
{
"code": null,
"e": 80109,
"s": 79945,
"text": "The Table of Contents (ToC) is a hierarchy of the folders and topics in the Project Manager. In this chapter, we will see how to create and print ToCs in RoboHelp."
},
{
"code": null,
"e": 80408,
"s": 80109,
"text": "To create a ToC, right-click on the Table of Contents folder in the Project Manager and select ‘New Table of Contents’. Specify a name for the ToC. You can also browse for an existing ToC file (.hhc) by selecting the Copy Existing Table of Contents checkbox to create the ToC from an available ToC."
},
{
"code": null,
"e": 80642,
"s": 80408,
"text": "Click OK to open the Table of Contents pod. In the Table of Contents pod, click the AutoCreate TOC button. You have the option of deleting the current ToC before creating a new one or creating a new one using bookmarks in the topics."
},
{
"code": null,
"e": 80817,
"s": 80642,
"text": "To print a ToC, click the Table of Contents pod, go to the File tab and click on Print TOC. In the dialog box that appears, select the one of the following options to print −"
},
{
"code": null,
"e": 80860,
"s": 80817,
"text": "Overview − Print all book and page titles."
},
{
"code": null,
"e": 80903,
"s": 80860,
"text": "Overview − Print all book and page titles."
},
{
"code": null,
"e": 81028,
"s": 80903,
"text": "Detailed − Print all book and page titles, the topic titles linked to each, and the folders in which the topics are located."
},
{
"code": null,
"e": 81153,
"s": 81028,
"text": "Detailed − Print all book and page titles, the topic titles linked to each, and the folders in which the topics are located."
},
{
"code": null,
"e": 81227,
"s": 81153,
"text": "You can modify the print options by clicking on Properties or Page Setup."
},
{
"code": null,
"e": 81454,
"s": 81227,
"text": "You can rename ToC books and pages without affecting the topic title linked to it. You can also change the topic title without affecting the ToC. In RoboHelp, you can rename, reorder or change properties of ToC books or pages."
},
{
"code": null,
"e": 81594,
"s": 81454,
"text": "To rename a ToC book or page, right-click a book or page in the Table of Contents pod and select Rename. Type the new name and press Enter."
},
{
"code": null,
"e": 81688,
"s": 81594,
"text": "Select a book or page in the Table of Contents pod and drag the item to a different location."
},
{
"code": null,
"e": 81944,
"s": 81688,
"text": "To rename a book or page or edit a window frame, right-click on the book or the page in the Table of Contents pod. Click on Properties to open the TOC Book Properties dialog box. Make the desired changes in the General and Advanced tabs and then click OK."
},
{
"code": null,
"e": 82035,
"s": 81944,
"text": "RoboHelp provides several options for managing ToCs and resolving errors and broken links."
},
{
"code": null,
"e": 82221,
"s": 82035,
"text": "We can get different forms of ToC reports, which we can print, copy and email. To access these reports, go to the Tools tab and in the Reports section, select the type of report needed."
},
{
"code": null,
"e": 82409,
"s": 82221,
"text": "The TOC Report displays the hierarchy of books and pages in a table of contents. If you change topic titles or filenames, you can compare them with the titles used in the books and pages."
},
{
"code": null,
"e": 82460,
"s": 82409,
"text": "You can choose from the following report formats −"
},
{
"code": null,
"e": 82600,
"s": 82460,
"text": "Detailed − Includes titles of books and pages, names of topics that are linked to them and names of folders in which the files are located."
},
{
"code": null,
"e": 82740,
"s": 82600,
"text": "Detailed − Includes titles of books and pages, names of topics that are linked to them and names of folders in which the files are located."
},
{
"code": null,
"e": 82822,
"s": 82740,
"text": "Overview − Includes titles of books and pages and names of topics linked to them."
},
{
"code": null,
"e": 82904,
"s": 82822,
"text": "Overview − Includes titles of books and pages and names of topics linked to them."
},
{
"code": null,
"e": 83063,
"s": 82904,
"text": "You can identify broken links when they appear in the Table of Contents pod with a red X. In the Project tab, click on Broken Links in the Navigation section."
},
{
"code": null,
"e": 83159,
"s": 83063,
"text": "Shows all references to the missing topic. The Open Book icon indicates broken TOC references."
},
{
"code": null,
"e": 83295,
"s": 83159,
"text": "Displays topics missing from the project. To remove a TOC item, select it under References to Selected Topic, and then click on Delete."
},
{
"code": null,
"e": 83513,
"s": 83295,
"text": "We can create multiple ToCs for a single project, which can be used for a single-source publishing such as separate tables of contents for a project that contains multiple languages or outputs for different audiences."
},
{
"code": null,
"e": 83677,
"s": 83513,
"text": "Double-click on the table of contents in the Table of Contents folder in the Project Manager pod. Drag books and pages from one Table of Contents pod to the other."
},
{
"code": null,
"e": 83966,
"s": 83677,
"text": "A project can have multiple ToCs. Right-click on the Table of Contents folder in the Project Manager pod and select New Table of Contents. In the New Table of Contents dialog box, type a name for the ToC and click OK. An empty table of contents is created in the Table of Contents folder."
},
{
"code": null,
"e": 84341,
"s": 83966,
"text": "It is also possible to merge multiple ToCs in the project into a single ToC. To do this, select the book or page where you want to merge the table of contents in the Table of Contents pod and click on the Insert TOC Placeholder button. In the Insert TOC Placeholder dialog box, select the table of contents to merge in the Select Table of Contents menu and then click on OK."
},
{
"code": null,
"e": 84512,
"s": 84341,
"text": "You create an index by adding keywords and associating them with topics. You can spellcheck an index, and you can use topic To Do lists to track your work while indexing."
},
{
"code": null,
"e": 84787,
"s": 84512,
"text": "Open the Index pod by going to the Pods menu in the Project tab. To add a keyword, click the New Index Keyword button in the Index pod toolbar. Type the keyword in the text box and press Enter. The new keyword appears in bold, indicating that it is not yet linked to topics."
},
{
"code": null,
"e": 85006,
"s": 84787,
"text": "Open the Topic List pod from the Pods menu in the Project tab. To link the keyword to topics, drag topics from the Topic List pod to the lower panel in the Index pod. The linked keyword changes from bold to plain text."
},
{
"code": null,
"e": 85407,
"s": 85006,
"text": "Index keywords can be copied between topics. After copying, you can customize them to work with individual topics. Right-click on a topic in the Topic List pod and click Properties. In the Index tab, click Add Existing. On the left, a list of all keywords in the project appears. On the right, a list of all keywords for the current topic appears. If the topic is not yet indexed, no keywords appear."
},
{
"code": null,
"e": 85588,
"s": 85407,
"text": "To copy a single keyword, select it on the left and click the single arrow button or click the double arrow button to copy all keywords. Click OK to link the keywords to the topic."
},
{
"code": null,
"e": 85773,
"s": 85588,
"text": "Index keywords can be cross-referenced so that when users select the cross-referenced keyword in the index, an alternate keyword appears which the user can select to display the topic."
},
{
"code": null,
"e": 86077,
"s": 85773,
"text": "Add a keyword to cross-reference in the Index pod. Right-click a keyword and select Properties. In the Index Keyword Properties dialog box, select the Cross-References checkbox and from the dropdown menu, select an alternate keyword. The cross-reference appears in the lower panel of the Index Designer."
},
{
"code": null,
"e": 86300,
"s": 86077,
"text": "RoboHelp allows you to edit and sort index keywords. Other layouts have sorted indexes but changing the sorting of keywords is available only in the HTML Help layout. Moving an index keyword moves its sub keywords as well."
},
{
"code": null,
"e": 86344,
"s": 86300,
"text": "You can sort index keywords in three ways −"
},
{
"code": null,
"e": 86403,
"s": 86344,
"text": "Select a keyword and click an arrow button in the toolbar."
},
{
"code": null,
"e": 86462,
"s": 86403,
"text": "Select a keyword and click an arrow button in the toolbar."
},
{
"code": null,
"e": 86480,
"s": 86462,
"text": "Drag the keyword."
},
{
"code": null,
"e": 86498,
"s": 86480,
"text": "Drag the keyword."
},
{
"code": null,
"e": 86595,
"s": 86498,
"text": "Right-click a keyword. In the Sort menu, select either Current Level or Current Level and Below."
},
{
"code": null,
"e": 86692,
"s": 86595,
"text": "Right-click a keyword. In the Sort menu, select either Current Level or Current Level and Below."
},
{
"code": null,
"e": 86758,
"s": 86692,
"text": "Sorting is available only if the action is allowed for the index."
},
{
"code": null,
"e": 86964,
"s": 86758,
"text": "To rename a topic keyword referenced by a specific topic, change the topic properties. If other topics use the same keyword, the original keyword remains in the index. Only the topic you change is updated."
},
{
"code": null,
"e": 87120,
"s": 86964,
"text": "In the Topic List pod, right-click a topic and click Properties. Select a keyword in the Index tab. Type the new keyword in the text box and click Replace."
},
{
"code": null,
"e": 87336,
"s": 87120,
"text": "Removing a keyword from a topic only affects the current topic. Other topics that reference the keyword are still linked to it. In the Topic Properties dialog box, select a keyword in the Index tab and click Delete."
},
{
"code": null,
"e": 87468,
"s": 87336,
"text": "You can use reports to manage indexes. There are two types of reports for indexes – Index report and Unused Index Keywords reports."
},
{
"code": null,
"e": 87733,
"s": 87468,
"text": "The Index report lets you display all the keywords, a list of keywords with their related topics, or a list of topics and their related keywords. The Unused Index Keywords report lists keywords that topics do not reference. These keywords reside in the index file."
},
{
"code": null,
"e": 87889,
"s": 87733,
"text": "From the Tools tab, select Index in the Reports section. View the report and click Close to close the report. You can also print, copy or email the report."
},
{
"code": null,
"e": 88167,
"s": 87889,
"text": "Open the Broken Links folder in the Project Manager pod. Missing topics if any will be listed with a red X. Right-click a missing topic and click on Properties. Keywords that reference the missing topic appear with a key icon, which can be removed or relinked in the Index pod."
},
{
"code": null,
"e": 88294,
"s": 88167,
"text": "RoboHelp can automatically build an index based on the topic contents. You can select from suggested keywords or use your own."
},
{
"code": null,
"e": 88501,
"s": 88294,
"text": "The Smart Index wizard can search the content of topics and suggest keywords. In the Tools tab, click on Smart Index Wizard. In the Smart Index Wizard dialog box, select from the following search criteria −"
},
{
"code": null,
"e": 88604,
"s": 88501,
"text": "Find new and existing index keywords − Add keywords based on topic content and existing index entries."
},
{
"code": null,
"e": 88707,
"s": 88604,
"text": "Find new and existing index keywords − Add keywords based on topic content and existing index entries."
},
{
"code": null,
"e": 88826,
"s": 88707,
"text": "Add existing index keywords to topic(s) − Search topics for keywords already used and link the keywords to the topics."
},
{
"code": null,
"e": 88945,
"s": 88826,
"text": "Add existing index keywords to topic(s) − Search topics for keywords already used and link the keywords to the topics."
},
{
"code": null,
"e": 89123,
"s": 88945,
"text": "Use custom search settings − Select Settings, and set custom search options. In the Smart Index Settings dialog box, you can define an effective language to find index keywords."
},
{
"code": null,
"e": 89301,
"s": 89123,
"text": "Use custom search settings − Select Settings, and set custom search options. In the Smart Index Settings dialog box, you can define an effective language to find index keywords."
},
{
"code": null,
"e": 89353,
"s": 89301,
"text": "In the next screen, specify the following options −"
},
{
"code": null,
"e": 89399,
"s": 89353,
"text": "Folder − Search topics in a specified folder."
},
{
"code": null,
"e": 89445,
"s": 89399,
"text": "Folder − Search topics in a specified folder."
},
{
"code": null,
"e": 89479,
"s": 89445,
"text": "Status − Search topics by status."
},
{
"code": null,
"e": 89513,
"s": 89479,
"text": "Status − Search topics by status."
},
{
"code": null,
"e": 89604,
"s": 89513,
"text": "Check only new topics (that have not been Smart Indexed) − Search only non-indexed topics."
},
{
"code": null,
"e": 89695,
"s": 89604,
"text": "Check only new topics (that have not been Smart Indexed) − Search only non-indexed topics."
},
{
"code": null,
"e": 89907,
"s": 89695,
"text": "Click on Next to see suggested keywords for the first topic. Select, deselect, rename or remove keywords. Then, click on Next, and click Close in the Results dialog box. The new keywords appear in the Index pod."
},
{
"code": null,
"e": 90031,
"s": 89907,
"text": "Open the Smart Index Wizard and click on Next twice. Select a keyword in the list, click on Options, and select Synonyms..."
},
{
"code": null,
"e": 90248,
"s": 90031,
"text": "The keyword appears in the Word box. You can also click on Antonyms to see antonyms for the keyword. You can look up synonyms and antonyms for additional words by typing the word in the Word box and clicking Look Up."
},
{
"code": null,
"e": 90423,
"s": 90248,
"text": "Select the best match for the word in the Categories section and under Synonyms select a word to add as a keyword. Click Add to Topic and click Close to close the dialog box."
},
{
"code": null,
"e": 90612,
"s": 90423,
"text": "Multiple indexes can be created in the same project, which are added to the Index folder. You can right-click on any index and select Set as Default to set that index as the default index."
},
{
"code": null,
"e": 90896,
"s": 90612,
"text": "To merge the indexes within a project, open the Index folder in the Project Manager pod, and double-click on an index. In the Index pod, select a keyword where you want to insert the merged index and click the Insert Index Placeholder button. Select the index to insert and click OK."
},
{
"code": null,
"e": 90995,
"s": 90896,
"text": "The merged index appears with the New Index icon. Double-click on the icon and then click on View."
},
{
"code": null,
"e": 91161,
"s": 90995,
"text": "You can select a custom font for displaying book and page titles and can create a 3D look for the ToC. You can also add ToC and index controls for better navigation."
},
{
"code": null,
"e": 91386,
"s": 91161,
"text": "Right-click on a layout for HTML Help output in the Single Source Layouts pod and select Properties. Click Edit next to Advanced Settings and click on the TOC Styles tab. Set the style options as needed and then click on OK."
},
{
"code": null,
"e": 91611,
"s": 91386,
"text": "Open a topic in the Design view. Click where you want to add the table of contents. In the HTML section of the Insert tab, select Table of Contents from the Javascript menu. The Contents control appears in the Design Editor."
},
{
"code": null,
"e": 91744,
"s": 91611,
"text": "To test the control, generate the project. The Table of Contents control displays the same table of contents as in the final output."
},
{
"code": null,
"e": 92034,
"s": 91744,
"text": "If your project does not support a tri-pane design, you can add an index control to a topic to make the index file available. The index appears when the topic is opened with the index control. In the Design Editor, open the topic with the control and click where you want to add the index."
},
{
"code": null,
"e": 92274,
"s": 92034,
"text": "In the HTML section of the Insert tab, select Index from the JavaScript menu. The Index control appears in the Design Editor. To test the index control, compile the project. The index control displays the same index as in the final output."
},
{
"code": null,
"e": 92600,
"s": 92274,
"text": "To create a Glossary, Double-click a glossary in the Glossary folder, in the Project Manager Pod. In the Glossary pod, type a term in the Term box. Click on the Add Term button (plus sign) or press Enter. The term appears in bold, indicating that it does not have a definition. In the Definition For panel, type a definition."
},
{
"code": null,
"e": 92684,
"s": 92600,
"text": "For terms and definitions to appear within topics, add expanding glossary hotspots."
},
{
"code": null,
"e": 92851,
"s": 92684,
"text": "Before importing or changing glossaries, it is always helpful to print a detailed report of the glossary to determine the terms that exists and to compare definitions"
},
{
"code": null,
"e": 93172,
"s": 92851,
"text": "Select a glossary in the Glossary folder in the Project Manager pod. In the Project tab, select Glossary from the dropdown menu in the Import section. Click on the Browse button to navigate to a GLO file. For definitions in the external glossary to overwrite matching terms, select Replace Existing Glossary Definitions."
},
{
"code": null,
"e": 93287,
"s": 93172,
"text": "Select one or more terms in the Terms in Imported glossary list, click on Add or Add All button and then click OK."
},
{
"code": null,
"e": 93399,
"s": 93287,
"text": "To change the glossary definitions, select the term to change in the Glossary pod and edit the definition text."
},
{
"code": null,
"e": 93504,
"s": 93399,
"text": "You can create multiple glossaries in the same project. New glossaries are added to the Glossary folder."
},
{
"code": null,
"e": 93551,
"s": 93504,
"text": "Note − You cannot delete the default glossary."
},
{
"code": null,
"e": 93620,
"s": 93551,
"text": "To create multiple glossary, we should follow the steps given below."
},
{
"code": null,
"e": 93708,
"s": 93620,
"text": "In the Project Manager Pod, right-click on the Glossary folder and select New Glossary."
},
{
"code": null,
"e": 93796,
"s": 93708,
"text": "In the Project Manager Pod, right-click on the Glossary folder and select New Glossary."
},
{
"code": null,
"e": 93873,
"s": 93796,
"text": "You can also click on the Create/View Glossary File button and click on New."
},
{
"code": null,
"e": 93950,
"s": 93873,
"text": "You can also click on the Create/View Glossary File button and click on New."
},
{
"code": null,
"e": 93979,
"s": 93950,
"text": "Type a name in the text box."
},
{
"code": null,
"e": 94008,
"s": 93979,
"text": "Type a name in the text box."
},
{
"code": null,
"e": 94125,
"s": 94008,
"text": "To copy an existing glossary, select Copy Existing Glossary and click the browse button to navigate to the glossary."
},
{
"code": null,
"e": 94242,
"s": 94125,
"text": "To copy an existing glossary, select Copy Existing Glossary and click the browse button to navigate to the glossary."
},
{
"code": null,
"e": 94427,
"s": 94242,
"text": "The Glossary Hotspot wizard finds glossary terms within topics and marks them in the topics. You can mark all terms to convert to expanding hotspot when you generate or preview output."
},
{
"code": null,
"e": 94482,
"s": 94427,
"text": "Note − Glossary panel is not supported in Oracle Help."
},
{
"code": null,
"e": 94641,
"s": 94482,
"text": "To add expanding glossary hotspots, drag a term from the Glossary pod into a topic. You can also click the Glossary Hotspot Wizard button in the Glossary pod."
},
{
"code": null,
"e": 94897,
"s": 94641,
"text": "The Glossary Hotspot Wizard finds glossary terms within topics and marks them in the topics. You can mark all the terms to convert to expanding hotspot, when you generate or preview the output. Preview a hotspot by double-clicking it in the Design Editor."
},
{
"code": null,
"e": 95123,
"s": 94897,
"text": "Open the Glossary Hotspot Wizard as discussed above. Select the Confirm marking Terms for each topic checkbox. Select a folder and status to search. From the Select Term menu, select the term to remove and then click on Next."
},
{
"code": null,
"e": 95350,
"s": 95123,
"text": "We can create links with most items you see in the Project Manager and TOC Composer including Topics, Bookmarks, URLs, Baggage Files, Newsgroups, FTP Sites, Files (such as PDF) associated with other programs and remote topics."
},
{
"code": null,
"e": 95574,
"s": 95350,
"text": "Select the insertion point for the link in the Design Editor and click the Insert Hyperlink button from the Links section of the Insert tab. Select an option from the Link To menu and specify the source location in the box."
},
{
"code": null,
"e": 95617,
"s": 95574,
"text": "Select from one of the following options −"
},
{
"code": null,
"e": 95774,
"s": 95617,
"text": "Display in Frame − This option defines the frameset for displaying the destination content. You can select the frame type or enter custom frame information."
},
{
"code": null,
"e": 95931,
"s": 95774,
"text": "Display in Frame − This option defines the frameset for displaying the destination content. You can select the frame type or enter custom frame information."
},
{
"code": null,
"e": 96050,
"s": 95931,
"text": "Display in auto-sizing popup − Displays the destination topic in a pop-up window rather than in the viewer or browser."
},
{
"code": null,
"e": 96169,
"s": 96050,
"text": "Display in auto-sizing popup − Displays the destination topic in a pop-up window rather than in the viewer or browser."
},
{
"code": null,
"e": 96330,
"s": 96169,
"text": "Display in custom-sized popup − Displays the destination topic in a pop-up window. For sizing the window manually, type a number in the Width and Height fields."
},
{
"code": null,
"e": 96491,
"s": 96330,
"text": "Display in custom-sized popup − Displays the destination topic in a pop-up window. For sizing the window manually, type a number in the Width and Height fields."
},
{
"code": null,
"e": 96671,
"s": 96491,
"text": "Add tool tip text to appear when you hover over the link. Select a local topic, bookmark, frame, or URL in the Select destination (file or URL) dropdown menu and then click on OK."
},
{
"code": null,
"e": 96831,
"s": 96671,
"text": "Bookmarks can be used to create incremental links within a topic. The Bookmark icon appears next to the bookmarked objects. To view bookmarks from the Project."
},
{
"code": null,
"e": 96881,
"s": 96831,
"text": "Manager, click on the plus sign next to a topic."
},
{
"code": null,
"e": 97116,
"s": 96881,
"text": "Click on the left of the desired location for the bookmark in the Design Editor. Then click the Insert Bookmark icon from the Links section of the Insert tab. Enter a name, without spaces, using any combination of letters and numbers."
},
{
"code": null,
"e": 97263,
"s": 97116,
"text": "After you save the topic, bookmark icons appear indented under topics listed in the Project Manager pod and next to topics in the Topics List pod."
},
{
"code": null,
"e": 97374,
"s": 97263,
"text": "Open the topic with a bookmark. Double-click the bookmark next to the topic, edit the name, and then click OK."
},
{
"code": null,
"e": 97449,
"s": 97374,
"text": "We can link images, sounds, videos and other multimedia files in RoboHelp."
},
{
"code": null,
"e": 97650,
"s": 97449,
"text": "Place the cursor where you want to link in the Design Editor or select text or an image to create a hotspot for the link. Click on the Insert Hyperlink button from the Links section of the Insert tab."
},
{
"code": null,
"e": 97764,
"s": 97650,
"text": "In Link To section, click on the triangle button and select Multimedia... Select the file to link and click Open."
},
{
"code": null,
"e": 97928,
"s": 97764,
"text": "You can also add links from images and multimedia. In the Design Editor, click on the multimedia object or the image to link and then follow the steps given below."
},
{
"code": null,
"e": 98007,
"s": 97928,
"text": "Click on the Insert Hyperlink button from the Links section of the Insert tab."
},
{
"code": null,
"e": 98086,
"s": 98007,
"text": "Click on the Insert Hyperlink button from the Links section of the Insert tab."
},
{
"code": null,
"e": 98189,
"s": 98086,
"text": "To link from multimedia, in the Link To section, click on the triangle button and select Multimedia..."
},
{
"code": null,
"e": 98292,
"s": 98189,
"text": "To link from multimedia, in the Link To section, click on the triangle button and select Multimedia..."
},
{
"code": null,
"e": 98371,
"s": 98292,
"text": "To link from images, select the destination. Images can contain only one link."
},
{
"code": null,
"e": 98450,
"s": 98371,
"text": "To link from images, select the destination. Images can contain only one link."
},
{
"code": null,
"e": 98523,
"s": 98450,
"text": "In this chapter, we will learn how to link external sources in RoboHelp."
},
{
"code": null,
"e": 98770,
"s": 98523,
"text": "External topics can be Microsoft HTML Help Projects or other such related projects. Click on the Insert Hyperlink button from the Links section of the Insert tab. In the Link To section, click on the triangle dropdown menu to select Remote Topic."
},
{
"code": null,
"e": 98999,
"s": 98770,
"text": "Select a link location in the Design Editor and enter text. Highlight the text, click on the Insert Hyperlink button from the Links section of the Insert tab. Click on the triangle button next to Link To and then select File...."
},
{
"code": null,
"e": 99290,
"s": 98999,
"text": "Browse to a file, open it, and copy it into the project folder. Generate the file to test links to external topics. For WebHelp projects, the external file must be distributed in the WebHelp folder. For Microsoft HTML Help Projects, the external file must the distributed with the CHM file."
},
{
"code": null,
"e": 99466,
"s": 99290,
"text": "Choose a location for the link in the Design Editor or select text or an image to define a hotspot. Click the Insert Hyperlink button from the Links section of the Insert tab."
},
{
"code": null,
"e": 99553,
"s": 99466,
"text": "In the Link To section, click the triangle button and then select from the following −"
},
{
"code": null,
"e": 99588,
"s": 99553,
"text": "To link to e-mail or select Email."
},
{
"code": null,
"e": 99623,
"s": 99588,
"text": "To link to e-mail or select Email."
},
{
"code": null,
"e": 99686,
"s": 99623,
"text": "To link to FTP sites or newsgroups, select FTP or Usenet News."
},
{
"code": null,
"e": 99749,
"s": 99686,
"text": "To link to FTP sites or newsgroups, select FTP or Usenet News."
},
{
"code": null,
"e": 99803,
"s": 99749,
"text": "To link to intranets or websites, select Web Address."
},
{
"code": null,
"e": 99857,
"s": 99803,
"text": "To link to intranets or websites, select Web Address."
},
{
"code": null,
"e": 99940,
"s": 99857,
"text": "In the next chapter, we will discuss how to maintain and repair links in RoboHelp."
},
{
"code": null,
"e": 100074,
"s": 99940,
"text": "Maintaining and repairing links is a very important component of RoboHelp. Let us learn how this is done and what its advantages are."
},
{
"code": null,
"e": 100142,
"s": 100074,
"text": "To update and remove links, we should follow the steps given below."
},
{
"code": null,
"e": 100186,
"s": 100142,
"text": "Open the topic containing the desired link."
},
{
"code": null,
"e": 100230,
"s": 100186,
"text": "Open the topic containing the desired link."
},
{
"code": null,
"e": 100321,
"s": 100230,
"text": "To update the link, right-click on the link, select Hyperlink Properties and make changes."
},
{
"code": null,
"e": 100412,
"s": 100321,
"text": "To update the link, right-click on the link, select Hyperlink Properties and make changes."
},
{
"code": null,
"e": 100480,
"s": 100412,
"text": "To remove a link, right-click the link and select Remove Hyperlink."
},
{
"code": null,
"e": 100548,
"s": 100480,
"text": "To remove a link, right-click the link and select Remove Hyperlink."
},
{
"code": null,
"e": 100615,
"s": 100548,
"text": "To remove the link and the text, select the text and press Delete."
},
{
"code": null,
"e": 100682,
"s": 100615,
"text": "To remove the link and the text, select the text and press Delete."
},
{
"code": null,
"e": 100743,
"s": 100682,
"text": "To fix broken links, we should follow the steps given below."
},
{
"code": null,
"e": 101007,
"s": 100743,
"text": "Click on the Topic References button in the Navigation section of the Project tab to open the Topic References dialog box. To fix a link, first select a link in the References to the Selected Topic and then click on Edit or Delete to edit or remove the hyperlink."
},
{
"code": null,
"e": 101271,
"s": 101007,
"text": "Click on the Topic References button in the Navigation section of the Project tab to open the Topic References dialog box. To fix a link, first select a link in the References to the Selected Topic and then click on Edit or Delete to edit or remove the hyperlink."
},
{
"code": null,
"e": 101419,
"s": 101271,
"text": "To fix a TOC item, index keyword, or image map, first select the item and then click Edit and select a valid destination to repair the broken link."
},
{
"code": null,
"e": 101567,
"s": 101419,
"text": "To fix a TOC item, index keyword, or image map, first select the item and then click Edit and select a valid destination to repair the broken link."
},
{
"code": null,
"e": 101636,
"s": 101567,
"text": "To remove TOC entries, select the TOC item and then click on Delete."
},
{
"code": null,
"e": 101705,
"s": 101636,
"text": "To remove TOC entries, select the TOC item and then click on Delete."
},
{
"code": null,
"e": 102043,
"s": 101705,
"text": "Link controls are navigational alternatives to the TOC and index. A link control works like a link and can appear as text, a button, or an image. Link controls can direct users to related topics and information. They save the user’s time spent in searching for topics. They also help to organize information for different kinds of users."
},
{
"code": null,
"e": 102314,
"s": 102043,
"text": "Link controls manage topic content by keeping information needed by multiple topics in a single topic and providing access to it from several places with link controls. You can manage topic layout by inserting link controls as objects rather than as long lines of links."
},
{
"code": null,
"e": 102637,
"s": 102314,
"text": "Click on a location for the control in the Design Editor. In the Links section of the Insert tab, click on Related Topics. In the Related Topic Wizard – Link Options dialog box, choose an option to show related topics as a button, which can be a label or an image, or to show related topics as text and then click on Next."
},
{
"code": null,
"e": 102872,
"s": 102637,
"text": "From the Topics in the project section, select a topic and click on Add. Continue to add all the topics you want to appear as related topics. Click on Change to update the topic name in Related Topics if needed and then click on Next."
},
{
"code": null,
"e": 103056,
"s": 102872,
"text": "Choose whether options should be displayed in a Topics Found dialog or in a Popup menu. Select an option to display the selected topic in a frame or new window and then click on Next."
},
{
"code": null,
"e": 103089,
"s": 103056,
"text": "Select display and font options."
},
{
"code": null,
"e": 103148,
"s": 103089,
"text": "Click on Finish and then click on the View button to test."
},
{
"code": null,
"e": 103437,
"s": 103148,
"text": "DoubleTo create and assign ‘See Also’ keywords, click on the See Also Folder in the Project Manager pod to open the See Also pod. You can also type the See Also keyword in the text box and click the plus sign. The keyword appears in bold, indicating that no topics are associated with it."
},
{
"code": null,
"e": 103511,
"s": 103437,
"text": "Let us now consider the following steps for adding topics, keywords, etc."
},
{
"code": null,
"e": 103582,
"s": 103511,
"text": "To assign topics to the See Also keyword, click on the Topic List pod."
},
{
"code": null,
"e": 103653,
"s": 103582,
"text": "To assign topics to the See Also keyword, click on the Topic List pod."
},
{
"code": null,
"e": 103784,
"s": 103653,
"text": "To add a keyword to multiple topics, select a topic, drag it into the lower pod, and repeat for all the topics you want to assign."
},
{
"code": null,
"e": 103915,
"s": 103784,
"text": "To add a keyword to multiple topics, select a topic, drag it into the lower pod, and repeat for all the topics you want to assign."
},
{
"code": null,
"e": 104108,
"s": 103915,
"text": "To add the keyword to individual topics, click on the Topic List pod, select a topic, click the Properties button and select See Also. Type the keyword to assign to the topic and click on Add."
},
{
"code": null,
"e": 104301,
"s": 104108,
"text": "To add the keyword to individual topics, click on the Topic List pod, select a topic, click the Properties button and select See Also. Type the keyword to assign to the topic and click on Add."
},
{
"code": null,
"e": 104344,
"s": 104301,
"text": "Add a See Also control to the new keyword."
},
{
"code": null,
"e": 104387,
"s": 104344,
"text": "Add a See Also control to the new keyword."
},
{
"code": null,
"e": 104469,
"s": 104387,
"text": "To change, reuse or remove link controls, we should follow the steps given below."
},
{
"code": null,
"e": 104532,
"s": 104469,
"text": "Open a topic containing the link control In the Design Editor."
},
{
"code": null,
"e": 104595,
"s": 104532,
"text": "Open a topic containing the link control In the Design Editor."
},
{
"code": null,
"e": 104668,
"s": 104595,
"text": "To change a control, double-click the control and change its properties."
},
{
"code": null,
"e": 104741,
"s": 104668,
"text": "To change a control, double-click the control and change its properties."
},
{
"code": null,
"e": 104860,
"s": 104741,
"text": "To reuse a control, right-click on the control and select Copy. Right-click in the destination topic and select Paste."
},
{
"code": null,
"e": 104979,
"s": 104860,
"text": "To reuse a control, right-click on the control and select Copy. Right-click in the destination topic and select Paste."
},
{
"code": null,
"e": 105040,
"s": 104979,
"text": "To remove a control, select the control and click on Delete."
},
{
"code": null,
"e": 105101,
"s": 105040,
"text": "To remove a control, select the control and click on Delete."
},
{
"code": null,
"e": 105172,
"s": 105101,
"text": "In the next chapter, we will learn how to work with text-only pop-ups."
},
{
"code": null,
"e": 105285,
"s": 105172,
"text": "We can create short text passages called text-only pop-up messages that appear when a user clicks a linked term."
},
{
"code": null,
"e": 105424,
"s": 105285,
"text": "Select the text in the Design Editor and from the Insert tab, click on the Text Popup icon. Type the pop-up text directly into the window."
},
{
"code": null,
"e": 105573,
"s": 105424,
"text": "To edit text-only pop-ups, Right-click on the text, which has been assigned the text-only pop-up. Then we should select the Text Popup Properties..."
},
{
"code": null,
"e": 105764,
"s": 105573,
"text": "The next step is to type or edit the text in the Popup Text box. You can also change the size, background color, fonts and margins. Future text-only pop-ups will carry forward these options."
},
{
"code": null,
"e": 105989,
"s": 105764,
"text": "Browse sequences help readers in navigating through a series of topics. A single topic can belong to multiple browse sequences but HTML files or external topics from other help systems cannot be included in browse sequences."
},
{
"code": null,
"e": 106275,
"s": 105989,
"text": "To create browse sequences automatically, create the table of contents. From the Navigation section of the Project tab, click on Browse Sequences. In the Browse Sequence Editor dialog box, click on Auto-create using TOC... to open the Auto-create Browse Sequences using TOC dialog box."
},
{
"code": null,
"e": 106476,
"s": 106275,
"text": "Enter the number of levels from the TOC hierarchy that you want to include in the browse sequence, and then click on OK. Click OK again. Click on Yes, if you see the Enable Browse Sequence dialog box."
},
{
"code": null,
"e": 106894,
"s": 106476,
"text": "To create browse sequences manually, from the Navigation section of the Project tab, click on Browse Sequences to open the Browse Sequence Editor dialog box. Click on New and then name the browse sequence. From the Available Topics list, select the folder containing the topics you are adding and add topics to the Browse Sequences Pane and click on OK. Click on Yes, if you see the Enable Browse Sequence dialog box."
},
{
"code": null,
"e": 107275,
"s": 106894,
"text": "RoboHelp supports many features for search. For example, we can have a multi-language search, which users can use to search for terms in other languages (if they are embedded in the topic). We can also search for Chinese/Japanese/Korean (CJK) search terms with WebHelp, FlashHelp and AIRHelp outputs. You can also use Boolean operators such as AND, OR and NOT to perform searches."
},
{
"code": null,
"e": 107509,
"s": 107275,
"text": "You can add or edit search metadata by going to Project Settings in the File section of the Project tab. Click on the ‘Advanced’ button next to the Language dropdown menu to open the Advanced Settings for the Localization dialog box."
},
{
"code": null,
"e": 107558,
"s": 107509,
"text": "Set the following metadata components as needed."
},
{
"code": null,
"e": 107811,
"s": 107558,
"text": "Used to define synonyms in search terms. For example, if the synonymous terms are, ‘Processor’ and ‘CPU’, RoboHelp returns topics containing ‘Intel’ with the term highlighted. Remember that we can specify only words in the Synonyms tab and not phrases."
},
{
"code": null,
"e": 108154,
"s": 107811,
"text": "Used to associate specific words or phrases with the current topic. You can choose words or phrases that are relevant but not generally found in the contents. For example, if ‘Adobe Systems’ is associated with a topic, when the user searches for ‘Adobe Systems’, the topic is displayed even though if it actually doesn’t contain this keyword."
},
{
"code": null,
"e": 108195,
"s": 108154,
"text": "Use the Phrases tab to add the keywords."
},
{
"code": null,
"e": 108386,
"s": 108195,
"text": "Used to ignore words to display relevant search results. Common words such as ‘a’, ‘an’, ‘the’ etc., can be ignored to ensure that RoboHelp displays only the results for the keywords needed."
},
{
"code": null,
"e": 108472,
"s": 108386,
"text": "In this chapter, we will understand how to optimize and configure search in RoboHelp."
},
{
"code": null,
"e": 108537,
"s": 108472,
"text": "RoboHelp supports many ways to optimize the content for search −"
},
{
"code": null,
"e": 108722,
"s": 108537,
"text": "Make Office and PDF files searchable (WebHelp/Pro, FlashHelp/Pro) − When baggage files are referenced in a topic through a hyperlink, users can search for them in the published output."
},
{
"code": null,
"e": 108907,
"s": 108722,
"text": "Make Office and PDF files searchable (WebHelp/Pro, FlashHelp/Pro) − When baggage files are referenced in a topic through a hyperlink, users can search for them in the published output."
},
{
"code": null,
"e": 109198,
"s": 108907,
"text": "Exclude specified baggage file types from search (Multiscreen HTML5, WebHelp, FlashHelp, and AIR Help) − The Exclude Baggage File Types from Search option lets you exclude baggage files of specified types from search. For example, you can exclude all PDF files in your projects from search."
},
{
"code": null,
"e": 109489,
"s": 109198,
"text": "Exclude specified baggage file types from search (Multiscreen HTML5, WebHelp, FlashHelp, and AIR Help) − The Exclude Baggage File Types from Search option lets you exclude baggage files of specified types from search. For example, you can exclude all PDF files in your projects from search."
},
{
"code": null,
"e": 109566,
"s": 109489,
"text": "You can configure the search experience of end users in the following ways −"
},
{
"code": null,
"e": 109737,
"s": 109566,
"text": "Show Total Number Of Search Results (WebHelp and AIRHelp) − This option enables display of the total number of results for a search string entered by users in the output."
},
{
"code": null,
"e": 109908,
"s": 109737,
"text": "Show Total Number Of Search Results (WebHelp and AIRHelp) − This option enables display of the total number of results for a search string entered by users in the output."
},
{
"code": null,
"e": 110072,
"s": 109908,
"text": "Hide Rank column in search results (WebHelp and WebHelp Pro) − The Rank column in search results can be hidden to provide more space for displaying search results."
},
{
"code": null,
"e": 110236,
"s": 110072,
"text": "Hide Rank column in search results (WebHelp and WebHelp Pro) − The Rank column in search results can be hidden to provide more space for displaying search results."
},
{
"code": null,
"e": 110492,
"s": 110236,
"text": "You can display content from specified URLs based on user search terms using external content search. When a user performs a search using any of these search terms, RoboHelp returns the title and description of the corresponding URL in the search results."
},
{
"code": null,
"e": 110672,
"s": 110492,
"text": "From the Open section of the Project tab, click on the Pods icon and select External Content Search to open the External Content Search pod. The pod allows the following options −"
},
{
"code": null,
"e": 110795,
"s": 110672,
"text": "Add − Click Add and specify search terms (separated by a comma, space, or semicolon) and the URL for the external content."
},
{
"code": null,
"e": 110918,
"s": 110795,
"text": "Add − Click Add and specify search terms (separated by a comma, space, or semicolon) and the URL for the external content."
},
{
"code": null,
"e": 111016,
"s": 110918,
"text": "Edit − Select the entry you want to edit and click on Edit. Modify the details and then click OK."
},
{
"code": null,
"e": 111114,
"s": 111016,
"text": "Edit − Select the entry you want to edit and click on Edit. Modify the details and then click OK."
},
{
"code": null,
"e": 111275,
"s": 111114,
"text": "Import − Allows you to select the SearchOptions.xml file from a project to import the external content search settings of that project into the current project."
},
{
"code": null,
"e": 111436,
"s": 111275,
"text": "Import − Allows you to select the SearchOptions.xml file from a project to import the external content search settings of that project into the current project."
},
{
"code": null,
"e": 111499,
"s": 111436,
"text": "Export − Select a folder to export the SearchOptions.xml file."
},
{
"code": null,
"e": 111562,
"s": 111499,
"text": "Export − Select a folder to export the SearchOptions.xml file."
},
{
"code": null,
"e": 111636,
"s": 111562,
"text": "Search − Allows you to specify a string to search for a particular entry."
},
{
"code": null,
"e": 111710,
"s": 111636,
"text": "Search − Allows you to specify a string to search for a particular entry."
},
{
"code": null,
"e": 111795,
"s": 111710,
"text": "RoboHelp supports standard image formats such as GIF, JPEG, BMP, MRB, WMF, PNG, etc."
},
{
"code": null,
"e": 112104,
"s": 111795,
"text": "You can use the Graphics Locator to scan hard drives and folders for image files, view thumbnails, and copy files. Double-click on the Graphics Locator in the Toolbox pod and select the graphic file format that we have to search. Enter the path for the search or browse to a new location and click on Search."
},
{
"code": null,
"e": 112184,
"s": 112104,
"text": "To add an image to a topic in RoboHelp, we should follow the steps given below."
},
{
"code": null,
"e": 112294,
"s": 112184,
"text": "Select a location for the image in the Design Editor. In the Media section of the Insert tab, click on Image."
},
{
"code": null,
"e": 112404,
"s": 112294,
"text": "Select a location for the image in the Design Editor. In the Media section of the Insert tab, click on Image."
},
{
"code": null,
"e": 112555,
"s": 112404,
"text": "You can either browse to a file or insert image from a project. You can also drag images from the Images folder of the Project Manager into the topic."
},
{
"code": null,
"e": 112706,
"s": 112555,
"text": "You can either browse to a file or insert image from a project. You can also drag images from the Images folder of the Project Manager into the topic."
},
{
"code": null,
"e": 112746,
"s": 112706,
"text": "Click OK to close the Image dialog box."
},
{
"code": null,
"e": 112786,
"s": 112746,
"text": "Click OK to close the Image dialog box."
},
{
"code": null,
"e": 112914,
"s": 112786,
"text": "Select the image to edit In the Design Editor, right-click the image and choose Image Properties to set the following options −"
},
{
"code": null,
"e": 112973,
"s": 112914,
"text": "Text Wrapping − Align the image with the surrounding text."
},
{
"code": null,
"e": 113032,
"s": 112973,
"text": "Text Wrapping − Align the image with the surrounding text."
},
{
"code": null,
"e": 113109,
"s": 113032,
"text": "Screen Tip − Text to display when the user hovers the cursor over the image."
},
{
"code": null,
"e": 113186,
"s": 113109,
"text": "Screen Tip − Text to display when the user hovers the cursor over the image."
},
{
"code": null,
"e": 113249,
"s": 113186,
"text": "ALT Text − Text to display when the image cannot be displayed."
},
{
"code": null,
"e": 113312,
"s": 113249,
"text": "ALT Text − Text to display when the image cannot be displayed."
},
{
"code": null,
"e": 113435,
"s": 113312,
"text": "Size − Set the dimensions of the image in pixels. Select Maintain aspect ratio to maintain the height to width proportion."
},
{
"code": null,
"e": 113558,
"s": 113435,
"text": "Size − Set the dimensions of the image in pixels. Select Maintain aspect ratio to maintain the height to width proportion."
},
{
"code": null,
"e": 113618,
"s": 113558,
"text": "Margins − Specify the space between the image and the text."
},
{
"code": null,
"e": 113678,
"s": 113618,
"text": "Margins − Specify the space between the image and the text."
},
{
"code": null,
"e": 113735,
"s": 113678,
"text": "Borders − Add a border to the image and specify a style."
},
{
"code": null,
"e": 113792,
"s": 113735,
"text": "Borders − Add a border to the image and specify a style."
},
{
"code": null,
"e": 114017,
"s": 113792,
"text": "It is possible to launch Adobe Captivate from RoboHelp and create demo topics. You can also insert SWF and HTML5 output of Adobe Captivate demos in the existing topics. The demo source can be opened from RoboHelp and edited."
},
{
"code": null,
"e": 114287,
"s": 114017,
"text": "Click on the Document icon in the Import section of the Project tab and select Adobe Captivate Demo to open the Select Adobe Captivate Demo dialog box. Specify a title, path for HTML output and path for SWF output for the new topic that you want to create for the demo."
},
{
"code": null,
"e": 114428,
"s": 114287,
"text": "If you have skipped specifying the corresponding SWF output path, RoboHelp adds a non-editable placeholder SWF for use in the Design Editor."
},
{
"code": null,
"e": 114764,
"s": 114428,
"text": "RoboHelp allows you to add a wide variety of multimedia content to your help projects. You can add both online and offline content. Depending on the output and the target browser, RoboHelp allows you to incorporate MPEG4, QuickTime and Ogg files along with a host of other compatible formats such as Real Media and Windows Media files."
},
{
"code": null,
"e": 114933,
"s": 114764,
"text": "To add a multimedia object, select a location in the topic where you would like to insert the multimedia and select Multimedia from the Media section of the Insert tab."
},
{
"code": null,
"e": 115243,
"s": 114933,
"text": "Select the Local File to insert multimedia from disk or select Web URL to link to a multimedia file online. Click on the Browse icon next to the Source field to browse to the location on disk. If you have already added files earlier, they will be seen in the Multimedia section in the Project Folders Section."
},
{
"code": null,
"e": 115512,
"s": 115243,
"text": "For online sources, input the Source URL rather than the HTTP URL. The Source URL can be found in the embed code of the online multimedia content beginning with ‘src=’ in the code. You can however use HTTP URLs, if you are inserting YouTube, Vimeo or DailyMotion links"
},
{
"code": null,
"e": 115609,
"s": 115512,
"text": "To remove a multimedia object, simply click the object and press the Delete key on the keyboard."
},
{
"code": null,
"e": 115874,
"s": 115609,
"text": "Dynamic HTML or DHTML is used to create interactive web pages using a combination of HTML, JavaScript, CSS and DOM. With DHTML, it is possible to add effects to HTML pages that are often difficult to achieve. RoboHelp allows you to add DHTML to your help projects."
},
{
"code": null,
"e": 116014,
"s": 115874,
"text": "Select an element in the Design Editor and from the DHTML section of the Insert tab, click on the Effects dropdown menu and select Effects."
},
{
"code": null,
"e": 116247,
"s": 116014,
"text": "Select event for initiating the effect from the When list and from the ‘What’ list, select the effect you want to apply. Adjust the relevant properties in the Settings section. DHTML effects are indicated with light grey hash marks."
},
{
"code": null,
"e": 116391,
"s": 116247,
"text": "With the topic open in the Design Editor, go the DHTML section of the Insert tab, click on the Effects dropdown menu and select Remove Effects."
},
{
"code": null,
"e": 116470,
"s": 116391,
"text": "The light grey hash marks are no longer associated with the text or paragraph."
},
{
"code": null,
"e": 116650,
"s": 116470,
"text": "You can open DHTML effects using triggers. When you click a text or an image that is associated with a trigger, a target appears. It is important that triggers and targets reside."
},
{
"code": null,
"e": 116795,
"s": 116650,
"text": "Select a text or image in the Design Editor and from the DHTML section of the Insert tab, click on the Trigger dropdown menu and select Trigger."
},
{
"code": null,
"e": 116985,
"s": 116795,
"text": "A cable drum icon is seen on the content to which the trigger is applied. Hash marks indicate application of the DHTML effect. The next step is to connect the trigger to an image or a text."
},
{
"code": null,
"e": 117397,
"s": 116985,
"text": "To connect the trigger to a text or an image, select the text or image to use as a target and from the DHTML section of the Insert tab, click on the Effects dropdown menu and select Effects. In the ‘When’ section, select the 1st Trigger Activation and under ‘What’ select the effect that occurs when the user clicks the trigger. Set the required properties under Settings. Repeat for the 2nd Trigger Activation."
},
{
"code": null,
"e": 117557,
"s": 117397,
"text": "A plug icon appears to indicate that it is a target. For images, you can drag the cable icon onto any image and select the required DHTML effect as the target."
},
{
"code": null,
"e": 117736,
"s": 117557,
"text": "To remove a DHTML trigger, select the item associated with the trigger and from the DHTML section of the Insert tab, click on the Trigger dropdown menu and select Remove Trigger."
},
{
"code": null,
"e": 117771,
"s": 117736,
"text": "Marquees are moving text messages."
},
{
"code": null,
"e": 118047,
"s": 117771,
"text": "To insert a marquee, select a text in the topic and from the HTML section of the Insert tab click on the Text Box dropdown menu and select Marquee. To change properties of the marquee, right-click on the marquee and click on Marquee Properties to change the marquee settings."
},
{
"code": null,
"e": 118127,
"s": 118047,
"text": "Click OK to apply the settings to the marquee and close the Marquee dialog box."
},
{
"code": null,
"e": 118227,
"s": 118127,
"text": "To delete a marquee, click on the boundary of the marquee and press the Delete key on the keyboard."
},
{
"code": null,
"e": 118285,
"s": 118227,
"text": "RoboHelp makes it easy to insert HTML comments in topics."
},
{
"code": null,
"e": 118502,
"s": 118285,
"text": "To insert an HTML comment, open a topic in the Design Editor and place the cursor where you wish to insert the comment. From the HTML section of the Insert tab, click on the Text Box dropdown menu and select Comment."
},
{
"code": null,
"e": 118599,
"s": 118502,
"text": "Type your comment in the Comment Editor in the following format - <!--a comment -> and click OK."
},
{
"code": null,
"e": 118888,
"s": 118599,
"text": "You can insert inline frames (iframes) to show PDFs or URLs within a HTML page. To insert an iframe, open a topic in the Design Editor and place the cursor where you wish to insert the iframe. From the HTML section of the Insert tab, click on the Text Box dropdown menu and select Iframe."
},
{
"code": null,
"e": 119017,
"s": 118888,
"text": "Enter a name in the Name field and click on the Browse button to select a URL, HTML file, or PDF file to link and then click OK."
},
{
"code": null,
"e": 119074,
"s": 119017,
"text": "You can optionally set border options in the Border tab."
},
{
"code": null,
"e": 119319,
"s": 119074,
"text": "Conditional texts allow you to create subsets of a content within a content to suit the target audience. For example, you can choose to tag certain parts of the content and choose to exclude them in the final output via a conditional build tag."
},
{
"code": null,
"e": 119524,
"s": 119319,
"text": "In the New section of the Project tab, click on Tag. Type a name for the tag in the New Conditional Build Tag dialog box. You can also select a color for the tag by clicking on the Build Tag Color button."
},
{
"code": null,
"e": 119603,
"s": 119524,
"text": "By default, RoboHelp provides two tags – Online and Print in all new projects."
},
{
"code": null,
"e": 119768,
"s": 119603,
"text": "Open the Topic List pod and select a topic or multiple topics. From the Edit tab, in the Tags section, click on the Apply dropdown menu and click on New/Multiple..."
},
{
"code": null,
"e": 119915,
"s": 119768,
"text": "Select the conditional tag that you wish to apply. When the conditional tag is applied, the content is overlaid with the color of the tag defined."
},
{
"code": null,
"e": 120180,
"s": 119915,
"text": "To apply tags to folders, indexes and ToCs, click on the corresponding folder in the Project Manager pod and from the Edit tab, in the Tags section, click on the Apply dropdown menu and click on New/Multiple... Select the conditional tag(s) that you wish to apply."
},
{
"code": null,
"e": 120707,
"s": 120180,
"text": "Sometimes, you might feel the need to create help files relative to the action performed by the user. Such help is called Context-Sensitive Help (CSH). For example, you can provide help information when a user hovers over a dialog box or other objects. The process of creating a CSH involves specifying map IDs and map files. The help engine receives the map number and help file name whenever the user accesses a CSH. The Help engine then matches the map number to a topic ID and HTM file and displays the correct help topic."
},
{
"code": null,
"e": 120746,
"s": 120707,
"text": "RoboHelp supports three types of CSH −"
},
{
"code": null,
"e": 120941,
"s": 120746,
"text": "Window-level − This level of CSH provides topics for windows, dialog boxes and other fields. Users can access window-level CSH by calling the Help function within the application or pressing F1."
},
{
"code": null,
"e": 121136,
"s": 120941,
"text": "Window-level − This level of CSH provides topics for windows, dialog boxes and other fields. Users can access window-level CSH by calling the Help function within the application or pressing F1."
},
{
"code": null,
"e": 121355,
"s": 121136,
"text": "Field-level (What's This?) − This CSH describes information when a user clicks on a question mark icon and then clicks a field or function. “What’s This?” topics are supported only by WinHelp and MS HTML Help projects."
},
{
"code": null,
"e": 121574,
"s": 121355,
"text": "Field-level (What's This?) − This CSH describes information when a user clicks on a question mark icon and then clicks a field or function. “What’s This?” topics are supported only by WinHelp and MS HTML Help projects."
},
{
"code": null,
"e": 121798,
"s": 121574,
"text": "Airplane Help − This usually refers to offline help that is called when there is no access to the internet. Using Airplane Help requires associating the offline Help system with the RH_AssociateOfflineHelp program function."
},
{
"code": null,
"e": 122022,
"s": 121798,
"text": "Airplane Help − This usually refers to offline help that is called when there is no access to the internet. Using Airplane Help requires associating the offline Help system with the RH_AssociateOfflineHelp program function."
},
{
"code": null,
"e": 122150,
"s": 122022,
"text": "Before looking at creating and managing map IDs, it is important to acquaint ourselves with map numbers, map files and map IDs."
},
{
"code": null,
"e": 122311,
"s": 122150,
"text": "Map Number − A map number is a number associated with a topic ID. Map numbers and topics IDs are stored in map files, which are called upon when CSH is invoked."
},
{
"code": null,
"e": 122472,
"s": 122311,
"text": "Map Number − A map number is a number associated with a topic ID. Map numbers and topics IDs are stored in map files, which are called upon when CSH is invoked."
},
{
"code": null,
"e": 122620,
"s": 122472,
"text": "Map File − A map file contains the map number and topic IDs. A project can contain multiple map files. Map files have the extension .h, .hh or .hm."
},
{
"code": null,
"e": 122768,
"s": 122620,
"text": "Map File − A map file contains the map number and topic IDs. A project can contain multiple map files. Map files have the extension .h, .hh or .hm."
},
{
"code": null,
"e": 122825,
"s": 122768,
"text": "Map ID − A map ID pairs the map number with a topic ID. "
},
{
"code": null,
"e": 122882,
"s": 122825,
"text": "Map ID − A map ID pairs the map number with a topic ID. "
},
{
"code": null,
"e": 123013,
"s": 122882,
"text": "A map file can be created by either authors or developers. Open the Output Setup Pod and expand the Context-Sensitive Help folder."
},
{
"code": null,
"e": 123134,
"s": 123013,
"text": "Right click on the Map Files folder and click on New Map File... Enter a name for the new map file and then click on OK."
},
{
"code": null,
"e": 123197,
"s": 123134,
"text": "For creating a Map ID, we should follow the steps given below."
},
{
"code": null,
"e": 123319,
"s": 123197,
"text": "Expand the Map Files folder in the Context-Sensitive Help folder in the Output Setup pod and double click on All Map IDs."
},
{
"code": null,
"e": 123441,
"s": 123319,
"text": "Expand the Map Files folder in the Context-Sensitive Help folder in the Output Setup pod and double click on All Map IDs."
},
{
"code": null,
"e": 123511,
"s": 123441,
"text": "In the Map File dropdown menu, select a map file to store the map ID."
},
{
"code": null,
"e": 123581,
"s": 123511,
"text": "In the Map File dropdown menu, select a map file to store the map ID."
},
{
"code": null,
"e": 123637,
"s": 123581,
"text": "Then, click on the Create Map ID or Edit Map ID button."
},
{
"code": null,
"e": 123693,
"s": 123637,
"text": "Then, click on the Create Map ID or Edit Map ID button."
},
{
"code": null,
"e": 123782,
"s": 123693,
"text": "Type a word or phrase to identify the topic in Topic ID and type a number in Map Number."
},
{
"code": null,
"e": 123871,
"s": 123782,
"text": "Type a word or phrase to identify the topic in Topic ID and type a number in Map Number."
},
{
"code": null,
"e": 124060,
"s": 123871,
"text": "We can dynamically edit a context-sensitive help topic (CST) associated with an application dialog box. Technical authors can open the application and associate the Help topic dynamically."
},
{
"code": null,
"e": 124384,
"s": 124060,
"text": "RoboHelp makes it easy to map a Help project with an application. Open the Help project that belongs to the application for which a CSH needs to be created. In the CSH section of the Tools tab, click on Open CSH Help, browse to the path of the executable for which the CSH needs to be mapped. Then click on the Open button."
},
{
"code": null,
"e": 124596,
"s": 124384,
"text": "When the application launches, select a dialog box in the application, which needs CSH mapping and press F1 or click on Help. Select a map file from the Project Map File popup menu in the CSH Options dialog box."
},
{
"code": null,
"e": 124856,
"s": 124596,
"text": "From here, we can either map the application to an existing topic (Map to selected topic) or map it to a new topic (Map to New Topic) and then click OK. We can also edit the topic contents (Edit Mapped Topic) or remove the mapping altogether (Remove Mapping)."
},
{
"code": null,
"e": 125096,
"s": 124856,
"text": "Developers can use RoboHelp APIs to create custom dialog boxes based on their requirements. RH_ShowHelp is the program function that calls the Help files in the project. Supported languages include Visual Basic, C/C++, JavaScript and Java."
},
{
"code": null,
"e": 125332,
"s": 125096,
"text": "The files for respective languages are located in Install Directory\\Adobe\\Adobe RoboHelp (version)\\CSH API. The RoboHelp documentation lists the parameters contained in RH_ShowHelp. They following table describes all these parameters −"
},
{
"code": null,
"e": 125340,
"s": 125332,
"text": "hParent"
},
{
"code": null,
"e": 125414,
"s": 125340,
"text": "This parameter closes the Help dialog, when the calling window is closed."
},
{
"code": null,
"e": 125428,
"s": 125414,
"text": "a_pszHelpFile"
},
{
"code": null,
"e": 125499,
"s": 125428,
"text": "This parameter specifies the Help Source depending on the Output type."
},
{
"code": null,
"e": 125551,
"s": 125499,
"text": "For Webhelp/FlashHelp: \"Path to project start page\""
},
{
"code": null,
"e": 125602,
"s": 125551,
"text": "For Webhelp Pro: \"http://<ServerName>/roboapi.asp\""
},
{
"code": null,
"e": 125638,
"s": 125602,
"text": "For HTML Help: \"Path to .CHM file\"."
},
{
"code": null,
"e": 125647,
"s": 125638,
"text": "uCommand"
},
{
"code": null,
"e": 125697,
"s": 125647,
"text": "This parameter contains the following constants −"
},
{
"code": null,
"e": 125755,
"s": 125697,
"text": "HH_DISPLAY_INDEX − Displays Index pane and default topic."
},
{
"code": null,
"e": 125815,
"s": 125755,
"text": "HH_DISPLAY_SEARCH − Displays Search pane and default topic."
},
{
"code": null,
"e": 125874,
"s": 125815,
"text": "HH_DISPLAY_TOC − Displays Contents pane and default topic."
},
{
"code": null,
"e": 125948,
"s": 125874,
"text": "HH_HELP_CONTEXT − Opens topic associated with map ID in dwData parameter."
},
{
"code": null,
"e": 125955,
"s": 125948,
"text": "dwData"
},
{
"code": null,
"e": 126104,
"s": 125955,
"text": "This parameter is used to obtain the map ID and export the map file for the programming language. Use the HH_HELP_CONTEXT in the uCommand parameter."
},
{
"code": null,
"e": 126312,
"s": 126104,
"text": "For more information or to further connect CSH topics to the languages listed above, refer to the Adobe RoboHelp documentation available on the following link – https://helpx.adobe.com/support/robohelp.html."
},
{
"code": null,
"e": 126561,
"s": 126312,
"text": "The ‘What’s This?’ Help can be used to add CSH to controls and fields in dialog boxes. For MS HTML Help files, the composer supports .exe, .dll and .ocx files. The Help files are created in a Context.txt file, which is then attached to the project."
},
{
"code": null,
"e": 126766,
"s": 126561,
"text": "To create a What’s This? Help file, expand the Context-Sensitive Help folder in the Output Setup pod. Right click on the What’s This? Help Files folder and click on Create/Import What’s This? Help File..."
},
{
"code": null,
"e": 126997,
"s": 126766,
"text": "In the Create/Import What’s This? Help File dialog box, select the text file containing the What’s This? Help content. Alternatively, you can type a name for the What’s This? Help file and RoboHelp will create a .txt file for you."
},
{
"code": null,
"e": 127199,
"s": 126997,
"text": "When you create a new What’s This? Help file, you will be given the option to link the topic IDs with the corresponding map numbers. We should now follow the steps given below to complete the process −"
},
{
"code": null,
"e": 127253,
"s": 127199,
"text": "Enter the topic ID and the corresponding map numbers."
},
{
"code": null,
"e": 127310,
"s": 127253,
"text": "In the Topic Text field, enter the content of the topic."
},
{
"code": null,
"e": 127368,
"s": 127310,
"text": "Click on Add/Update to link the topic and the map number."
},
{
"code": null,
"e": 127391,
"s": 127368,
"text": "Click Close when done."
},
{
"code": null,
"e": 127689,
"s": 127391,
"text": "Single-source layouts (SSLs) are templates for different output types of the project. For example, you can create an SSL that has different settings for different types of outputs such as eBooks, WebHelp, Responsive HTML5, etc. SSLs allows us to define output settings and enable batch publishing."
},
{
"code": null,
"e": 127986,
"s": 127689,
"text": "Primary layouts lets us set the default layout for our work. Additional options can then be specified to the primary layout. To specify a primary layout, right click a layout in the Outputs (SSL) pod and click on Set as Primary Output. Additional windows created are based on this primary layout."
},
{
"code": null,
"e": 128141,
"s": 127986,
"text": "To create an SSL, click on the Create Output in the Outputs (SSL) pod. You can also duplicate an existing layout by clicking on the Duplicate Output icon."
},
{
"code": null,
"e": 128260,
"s": 128141,
"text": "Then, type a name in the Output Name box and select an output type in the Output Type dropdown menu and then click OK."
},
{
"code": null,
"e": 128451,
"s": 128260,
"text": "The Dynamic User Centric Content (DUCC) helps users to toggle between different types of layouts, which cater to different products. Each layout will contain its own ToC, Index and Glossary."
},
{
"code": null,
"e": 128616,
"s": 128451,
"text": "DUCC works best with Adobe AIR and WebHelp outputs. For example, you can create content categories in an Adobe AIR layout, which can be then selected in the output."
},
{
"code": null,
"e": 128734,
"s": 128616,
"text": "From the Outputs (SSL) pod, click on the Create Output button in the toolbar and select the output type as Adobe AIR."
},
{
"code": null,
"e": 129000,
"s": 128734,
"text": "Then, right click on the Adobe AIR output in the Outputs (SSL) pod and click on Properties. In the Content Categories tab, select the categories that you want the user to dynamically change. You can also create, edit, change the order or remove existing categories."
},
{
"code": null,
"e": 129069,
"s": 129000,
"text": "Each content category has its own ToC, Index, Browse Sequences, etc."
},
{
"code": null,
"e": 129348,
"s": 129069,
"text": "It is possible to publish native ASPX or HTML outputs directly to a Microsoft SharePoint server from RoboHelp. SharePoint acts as a single resource for multiple web applications and content management. Hence, it makes it easy for users in SMEs to access centralized information."
},
{
"code": null,
"e": 129549,
"s": 129348,
"text": "The Multiscreen HTML5 SSL enables direct publishing of native (ASPX) outputs to a SharePoint 2010 library or SharePoint 2007 folder. The topics appear as a single HTML page when viewed in the browser."
},
{
"code": null,
"e": 129769,
"s": 129549,
"text": "In the Outputs (SSL) pod, right click on the Multiscreen HTML5 output and click on Properties. In the Multiscreen HTML5 Settings dialog box, click on SharePoint (Native) and specify the SharePoint version on the server."
},
{
"code": null,
"e": 129919,
"s": 129769,
"text": "You can also create custom master pages for each of the device profiles by clicking on the device profile name and selecting the type of master page."
},
{
"code": null,
"e": 130171,
"s": 129919,
"text": "Similar to ASPX multiscreen output, you can publish WebHelp, FlashHelp as well as Adobe AIR output directly to SharePoint. To publish a WebHelp output, double click on the WebHelp output in the Outputs(SSL) pod to open the WebHelp settings dialog box."
},
{
"code": null,
"e": 130351,
"s": 130171,
"text": "Then, click on Publish and select the SharePoint server to which we would like the output to be published. We can also add new SharePoint servers by clicking on the New... button."
},
{
"code": null,
"e": 130778,
"s": 130351,
"text": "Most modern browsers are available on multiple platforms and are optimized to scale content dynamically based on screen size. However, this might not be always sufficient and sometimes you might need to target content to a specific screen size or form factor. Using Multiscreen HTML5 SSL enables us to optimize our content for the specific screen size, so that the users are automatically presented the most optimized content."
},
{
"code": null,
"e": 130823,
"s": 130778,
"text": "You can also publish content to HTTPS sites."
},
{
"code": null,
"e": 130868,
"s": 130823,
"text": "You can also publish content to HTTPS sites."
},
{
"code": null,
"e": 131061,
"s": 130868,
"text": "While using Multiscreen HTML5 outputs, make sure to specify the default screen profile, screen resolution and browser agent to ensure that the content renders as intended on the chosen device."
},
{
"code": null,
"e": 131254,
"s": 131061,
"text": "While using Multiscreen HTML5 outputs, make sure to specify the default screen profile, screen resolution and browser agent to ensure that the content renders as intended on the chosen device."
},
{
"code": null,
"e": 131345,
"s": 131254,
"text": "The Adobe RoboHelp documentation lists the following supported browsers for HTML5 output −"
},
{
"code": null,
"e": 131526,
"s": 131345,
"text": "RoboHelp can also publish outputs in MS HTML, JavaHelp and Oracle Help layouts. Each layout is designed to work with applications written in their respective programming languages."
},
{
"code": null,
"e": 131692,
"s": 131526,
"text": "The MS HTML projects include HTM files for the topics along with Index, ToC, Related topics, etc. The MS HTML files can be generated at any point during the project."
},
{
"code": null,
"e": 131989,
"s": 131692,
"text": "We can also extract topics from the CHM files using RoboHelp. To do so, open the Toolbox pod and double click on the HTML Help Studio icon. Go to the File menu and click on Open to select a CHM file. Select All Files or individual files and click on Extract to extract to a specified destination."
},
{
"code": null,
"e": 132269,
"s": 131989,
"text": "JavaHelp projects include compressed output files that work with Java applications that run on various platforms. JavaHelp can also be created from existing WinHelp or HTML projects. RoboHelp can output directly to the JavaHelp format along with HTML features such as hyperlinks."
},
{
"code": null,
"e": 132557,
"s": 132269,
"text": "We will need Sun Java 2 SDK (or later) and JavaHelp 1.1.3 (or later) to author JavaHelp content. The user needs to have Java Runtime Environment (JRE) 1.2.1 (or later) and JavaHelp 1.1.3 (or later) to view JavaHelp JAR files. JavaHelp does not support text animations or special effects."
},
{
"code": null,
"e": 132915,
"s": 132557,
"text": "Similar to JavaHelp, Oracle Help projects also work with applications written in Java or other programming languages. The Oracle Help file is stored as a compressed JAR file. To author or view Oracle Help files, Oracle Help components 3.2.2 or 4.1.2 (or later), Sun Java 2 SDK (or later) and the Java Runtime Environment (JRE) 1.2.1 (or later) are required."
},
{
"code": null,
"e": 133096,
"s": 132915,
"text": "Oracle Help uses a default window for displaying topics. If we want the topic to be displayed in its own window, open the topic in the HTML Editor and edit the following Meta tag −"
},
{
"code": null,
"e": 133150,
"s": 133096,
"text": "meta name = “window-type” content = [“window name”] \n"
},
{
"code": null,
"e": 133293,
"s": 133150,
"text": "Help content can be distributed in the EPUB or Kindle Book formats, so that it can be read on eBook readers, tablets and other mobile devices."
},
{
"code": null,
"e": 133487,
"s": 133293,
"text": "To generate eBook outputs, double click on the eBook in the Outputs (SSL) pod to open the eBook Settings page. In the General Page under the eBook Formats, select EPUB 3 or Kindle Book or both."
},
{
"code": null,
"e": 133730,
"s": 133487,
"text": "For EPUB 3, RoboHelp generates .epub files. For Kindle Book, RoboHelp generates a Kindle Format 8 and Mobi file using the KindleGen converter. The link to download the KindleGen converter is available in the Kindle Book Generation dialog box."
},
{
"code": null,
"e": 133925,
"s": 133730,
"text": "The EPUB output can be validated by clicking on the Validate EPUB 3 Output under Options. This requires downloading a Java EpubCheck file, which is available in the link shown in the dialog box."
},
{
"code": null,
"e": 134099,
"s": 133925,
"text": "To add a cover image to the eBook, click Meta Information on the left hand side pane and under Cover Image, select the path to the image that you wish to be the cover image."
},
{
"code": null,
"e": 134398,
"s": 134099,
"text": "We can also embed fonts used in the project along with the EPUB, so that users need not have the fonts installed natively on their reader. To do so, click on Content in the left hand side pane and tick the Embed Fonts checkbox. Click on Manage... to select the fonts you wish to embed in the eBook."
},
{
"code": null,
"e": 134567,
"s": 134398,
"text": "RoboHelp makes it easy for effective collaboration among all stakeholders involved in the project. We will look at some of the review and collaboration features below −"
},
{
"code": null,
"e": 134819,
"s": 134567,
"text": "We can directly insert our comments in the Design Editor. The Review tab contains all the tools we need to add/edit reviews and track changes. To track changes in the Design Editor, click on Track Changes in the Tracking section of the Review toolbar."
},
{
"code": null,
"e": 134882,
"s": 134819,
"text": "Note − RoboHelp cannot track formatting and structure changes."
},
{
"code": null,
"e": 135067,
"s": 134882,
"text": "You can also create a PDF that can be sent to the reviewers. The PDF uses the same-tagged structure as the RoboHelp project, so that we can directly import those reviews into RoboHelp."
},
{
"code": null,
"e": 135311,
"s": 135067,
"text": "To create a PDF for review, in the PDF section of the Review tab, click on Create PDF to open the Create PDF for Review dialog box. Here, you can select the topics to be included for review and define Conditional Build Tag Expressions as well."
},
{
"code": null,
"e": 135510,
"s": 135311,
"text": "We can import a reviewed PDF by clicking on the Import Comments in the PDF section of the Review tab. However, for the import to be successful, the PDF should have been created from within RoboHelp."
},
{
"code": null,
"e": 135790,
"s": 135510,
"text": "Comments made by you or stakeholders can be accepted or rejected from the Design Editor. All the comments in the project can be viewed as a list in the Review Pane pod. The Review Pane pod allows you to filter comments and accept/reject them. Each comment can also have a status."
},
{
"code": null,
"e": 135927,
"s": 135790,
"text": "Often, teams work on big projects are distributed and work simultaneously. Whereas, the content is hosted on different servers such as −"
},
{
"code": null,
"e": 135935,
"s": 135927,
"text": "Dropbox"
},
{
"code": null,
"e": 135944,
"s": 135935,
"text": "OneDrive"
},
{
"code": null,
"e": 135957,
"s": 135944,
"text": "Google Drive"
},
{
"code": null,
"e": 135974,
"s": 135957,
"text": "SharePoint, etc."
},
{
"code": null,
"e": 136303,
"s": 135974,
"text": "RoboHelp can help you add resources from across cloud and file-system based locations into the project. To add a shared location, in the Open section of the Review tab, click on Pods and click on Resource Manager. In the Resource Manager pod, click on Add Shared Location and specify the type of shared location you want to add."
},
{
"code": null,
"e": 136530,
"s": 136303,
"text": "The Resource Manager pod also allows you to order your resources as categories. To add a category, click on the Add/Edit Categories icon and add the corresponding file types to a category such as .avi and .flv files for Video."
},
{
"code": null,
"e": 136881,
"s": 136530,
"text": "ActiveX controls are small programs that run in Windows applications such as Internet Explorer and HTML Help Viewer to enable additional functionality to the HTML page. RoboHelp comes with several ActiveX controls that you can use for HTML Help. By default, ActiveX controls such as HHCTRL.OCX are included to provide ToC, index and full text search."
},
{
"code": null,
"e": 136938,
"s": 136881,
"text": "The most common types of HTML ActiveX controls include −"
},
{
"code": null,
"e": 136955,
"s": 136938,
"text": "Calendar Control"
},
{
"code": null,
"e": 136970,
"s": 136955,
"text": "Custom Buttons"
},
{
"code": null,
"e": 136977,
"s": 136970,
"text": "Banner"
},
{
"code": null,
"e": 136983,
"s": 136977,
"text": "Chart"
},
{
"code": null,
"e": 137002,
"s": 136983,
"text": "Calculations, etc."
},
{
"code": null,
"e": 137147,
"s": 137002,
"text": "You might need to distribute the ActiveX controls located in the Redist directory of your Adobe RoboHelp installation to users who require them."
},
{
"code": null,
"e": 137349,
"s": 137147,
"text": "To insert an ActiveX control, place the cursor in the topic where the control is desired and from the HTML section of the Insert tab, click on the JavaScript dropdown menu and click on ActiveX Control."
},
{
"code": null,
"e": 137522,
"s": 137349,
"text": "Select the desired ActiveX control from the list and click on OK to add the control to your topic. You can double click on the added ActiveX control to view its properties."
},
{
"code": null,
"e": 137584,
"s": 137522,
"text": "Note − Not all ActiveX controls have properties dialog boxes."
},
{
"code": null,
"e": 137721,
"s": 137584,
"text": "RoboHelp allows you to add forms to topics where the user can fill in information and create frames and framesets to help in navigation."
},
{
"code": null,
"e": 137896,
"s": 137721,
"text": "To insert a form, place the cursor in the topic where the form is desired and from the HTML section of the Insert tab, click on the HTML Form dropdown menu and click on Form."
},
{
"code": null,
"e": 138003,
"s": 137896,
"text": "A placeholder will be inserted in the text. Double click on the placeholder to edit the form’s properties."
},
{
"code": null,
"e": 138289,
"s": 138003,
"text": "Frames divide the help viewer into different regions for each topic. Framesets allow the topics to change, while keeping some topics stationary. Though you can create multiple frames in a frameset, creating too many frames can clutter the interface and even cause increased load times."
},
{
"code": null,
"e": 138448,
"s": 138289,
"text": "In the Project Manger tab (click on Toggle Project Manager View if required), right click on the Project Files folder and in the ‘New’ menu click on Frameset."
},
{
"code": null,
"e": 138532,
"s": 138448,
"text": "Select a frameset template from the options given. Enter a title and click on Next."
},
{
"code": null,
"e": 138625,
"s": 138532,
"text": "The framesets can be seen in the HTML Files folder in the Project Manager and can be edited."
},
{
"code": null,
"e": 138730,
"s": 138625,
"text": "HTML Help controls help in navigating the content. They are portable and be copied into multiple topics."
},
{
"code": null,
"e": 138909,
"s": 138730,
"text": "To reuse a HTML Help control, open the topic that contains the control in the Design Editor, right click the control and click Copy. Paste it in the topic that needs the control."
},
{
"code": null,
"e": 139107,
"s": 138909,
"text": "To add WinHelp topic controls, select a desired location for the WinHelp topic control and from the HTML section of the Insert tab, click on the JavaScript dropdown menu and click on WinHelp Topic."
},
{
"code": null,
"e": 139177,
"s": 139107,
"text": "Follow the prompts in the wizard to insert the WinHelp topic control."
},
{
"code": null,
"e": 139479,
"s": 139177,
"text": "Index controls can be useful when the project does not support a tri-pane design containing an index tab. To insert an index control, place the cursor in the topic where the index control is desired and from the HTML section of the Insert tab, click on the JavaScript dropdown menu and click on Index."
},
{
"code": null,
"e": 139681,
"s": 139479,
"text": "To add a ToC control, place the cursor in the topic where the ToC control is desired. Then from the HTML section of the Insert tab, click on the JavaScript dropdown menu and click on Table of Contents."
},
{
"code": null,
"e": 139737,
"s": 139681,
"text": "Compile the project to test the index and ToC controls."
},
{
"code": null,
"e": 140048,
"s": 139737,
"text": "Splash screens can be displayed when the topic opens in the viewer. Bitmap and GIF images can be used for splash screens. To add a splash screen, open the topic for which the splash screen is desired and from the HTML section of the Insert tab, click on the JavaScript dropdown menu and click on Splash Screen."
},
{
"code": null,
"e": 140258,
"s": 140048,
"text": "Select the image file to use for the splash screen. You can also set the duration for which the splash screen is to be displayed by setting the amount of time in the Duration of splash display (Seconds) field."
},
{
"code": null,
"e": 140320,
"s": 140258,
"text": "Click on Finish. Preview the topic to test the splash screen."
},
{
"code": null,
"e": 140355,
"s": 140320,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 140372,
"s": 140355,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 140405,
"s": 140372,
"text": "\n 36 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 140433,
"s": 140405,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 140467,
"s": 140433,
"text": "\n 15 Lectures \n 15 hours \n"
},
{
"code": null,
"e": 140476,
"s": 140467,
"text": " Sanjeev"
},
{
"code": null,
"e": 140508,
"s": 140476,
"text": "\n 14 Lectures \n 48 mins\n"
},
{
"code": null,
"e": 140521,
"s": 140508,
"text": " Ermin Dedic"
},
{
"code": null,
"e": 140558,
"s": 140521,
"text": "\n 127 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 140580,
"s": 140558,
"text": " Aleksandar Cucukovic"
},
{
"code": null,
"e": 140617,
"s": 140580,
"text": "\n 103 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 140639,
"s": 140617,
"text": " Aleksandar Cucukovic"
},
{
"code": null,
"e": 140646,
"s": 140639,
"text": " Print"
},
{
"code": null,
"e": 140657,
"s": 140646,
"text": " Add Notes"
}
]
|
Wrap the flex items with CSS | To wrap the flex items, use the flex-wrap property. You can try to run the following code to implement the flex-wrap property
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.mycontainer {
display: flex;
background-color: #D7BDE2;
flex-wrap: wrap;
}
.mycontainer > div {
background-color: white;
text-align: center;
line-height: 40px;
font-size: 25px;
width: 100px;
margin: 5px;
}
</style>
</head>
<body>
<h1>Quiz</h1>
<div class = "mycontainer">
<div>Q1</div>
<div>Q2</div>
<div>Q3</div>
<div>Q4</div>
<div>Q5</div>
<div>Q6</div>
<div>Q7</div>
<div>Q8</div>
<div>Q9</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1188,
"s": 1062,
"text": "To wrap the flex items, use the flex-wrap property. You can try to run the following code to implement the flex-wrap property"
},
{
"code": null,
"e": 1198,
"s": 1188,
"text": "Live Demo"
},
{
"code": null,
"e": 1925,
"s": 1198,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .mycontainer {\n display: flex;\n background-color: #D7BDE2;\n flex-wrap: wrap;\n }\n .mycontainer > div {\n background-color: white;\n text-align: center;\n line-height: 40px;\n font-size: 25px;\n width: 100px;\n margin: 5px;\n }\n </style>\n </head>\n <body>\n <h1>Quiz</h1>\n <div class = \"mycontainer\">\n <div>Q1</div>\n <div>Q2</div>\n <div>Q3</div>\n <div>Q4</div>\n <div>Q5</div>\n <div>Q6</div>\n <div>Q7</div>\n <div>Q8</div>\n <div>Q9</div>\n </div>\n </body>\n</html>"
}
]
|
The 3 Ways To Compute Feature Importance in the Random Forest | by Piotr Płoński | Towards Data Science | The feature importance describes which features are relevant. It can help with a better understanding of the solved problem and sometimes lead to model improvement by utilizing feature selection. In this post, I will present 3 ways (with code) to compute feature importance for the Random Forest algorithm from scikit-learn package (in Python).
The Random Forest algorithm has built-in feature importance which can be computed in two ways:
Gini importance (or mean decrease impurity), which is computed from the Random Forest structure. Let’s look at how the Random Forest is constructed. It is a set of Decision Trees. Each Decision Tree is a set of internal nodes and leaves. In the internal node, the selected feature is used to make a decision on how to divide the data set into two separate sets with similar responses within. The features for internal nodes are selected with some criterion, which for classification tasks can be Gini impurity or information gain, and for regression is variance reduction. We can measure how each feature decreases the impurity of the split (the feature with the highest decrease is selected for internal node). For each feature, we can collect how on average it decreases the impurity. The average over all trees in the forest is the measure of the feature importance. This method is available in scikit-learn the implementation of the Random Forest (for both classifier and regressor). It is worth mentioning that in this method, we should look at the relative values of the computed importances. This biggest advantage of this method is the speed of computation - all needed values are computed during the Radom Forest training. The drawback of the method is a tendency to prefer (select as important) numerical features and categorical features with high cardinality. What is more, in the case of correlated features it can select one of the features and neglect the importance of the second one (which can lead to wrong conclusions).
Mean Decrease Accuracy — is a method of computing the feature importance on permuted out-of-bag (OOB) samples based on a mean decrease in the accuracy. This method is not implemented in the scikit-learn package. The very similar to this method is permutation-based importance described below in this post.
I will show how to compute feature importance for the Random Forest with scikit-learn package and Boston dataset (house price regression task).
# Let's load the packagesimport numpy as npimport pandas as pdfrom sklearn.datasets import load_bostonfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.inspection import permutation_importanceimport shapfrom matplotlib import pyplot as pltplt.rcParams.update({'figure.figsize': (12.0, 8.0)})plt.rcParams.update({'font.size': 14})
Load the data set and split for training and testing.
boston = load_boston()X = pd.DataFrame(boston.data, columns=boston.feature_names)y = boston.targetX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=12)
Fit the Random Forest Regressor with 100 Decision Trees:
rf = RandomForestRegressor(n_estimators=100)rf.fit(X_train, y_train)
To get the feature importances from the Random Forest model use the feature_importances_ argument:
rf.feature_importances_array([0.04054781, 0.00149293, 0.00576977, 0.00071805, 0.02944643, 0.25261155, 0.01969354, 0.05781783, 0.0050257 , 0.01615872, 0.01066154, 0.01185997, 0.54819617])
Let’s plot the importances (chart will be easier to interpret than values).
plt.barh(boston.feature_names, rf.feature_importances_)
To have an even better chart, let’s sort the features, and plot again:
sorted_idx = rf.feature_importances_.argsort()plt.barh(boston.feature_names[sorted_idx], rf.feature_importances_[sorted_idx])plt.xlabel("Random Forest Feature Importance")
The permutation-based importance can be used to overcome drawbacks of default feature importance computed with mean impurity decrease. It is implemented in scikit-learn as permutation_importance method. As arguments it requires trained model (can be any model compatible with scikit-learn API) and validation (test data). This method will randomly shuffle each feature and compute the change in the model's performance. The features which impact the performance the most are the most important one.
Permutation importance can be easily computed:
perm_importance = permutation_importance(rf, X_test, y_test)
To plot the importance:
sorted_idx = perm_importance.importances_mean.argsort()plt.barh(boston.feature_names[sorted_idx], perm_importance.importances_mean[sorted_idx])plt.xlabel("Permutation Importance")
The permutation-based importance is computationally expensive. The permutation-based method can have problems with highly-correlated features, it can report them as unimportant.
The SHAP interpretation can be used (it is model-agnostic) to compute the feature importances from the Random Forest. It is using the Shapley values from game theory to estimate how does each feature contributes to the prediction. It can be easily installed ( pip install shap) and used with scikit-learn Random Forest:
explainer = shap.TreeExplainer(rf)shap_values = explainer.shap_values(X_test)
To plot feature importance as the horizontal bar plot we need to use summary_plot the method:
shap.summary_plot(shap_values, X_test, plot_type="bar")
The feature importance can be plotted with more details, showing the feature value:
shap.summary_plot(shap_values, X_test)
The computing feature importances with SHAP can be computationally expensive. However, it can provide more information like decision plots or dependence plots.
The 3 ways to compute the feature importance for the scikit-learn Random Forest was presented:
built-in feature importance
permutation-based importance
computed with SHAP values
In my opinion, it is always good to check all methods and compare the results. I’m using permutation and SHAP based methods in MLJAR’s AutoML open-source package mljar-supervised. I'm using them because they are model-agnostic and works well with algorithms not from scikit-learn: Xgboost, Neural Networks (keras+tensorflow), LigthGBM, CatBoost.
The more accurate model is, the more trustworthy computed importance is.
The computed importances describe how important features are for the machine learning model. It is an approximation of how important features are in the data
The mljar-supervised is an open-source Automated Machine Learning (AutoML) Python package that works with tabular data. It is designed to save time for a data scientist. It abstracts the common way to preprocess the data, construct the machine learning models, and perform hyper-parameters tuning to find the best model. It is no black-box as you can see exactly how the ML pipeline is constructed (with a detailed Markdown report for each ML model).
Originally published at https://mljar.com on June 29, 2020. | [
{
"code": null,
"e": 392,
"s": 47,
"text": "The feature importance describes which features are relevant. It can help with a better understanding of the solved problem and sometimes lead to model improvement by utilizing feature selection. In this post, I will present 3 ways (with code) to compute feature importance for the Random Forest algorithm from scikit-learn package (in Python)."
},
{
"code": null,
"e": 487,
"s": 392,
"text": "The Random Forest algorithm has built-in feature importance which can be computed in two ways:"
},
{
"code": null,
"e": 2026,
"s": 487,
"text": "Gini importance (or mean decrease impurity), which is computed from the Random Forest structure. Let’s look at how the Random Forest is constructed. It is a set of Decision Trees. Each Decision Tree is a set of internal nodes and leaves. In the internal node, the selected feature is used to make a decision on how to divide the data set into two separate sets with similar responses within. The features for internal nodes are selected with some criterion, which for classification tasks can be Gini impurity or information gain, and for regression is variance reduction. We can measure how each feature decreases the impurity of the split (the feature with the highest decrease is selected for internal node). For each feature, we can collect how on average it decreases the impurity. The average over all trees in the forest is the measure of the feature importance. This method is available in scikit-learn the implementation of the Random Forest (for both classifier and regressor). It is worth mentioning that in this method, we should look at the relative values of the computed importances. This biggest advantage of this method is the speed of computation - all needed values are computed during the Radom Forest training. The drawback of the method is a tendency to prefer (select as important) numerical features and categorical features with high cardinality. What is more, in the case of correlated features it can select one of the features and neglect the importance of the second one (which can lead to wrong conclusions)."
},
{
"code": null,
"e": 2332,
"s": 2026,
"text": "Mean Decrease Accuracy — is a method of computing the feature importance on permuted out-of-bag (OOB) samples based on a mean decrease in the accuracy. This method is not implemented in the scikit-learn package. The very similar to this method is permutation-based importance described below in this post."
},
{
"code": null,
"e": 2476,
"s": 2332,
"text": "I will show how to compute feature importance for the Random Forest with scikit-learn package and Boston dataset (house price regression task)."
},
{
"code": null,
"e": 2871,
"s": 2476,
"text": "# Let's load the packagesimport numpy as npimport pandas as pdfrom sklearn.datasets import load_bostonfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.inspection import permutation_importanceimport shapfrom matplotlib import pyplot as pltplt.rcParams.update({'figure.figsize': (12.0, 8.0)})plt.rcParams.update({'font.size': 14})"
},
{
"code": null,
"e": 2925,
"s": 2871,
"text": "Load the data set and split for training and testing."
},
{
"code": null,
"e": 3114,
"s": 2925,
"text": "boston = load_boston()X = pd.DataFrame(boston.data, columns=boston.feature_names)y = boston.targetX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=12)"
},
{
"code": null,
"e": 3171,
"s": 3114,
"text": "Fit the Random Forest Regressor with 100 Decision Trees:"
},
{
"code": null,
"e": 3240,
"s": 3171,
"text": "rf = RandomForestRegressor(n_estimators=100)rf.fit(X_train, y_train)"
},
{
"code": null,
"e": 3339,
"s": 3240,
"text": "To get the feature importances from the Random Forest model use the feature_importances_ argument:"
},
{
"code": null,
"e": 3538,
"s": 3339,
"text": "rf.feature_importances_array([0.04054781, 0.00149293, 0.00576977, 0.00071805, 0.02944643, 0.25261155, 0.01969354, 0.05781783, 0.0050257 , 0.01615872, 0.01066154, 0.01185997, 0.54819617])"
},
{
"code": null,
"e": 3614,
"s": 3538,
"text": "Let’s plot the importances (chart will be easier to interpret than values)."
},
{
"code": null,
"e": 3670,
"s": 3614,
"text": "plt.barh(boston.feature_names, rf.feature_importances_)"
},
{
"code": null,
"e": 3741,
"s": 3670,
"text": "To have an even better chart, let’s sort the features, and plot again:"
},
{
"code": null,
"e": 3913,
"s": 3741,
"text": "sorted_idx = rf.feature_importances_.argsort()plt.barh(boston.feature_names[sorted_idx], rf.feature_importances_[sorted_idx])plt.xlabel(\"Random Forest Feature Importance\")"
},
{
"code": null,
"e": 4412,
"s": 3913,
"text": "The permutation-based importance can be used to overcome drawbacks of default feature importance computed with mean impurity decrease. It is implemented in scikit-learn as permutation_importance method. As arguments it requires trained model (can be any model compatible with scikit-learn API) and validation (test data). This method will randomly shuffle each feature and compute the change in the model's performance. The features which impact the performance the most are the most important one."
},
{
"code": null,
"e": 4459,
"s": 4412,
"text": "Permutation importance can be easily computed:"
},
{
"code": null,
"e": 4520,
"s": 4459,
"text": "perm_importance = permutation_importance(rf, X_test, y_test)"
},
{
"code": null,
"e": 4544,
"s": 4520,
"text": "To plot the importance:"
},
{
"code": null,
"e": 4724,
"s": 4544,
"text": "sorted_idx = perm_importance.importances_mean.argsort()plt.barh(boston.feature_names[sorted_idx], perm_importance.importances_mean[sorted_idx])plt.xlabel(\"Permutation Importance\")"
},
{
"code": null,
"e": 4902,
"s": 4724,
"text": "The permutation-based importance is computationally expensive. The permutation-based method can have problems with highly-correlated features, it can report them as unimportant."
},
{
"code": null,
"e": 5222,
"s": 4902,
"text": "The SHAP interpretation can be used (it is model-agnostic) to compute the feature importances from the Random Forest. It is using the Shapley values from game theory to estimate how does each feature contributes to the prediction. It can be easily installed ( pip install shap) and used with scikit-learn Random Forest:"
},
{
"code": null,
"e": 5300,
"s": 5222,
"text": "explainer = shap.TreeExplainer(rf)shap_values = explainer.shap_values(X_test)"
},
{
"code": null,
"e": 5394,
"s": 5300,
"text": "To plot feature importance as the horizontal bar plot we need to use summary_plot the method:"
},
{
"code": null,
"e": 5450,
"s": 5394,
"text": "shap.summary_plot(shap_values, X_test, plot_type=\"bar\")"
},
{
"code": null,
"e": 5534,
"s": 5450,
"text": "The feature importance can be plotted with more details, showing the feature value:"
},
{
"code": null,
"e": 5573,
"s": 5534,
"text": "shap.summary_plot(shap_values, X_test)"
},
{
"code": null,
"e": 5733,
"s": 5573,
"text": "The computing feature importances with SHAP can be computationally expensive. However, it can provide more information like decision plots or dependence plots."
},
{
"code": null,
"e": 5828,
"s": 5733,
"text": "The 3 ways to compute the feature importance for the scikit-learn Random Forest was presented:"
},
{
"code": null,
"e": 5856,
"s": 5828,
"text": "built-in feature importance"
},
{
"code": null,
"e": 5885,
"s": 5856,
"text": "permutation-based importance"
},
{
"code": null,
"e": 5911,
"s": 5885,
"text": "computed with SHAP values"
},
{
"code": null,
"e": 6257,
"s": 5911,
"text": "In my opinion, it is always good to check all methods and compare the results. I’m using permutation and SHAP based methods in MLJAR’s AutoML open-source package mljar-supervised. I'm using them because they are model-agnostic and works well with algorithms not from scikit-learn: Xgboost, Neural Networks (keras+tensorflow), LigthGBM, CatBoost."
},
{
"code": null,
"e": 6330,
"s": 6257,
"text": "The more accurate model is, the more trustworthy computed importance is."
},
{
"code": null,
"e": 6488,
"s": 6330,
"text": "The computed importances describe how important features are for the machine learning model. It is an approximation of how important features are in the data"
},
{
"code": null,
"e": 6939,
"s": 6488,
"text": "The mljar-supervised is an open-source Automated Machine Learning (AutoML) Python package that works with tabular data. It is designed to save time for a data scientist. It abstracts the common way to preprocess the data, construct the machine learning models, and perform hyper-parameters tuning to find the best model. It is no black-box as you can see exactly how the ML pipeline is constructed (with a detailed Markdown report for each ML model)."
}
]
|
C++ program for hashing with chaining | Hashing is the method by which we can map any length data element to a fixed size key. hashing works as key-value pairs.
Hashing function is the function that does the mapping in a hash map. the data elements that are given as input to the Hash Function may get same hash key. In this case the elements may overlap. To avoid overlapping of elements which have the same hash key the concept of chaining was introduced.
In order to create a hashmap we need hashing function that will define the index value of the data element.
We have a hash table, with n buckets. To insert a node into a hash table, we are given a hash function as
hashIndex = key % noOfBuckets
Now, we will use this hash function and calculate the hashindex of every inserted value to the hashmap.
Insert element and calculate the hashIndex of given key value and then insert the new node to the end of the list.
Insert element and calculate the hashIndex of given key value and then insert the new node to the end of the list.
To delete a node, we will calculate the hash index and in the bucket corresponding to hash Index we will search for the element in the bucket and remove it.
To delete a node, we will calculate the hash index and in the bucket corresponding to hash Index we will search for the element in the bucket and remove it.
Live Demo
#include<iostream>
#include <list>
using namespace std;
class Hash{
int BUCKET;
list < int >*table;
public:
Hash (int V);
void insertItem (int x);
void deleteItem (int key);
int hashFunction (int x){
return (x % BUCKET);
}
void displayHash ();
};
Hash::Hash (int b){
this->BUCKET = b;
table = new list < int >[BUCKET];
}
void Hash::insertItem (int key){
int index = hashFunction (key);
table[index].push_back (key);
}
void Hash::deleteItem (int key){
int index = hashFunction (key);
list < int >::iterator i;
for (i = table[index].begin (); i != table[index].end (); i++){
if (*i == key)
break;
}
if (i != table[index].end ())
table[index].erase (i);
}
void Hash::displayHash (){
for (int i = 0; i < BUCKET; i++){
cout << i;
for (auto x:table[i])
cout << " --> " << x;
cout << endl;
}
}
int main (){
int a[] = { 5, 12, 67, 9, 16 };
int n = 5;
Hash h (7);
for (int i = 0; i < n; i++)
h.insertItem (a[i]);
h.deleteItem (12);
h.displayHash ();
return 0;
}
0
1
2 --> 9 --> 16
3
4 --> 67
5 --> 5
6 | [
{
"code": null,
"e": 1183,
"s": 1062,
"text": "Hashing is the method by which we can map any length data element to a fixed size key. hashing works as key-value pairs."
},
{
"code": null,
"e": 1480,
"s": 1183,
"text": "Hashing function is the function that does the mapping in a hash map. the data elements that are given as input to the Hash Function may get same hash key. In this case the elements may overlap. To avoid overlapping of elements which have the same hash key the concept of chaining was introduced."
},
{
"code": null,
"e": 1588,
"s": 1480,
"text": "In order to create a hashmap we need hashing function that will define the index value of the data element."
},
{
"code": null,
"e": 1694,
"s": 1588,
"text": "We have a hash table, with n buckets. To insert a node into a hash table, we are given a hash function as"
},
{
"code": null,
"e": 1724,
"s": 1694,
"text": "hashIndex = key % noOfBuckets"
},
{
"code": null,
"e": 1828,
"s": 1724,
"text": "Now, we will use this hash function and calculate the hashindex of every inserted value to the hashmap."
},
{
"code": null,
"e": 1943,
"s": 1828,
"text": "Insert element and calculate the hashIndex of given key value and then insert the new node to the end of the list."
},
{
"code": null,
"e": 2058,
"s": 1943,
"text": "Insert element and calculate the hashIndex of given key value and then insert the new node to the end of the list."
},
{
"code": null,
"e": 2215,
"s": 2058,
"text": "To delete a node, we will calculate the hash index and in the bucket corresponding to hash Index we will search for the element in the bucket and remove it."
},
{
"code": null,
"e": 2372,
"s": 2215,
"text": "To delete a node, we will calculate the hash index and in the bucket corresponding to hash Index we will search for the element in the bucket and remove it."
},
{
"code": null,
"e": 2383,
"s": 2372,
"text": " Live Demo"
},
{
"code": null,
"e": 3466,
"s": 2383,
"text": "#include<iostream>\n#include <list>\nusing namespace std;\nclass Hash{\n int BUCKET;\n list < int >*table;\n public:\n Hash (int V);\n void insertItem (int x);\n void deleteItem (int key);\n int hashFunction (int x){\n return (x % BUCKET);\n }\n void displayHash ();\n};\nHash::Hash (int b){\n this->BUCKET = b;\n table = new list < int >[BUCKET];\n}\nvoid Hash::insertItem (int key){\n int index = hashFunction (key);\n table[index].push_back (key);\n}\nvoid Hash::deleteItem (int key){\n int index = hashFunction (key);\n list < int >::iterator i;\n for (i = table[index].begin (); i != table[index].end (); i++){\n if (*i == key)\n break;\n }\n if (i != table[index].end ())\n table[index].erase (i);\n}\nvoid Hash::displayHash (){\n for (int i = 0; i < BUCKET; i++){\n cout << i;\n for (auto x:table[i])\n cout << \" --> \" << x;\n cout << endl;\n }\n}\n int main (){\n int a[] = { 5, 12, 67, 9, 16 };\n int n = 5;\n Hash h (7);\n for (int i = 0; i < n; i++)\n h.insertItem (a[i]);\n h.deleteItem (12);\n h.displayHash ();\n return 0;\n}"
},
{
"code": null,
"e": 3506,
"s": 3466,
"text": "0\n1\n2 --> 9 --> 16\n3\n4 --> 67\n5 --> 5\n6"
}
]
|
Flutter - Dots Indicator - GeeksforGeeks | 15 Feb, 2021
Dots Indicator can be used to Show an increment or decrement to a value in a Flutter application through the UI. Moreover, it can also be used as an Increment or decrement component for a value through user interaction. To summarize its use case it can be improvised to use for multiple functionalities inside a flutter application.
In this article, we will look into the dots_indicator package and its uses in a flutter application by building a simple app. To build the app follow the below steps:
Add the dependency to the pubspec.yaml file
Import the dependency into the main.dart file
Use StatefulWidget for structuring the application
Initialize a state that holds a value that can be updated using buttons
Add buttons for respective increment or decrement action
Let’s look into the steps in detail.
Use the below image as an illustration for adding the dots_indicator dependency to the pubspec.yaml file:
To import the dependency to the main.dart file, use the below line of code:
import 'package:dots_indicator/dots_indicator.dart';
To give a simple structure to the example app, use a StatefulWidget, and extend it so that further components could be added to its body as shown below:
Dart
class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { // initialize the stage here later @override Widget build(BuildContext context) { const decorator = DotsDecorator( activeColor: Colors.green, activeSize: Size.square(30.0), activeShape: RoundedRectangleBorder(), ); return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), // add contents of the body here body: ) }}
The state in the application can be initialized to have a default value that can be manipulated later using the buttons that we will be adding in the next step follow the below code:
Dart
void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { final _totalDots = 5; double _currentPosition = 0.0; double _validPosition(double position) { if (position >= _totalDots) return 0; if (position < 0) return _totalDots - 1.0; return position; } void _updatePosition(double position) { setState(() => _currentPosition = _validPosition(position)); }
For the sake of simplicity, we will be adding two FloatingActionButton to increment and decrement the dots respectively based on the initial state. We will also be adding two dots indicator, one vertical and the other horizontal that will be visible in the UI as follows:
Dart
FloatingActionButton( child: const Icon(Icons.remove), backgroundColor: Colors.green, onPressed: () { _currentPosition = _currentPosition.ceilToDouble(); _updatePosition(max(--_currentPosition, 0)); },),FloatingActionButton( child: const Icon(Icons.add), backgroundColor: Colors.green, onPressed: () { _currentPosition = _currentPosition.floorToDouble(); _updatePosition(min( ++_currentPosition, _totalDots.toDouble(), )); },)
Complete Source Code:
Dart
import 'dart:math'; import 'package:flutter/material.dart';import 'package:dots_indicator/dots_indicator.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { final _totalDots = 5; double _currentPosition = 0.0; double _validPosition(double position) { if (position >= _totalDots) return 0; if (position < 0) return _totalDots - 1.0; return position; } void _updatePosition(double position) { setState(() => _currentPosition = _validPosition(position)); } Widget _buildRow(List<Widget> widgets) { return Padding( padding: const EdgeInsets.only(bottom: 20.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: widgets, ), ); } String getCurrentPositionPretty() { return (_currentPosition + 1.0).toStringAsPrecision(2); } @override Widget build(BuildContext context) { const decorator = DotsDecorator( activeColor: Colors.green, activeSize: Size.square(30.0), activeShape: RoundedRectangleBorder(), ); return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center( child: ListView( shrinkWrap: true, padding: const EdgeInsets.all(16.0), children: [ Text( 'Current position ${getCurrentPositionPretty()} / $_totalDots', style: const TextStyle( fontWeight: FontWeight.w600, fontSize: 16.0, ), textAlign: TextAlign.center, ), const SizedBox(height: 16.0), _buildRow([ Slider( value: _currentPosition, max: (_totalDots - 1).toDouble(), onChanged: _updatePosition, ) ]), _buildRow([ FloatingActionButton( child: const Icon(Icons.remove), backgroundColor: Colors.green, onPressed: () { _currentPosition = _currentPosition.ceilToDouble(); _updatePosition(max(--_currentPosition, 0)); }, ), FloatingActionButton( child: const Icon(Icons.add), backgroundColor: Colors.green, onPressed: () { _currentPosition = _currentPosition.floorToDouble(); _updatePosition(min( ++_currentPosition, _totalDots.toDouble(), )); }, ) ]), _buildRow([ Text( 'Vertical', style: TextStyle(fontWeight: FontWeight.w700, fontSize: 18.0), ), ]), _buildRow([ DotsIndicator( dotsCount: _totalDots, position: _currentPosition, axis: Axis.vertical, reversed: true, decorator: decorator, ), ]), _buildRow([ Text( 'Horizontal', style: TextStyle(fontWeight: FontWeight.w700, fontSize: 18.0)), DotsIndicator( dotsCount: _totalDots, position: _currentPosition, decorator: decorator, ), ]), ], ), ), ), ); }}
Output:
android
Flutter
Flutter UI-components
Flutter-widgets
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - Stack Widget
Android Studio Setup for Flutter Development
Flutter - Custom Bottom Navigation Bar
Flutter Tutorial
Flutter - Flexible Widget
Flutter - Stack Widget
Flutter - BorderRadius Widget | [
{
"code": null,
"e": 24010,
"s": 23982,
"text": "\n15 Feb, 2021"
},
{
"code": null,
"e": 24343,
"s": 24010,
"text": "Dots Indicator can be used to Show an increment or decrement to a value in a Flutter application through the UI. Moreover, it can also be used as an Increment or decrement component for a value through user interaction. To summarize its use case it can be improvised to use for multiple functionalities inside a flutter application."
},
{
"code": null,
"e": 24510,
"s": 24343,
"text": "In this article, we will look into the dots_indicator package and its uses in a flutter application by building a simple app. To build the app follow the below steps:"
},
{
"code": null,
"e": 24554,
"s": 24510,
"text": "Add the dependency to the pubspec.yaml file"
},
{
"code": null,
"e": 24600,
"s": 24554,
"text": "Import the dependency into the main.dart file"
},
{
"code": null,
"e": 24651,
"s": 24600,
"text": "Use StatefulWidget for structuring the application"
},
{
"code": null,
"e": 24723,
"s": 24651,
"text": "Initialize a state that holds a value that can be updated using buttons"
},
{
"code": null,
"e": 24780,
"s": 24723,
"text": "Add buttons for respective increment or decrement action"
},
{
"code": null,
"e": 24817,
"s": 24780,
"text": "Let’s look into the steps in detail."
},
{
"code": null,
"e": 24923,
"s": 24817,
"text": "Use the below image as an illustration for adding the dots_indicator dependency to the pubspec.yaml file:"
},
{
"code": null,
"e": 24999,
"s": 24923,
"text": "To import the dependency to the main.dart file, use the below line of code:"
},
{
"code": null,
"e": 25054,
"s": 24999,
"text": "import 'package:dots_indicator/dots_indicator.dart';\n\n"
},
{
"code": null,
"e": 25207,
"s": 25054,
"text": "To give a simple structure to the example app, use a StatefulWidget, and extend it so that further components could be added to its body as shown below:"
},
{
"code": null,
"e": 25212,
"s": 25207,
"text": "Dart"
},
{
"code": "class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { // initialize the stage here later @override Widget build(BuildContext context) { const decorator = DotsDecorator( activeColor: Colors.green, activeSize: Size.square(30.0), activeShape: RoundedRectangleBorder(), ); return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), // add contents of the body here body: ) }}",
"e": 25814,
"s": 25212,
"text": null
},
{
"code": null,
"e": 25997,
"s": 25814,
"text": "The state in the application can be initialized to have a default value that can be manipulated later using the buttons that we will be adding in the next step follow the below code:"
},
{
"code": null,
"e": 26002,
"s": 25997,
"text": "Dart"
},
{
"code": "void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { final _totalDots = 5; double _currentPosition = 0.0; double _validPosition(double position) { if (position >= _totalDots) return 0; if (position < 0) return _totalDots - 1.0; return position; } void _updatePosition(double position) { setState(() => _currentPosition = _validPosition(position)); }",
"e": 26490,
"s": 26002,
"text": null
},
{
"code": null,
"e": 26762,
"s": 26490,
"text": "For the sake of simplicity, we will be adding two FloatingActionButton to increment and decrement the dots respectively based on the initial state. We will also be adding two dots indicator, one vertical and the other horizontal that will be visible in the UI as follows:"
},
{
"code": null,
"e": 26767,
"s": 26762,
"text": "Dart"
},
{
"code": "FloatingActionButton( child: const Icon(Icons.remove), backgroundColor: Colors.green, onPressed: () { _currentPosition = _currentPosition.ceilToDouble(); _updatePosition(max(--_currentPosition, 0)); },),FloatingActionButton( child: const Icon(Icons.add), backgroundColor: Colors.green, onPressed: () { _currentPosition = _currentPosition.floorToDouble(); _updatePosition(min( ++_currentPosition, _totalDots.toDouble(), )); },)",
"e": 27227,
"s": 26767,
"text": null
},
{
"code": null,
"e": 27249,
"s": 27227,
"text": "Complete Source Code:"
},
{
"code": null,
"e": 27254,
"s": 27249,
"text": "Dart"
},
{
"code": "import 'dart:math'; import 'package:flutter/material.dart';import 'package:dots_indicator/dots_indicator.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { final _totalDots = 5; double _currentPosition = 0.0; double _validPosition(double position) { if (position >= _totalDots) return 0; if (position < 0) return _totalDots - 1.0; return position; } void _updatePosition(double position) { setState(() => _currentPosition = _validPosition(position)); } Widget _buildRow(List<Widget> widgets) { return Padding( padding: const EdgeInsets.only(bottom: 20.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: widgets, ), ); } String getCurrentPositionPretty() { return (_currentPosition + 1.0).toStringAsPrecision(2); } @override Widget build(BuildContext context) { const decorator = DotsDecorator( activeColor: Colors.green, activeSize: Size.square(30.0), activeShape: RoundedRectangleBorder(), ); return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center( child: ListView( shrinkWrap: true, padding: const EdgeInsets.all(16.0), children: [ Text( 'Current position ${getCurrentPositionPretty()} / $_totalDots', style: const TextStyle( fontWeight: FontWeight.w600, fontSize: 16.0, ), textAlign: TextAlign.center, ), const SizedBox(height: 16.0), _buildRow([ Slider( value: _currentPosition, max: (_totalDots - 1).toDouble(), onChanged: _updatePosition, ) ]), _buildRow([ FloatingActionButton( child: const Icon(Icons.remove), backgroundColor: Colors.green, onPressed: () { _currentPosition = _currentPosition.ceilToDouble(); _updatePosition(max(--_currentPosition, 0)); }, ), FloatingActionButton( child: const Icon(Icons.add), backgroundColor: Colors.green, onPressed: () { _currentPosition = _currentPosition.floorToDouble(); _updatePosition(min( ++_currentPosition, _totalDots.toDouble(), )); }, ) ]), _buildRow([ Text( 'Vertical', style: TextStyle(fontWeight: FontWeight.w700, fontSize: 18.0), ), ]), _buildRow([ DotsIndicator( dotsCount: _totalDots, position: _currentPosition, axis: Axis.vertical, reversed: true, decorator: decorator, ), ]), _buildRow([ Text( 'Horizontal', style: TextStyle(fontWeight: FontWeight.w700, fontSize: 18.0)), DotsIndicator( dotsCount: _totalDots, position: _currentPosition, decorator: decorator, ), ]), ], ), ), ), ); }}",
"e": 30938,
"s": 27254,
"text": null
},
{
"code": null,
"e": 30946,
"s": 30938,
"text": "Output:"
},
{
"code": null,
"e": 30954,
"s": 30946,
"text": "android"
},
{
"code": null,
"e": 30962,
"s": 30954,
"text": "Flutter"
},
{
"code": null,
"e": 30984,
"s": 30962,
"text": "Flutter UI-components"
},
{
"code": null,
"e": 31000,
"s": 30984,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 31005,
"s": 31000,
"text": "Dart"
},
{
"code": null,
"e": 31013,
"s": 31005,
"text": "Flutter"
},
{
"code": null,
"e": 31111,
"s": 31013,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31150,
"s": 31111,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 31176,
"s": 31150,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 31202,
"s": 31176,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 31225,
"s": 31202,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 31270,
"s": 31225,
"text": "Android Studio Setup for Flutter Development"
},
{
"code": null,
"e": 31309,
"s": 31270,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 31326,
"s": 31309,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 31352,
"s": 31326,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 31375,
"s": 31352,
"text": "Flutter - Stack Widget"
}
]
|
Vue.js | Introduction & Installation - GeeksforGeeks | 20 Oct, 2020
VueJS is one of the best frameworks for JavaScript like ReactJS. The VueJS is used to design the user interface layer, it is easy to pick up for any developers. It is compatible with other libraries and extensions as well. If you want to create a single page application then VueJS is the first choice in my opinion. In the development field, there may be so many issues that can not be solved by using a single library, so the VueJS is compatible with other libraries so you can easily go for it. The VueJS is supported by all popular browsers like Chrome, Firefox, IE, Safari, etc. You can easily compare this library with your favorite libraries.
Difference between ReactJS and Vue.js
Difference between VueJS and AngularJS
Installation of VueJS: The VueJs can be used in three different ways those are listed below:
Directly included CDN file.
Install through the npm.
By CLI use VueJS
Directly include CDN file: You need to download the VueJS Development Version and Production Version then include it in the script tag.CDN:
For learning purpose, you can use below script(with the specific version):<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script>For production purpose, you can use below script:<script src=”https://cdn.jsdelivr.net/npm/[email protected]′′></script>For ES modules compatible, use below script:<script type=”module”>import Vue from ‘https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.esm.browser.js'</script>
For learning purpose, you can use below script(with the specific version):<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script>
<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script>
For production purpose, you can use below script:<script src=”https://cdn.jsdelivr.net/npm/[email protected]′′></script>
<script src=”https://cdn.jsdelivr.net/npm/[email protected]′′></script>
For ES modules compatible, use below script:<script type=”module”>import Vue from ‘https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.esm.browser.js'</script>
<script type=”module”>import Vue from ‘https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.esm.browser.js'</script>
Install through the npm: Before applying this procedure you must have installed npm, to check npm installed or not run the below command:
npm -v
If not, you can install that through node.js installation procedure for:
Installation of Node.js on WindowsInstallation of Node.js on Linux
Installation of Node.js on Windows
Installation of Node.js on Linux
Now you are ready to install the VueJS, to do so run the below command. It will install the most updated stable version of VueJS.
npm install vue
By CLI use VueJS: Open your terminal or command prompt and run the below command.
npm install --global vue-cli
Let’s create a project through webpack:
Step 1: Run the below command to create the project.
vue init webpack myproject
Step 2: Now get into the myproject folder by using below command.
cd myproject
Step 3: Run the below command to run locally your project.
npm run dev
bunnyram19
Vue.JS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Set the value of an input field in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Form validation using HTML and JavaScript
Express.js express.Router() Function
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
Top 10 Angular Libraries For Web Developers
How to create footer to stay at the bottom of a Web page? | [
{
"code": null,
"e": 24410,
"s": 24382,
"text": "\n20 Oct, 2020"
},
{
"code": null,
"e": 25060,
"s": 24410,
"text": "VueJS is one of the best frameworks for JavaScript like ReactJS. The VueJS is used to design the user interface layer, it is easy to pick up for any developers. It is compatible with other libraries and extensions as well. If you want to create a single page application then VueJS is the first choice in my opinion. In the development field, there may be so many issues that can not be solved by using a single library, so the VueJS is compatible with other libraries so you can easily go for it. The VueJS is supported by all popular browsers like Chrome, Firefox, IE, Safari, etc. You can easily compare this library with your favorite libraries."
},
{
"code": null,
"e": 25098,
"s": 25060,
"text": "Difference between ReactJS and Vue.js"
},
{
"code": null,
"e": 25137,
"s": 25098,
"text": "Difference between VueJS and AngularJS"
},
{
"code": null,
"e": 25230,
"s": 25137,
"text": "Installation of VueJS: The VueJs can be used in three different ways those are listed below:"
},
{
"code": null,
"e": 25258,
"s": 25230,
"text": "Directly included CDN file."
},
{
"code": null,
"e": 25283,
"s": 25258,
"text": "Install through the npm."
},
{
"code": null,
"e": 25300,
"s": 25283,
"text": "By CLI use VueJS"
},
{
"code": null,
"e": 25440,
"s": 25300,
"text": "Directly include CDN file: You need to download the VueJS Development Version and Production Version then include it in the script tag.CDN:"
},
{
"code": null,
"e": 25852,
"s": 25440,
"text": "For learning purpose, you can use below script(with the specific version):<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script>For production purpose, you can use below script:<script src=”https://cdn.jsdelivr.net/npm/[email protected]′′></script>For ES modules compatible, use below script:<script type=”module”>import Vue from ‘https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.esm.browser.js'</script>"
},
{
"code": null,
"e": 25995,
"s": 25852,
"text": "For learning purpose, you can use below script(with the specific version):<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script>"
},
{
"code": null,
"e": 26064,
"s": 25995,
"text": "<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script>"
},
{
"code": null,
"e": 26178,
"s": 26064,
"text": "For production purpose, you can use below script:<script src=”https://cdn.jsdelivr.net/npm/[email protected]′′></script>"
},
{
"code": null,
"e": 26243,
"s": 26178,
"text": "<script src=”https://cdn.jsdelivr.net/npm/[email protected]′′></script>"
},
{
"code": null,
"e": 26400,
"s": 26243,
"text": "For ES modules compatible, use below script:<script type=”module”>import Vue from ‘https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.esm.browser.js'</script>"
},
{
"code": null,
"e": 26513,
"s": 26400,
"text": "<script type=”module”>import Vue from ‘https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.esm.browser.js'</script>"
},
{
"code": null,
"e": 26651,
"s": 26513,
"text": "Install through the npm: Before applying this procedure you must have installed npm, to check npm installed or not run the below command:"
},
{
"code": null,
"e": 26658,
"s": 26651,
"text": "npm -v"
},
{
"code": null,
"e": 26731,
"s": 26658,
"text": "If not, you can install that through node.js installation procedure for:"
},
{
"code": null,
"e": 26798,
"s": 26731,
"text": "Installation of Node.js on WindowsInstallation of Node.js on Linux"
},
{
"code": null,
"e": 26833,
"s": 26798,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 26866,
"s": 26833,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26996,
"s": 26866,
"text": "Now you are ready to install the VueJS, to do so run the below command. It will install the most updated stable version of VueJS."
},
{
"code": null,
"e": 27012,
"s": 26996,
"text": "npm install vue"
},
{
"code": null,
"e": 27094,
"s": 27012,
"text": "By CLI use VueJS: Open your terminal or command prompt and run the below command."
},
{
"code": null,
"e": 27123,
"s": 27094,
"text": "npm install --global vue-cli"
},
{
"code": null,
"e": 27163,
"s": 27123,
"text": "Let’s create a project through webpack:"
},
{
"code": null,
"e": 27216,
"s": 27163,
"text": "Step 1: Run the below command to create the project."
},
{
"code": null,
"e": 27244,
"s": 27216,
"text": "vue init webpack myproject\n"
},
{
"code": null,
"e": 27310,
"s": 27244,
"text": "Step 2: Now get into the myproject folder by using below command."
},
{
"code": null,
"e": 27324,
"s": 27310,
"text": "cd myproject\n"
},
{
"code": null,
"e": 27383,
"s": 27324,
"text": "Step 3: Run the below command to run locally your project."
},
{
"code": null,
"e": 27396,
"s": 27383,
"text": "npm run dev\n"
},
{
"code": null,
"e": 27407,
"s": 27396,
"text": "bunnyram19"
},
{
"code": null,
"e": 27414,
"s": 27407,
"text": "Vue.JS"
},
{
"code": null,
"e": 27425,
"s": 27414,
"text": "JavaScript"
},
{
"code": null,
"e": 27442,
"s": 27425,
"text": "Web Technologies"
},
{
"code": null,
"e": 27540,
"s": 27442,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27549,
"s": 27540,
"text": "Comments"
},
{
"code": null,
"e": 27562,
"s": 27549,
"text": "Old Comments"
},
{
"code": null,
"e": 27607,
"s": 27562,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27653,
"s": 27607,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 27725,
"s": 27653,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27771,
"s": 27725,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 27813,
"s": 27771,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 27850,
"s": 27813,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 27895,
"s": 27850,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27955,
"s": 27895,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 27999,
"s": 27955,
"text": "Top 10 Angular Libraries For Web Developers"
}
]
|
How to leave space with EmptyBorder in Java Swing | Llet us first create a JPanel and set titled border:
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Demo Panel"));
Now to create Empty Border:
JPanel panel2 = new JPanel(new BorderLayout());
panel2.add(panel, BorderLayout.CENTER);
panel2.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
The following is an example to leave space with EmptyBorder in Java Swing:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
public static void main(String[] args) {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Demo Panel"));
JPanel panel2 = new JPanel(new BorderLayout());
panel2.add(panel, BorderLayout.CENTER);
panel2.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
panel2.setPreferredSize(new Dimension(700, 350));
JFrame frame = new JFrame("Set Space");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel2);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
} | [
{
"code": null,
"e": 1115,
"s": 1062,
"text": "Llet us first create a JPanel and set titled border:"
},
{
"code": null,
"e": 1209,
"s": 1115,
"text": "JPanel panel = new JPanel();\npanel.setBorder(BorderFactory.createTitledBorder(\"Demo Panel\"));"
},
{
"code": null,
"e": 1237,
"s": 1209,
"text": "Now to create Empty Border:"
},
{
"code": null,
"e": 1396,
"s": 1237,
"text": "JPanel panel2 = new JPanel(new BorderLayout());\npanel2.add(panel, BorderLayout.CENTER);\npanel2.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));"
},
{
"code": null,
"e": 1471,
"s": 1396,
"text": "The following is an example to leave space with EmptyBorder in Java Swing:"
},
{
"code": null,
"e": 2264,
"s": 1471,
"text": "import java.awt.BorderLayout;\nimport java.awt.Dimension;\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\npublic class SwingDemo {\n public static void main(String[] args) {\n JPanel panel = new JPanel();\n panel.setBorder(BorderFactory.createTitledBorder(\"Demo Panel\"));\n JPanel panel2 = new JPanel(new BorderLayout());\n panel2.add(panel, BorderLayout.CENTER);\n panel2.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));\n panel2.setPreferredSize(new Dimension(700, 350));\n JFrame frame = new JFrame(\"Set Space\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setContentPane(panel2);\n frame.pack();\n frame.setLocationByPlatform(true);\n frame.setVisible(true);\n }\n}"
}
]
|
How to use vector class in Android listview? | This example demonstrate about How to use vector class in Android listview
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<EditText
android:id = "@+id/name"
android:layout_width = "match_parent"
android:hint = "Enter Name"
android:layout_height = "wrap_content" />
<LinearLayout
android:layout_width = "wrap_content"
android:layout_height = "wrap_content">
<Button
android:id = "@+id/save"
android:text = "Save"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
<Button
android:id = "@+id/refresh"
android:text = "Refresh"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>
<ListView
android:id = "@+id/listView"
android:layout_width = "match_parent"
android:layout_height = "wrap_content">
</ListView>
</LinearLayout>
In the above code, we have taken the name and record number as Edit text, when user clicks on save button it will store the data into ArrayList. Click on the refresh button to get the changes of the listview.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Vector;
public class MainActivity extends AppCompatActivity {
EditText name;
ArrayAdapter vectorAdapter;
Vector<String> vector_list;
private ListView listView;
@Override
protected void onCreate(Bundle readdInstanceState) {
super.onCreate(readdInstanceState);
setContentView(R.layout.activity_main);
vector_list = new Vector<String>();
name = findViewById(R.id.name);
listView = findViewById(R.id.listView);
findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vectorAdapter.notifyDataSetChanged();
listView.invalidateViews();
listView.refreshDrawableState();
}
});
findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty()) {
vector_list.add(name.getText().toString());
vectorAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, vector_list);
listView.setAdapter(vectorAdapter);
Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show();
} else {
name.setError("Enter NAME");
}
}
});
}
}
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 the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
In the above result, we are inserting name of vector elements to adater.
Click here to download the project code | [
{
"code": null,
"e": 1137,
"s": 1062,
"text": "This example demonstrate about How to use vector class in Android listview"
},
{
"code": null,
"e": 1266,
"s": 1137,
"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": 1331,
"s": 1266,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2481,
"s": 1331,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/name\"\n android:layout_width = \"match_parent\"\n android:hint = \"Enter Name\"\n android:layout_height = \"wrap_content\" />\n <LinearLayout\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\">\n <Button\n android:id = \"@+id/save\"\n android:text = \"Save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/refresh\"\n android:text = \"Refresh\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n </LinearLayout>\n <ListView\n android:id = \"@+id/listView\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n </ListView>\n</LinearLayout>"
},
{
"code": null,
"e": 2690,
"s": 2481,
"text": "In the above code, we have taken the name and record number as Edit text, when user clicks on save button it will store the data into ArrayList. Click on the refresh button to get the changes of the listview."
},
{
"code": null,
"e": 2747,
"s": 2690,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4403,
"s": 2747,
"text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Toast;\nimport java.util.Vector;\npublic class MainActivity extends AppCompatActivity {\n EditText name;\n ArrayAdapter vectorAdapter;\n Vector<String> vector_list;\n private ListView listView;\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n vector_list = new Vector<String>();\n name = findViewById(R.id.name);\n listView = findViewById(R.id.listView);\n findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n vectorAdapter.notifyDataSetChanged();\n listView.invalidateViews();\n listView.refreshDrawableState();\n }\n });\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n vector_list.add(name.getText().toString());\n vectorAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, vector_list);\n listView.setAdapter(vectorAdapter);\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n name.setError(\"Enter NAME\");\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 4754,
"s": 4403,
"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 the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 4827,
"s": 4754,
"text": "In the above result, we are inserting name of vector elements to adater."
},
{
"code": null,
"e": 4867,
"s": 4827,
"text": "Click here to download the project code"
}
]
|
Predicting Employee Churn with Classification Machine Learning Model | Col Jung | Towards Data Science | It’s well-known in HR that recruiting new employees is substantially more expensive than retaining existing talent. Employees who depart take with them valuable experience and knowledge from your organisation. According to Forbes, the cost of an entry-level position turning over is estimated at 50% of that employee’s salary. For mid-level employees, it’s estimated at 125% of salary, and for senior executives, a whopping 200% of salary.
We’ll train some machine learning models in a Jupyter notebook using data about an employee’s position, happiness, performance, workload and tenure to predict whether they’re going to stay or leave.
Our target variable’s categorical, hence the ML task is classification. (For a numerical target, the task becomes regression.)
We’ll use a dataset from elitedatascience.com that simulates a large company with 14,249 past and present employees. There are 10 columns.
The steps are:
EDA & data-processing: explore, visualise and clean the data.Feature engineering: leverage domain expertise and create new features.Model training: we’ll train and tune some tried-and-true classification algorithms, such as logistic regression, random forests and gradient-boosted trees.Performance evaluation: we’ll look at a range of scores including F1 and AUROC.Deployment: batch-run or get some data engineers / ML engineers to build an automated pipeline?
EDA & data-processing: explore, visualise and clean the data.
Feature engineering: leverage domain expertise and create new features.
Model training: we’ll train and tune some tried-and-true classification algorithms, such as logistic regression, random forests and gradient-boosted trees.
Performance evaluation: we’ll look at a range of scores including F1 and AUROC.
Deployment: batch-run or get some data engineers / ML engineers to build an automated pipeline?
Ideally, the company will run the model on their current permanent employees to identify those at-risk. This is an example of machine learning providing actionable business insights.
Exploratory data analysis (EDA) helps us understand the data and provides ideas and insights for data cleaning and feature engineering. Data cleaning prepares the data for our algorithms while feature engineering is the magic sauce that will really help our algorithms draw out the underlying patterns from the dataset. Remember:
Better data always beats fancier algorithms!
We start by loading some standard data science Python packages into JupyterLab.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sbfrom sklearn.linear_model import LogisticRegressionfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import GridSearchCVfrom sklearn.metrics import confusion_matrix, accuracy_score, f1_score, roc_curve, roc_auc_scoreimport pickle
Import the dataset:
df = pd.read_csv('employee_data.csv')
Here’s a snapshot of our dataframe again. The shape is (14,249, 10).
The target variable is status. This categorical variable takes the value Employed or Left.
There are 25 columns/features:
department
salary
satisfaction, filed_complaint — proxies for happiness
last_evaluation, recently_promoted — proxies for performance
avg_monthly_hrs, n_projects — proxies for workload
tenure — proxy for experience
Let’s plot some quick histograms to get an idea of the distributions of our numerical features.
df.hist(figsize=(10,10), xrot=-45)
Things to do to our numerical features to ensure the data will play nice with our algorithms:
Convert the NaN’s in filed_complaint and recently_promoted to 0. They were incorrectly labelled.
Create an indicator variable for the missing data in the last_evaluation feature, before converting the NaN’s to zero.
df.filed_complaint.fillna(0, inplace=True)df.recently_promoted.fillna(0, inplace=True)df['last_evaluation_missing'] = df.last_evaluation.isnull().astype(int)df.last_evaluation.fillna(0, inplace=True)
Here is a correlation heatmap for our numerical features.
sb.heatmap(df.corr(), annot=True, cmap=’RdBu_r’, vmin=-1, vmax=1)
Let’s plot some quick bar plots for our categorical features. Seaborn is great for this.
for feature in df.dtypes[df.dtypes=='object'].index: sb.countplot(data=df, y='{}'.format(features))
The biggest department is sales. Only a small proportion of employees are in the high salary bracket. And our dataset is imbalanced in that only a minority of employees have left the company, i.e. only a small proportion of our employees have status = Left. This has ramifications for the metrics we choose to evaluate our algorithms’ performances. We’ll talk more about this in the Results.
From a data-cleaning point of view, the IT and information_technology classes for the department feature should be merged together:
df.department.replace('information_technology', 'IT', inplace=True)
Moreover, HR only cares about permanent employees, so we should filter out the temp department:
df = df[df.department != 'temp']
Thus our department feature should look more like this:
Things to do to our categorical features to ensure the data will play nice with our algorithms:
Missing data for the department feature should be lumped into its own Missing class.
The department and salary categorical features should also be one-hot encoded.
The target variable status should be converted to binary.
df['department'].fillna('Missing', inplace=True)df = pd.get_dummies(df, columns=['department', 'salary'])df['status'] = pd.get_dummies(df.status).Left
We can draw further insights by segmenting numerical features against categorical ones. Let’s start off with some univariate segmentations.
Specifically, we’re going to segment numerical features representing happiness, performance, workload and experience by our categorical target variable status.
Segment satisfaction by status:
sb.violinplot(y='status', x='satisfaction', data=df)
An insight is that a number of churned employees were very satisfied with their jobs.
Segment last_evaluation status:
sb.violinplot(y='status', x='last_evaluation', data=df)
An insight is a large number of churned employees were high performers. Perhaps they felt no further opportunities for growth by staying?
Segment avg_monthly_hrs and n_projects by status:
sb.violinplot(y='status', x='avg_monthly_hrs', data=df)sb.violinplot(y='status', x='n_projects', data=df)
It appears that those who have churned tended to either have a fairly large workload or a fairly low workload. Do these represent burnt out and disengaged former employees?
Segment tenure by status:
sb.violinplot(y='status', x='tenure', data=df)
We note that employee churn suddenly during the 3rd year. Those who are still around after 6 years tend to stay.
Check out the following bivariate segmentations that will motivate our feature engineering later on.
For each plot, we’re going to segment two numerical features (representing happiness, performance, workload or experience) by status. This might give us some clusters based on employee stereotypes.
Performance and happiness:
Whoops, the Employed workers make this graph hard to read. Let’s just display the Left workers only, as they’re the ones we’re really trying to understand.
sb.lmplot(x='satisfaction', y='last_evaluation', data=df[df.status=='Left'], fit_reg=False )
We have three clusters of churned employees:
Underperformers: last_evaluation < 0.6
Unhappy: satisfaction_level < 0.2
Overachievers: last_evaluation > 0.8 and satisfaction > 0.7
Workload and performance:
sb.lmplot(x='last_evaluation', y='avg_monthly_hrs', data=df[df.status=='Left'], fit_reg=False )
We have two clusters of churned employees:
Stars: avg_monthly_hrs > 215 and last_evaluation > 0.75
Slackers: avg_monthly_hrs < 165 and last_evaluation < 0.65
Workload and happiness:
sb.lmplot(x='satisfaction', y='avg_monthly_hrs', data=df[df.status=='Left'], fit_reg=False, )
We have three clusters of churned employees:
Workaholics: avg_monthly_hrs > 210 and satisfation > 0.7
Just-a-job: avg_monthly_hrs < 170
Overworked: avg_monthly_hrs > 225 and satisfaction < 0.2
Let’s engineer new features for these 8 ‘stereotypical’ clusters of employees:
df['underperformer'] = ((df.last_evaluation < 0.6) & (df.last_evaluation_missing==0)).astype(int)df['unhappy'] = (df.satisfaction < 0.2).astype(int)df['overachiever'] = ((df.last_evaluation > 0.8) & (df.satisfaction > 0.7)).astype(int)df['stars'] = ((df.avg_monthly_hrs > 215) & (df.last_evaluation > 0.75)).astype(int)df['slackers'] = ((df.avg_monthly_hrs < 165) & (df.last_evaluation < 0.65) & (df.last_evaluation_missing==0)).astype(int)df['workaholic'] = ((df.avg_monthly_hrs > 210) & (df.satisfaction > 0.7)).astype(int)df['justajob'] = (df.avg_monthly_hrs < 170).astype(int)df['overworked'] = ((df.avg_monthly_hrs > 225) & (df.satisfaction < 0.2)).astype(int)
We can take a glance at the proportion of employees in each of these 8 groups.
df[['underperformer', 'unhappy', 'overachiever', 'stars', 'slackers', 'workaholic', 'justajob', 'overworked']].mean()underperformer 0.285257unhappy 0.092195overachiever 0.177069stars 0.241825slackers 0.167686workaholic 0.226685justajob 0.339281overworked 0.071581
34% of employees are just-a-job employees — non-inspired and just here for the weekly pay cheque — while only 7% are flat out overworked.
Analytical base table: The dataset after applying all of these data cleaning steps and feature engineering is our analytical base table. This is the data on which we train our models.
Our ABT has 14,068 employees and 31 columns — see below for a snippet. Recall our original dataset had 14,249 employees and just 10 columns!
We’re going to train four tried-and-true classification models:
logistic regressions (L1 and L2-regularised)
random forests
gradient-boosted trees
First, let’s split our analytical base table.
y = df.statusX = df.drop('status', axis=1)
We’ll then split into training and test sets. Our dataset is mildly imbalanced, so we’ll use stratified sampling to compensate.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234, stratify=df.status)
We’ll set up a pipeline object to train. This will streamline our model training process.
pipelines = { 'l1': make_pipeline(StandardScaler(), LogisticRegression(penalty='l1', random_state=123)), 'l2': make_pipeline(StandardScaler(), LogisticRegression(penalty='l2', random_state=123)), 'rf': make_pipeline( RandomForestClassifier(random_state=123)), 'gb': make_pipeline( GradientBoostingClassifier(random_state=123)) }
We also want to tune the hyperparameters for each algorithm. For logistic regression, the most impactful hyperparameter is the strength of the regularisation, C.
l1_hyperparameters = {'logisticregression__C' : [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 50, 100, 500, 1000] }l2_hyperparameters = {'logisticregression__C' : [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 50, 100, 500, 1000] }
For our random forest, we’ll tune the number of estimators (n_estimators), the max number of features to consider during a split (max_features), and the min number of samples to be a leaf (min_samples_leaf).
rf_hyperparameters = { 'randomforestclassifier__n_estimators' : [100, 200], 'randomforestclassifier__max_features' : ['auto', 'sqrt', 0.33], 'randomforestclassifier__min_samples_leaf' : [1, 3, 5, 10] }
For our gradient-boosted tree, we’ll tune the number of estimators (n_estimators), learning rate, and the maximum depth of each tree (max_depth).
gb_hyperparameters = { 'gradientboostingclassifier__n_estimators' : [100, 200], 'gradientboostingclassifier__learning_rate' : [0.05, 0.1, 0.2], 'gradientboostingclassifier__max_depth' : [1, 3, 5] }
We’ll save these hyperparameters in a dictionary.
hyperparameters = { 'l1' : l1_hyperparameters, 'l2' : l2_hyperparameters, 'rf' : rf_hyperparameters, 'gb' : gb_hyperparameters }
Finally, we’ll fit and tune our models. Using GridSearchCV we can train all of these models with cross-validation on all of our declared hyperparameters with just a few lines of code!
fitted_models = {}for name, pipeline in pipelines.items(): model = GridSearchCV(pipeline, hyperparameters[name], cv=10, n_jobs=-1) model.fit(X_train, y_train) fitted_models[name] = model
I’ve written a dedicated article on popular machine learning metrics, including the ones used below.
We’ll start by printing the cross-validation scores. This is the average performance across the 10 hold-out folds and is a way to get a reliable estimate of the model performance using only your training data.
for name, model in fitted_models.items(): print(name, model.best_score_)Output:l1 0.9088324151412831l2 0.9088324151412831rf 0.9793851075173272gb 0.975475386529234
Moving onto the test data, we’ll:
calculate accuracy;
print the confusion matrix and calculate precision, recall and F1-score;
display the ROC and calculate the AUROC score.
Accuracy measures the proportion of correctly labelled predictions, however it is an inappropriate metric for imbalanced datasets, e.g. email spam filtration (spam vs. not spam) and medical testing (sick vs. not sick). For instance, if our dataset only had 1% of employees satisfying target=Left, then a model that always predicts the employee is still working at the company would instantly score 99% accuracy. In these situations, precision or recall is more appropriate. Whichever you use often depends on whether you want to minimise Type 1 errors (False Positives) or Type 2 errors (False Negatives). For spam emails, Type 1 errors are worse (some spam is OK as long as you don’t accidentally filter out an important email!) while Type 2 errors are unacceptable for medical testing (telling someone they didn’t have cancer when they did is a disaster!). The F1-score gets you the best of both worlds by taking the weighted average of precision and recall.
The area under the ROC, known as the AUROC is another standard metric for classification problems. It’s an effective measurement of a classifier’s ability to distinguish between classes and separate signal from noise. This metric is also robust against imbalanced datasets.
Here is the code to generate these scores and plots:
for name, model in fitted_models.items(): print('Results for:', name) # obtain predictions pred = fitted_models[name].predict(X_test) # confusion matrix cm = confusion_matrix(y_test, pred) print(cm) # accuracy score print('Accuracy:', accuracy_score(y_test, pred)) # precision precision = cm[1][1]/(cm[0][1]+cm[1][1]) print('Precision:', precision) # recall recall = cm[1][1]/(cm[1][0]+cm[1][1]) print('Recall:', recall) # F1_score print('F1:', f1_score(y_test, pred)) # obtain prediction probabilities pred = fitted_models[name].predict_proba(X_test) pred = [p[1] for p in pred] # plot ROC fpr, tpr, thresholds = roc_curve(y_test, pred) plt.title('Receiver Operating Characteristic (ROC)') plt.plot(fpr, tpr, label=name) plt.legend(loc='lower right') plt.plot([0,1],[0,1],'k--') plt.xlim([-0.1,1.1]) plt.ylim([-0.1,1.1]) plt.ylabel('True Positive Rate (TPR) i.e. Recall') plt.xlabel('False Positive Rate (FPR)') plt.show() # AUROC score print('AUROC:', roc_auc_score(y_test, pred))
Logistic regression (L1-regularised):
Output:[[2015 126] [ 111 562]]Accuracy: 0.9157782515991472Precision: 0.8168604651162791Recall: 0.8350668647845468F1: 0.8258633357825129AUROC: 0.9423905869485105
Logistic regression (L2-regularised):
Output:[[2014 127] [ 110 563]]Accuracy: 0.9157782515991472Precision: 0.8159420289855073Recall: 0.836552748885587F1: 0.8261188554658841AUROC: 0.9423246556128734
Gradient-boosted tree:
Output:[[2120 21] [ 48 625]]Accuracy: 0.9754797441364605Precision: 0.9674922600619195Recall: 0.9286775631500743F1: 0.9476876421531464AUROC: 0.9883547910913578
Random forest:
Output:[[2129 12] [ 45 628]]Accuracy: 0.9797441364605544Precision: 0.98125Recall: 0.9331352154531947F1: 0.9565879664889566AUROC: 0.9916117990718256
The winning algorithm is the random forest with an AUROC of 99% and a F1-score of 96%. This algorithm has a 99% chance of distinguishing between a Left and Employed worker... pretty good!
Out of 2814 employees in the test set, the algorithm:
correctly classified 628 Left workers (True Positives) while getting 12 wrong (Type I errors), and
correctly classified 2129 Employed workers (True Negatives) while getting 45 wrong (Type II errors).
FYI, here are the hyperparameters of the winning random forest, tuned using GridSearchCV.
RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features=0.33, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0, n_estimators=200, n_jobs=None, oob_score=False, random_state=123, verbose=0, warm_start=False )
Consider the following code.
coef = winning_model.feature_importances_ind = np.argsort(-coef)for i in range(X_train.shape[1]): print("%d. %s (%f)" % (i + 1, X.columns[ind[i]], coef[ind[i]]))x = range(X_train.shape[1])y = coef[ind][:X_train.shape[1]]plt.title("Feature importances")ax = plt.subplot()plt.barh(x, y, color='red')ax.set_yticks(x)ax.set_yticklabels(X.columns[ind])plt.gca().invert_yaxis()
This will print a list of features ranked by importance and a corresponding bar plot.
Ranking of feature importance:1. n_projects (0.201004)2. satisfaction (0.178810)3. tenure (0.169454)4. avg_monthly_hrs (0.091827)5. stars (0.074373)6. overworked (0.068334)7. last_evaluation (0.063630)8. slackers (0.028261)9. overachiever (0.027244)10. workaholic (0.018925)11. justajob (0.016831)12. unhappy (0.016486)13. underperformer (0.006015)14. last_evaluation_missing (0.005084)15. salary_low (0.004372)16. filed_complaint (0.004254)17. salary_high (0.003596)18. department_engineering (0.003429)19. department_sales (0.003158)20. salary_medium (0.003122)21. department_support (0.002655)22. department_IT (0.001628)23. department_finance (0.001389)24. department_management (0.001239)25. department_Missing (0.001168)26. department_marketing (0.001011)27. recently_promoted (0.000983)28. department_product (0.000851)29. department_admin (0.000568)30. department_procurement (0.000296)
There are three particularly strong predictors for employee churn:
n_projects (workload)
satisfaction (happiness) and
tenure (experience).
Moreover, these two engineered features also ranked high on the feature importance:
stars (high happiness & workload), and
overworked (low happiness & high workload).
Interesting, but not entirely surprising. The stars might have left for better opportunities while the overworked left after burning out.
An executable version of this model (.pkl) can be saved from the Jupyter notebook.
with open('final_model.pkl', 'wb') as f: pickle.dump(fitted_models['rf'].best_estimator_, f)
HR could pre-process new employee data before feeding it into the trained model. This is called a batch-run.
In a large organisation, they might want to deploy the model into an production environment by engaging with data engineers and machine learning engineers. These specialists build an automated pipeline around our model, ensuring that fresh data can be pre-processed and predictions reported to HR on a regular basis.
We started with a business problem: HR in a large company wanted actionable insights on their employee churn.
We trained a winning random forest model on a big load of historical data comprising over 14,000 past and present employees.
HR can run new data on our trained .pkl file on a manual basis, or an automated pipeline could be built by their engineering department.
Our model was a binary classification model, where the target variable is categorical. It predicts a discrete number of possibilities — here, churn or no churn.
The other side of the coin for supervised learning are regression models, whose target variable is numerical. Over here, I trained one that predicts house prices.
Finally, I wrote a piece here on where machine learning sits in the field of mathematical modelling.
Differential Equations versus Machine Learning — here
Math Modelling versus Machine Learning for COVID-19 — here
Predict House Prices with Regression — here
Predict Employee Churn with Classification — here
Popular Machine Learning Performance Metrics — here
Jupyter Notebooks versus Dataiku DSS — here
Join here with my referral link. I will earn a small commission with no extra cost to you. Thanks for your support.
Get a permanent fee discount on the biggest exchanges:
FTX. Get 5% off trading fees (link)
Binance. Get 5% off trading fees (link)
Sign up below for a free deposit bonus:
Nexo. Get $25 free BTC with $100 deposit (link)
Celsius. Get $50 free BTC with $400 deposit (link)
Always wanted a Crypto.com Metal VISA debit card?
Get up to 8% cashbacks on daily shopping + free Spotify, Netflix, Amazon Prime, airport lounge access and more!
Register here and get $25 worth of CRO for free.
Use referral code ‘col’Complete registration & KYC on AppIn App, apply for a Ruby Steel card or aboveBuy and stake $400+ worth of CRO as required
Use referral code ‘col’
Complete registration & KYC on App
In App, apply for a Ruby Steel card or above
Buy and stake $400+ worth of CRO as required
Your shiny new Metal VISA card will arrive in the mail! Woohoo.
...and $25 worth of CRO is now instantly unlocked in your Crypto.com App.
Staking CRO provides a host of benefits, such as earning you 8.5% interest on BTC & ETH holdings and 14% on USDC stablecoins!
Thanks for reading! | [
{
"code": null,
"e": 612,
"s": 172,
"text": "It’s well-known in HR that recruiting new employees is substantially more expensive than retaining existing talent. Employees who depart take with them valuable experience and knowledge from your organisation. According to Forbes, the cost of an entry-level position turning over is estimated at 50% of that employee’s salary. For mid-level employees, it’s estimated at 125% of salary, and for senior executives, a whopping 200% of salary."
},
{
"code": null,
"e": 811,
"s": 612,
"text": "We’ll train some machine learning models in a Jupyter notebook using data about an employee’s position, happiness, performance, workload and tenure to predict whether they’re going to stay or leave."
},
{
"code": null,
"e": 938,
"s": 811,
"text": "Our target variable’s categorical, hence the ML task is classification. (For a numerical target, the task becomes regression.)"
},
{
"code": null,
"e": 1077,
"s": 938,
"text": "We’ll use a dataset from elitedatascience.com that simulates a large company with 14,249 past and present employees. There are 10 columns."
},
{
"code": null,
"e": 1092,
"s": 1077,
"text": "The steps are:"
},
{
"code": null,
"e": 1554,
"s": 1092,
"text": "EDA & data-processing: explore, visualise and clean the data.Feature engineering: leverage domain expertise and create new features.Model training: we’ll train and tune some tried-and-true classification algorithms, such as logistic regression, random forests and gradient-boosted trees.Performance evaluation: we’ll look at a range of scores including F1 and AUROC.Deployment: batch-run or get some data engineers / ML engineers to build an automated pipeline?"
},
{
"code": null,
"e": 1616,
"s": 1554,
"text": "EDA & data-processing: explore, visualise and clean the data."
},
{
"code": null,
"e": 1688,
"s": 1616,
"text": "Feature engineering: leverage domain expertise and create new features."
},
{
"code": null,
"e": 1844,
"s": 1688,
"text": "Model training: we’ll train and tune some tried-and-true classification algorithms, such as logistic regression, random forests and gradient-boosted trees."
},
{
"code": null,
"e": 1924,
"s": 1844,
"text": "Performance evaluation: we’ll look at a range of scores including F1 and AUROC."
},
{
"code": null,
"e": 2020,
"s": 1924,
"text": "Deployment: batch-run or get some data engineers / ML engineers to build an automated pipeline?"
},
{
"code": null,
"e": 2203,
"s": 2020,
"text": "Ideally, the company will run the model on their current permanent employees to identify those at-risk. This is an example of machine learning providing actionable business insights."
},
{
"code": null,
"e": 2533,
"s": 2203,
"text": "Exploratory data analysis (EDA) helps us understand the data and provides ideas and insights for data cleaning and feature engineering. Data cleaning prepares the data for our algorithms while feature engineering is the magic sauce that will really help our algorithms draw out the underlying patterns from the dataset. Remember:"
},
{
"code": null,
"e": 2578,
"s": 2533,
"text": "Better data always beats fancier algorithms!"
},
{
"code": null,
"e": 2658,
"s": 2578,
"text": "We start by loading some standard data science Python packages into JupyterLab."
},
{
"code": null,
"e": 3231,
"s": 2658,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sbfrom sklearn.linear_model import LogisticRegressionfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import GridSearchCVfrom sklearn.metrics import confusion_matrix, accuracy_score, f1_score, roc_curve, roc_auc_scoreimport pickle"
},
{
"code": null,
"e": 3251,
"s": 3231,
"text": "Import the dataset:"
},
{
"code": null,
"e": 3289,
"s": 3251,
"text": "df = pd.read_csv('employee_data.csv')"
},
{
"code": null,
"e": 3358,
"s": 3289,
"text": "Here’s a snapshot of our dataframe again. The shape is (14,249, 10)."
},
{
"code": null,
"e": 3449,
"s": 3358,
"text": "The target variable is status. This categorical variable takes the value Employed or Left."
},
{
"code": null,
"e": 3480,
"s": 3449,
"text": "There are 25 columns/features:"
},
{
"code": null,
"e": 3491,
"s": 3480,
"text": "department"
},
{
"code": null,
"e": 3498,
"s": 3491,
"text": "salary"
},
{
"code": null,
"e": 3552,
"s": 3498,
"text": "satisfaction, filed_complaint — proxies for happiness"
},
{
"code": null,
"e": 3613,
"s": 3552,
"text": "last_evaluation, recently_promoted — proxies for performance"
},
{
"code": null,
"e": 3664,
"s": 3613,
"text": "avg_monthly_hrs, n_projects — proxies for workload"
},
{
"code": null,
"e": 3694,
"s": 3664,
"text": "tenure — proxy for experience"
},
{
"code": null,
"e": 3790,
"s": 3694,
"text": "Let’s plot some quick histograms to get an idea of the distributions of our numerical features."
},
{
"code": null,
"e": 3825,
"s": 3790,
"text": "df.hist(figsize=(10,10), xrot=-45)"
},
{
"code": null,
"e": 3919,
"s": 3825,
"text": "Things to do to our numerical features to ensure the data will play nice with our algorithms:"
},
{
"code": null,
"e": 4016,
"s": 3919,
"text": "Convert the NaN’s in filed_complaint and recently_promoted to 0. They were incorrectly labelled."
},
{
"code": null,
"e": 4135,
"s": 4016,
"text": "Create an indicator variable for the missing data in the last_evaluation feature, before converting the NaN’s to zero."
},
{
"code": null,
"e": 4343,
"s": 4135,
"text": "df.filed_complaint.fillna(0, inplace=True)df.recently_promoted.fillna(0, inplace=True)df['last_evaluation_missing'] = df.last_evaluation.isnull().astype(int)df.last_evaluation.fillna(0, inplace=True)"
},
{
"code": null,
"e": 4401,
"s": 4343,
"text": "Here is a correlation heatmap for our numerical features."
},
{
"code": null,
"e": 4467,
"s": 4401,
"text": "sb.heatmap(df.corr(), annot=True, cmap=’RdBu_r’, vmin=-1, vmax=1)"
},
{
"code": null,
"e": 4556,
"s": 4467,
"text": "Let’s plot some quick bar plots for our categorical features. Seaborn is great for this."
},
{
"code": null,
"e": 4659,
"s": 4556,
"text": "for feature in df.dtypes[df.dtypes=='object'].index: sb.countplot(data=df, y='{}'.format(features))"
},
{
"code": null,
"e": 5051,
"s": 4659,
"text": "The biggest department is sales. Only a small proportion of employees are in the high salary bracket. And our dataset is imbalanced in that only a minority of employees have left the company, i.e. only a small proportion of our employees have status = Left. This has ramifications for the metrics we choose to evaluate our algorithms’ performances. We’ll talk more about this in the Results."
},
{
"code": null,
"e": 5183,
"s": 5051,
"text": "From a data-cleaning point of view, the IT and information_technology classes for the department feature should be merged together:"
},
{
"code": null,
"e": 5251,
"s": 5183,
"text": "df.department.replace('information_technology', 'IT', inplace=True)"
},
{
"code": null,
"e": 5347,
"s": 5251,
"text": "Moreover, HR only cares about permanent employees, so we should filter out the temp department:"
},
{
"code": null,
"e": 5380,
"s": 5347,
"text": "df = df[df.department != 'temp']"
},
{
"code": null,
"e": 5436,
"s": 5380,
"text": "Thus our department feature should look more like this:"
},
{
"code": null,
"e": 5532,
"s": 5436,
"text": "Things to do to our categorical features to ensure the data will play nice with our algorithms:"
},
{
"code": null,
"e": 5617,
"s": 5532,
"text": "Missing data for the department feature should be lumped into its own Missing class."
},
{
"code": null,
"e": 5696,
"s": 5617,
"text": "The department and salary categorical features should also be one-hot encoded."
},
{
"code": null,
"e": 5754,
"s": 5696,
"text": "The target variable status should be converted to binary."
},
{
"code": null,
"e": 5905,
"s": 5754,
"text": "df['department'].fillna('Missing', inplace=True)df = pd.get_dummies(df, columns=['department', 'salary'])df['status'] = pd.get_dummies(df.status).Left"
},
{
"code": null,
"e": 6045,
"s": 5905,
"text": "We can draw further insights by segmenting numerical features against categorical ones. Let’s start off with some univariate segmentations."
},
{
"code": null,
"e": 6205,
"s": 6045,
"text": "Specifically, we’re going to segment numerical features representing happiness, performance, workload and experience by our categorical target variable status."
},
{
"code": null,
"e": 6237,
"s": 6205,
"text": "Segment satisfaction by status:"
},
{
"code": null,
"e": 6290,
"s": 6237,
"text": "sb.violinplot(y='status', x='satisfaction', data=df)"
},
{
"code": null,
"e": 6376,
"s": 6290,
"text": "An insight is that a number of churned employees were very satisfied with their jobs."
},
{
"code": null,
"e": 6408,
"s": 6376,
"text": "Segment last_evaluation status:"
},
{
"code": null,
"e": 6464,
"s": 6408,
"text": "sb.violinplot(y='status', x='last_evaluation', data=df)"
},
{
"code": null,
"e": 6602,
"s": 6464,
"text": "An insight is a large number of churned employees were high performers. Perhaps they felt no further opportunities for growth by staying?"
},
{
"code": null,
"e": 6652,
"s": 6602,
"text": "Segment avg_monthly_hrs and n_projects by status:"
},
{
"code": null,
"e": 6758,
"s": 6652,
"text": "sb.violinplot(y='status', x='avg_monthly_hrs', data=df)sb.violinplot(y='status', x='n_projects', data=df)"
},
{
"code": null,
"e": 6931,
"s": 6758,
"text": "It appears that those who have churned tended to either have a fairly large workload or a fairly low workload. Do these represent burnt out and disengaged former employees?"
},
{
"code": null,
"e": 6957,
"s": 6931,
"text": "Segment tenure by status:"
},
{
"code": null,
"e": 7004,
"s": 6957,
"text": "sb.violinplot(y='status', x='tenure', data=df)"
},
{
"code": null,
"e": 7117,
"s": 7004,
"text": "We note that employee churn suddenly during the 3rd year. Those who are still around after 6 years tend to stay."
},
{
"code": null,
"e": 7218,
"s": 7117,
"text": "Check out the following bivariate segmentations that will motivate our feature engineering later on."
},
{
"code": null,
"e": 7416,
"s": 7218,
"text": "For each plot, we’re going to segment two numerical features (representing happiness, performance, workload or experience) by status. This might give us some clusters based on employee stereotypes."
},
{
"code": null,
"e": 7443,
"s": 7416,
"text": "Performance and happiness:"
},
{
"code": null,
"e": 7599,
"s": 7443,
"text": "Whoops, the Employed workers make this graph hard to read. Let’s just display the Left workers only, as they’re the ones we’re really trying to understand."
},
{
"code": null,
"e": 7727,
"s": 7599,
"text": "sb.lmplot(x='satisfaction', y='last_evaluation', data=df[df.status=='Left'], fit_reg=False )"
},
{
"code": null,
"e": 7772,
"s": 7727,
"text": "We have three clusters of churned employees:"
},
{
"code": null,
"e": 7811,
"s": 7772,
"text": "Underperformers: last_evaluation < 0.6"
},
{
"code": null,
"e": 7845,
"s": 7811,
"text": "Unhappy: satisfaction_level < 0.2"
},
{
"code": null,
"e": 7905,
"s": 7845,
"text": "Overachievers: last_evaluation > 0.8 and satisfaction > 0.7"
},
{
"code": null,
"e": 7931,
"s": 7905,
"text": "Workload and performance:"
},
{
"code": null,
"e": 8062,
"s": 7931,
"text": "sb.lmplot(x='last_evaluation', y='avg_monthly_hrs', data=df[df.status=='Left'], fit_reg=False )"
},
{
"code": null,
"e": 8105,
"s": 8062,
"text": "We have two clusters of churned employees:"
},
{
"code": null,
"e": 8161,
"s": 8105,
"text": "Stars: avg_monthly_hrs > 215 and last_evaluation > 0.75"
},
{
"code": null,
"e": 8220,
"s": 8161,
"text": "Slackers: avg_monthly_hrs < 165 and last_evaluation < 0.65"
},
{
"code": null,
"e": 8244,
"s": 8220,
"text": "Workload and happiness:"
},
{
"code": null,
"e": 8373,
"s": 8244,
"text": "sb.lmplot(x='satisfaction', y='avg_monthly_hrs', data=df[df.status=='Left'], fit_reg=False, )"
},
{
"code": null,
"e": 8418,
"s": 8373,
"text": "We have three clusters of churned employees:"
},
{
"code": null,
"e": 8475,
"s": 8418,
"text": "Workaholics: avg_monthly_hrs > 210 and satisfation > 0.7"
},
{
"code": null,
"e": 8509,
"s": 8475,
"text": "Just-a-job: avg_monthly_hrs < 170"
},
{
"code": null,
"e": 8566,
"s": 8509,
"text": "Overworked: avg_monthly_hrs > 225 and satisfaction < 0.2"
},
{
"code": null,
"e": 8645,
"s": 8566,
"text": "Let’s engineer new features for these 8 ‘stereotypical’ clusters of employees:"
},
{
"code": null,
"e": 9311,
"s": 8645,
"text": "df['underperformer'] = ((df.last_evaluation < 0.6) & (df.last_evaluation_missing==0)).astype(int)df['unhappy'] = (df.satisfaction < 0.2).astype(int)df['overachiever'] = ((df.last_evaluation > 0.8) & (df.satisfaction > 0.7)).astype(int)df['stars'] = ((df.avg_monthly_hrs > 215) & (df.last_evaluation > 0.75)).astype(int)df['slackers'] = ((df.avg_monthly_hrs < 165) & (df.last_evaluation < 0.65) & (df.last_evaluation_missing==0)).astype(int)df['workaholic'] = ((df.avg_monthly_hrs > 210) & (df.satisfaction > 0.7)).astype(int)df['justajob'] = (df.avg_monthly_hrs < 170).astype(int)df['overworked'] = ((df.avg_monthly_hrs > 225) & (df.satisfaction < 0.2)).astype(int)"
},
{
"code": null,
"e": 9390,
"s": 9311,
"text": "We can take a glance at the proportion of employees in each of these 8 groups."
},
{
"code": null,
"e": 9720,
"s": 9390,
"text": "df[['underperformer', 'unhappy', 'overachiever', 'stars', 'slackers', 'workaholic', 'justajob', 'overworked']].mean()underperformer 0.285257unhappy 0.092195overachiever 0.177069stars 0.241825slackers 0.167686workaholic 0.226685justajob 0.339281overworked 0.071581"
},
{
"code": null,
"e": 9858,
"s": 9720,
"text": "34% of employees are just-a-job employees — non-inspired and just here for the weekly pay cheque — while only 7% are flat out overworked."
},
{
"code": null,
"e": 10042,
"s": 9858,
"text": "Analytical base table: The dataset after applying all of these data cleaning steps and feature engineering is our analytical base table. This is the data on which we train our models."
},
{
"code": null,
"e": 10183,
"s": 10042,
"text": "Our ABT has 14,068 employees and 31 columns — see below for a snippet. Recall our original dataset had 14,249 employees and just 10 columns!"
},
{
"code": null,
"e": 10247,
"s": 10183,
"text": "We’re going to train four tried-and-true classification models:"
},
{
"code": null,
"e": 10292,
"s": 10247,
"text": "logistic regressions (L1 and L2-regularised)"
},
{
"code": null,
"e": 10307,
"s": 10292,
"text": "random forests"
},
{
"code": null,
"e": 10330,
"s": 10307,
"text": "gradient-boosted trees"
},
{
"code": null,
"e": 10376,
"s": 10330,
"text": "First, let’s split our analytical base table."
},
{
"code": null,
"e": 10419,
"s": 10376,
"text": "y = df.statusX = df.drop('status', axis=1)"
},
{
"code": null,
"e": 10547,
"s": 10419,
"text": "We’ll then split into training and test sets. Our dataset is mildly imbalanced, so we’ll use stratified sampling to compensate."
},
{
"code": null,
"e": 10659,
"s": 10547,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234, stratify=df.status)"
},
{
"code": null,
"e": 10749,
"s": 10659,
"text": "We’ll set up a pipeline object to train. This will streamline our model training process."
},
{
"code": null,
"e": 11163,
"s": 10749,
"text": "pipelines = { 'l1': make_pipeline(StandardScaler(), LogisticRegression(penalty='l1', random_state=123)), 'l2': make_pipeline(StandardScaler(), LogisticRegression(penalty='l2', random_state=123)), 'rf': make_pipeline( RandomForestClassifier(random_state=123)), 'gb': make_pipeline( GradientBoostingClassifier(random_state=123)) }"
},
{
"code": null,
"e": 11325,
"s": 11163,
"text": "We also want to tune the hyperparameters for each algorithm. For logistic regression, the most impactful hyperparameter is the strength of the regularisation, C."
},
{
"code": null,
"e": 11668,
"s": 11325,
"text": "l1_hyperparameters = {'logisticregression__C' : [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 50, 100, 500, 1000] }l2_hyperparameters = {'logisticregression__C' : [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 50, 100, 500, 1000] }"
},
{
"code": null,
"e": 11876,
"s": 11668,
"text": "For our random forest, we’ll tune the number of estimators (n_estimators), the max number of features to consider during a split (max_features), and the min number of samples to be a leaf (min_samples_leaf)."
},
{
"code": null,
"e": 12090,
"s": 11876,
"text": "rf_hyperparameters = { 'randomforestclassifier__n_estimators' : [100, 200], 'randomforestclassifier__max_features' : ['auto', 'sqrt', 0.33], 'randomforestclassifier__min_samples_leaf' : [1, 3, 5, 10] }"
},
{
"code": null,
"e": 12236,
"s": 12090,
"text": "For our gradient-boosted tree, we’ll tune the number of estimators (n_estimators), learning rate, and the maximum depth of each tree (max_depth)."
},
{
"code": null,
"e": 12446,
"s": 12236,
"text": "gb_hyperparameters = { 'gradientboostingclassifier__n_estimators' : [100, 200], 'gradientboostingclassifier__learning_rate' : [0.05, 0.1, 0.2], 'gradientboostingclassifier__max_depth' : [1, 3, 5] }"
},
{
"code": null,
"e": 12496,
"s": 12446,
"text": "We’ll save these hyperparameters in a dictionary."
},
{
"code": null,
"e": 12640,
"s": 12496,
"text": "hyperparameters = { 'l1' : l1_hyperparameters, 'l2' : l2_hyperparameters, 'rf' : rf_hyperparameters, 'gb' : gb_hyperparameters }"
},
{
"code": null,
"e": 12824,
"s": 12640,
"text": "Finally, we’ll fit and tune our models. Using GridSearchCV we can train all of these models with cross-validation on all of our declared hyperparameters with just a few lines of code!"
},
{
"code": null,
"e": 13095,
"s": 12824,
"text": "fitted_models = {}for name, pipeline in pipelines.items(): model = GridSearchCV(pipeline, hyperparameters[name], cv=10, n_jobs=-1) model.fit(X_train, y_train) fitted_models[name] = model"
},
{
"code": null,
"e": 13196,
"s": 13095,
"text": "I’ve written a dedicated article on popular machine learning metrics, including the ones used below."
},
{
"code": null,
"e": 13406,
"s": 13196,
"text": "We’ll start by printing the cross-validation scores. This is the average performance across the 10 hold-out folds and is a way to get a reliable estimate of the model performance using only your training data."
},
{
"code": null,
"e": 13572,
"s": 13406,
"text": "for name, model in fitted_models.items(): print(name, model.best_score_)Output:l1 0.9088324151412831l2 0.9088324151412831rf 0.9793851075173272gb 0.975475386529234"
},
{
"code": null,
"e": 13606,
"s": 13572,
"text": "Moving onto the test data, we’ll:"
},
{
"code": null,
"e": 13626,
"s": 13606,
"text": "calculate accuracy;"
},
{
"code": null,
"e": 13699,
"s": 13626,
"text": "print the confusion matrix and calculate precision, recall and F1-score;"
},
{
"code": null,
"e": 13746,
"s": 13699,
"text": "display the ROC and calculate the AUROC score."
},
{
"code": null,
"e": 14707,
"s": 13746,
"text": "Accuracy measures the proportion of correctly labelled predictions, however it is an inappropriate metric for imbalanced datasets, e.g. email spam filtration (spam vs. not spam) and medical testing (sick vs. not sick). For instance, if our dataset only had 1% of employees satisfying target=Left, then a model that always predicts the employee is still working at the company would instantly score 99% accuracy. In these situations, precision or recall is more appropriate. Whichever you use often depends on whether you want to minimise Type 1 errors (False Positives) or Type 2 errors (False Negatives). For spam emails, Type 1 errors are worse (some spam is OK as long as you don’t accidentally filter out an important email!) while Type 2 errors are unacceptable for medical testing (telling someone they didn’t have cancer when they did is a disaster!). The F1-score gets you the best of both worlds by taking the weighted average of precision and recall."
},
{
"code": null,
"e": 14981,
"s": 14707,
"text": "The area under the ROC, known as the AUROC is another standard metric for classification problems. It’s an effective measurement of a classifier’s ability to distinguish between classes and separate signal from noise. This metric is also robust against imbalanced datasets."
},
{
"code": null,
"e": 15034,
"s": 14981,
"text": "Here is the code to generate these scores and plots:"
},
{
"code": null,
"e": 16138,
"s": 15034,
"text": "for name, model in fitted_models.items(): print('Results for:', name) # obtain predictions pred = fitted_models[name].predict(X_test) # confusion matrix cm = confusion_matrix(y_test, pred) print(cm) # accuracy score print('Accuracy:', accuracy_score(y_test, pred)) # precision precision = cm[1][1]/(cm[0][1]+cm[1][1]) print('Precision:', precision) # recall recall = cm[1][1]/(cm[1][0]+cm[1][1]) print('Recall:', recall) # F1_score print('F1:', f1_score(y_test, pred)) # obtain prediction probabilities pred = fitted_models[name].predict_proba(X_test) pred = [p[1] for p in pred] # plot ROC fpr, tpr, thresholds = roc_curve(y_test, pred) plt.title('Receiver Operating Characteristic (ROC)') plt.plot(fpr, tpr, label=name) plt.legend(loc='lower right') plt.plot([0,1],[0,1],'k--') plt.xlim([-0.1,1.1]) plt.ylim([-0.1,1.1]) plt.ylabel('True Positive Rate (TPR) i.e. Recall') plt.xlabel('False Positive Rate (FPR)') plt.show() # AUROC score print('AUROC:', roc_auc_score(y_test, pred))"
},
{
"code": null,
"e": 16176,
"s": 16138,
"text": "Logistic regression (L1-regularised):"
},
{
"code": null,
"e": 16354,
"s": 16176,
"text": "Output:[[2015 126] [ 111 562]]Accuracy: 0.9157782515991472Precision: 0.8168604651162791Recall: 0.8350668647845468F1: 0.8258633357825129AUROC: 0.9423905869485105"
},
{
"code": null,
"e": 16392,
"s": 16354,
"text": "Logistic regression (L2-regularised):"
},
{
"code": null,
"e": 16569,
"s": 16392,
"text": "Output:[[2014 127] [ 110 563]]Accuracy: 0.9157782515991472Precision: 0.8159420289855073Recall: 0.836552748885587F1: 0.8261188554658841AUROC: 0.9423246556128734"
},
{
"code": null,
"e": 16592,
"s": 16569,
"text": "Gradient-boosted tree:"
},
{
"code": null,
"e": 16770,
"s": 16592,
"text": "Output:[[2120 21] [ 48 625]]Accuracy: 0.9754797441364605Precision: 0.9674922600619195Recall: 0.9286775631500743F1: 0.9476876421531464AUROC: 0.9883547910913578"
},
{
"code": null,
"e": 16785,
"s": 16770,
"text": "Random forest:"
},
{
"code": null,
"e": 16952,
"s": 16785,
"text": "Output:[[2129 12] [ 45 628]]Accuracy: 0.9797441364605544Precision: 0.98125Recall: 0.9331352154531947F1: 0.9565879664889566AUROC: 0.9916117990718256"
},
{
"code": null,
"e": 17140,
"s": 16952,
"text": "The winning algorithm is the random forest with an AUROC of 99% and a F1-score of 96%. This algorithm has a 99% chance of distinguishing between a Left and Employed worker... pretty good!"
},
{
"code": null,
"e": 17194,
"s": 17140,
"text": "Out of 2814 employees in the test set, the algorithm:"
},
{
"code": null,
"e": 17293,
"s": 17194,
"text": "correctly classified 628 Left workers (True Positives) while getting 12 wrong (Type I errors), and"
},
{
"code": null,
"e": 17394,
"s": 17293,
"text": "correctly classified 2129 Employed workers (True Negatives) while getting 45 wrong (Type II errors)."
},
{
"code": null,
"e": 17484,
"s": 17394,
"text": "FYI, here are the hyperparameters of the winning random forest, tuned using GridSearchCV."
},
{
"code": null,
"e": 18215,
"s": 17484,
"text": "RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features=0.33, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0, n_estimators=200, n_jobs=None, oob_score=False, random_state=123, verbose=0, warm_start=False )"
},
{
"code": null,
"e": 18244,
"s": 18215,
"text": "Consider the following code."
},
{
"code": null,
"e": 18619,
"s": 18244,
"text": "coef = winning_model.feature_importances_ind = np.argsort(-coef)for i in range(X_train.shape[1]): print(\"%d. %s (%f)\" % (i + 1, X.columns[ind[i]], coef[ind[i]]))x = range(X_train.shape[1])y = coef[ind][:X_train.shape[1]]plt.title(\"Feature importances\")ax = plt.subplot()plt.barh(x, y, color='red')ax.set_yticks(x)ax.set_yticklabels(X.columns[ind])plt.gca().invert_yaxis()"
},
{
"code": null,
"e": 18705,
"s": 18619,
"text": "This will print a list of features ranked by importance and a corresponding bar plot."
},
{
"code": null,
"e": 19600,
"s": 18705,
"text": "Ranking of feature importance:1. n_projects (0.201004)2. satisfaction (0.178810)3. tenure (0.169454)4. avg_monthly_hrs (0.091827)5. stars (0.074373)6. overworked (0.068334)7. last_evaluation (0.063630)8. slackers (0.028261)9. overachiever (0.027244)10. workaholic (0.018925)11. justajob (0.016831)12. unhappy (0.016486)13. underperformer (0.006015)14. last_evaluation_missing (0.005084)15. salary_low (0.004372)16. filed_complaint (0.004254)17. salary_high (0.003596)18. department_engineering (0.003429)19. department_sales (0.003158)20. salary_medium (0.003122)21. department_support (0.002655)22. department_IT (0.001628)23. department_finance (0.001389)24. department_management (0.001239)25. department_Missing (0.001168)26. department_marketing (0.001011)27. recently_promoted (0.000983)28. department_product (0.000851)29. department_admin (0.000568)30. department_procurement (0.000296)"
},
{
"code": null,
"e": 19667,
"s": 19600,
"text": "There are three particularly strong predictors for employee churn:"
},
{
"code": null,
"e": 19689,
"s": 19667,
"text": "n_projects (workload)"
},
{
"code": null,
"e": 19718,
"s": 19689,
"text": "satisfaction (happiness) and"
},
{
"code": null,
"e": 19739,
"s": 19718,
"text": "tenure (experience)."
},
{
"code": null,
"e": 19823,
"s": 19739,
"text": "Moreover, these two engineered features also ranked high on the feature importance:"
},
{
"code": null,
"e": 19862,
"s": 19823,
"text": "stars (high happiness & workload), and"
},
{
"code": null,
"e": 19906,
"s": 19862,
"text": "overworked (low happiness & high workload)."
},
{
"code": null,
"e": 20044,
"s": 19906,
"text": "Interesting, but not entirely surprising. The stars might have left for better opportunities while the overworked left after burning out."
},
{
"code": null,
"e": 20127,
"s": 20044,
"text": "An executable version of this model (.pkl) can be saved from the Jupyter notebook."
},
{
"code": null,
"e": 20223,
"s": 20127,
"text": "with open('final_model.pkl', 'wb') as f: pickle.dump(fitted_models['rf'].best_estimator_, f)"
},
{
"code": null,
"e": 20332,
"s": 20223,
"text": "HR could pre-process new employee data before feeding it into the trained model. This is called a batch-run."
},
{
"code": null,
"e": 20649,
"s": 20332,
"text": "In a large organisation, they might want to deploy the model into an production environment by engaging with data engineers and machine learning engineers. These specialists build an automated pipeline around our model, ensuring that fresh data can be pre-processed and predictions reported to HR on a regular basis."
},
{
"code": null,
"e": 20759,
"s": 20649,
"text": "We started with a business problem: HR in a large company wanted actionable insights on their employee churn."
},
{
"code": null,
"e": 20884,
"s": 20759,
"text": "We trained a winning random forest model on a big load of historical data comprising over 14,000 past and present employees."
},
{
"code": null,
"e": 21021,
"s": 20884,
"text": "HR can run new data on our trained .pkl file on a manual basis, or an automated pipeline could be built by their engineering department."
},
{
"code": null,
"e": 21182,
"s": 21021,
"text": "Our model was a binary classification model, where the target variable is categorical. It predicts a discrete number of possibilities — here, churn or no churn."
},
{
"code": null,
"e": 21345,
"s": 21182,
"text": "The other side of the coin for supervised learning are regression models, whose target variable is numerical. Over here, I trained one that predicts house prices."
},
{
"code": null,
"e": 21446,
"s": 21345,
"text": "Finally, I wrote a piece here on where machine learning sits in the field of mathematical modelling."
},
{
"code": null,
"e": 21500,
"s": 21446,
"text": "Differential Equations versus Machine Learning — here"
},
{
"code": null,
"e": 21559,
"s": 21500,
"text": "Math Modelling versus Machine Learning for COVID-19 — here"
},
{
"code": null,
"e": 21603,
"s": 21559,
"text": "Predict House Prices with Regression — here"
},
{
"code": null,
"e": 21653,
"s": 21603,
"text": "Predict Employee Churn with Classification — here"
},
{
"code": null,
"e": 21705,
"s": 21653,
"text": "Popular Machine Learning Performance Metrics — here"
},
{
"code": null,
"e": 21749,
"s": 21705,
"text": "Jupyter Notebooks versus Dataiku DSS — here"
},
{
"code": null,
"e": 21865,
"s": 21749,
"text": "Join here with my referral link. I will earn a small commission with no extra cost to you. Thanks for your support."
},
{
"code": null,
"e": 21920,
"s": 21865,
"text": "Get a permanent fee discount on the biggest exchanges:"
},
{
"code": null,
"e": 21956,
"s": 21920,
"text": "FTX. Get 5% off trading fees (link)"
},
{
"code": null,
"e": 21996,
"s": 21956,
"text": "Binance. Get 5% off trading fees (link)"
},
{
"code": null,
"e": 22036,
"s": 21996,
"text": "Sign up below for a free deposit bonus:"
},
{
"code": null,
"e": 22084,
"s": 22036,
"text": "Nexo. Get $25 free BTC with $100 deposit (link)"
},
{
"code": null,
"e": 22135,
"s": 22084,
"text": "Celsius. Get $50 free BTC with $400 deposit (link)"
},
{
"code": null,
"e": 22185,
"s": 22135,
"text": "Always wanted a Crypto.com Metal VISA debit card?"
},
{
"code": null,
"e": 22297,
"s": 22185,
"text": "Get up to 8% cashbacks on daily shopping + free Spotify, Netflix, Amazon Prime, airport lounge access and more!"
},
{
"code": null,
"e": 22346,
"s": 22297,
"text": "Register here and get $25 worth of CRO for free."
},
{
"code": null,
"e": 22492,
"s": 22346,
"text": "Use referral code ‘col’Complete registration & KYC on AppIn App, apply for a Ruby Steel card or aboveBuy and stake $400+ worth of CRO as required"
},
{
"code": null,
"e": 22516,
"s": 22492,
"text": "Use referral code ‘col’"
},
{
"code": null,
"e": 22551,
"s": 22516,
"text": "Complete registration & KYC on App"
},
{
"code": null,
"e": 22596,
"s": 22551,
"text": "In App, apply for a Ruby Steel card or above"
},
{
"code": null,
"e": 22641,
"s": 22596,
"text": "Buy and stake $400+ worth of CRO as required"
},
{
"code": null,
"e": 22705,
"s": 22641,
"text": "Your shiny new Metal VISA card will arrive in the mail! Woohoo."
},
{
"code": null,
"e": 22779,
"s": 22705,
"text": "...and $25 worth of CRO is now instantly unlocked in your Crypto.com App."
},
{
"code": null,
"e": 22905,
"s": 22779,
"text": "Staking CRO provides a host of benefits, such as earning you 8.5% interest on BTC & ETH holdings and 14% on USDC stablecoins!"
}
]
|
How to pass a variable into a jQuery attribute-contains selector? | Yes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.
You can try to run the following code to learn how to pass a variable into a jQuery attribute-contains selector:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function() {
var testString = "vp-485858383";
$('[data-vp*="id: ' + testString + '"]').css('color', 'blue');
});
</script>
</head>
<body>
<div data-vp='{
id: vp-485858383,
customTwo: "test"
}'>
Hello World
</div>
</body>
</html> | [
{
"code": null,
"e": 1266,
"s": 1062,
"text": "Yes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string."
},
{
"code": null,
"e": 1379,
"s": 1266,
"text": "You can try to run the following code to learn how to pass a variable into a jQuery attribute-contains selector:"
},
{
"code": null,
"e": 1389,
"s": 1379,
"text": "Live Demo"
},
{
"code": null,
"e": 1760,
"s": 1389,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(function() {\n var testString = \"vp-485858383\";\n $('[data-vp*=\"id: ' + testString + '\"]').css('color', 'blue');\n});\n</script>\n</head>\n\n<body>\n<div data-vp='{\n id: vp-485858383,\n customTwo: \"test\"\n}'>\nHello World\n</div>\n</body>\n</html>"
}
]
|
How to find the most frequent factor value in an R data frame column? | To find the most frequent factor value in an R data frame column, we can use names function with which.max function after creating the table for the particular column. This might be required while doing factorial analysis and we want to know which factor occurs the most.
Check out the below examples to understand how it can be done.
Following snippet creates a sample data frame −
Factor_1<-factor(sample(LETTERS[1:4],20,replace=TRUE))
df1<-data.frame(Factor_1)
df1
The following dataframe is created −
Factor_1
1 B
2 D
3 B
4 D
5 C
6 D
7 D
8 C
9 C
10 C
11 C
12 C
13 C
14 C
15 A
16 D
17 C
18 C
19 B
20 C
To find which factor occurs the most in df1, add the following code to the above snippet −
Factor_1<-factor(sample(LETTERS[1:4],20,replace=TRUE))
df1<-data.frame(Factor_1)
names(which.max(table(df1$Factor_1)))
If you execute all the above given snippets as a single program, it generates the following output: −
[1] "C"
Following snippet creates a sample data frame −
Factor_2<-factor(sample(c("Male","Female"),20,replace=TRUE))
df2<-data.frame(Factor_2)
df2
The following dataframe is created −
Factor_2
1 Female
2 Female
3 Male
4 Female
5 Male
6 Male
7 Female
8 Male
9 Male
10 Female
11 Female
12 Female
13 Female
14 Male
15 Female
16 Female
17 Female
18 Female
19 Female
20 Female
To find which factor occurs the most in df2, add the following code to the above snippet −
Factor_2<-factor(sample(c("Male","Female"),20,replace=TRUE))
df2<-data.frame(Factor_2)
names(which.max(table(df2$Factor_2)))
If you execute all the above given snippets as a single program, it generates the following output: −
[1] "Female"
Following snippet creates a sample data frame −
Factor_3<-factor(sample(c("Hot","Cold","Warm","Lukewarm"),20,replace=TRUE))
df3<-data.frame(Factor_3)
df3
The following dataframe is created −
Factor_3
1 Hot
2 Lukewarm
3 Warm
4 Warm
5 Cold
6 Hot
7 Hot
8 Warm
9 Warm
10 Warm
11 Hot
12 Lukewarm
13 Cold
14 Lukewarm
15 Lukewarm
16 Lukewarm
17 Hot
18 Lukewarm
19 Lukewarm
20 Lukewarm
To find which factor occurs the most in df3, add the following code to the above snippet −
Factor_3<-factor(sample(c("Hot","Cold","Warm","Lukewarm"),20,replace=TRUE))
df3<-data.frame(Factor_3)
names(which.max(table(df3$Factor_3)))
If you execute all the above given snippets as a single program, it generates the following output: −
[1] "Lukewarm" | [
{
"code": null,
"e": 1334,
"s": 1062,
"text": "To find the most frequent factor value in an R data frame column, we can use names function with which.max function after creating the table for the particular column. This might be required while doing factorial analysis and we want to know which factor occurs the most."
},
{
"code": null,
"e": 1397,
"s": 1334,
"text": "Check out the below examples to understand how it can be done."
},
{
"code": null,
"e": 1445,
"s": 1397,
"text": "Following snippet creates a sample data frame −"
},
{
"code": null,
"e": 1530,
"s": 1445,
"text": "Factor_1<-factor(sample(LETTERS[1:4],20,replace=TRUE))\ndf1<-data.frame(Factor_1)\ndf1"
},
{
"code": null,
"e": 1567,
"s": 1530,
"text": "The following dataframe is created −"
},
{
"code": null,
"e": 1677,
"s": 1567,
"text": " Factor_1\n1 B\n2 D\n3 B\n4 D\n5 C\n6 D\n7 D\n8 C\n9 C\n10 C\n11 C\n12 C\n13 C\n14 C\n15 A\n16 D\n17 C\n18 C\n19 B\n20 C"
},
{
"code": null,
"e": 1768,
"s": 1677,
"text": "To find which factor occurs the most in df1, add the following code to the above snippet −"
},
{
"code": null,
"e": 1887,
"s": 1768,
"text": "Factor_1<-factor(sample(LETTERS[1:4],20,replace=TRUE))\ndf1<-data.frame(Factor_1)\nnames(which.max(table(df1$Factor_1)))"
},
{
"code": null,
"e": 1989,
"s": 1887,
"text": "If you execute all the above given snippets as a single program, it generates the following output: −"
},
{
"code": null,
"e": 1998,
"s": 1989,
"text": "[1] \"C\"\n"
},
{
"code": null,
"e": 2046,
"s": 1998,
"text": "Following snippet creates a sample data frame −"
},
{
"code": null,
"e": 2137,
"s": 2046,
"text": "Factor_2<-factor(sample(c(\"Male\",\"Female\"),20,replace=TRUE))\ndf2<-data.frame(Factor_2)\ndf2"
},
{
"code": null,
"e": 2174,
"s": 2137,
"text": "The following dataframe is created −"
},
{
"code": null,
"e": 2374,
"s": 2174,
"text": " Factor_2\n1 Female\n2 Female\n3 Male\n4 Female\n5 Male\n6 Male\n7 Female\n8 Male\n9 Male\n10 Female\n11 Female\n12 Female\n13 Female\n14 Male\n15 Female\n16 Female\n17 Female\n18 Female\n19 Female\n20 Female"
},
{
"code": null,
"e": 2465,
"s": 2374,
"text": "To find which factor occurs the most in df2, add the following code to the above snippet −"
},
{
"code": null,
"e": 2590,
"s": 2465,
"text": "Factor_2<-factor(sample(c(\"Male\",\"Female\"),20,replace=TRUE))\ndf2<-data.frame(Factor_2)\nnames(which.max(table(df2$Factor_2)))"
},
{
"code": null,
"e": 2692,
"s": 2590,
"text": "If you execute all the above given snippets as a single program, it generates the following output: −"
},
{
"code": null,
"e": 2706,
"s": 2692,
"text": "[1] \"Female\"\n"
},
{
"code": null,
"e": 2754,
"s": 2706,
"text": "Following snippet creates a sample data frame −"
},
{
"code": null,
"e": 2860,
"s": 2754,
"text": "Factor_3<-factor(sample(c(\"Hot\",\"Cold\",\"Warm\",\"Lukewarm\"),20,replace=TRUE))\ndf3<-data.frame(Factor_3)\ndf3"
},
{
"code": null,
"e": 2897,
"s": 2860,
"text": "The following dataframe is created −"
},
{
"code": null,
"e": 3096,
"s": 2897,
"text": " Factor_3\n1 Hot\n2 Lukewarm\n3 Warm\n4 Warm\n5 Cold\n6 Hot\n7 Hot\n8 Warm\n9 Warm\n10 Warm\n11 Hot\n12 Lukewarm\n13 Cold\n14 Lukewarm\n15 Lukewarm\n16 Lukewarm\n17 Hot\n18 Lukewarm\n19 Lukewarm\n20 Lukewarm"
},
{
"code": null,
"e": 3187,
"s": 3096,
"text": "To find which factor occurs the most in df3, add the following code to the above snippet −"
},
{
"code": null,
"e": 3327,
"s": 3187,
"text": "Factor_3<-factor(sample(c(\"Hot\",\"Cold\",\"Warm\",\"Lukewarm\"),20,replace=TRUE))\ndf3<-data.frame(Factor_3)\nnames(which.max(table(df3$Factor_3)))"
},
{
"code": null,
"e": 3429,
"s": 3327,
"text": "If you execute all the above given snippets as a single program, it generates the following output: −"
},
{
"code": null,
"e": 3445,
"s": 3429,
"text": "[1] \"Lukewarm\"\n"
}
]
|
Difference between HashMap and ConcurrentHashMap - GeeksforGeeks | 06 Aug, 2019
HashMap is the Class which is under Traditional Collection and ConcurrentHashMap is a Class which is under Concurrent Collections, apart from this there are various differences between them which are:
HashMap is non-Synchronized in nature i.e. HashMap is not Thread-safe whereas ConcurrentHashMap is Thread-safe in nature.
HashMap performance is relatively high because it is non-synchronized in nature and any number of threads can perform simultaneously. But ConcurrentHashMap performance is low sometimes because sometimes Threads are required to wait on ConcurrentHashMap.
While one thread is Iterating the HashMap object, if other thread try to add/modify the contents of Object then we will get Run-time exception saying ConcurrentModificationException.Whereas In ConcurrentHashMap we wont get any exception while performing any modification at the time of Iteration.Using HashMap// Java program to illustrate// HashMap drawbacksimport java.util.HashMap; class HashMapDemo extends Thread{ static HashMap<Integer,String> l=new HashMap<Integer,String>(); public void run() { try { Thread.sleep(1000); // Child thread trying to add // new element in the object l.put(103,"D"); } catch(InterruptedException e) { System.out.println("Child Thread going to add element"); } } public static void main(String[] args) throws InterruptedException { l.put(100,"A"); l.put(101,"B"); l.put(102,"C"); HashMapDemo t=new HashMapDemo(); t.start(); for (Object o : l.entrySet()) { Object s=o; System.out.println(s); Thread.sleep(1000); } System.out.println(l); }}Output:100=A
Exception in thread "main" java.util.ConcurrentModificationException
Using ConcurrentHashMap// Java program to illustrate// HashMap drawbacksimport java.util.HashMap;import java.util.concurrent.*; class HashMapDemo extends Thread{ static ConcurrentHashMap<Integer,String> l = new ConcurrentHashMap<Integer,String>(); public void run() { // Child add new element in the object l.put(103,"D"); try { Thread.sleep(2000); } catch(InterruptedException e) { System.out.println("Child Thread going to add element"); } } public static void main(String[] args) throws InterruptedException { l.put(100,"A"); l.put(101,"B"); l.put(102,"C"); HashMapDemo t=new HashMapDemo(); t.start(); for (Object o : l.entrySet()) { Object s=o; System.out.println(s); Thread.sleep(1000); } System.out.println(l); }}Output:100=A
101=B
102=C
103=D
{100=A, 101=B, 102=C, 103=D}
Using HashMap
// Java program to illustrate// HashMap drawbacksimport java.util.HashMap; class HashMapDemo extends Thread{ static HashMap<Integer,String> l=new HashMap<Integer,String>(); public void run() { try { Thread.sleep(1000); // Child thread trying to add // new element in the object l.put(103,"D"); } catch(InterruptedException e) { System.out.println("Child Thread going to add element"); } } public static void main(String[] args) throws InterruptedException { l.put(100,"A"); l.put(101,"B"); l.put(102,"C"); HashMapDemo t=new HashMapDemo(); t.start(); for (Object o : l.entrySet()) { Object s=o; System.out.println(s); Thread.sleep(1000); } System.out.println(l); }}
Output:
100=A
Exception in thread "main" java.util.ConcurrentModificationException
Using ConcurrentHashMap
// Java program to illustrate// HashMap drawbacksimport java.util.HashMap;import java.util.concurrent.*; class HashMapDemo extends Thread{ static ConcurrentHashMap<Integer,String> l = new ConcurrentHashMap<Integer,String>(); public void run() { // Child add new element in the object l.put(103,"D"); try { Thread.sleep(2000); } catch(InterruptedException e) { System.out.println("Child Thread going to add element"); } } public static void main(String[] args) throws InterruptedException { l.put(100,"A"); l.put(101,"B"); l.put(102,"C"); HashMapDemo t=new HashMapDemo(); t.start(); for (Object o : l.entrySet()) { Object s=o; System.out.println(s); Thread.sleep(1000); } System.out.println(l); }}
Output:
100=A
101=B
102=C
103=D
{100=A, 101=B, 102=C, 103=D}
In HashMap, null values are allowed for key and values, whereas in ConcurrentHashMap null value is not allowed for key and value, otherwise we will get Run-time exception saying NullPointerException.Using HashMap//Java Program to illustrate ConcurrentHashMap behaviourimport java.util.*;class ConcurrentHashMapDemo{ public static void main(String[] args) { HashMap m=new HashMap(); m.put(100,"Hello"); m.put(101,"Geeks"); m.put(102,"Geeks"); m.put(null,"World"); System.out.println(m); }} output:{null=World, 100=Hello, 101=Geeks, 102=Geeks}
Using ConcurrentHashMap//Java Program to illustrate HashMap behaviourimport java.util.concurrent.*;class ConcurrentHashMapDemo{ public static void main(String[] args) { ConcurrentHashMap m=new ConcurrentHashMap(); m.put(100,"Hello"); m.put(101,"Geeks"); m.put(102,"Geeks"); m.put(null,"World"); System.out.println(m); }} Output:Exception in thread "main" java.lang.NullPointerException
Using HashMap
//Java Program to illustrate ConcurrentHashMap behaviourimport java.util.*;class ConcurrentHashMapDemo{ public static void main(String[] args) { HashMap m=new HashMap(); m.put(100,"Hello"); m.put(101,"Geeks"); m.put(102,"Geeks"); m.put(null,"World"); System.out.println(m); }}
output:
{null=World, 100=Hello, 101=Geeks, 102=Geeks}
Using ConcurrentHashMap
//Java Program to illustrate HashMap behaviourimport java.util.concurrent.*;class ConcurrentHashMapDemo{ public static void main(String[] args) { ConcurrentHashMap m=new ConcurrentHashMap(); m.put(100,"Hello"); m.put(101,"Geeks"); m.put(102,"Geeks"); m.put(null,"World"); System.out.println(m); }}
Output:
Exception in thread "main" java.lang.NullPointerException
HashMap is introduced in JDK 1.2 whereas ConcurrentHashMap is introduced by SUN Microsystem in JDK 1.5.
RohanDodeja1
Java-Collections
Java-HashMap
Java-Map-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Multithreading in Java
Singleton Class in Java
LinkedList in Java
Overriding in Java | [
{
"code": null,
"e": 24506,
"s": 24478,
"text": "\n06 Aug, 2019"
},
{
"code": null,
"e": 24707,
"s": 24506,
"text": "HashMap is the Class which is under Traditional Collection and ConcurrentHashMap is a Class which is under Concurrent Collections, apart from this there are various differences between them which are:"
},
{
"code": null,
"e": 24829,
"s": 24707,
"text": "HashMap is non-Synchronized in nature i.e. HashMap is not Thread-safe whereas ConcurrentHashMap is Thread-safe in nature."
},
{
"code": null,
"e": 25083,
"s": 24829,
"text": "HashMap performance is relatively high because it is non-synchronized in nature and any number of threads can perform simultaneously. But ConcurrentHashMap performance is low sometimes because sometimes Threads are required to wait on ConcurrentHashMap."
},
{
"code": null,
"e": 27418,
"s": 25083,
"text": "While one thread is Iterating the HashMap object, if other thread try to add/modify the contents of Object then we will get Run-time exception saying ConcurrentModificationException.Whereas In ConcurrentHashMap we wont get any exception while performing any modification at the time of Iteration.Using HashMap// Java program to illustrate// HashMap drawbacksimport java.util.HashMap; class HashMapDemo extends Thread{ static HashMap<Integer,String> l=new HashMap<Integer,String>(); public void run() { try { Thread.sleep(1000); // Child thread trying to add // new element in the object l.put(103,\"D\"); } catch(InterruptedException e) { System.out.println(\"Child Thread going to add element\"); } } public static void main(String[] args) throws InterruptedException { l.put(100,\"A\"); l.put(101,\"B\"); l.put(102,\"C\"); HashMapDemo t=new HashMapDemo(); t.start(); for (Object o : l.entrySet()) { Object s=o; System.out.println(s); Thread.sleep(1000); } System.out.println(l); }}Output:100=A\nException in thread \"main\" java.util.ConcurrentModificationException\nUsing ConcurrentHashMap// Java program to illustrate// HashMap drawbacksimport java.util.HashMap;import java.util.concurrent.*; class HashMapDemo extends Thread{ static ConcurrentHashMap<Integer,String> l = new ConcurrentHashMap<Integer,String>(); public void run() { // Child add new element in the object l.put(103,\"D\"); try { Thread.sleep(2000); } catch(InterruptedException e) { System.out.println(\"Child Thread going to add element\"); } } public static void main(String[] args) throws InterruptedException { l.put(100,\"A\"); l.put(101,\"B\"); l.put(102,\"C\"); HashMapDemo t=new HashMapDemo(); t.start(); for (Object o : l.entrySet()) { Object s=o; System.out.println(s); Thread.sleep(1000); } System.out.println(l); }}Output:100=A\n101=B\n102=C\n103=D\n{100=A, 101=B, 102=C, 103=D}\n"
},
{
"code": null,
"e": 27432,
"s": 27418,
"text": "Using HashMap"
},
{
"code": "// Java program to illustrate// HashMap drawbacksimport java.util.HashMap; class HashMapDemo extends Thread{ static HashMap<Integer,String> l=new HashMap<Integer,String>(); public void run() { try { Thread.sleep(1000); // Child thread trying to add // new element in the object l.put(103,\"D\"); } catch(InterruptedException e) { System.out.println(\"Child Thread going to add element\"); } } public static void main(String[] args) throws InterruptedException { l.put(100,\"A\"); l.put(101,\"B\"); l.put(102,\"C\"); HashMapDemo t=new HashMapDemo(); t.start(); for (Object o : l.entrySet()) { Object s=o; System.out.println(s); Thread.sleep(1000); } System.out.println(l); }}",
"e": 28343,
"s": 27432,
"text": null
},
{
"code": null,
"e": 28351,
"s": 28343,
"text": "Output:"
},
{
"code": null,
"e": 28427,
"s": 28351,
"text": "100=A\nException in thread \"main\" java.util.ConcurrentModificationException\n"
},
{
"code": null,
"e": 28451,
"s": 28427,
"text": "Using ConcurrentHashMap"
},
{
"code": "// Java program to illustrate// HashMap drawbacksimport java.util.HashMap;import java.util.concurrent.*; class HashMapDemo extends Thread{ static ConcurrentHashMap<Integer,String> l = new ConcurrentHashMap<Integer,String>(); public void run() { // Child add new element in the object l.put(103,\"D\"); try { Thread.sleep(2000); } catch(InterruptedException e) { System.out.println(\"Child Thread going to add element\"); } } public static void main(String[] args) throws InterruptedException { l.put(100,\"A\"); l.put(101,\"B\"); l.put(102,\"C\"); HashMapDemo t=new HashMapDemo(); t.start(); for (Object o : l.entrySet()) { Object s=o; System.out.println(s); Thread.sleep(1000); } System.out.println(l); }}",
"e": 29402,
"s": 28451,
"text": null
},
{
"code": null,
"e": 29410,
"s": 29402,
"text": "Output:"
},
{
"code": null,
"e": 29464,
"s": 29410,
"text": "100=A\n101=B\n102=C\n103=D\n{100=A, 101=B, 102=C, 103=D}\n"
},
{
"code": null,
"e": 30495,
"s": 29464,
"text": "In HashMap, null values are allowed for key and values, whereas in ConcurrentHashMap null value is not allowed for key and value, otherwise we will get Run-time exception saying NullPointerException.Using HashMap//Java Program to illustrate ConcurrentHashMap behaviourimport java.util.*;class ConcurrentHashMapDemo{ public static void main(String[] args) { HashMap m=new HashMap(); m.put(100,\"Hello\"); m.put(101,\"Geeks\"); m.put(102,\"Geeks\"); m.put(null,\"World\"); System.out.println(m); }} output:{null=World, 100=Hello, 101=Geeks, 102=Geeks}\nUsing ConcurrentHashMap//Java Program to illustrate HashMap behaviourimport java.util.concurrent.*;class ConcurrentHashMapDemo{ public static void main(String[] args) { ConcurrentHashMap m=new ConcurrentHashMap(); m.put(100,\"Hello\"); m.put(101,\"Geeks\"); m.put(102,\"Geeks\"); m.put(null,\"World\"); System.out.println(m); }} Output:Exception in thread \"main\" java.lang.NullPointerException\n"
},
{
"code": null,
"e": 30509,
"s": 30495,
"text": "Using HashMap"
},
{
"code": "//Java Program to illustrate ConcurrentHashMap behaviourimport java.util.*;class ConcurrentHashMapDemo{ public static void main(String[] args) { HashMap m=new HashMap(); m.put(100,\"Hello\"); m.put(101,\"Geeks\"); m.put(102,\"Geeks\"); m.put(null,\"World\"); System.out.println(m); }} ",
"e": 30838,
"s": 30509,
"text": null
},
{
"code": null,
"e": 30846,
"s": 30838,
"text": "output:"
},
{
"code": null,
"e": 30893,
"s": 30846,
"text": "{null=World, 100=Hello, 101=Geeks, 102=Geeks}\n"
},
{
"code": null,
"e": 30917,
"s": 30893,
"text": "Using ConcurrentHashMap"
},
{
"code": "//Java Program to illustrate HashMap behaviourimport java.util.concurrent.*;class ConcurrentHashMapDemo{ public static void main(String[] args) { ConcurrentHashMap m=new ConcurrentHashMap(); m.put(100,\"Hello\"); m.put(101,\"Geeks\"); m.put(102,\"Geeks\"); m.put(null,\"World\"); System.out.println(m); }} ",
"e": 31267,
"s": 30917,
"text": null
},
{
"code": null,
"e": 31275,
"s": 31267,
"text": "Output:"
},
{
"code": null,
"e": 31334,
"s": 31275,
"text": "Exception in thread \"main\" java.lang.NullPointerException\n"
},
{
"code": null,
"e": 31438,
"s": 31334,
"text": "HashMap is introduced in JDK 1.2 whereas ConcurrentHashMap is introduced by SUN Microsystem in JDK 1.5."
},
{
"code": null,
"e": 31451,
"s": 31438,
"text": "RohanDodeja1"
},
{
"code": null,
"e": 31468,
"s": 31451,
"text": "Java-Collections"
},
{
"code": null,
"e": 31481,
"s": 31468,
"text": "Java-HashMap"
},
{
"code": null,
"e": 31499,
"s": 31481,
"text": "Java-Map-Programs"
},
{
"code": null,
"e": 31504,
"s": 31499,
"text": "Java"
},
{
"code": null,
"e": 31509,
"s": 31504,
"text": "Java"
},
{
"code": null,
"e": 31526,
"s": 31509,
"text": "Java-Collections"
},
{
"code": null,
"e": 31624,
"s": 31526,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31633,
"s": 31624,
"text": "Comments"
},
{
"code": null,
"e": 31646,
"s": 31633,
"text": "Old Comments"
},
{
"code": null,
"e": 31697,
"s": 31646,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 31729,
"s": 31697,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31748,
"s": 31729,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31766,
"s": 31748,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 31797,
"s": 31766,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 31829,
"s": 31797,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31852,
"s": 31829,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 31876,
"s": 31852,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 31895,
"s": 31876,
"text": "LinkedList in Java"
}
]
|
Twitter Sentiment Analysis using Python | In this article, we will be learning about the twitter sentimental analysis. We will register for twitter oAuth API, install all the dependencies and finally write our sentimental analyzer script.
An API(Application programming interface) is a gateway that allows you to access some servers(Twitter) internal functionality.
The prerequisite is that we have a twitter account set up with a verified phone number.
After this, we visit the Twitter website and tap on the create a new app icon. Now we fill all the credentials i.e. name and accept the developer agreement and finally click on create.
Now our app is created, on the top menu, we will click on the keys tab. Here we will be obtaining our OAuth verification details and all the tokenizers.
Now let's install all the dependencies −
1. tweepy module :
>>> pip install tweepy
2. textblob module :
>>> pip install textblob
It is a module used in sentiment analysis. It contains an inbuilt method to calculate sentiments on a scale of -1 to 1.
"token.sentiment.polarity"
First, we need all the access tokenizer from the twitter application website as created initially −
#Twitter credentials for the app interface
consumer_key = 'xxxxx'
consumer_secret = 'xxxx'
access_key= 'xxxx'
access_secret = 'xxxx'
No, we need to authenticate the credentials via script. For that, we create an authentication variable auth.
auth =tweepy.OauthHandler(consumer_key,consumer_secret)
now we set the access token with the help of authentication variable
auth.set_access_token(access_token,access_token_secret)
Now we create an API variable to perform our operations
api=tweepy.API(auth)
we need to get the public tweets via search method and store it in the form of a list.
public_tweet=api.search('Tutorialspoint')
for tweet in public_tweet:
print(tweet.text)
analysis=TextBlob(tweet.text)
print(analysis)
In the output, we observe to thing i.e. the polarity and subjectivity.
Polarity measures how positive or negative some text is.
Subjectivity measures the text that how much it is opinionated as compared to factual.
With the help of this sentiment analyzer, we are able to understand and extract human feelings out of the data. | [
{
"code": null,
"e": 1259,
"s": 1062,
"text": "In this article, we will be learning about the twitter sentimental analysis. We will register for twitter oAuth API, install all the dependencies and finally write our sentimental analyzer script."
},
{
"code": null,
"e": 1386,
"s": 1259,
"text": "An API(Application programming interface) is a gateway that allows you to access some servers(Twitter) internal functionality."
},
{
"code": null,
"e": 1474,
"s": 1386,
"text": "The prerequisite is that we have a twitter account set up with a verified phone number."
},
{
"code": null,
"e": 1659,
"s": 1474,
"text": "After this, we visit the Twitter website and tap on the create a new app icon. Now we fill all the credentials i.e. name and accept the developer agreement and finally click on create."
},
{
"code": null,
"e": 1812,
"s": 1659,
"text": "Now our app is created, on the top menu, we will click on the keys tab. Here we will be obtaining our OAuth verification details and all the tokenizers."
},
{
"code": null,
"e": 1853,
"s": 1812,
"text": "Now let's install all the dependencies −"
},
{
"code": null,
"e": 1941,
"s": 1853,
"text": "1. tweepy module :\n>>> pip install tweepy\n2. textblob module :\n>>> pip install textblob"
},
{
"code": null,
"e": 2061,
"s": 1941,
"text": "It is a module used in sentiment analysis. It contains an inbuilt method to calculate sentiments on a scale of -1 to 1."
},
{
"code": null,
"e": 2088,
"s": 2061,
"text": "\"token.sentiment.polarity\""
},
{
"code": null,
"e": 2188,
"s": 2088,
"text": "First, we need all the access tokenizer from the twitter application website as created initially −"
},
{
"code": null,
"e": 2321,
"s": 2188,
"text": "#Twitter credentials for the app interface\nconsumer_key = 'xxxxx'\nconsumer_secret = 'xxxx'\naccess_key= 'xxxx'\naccess_secret = 'xxxx'"
},
{
"code": null,
"e": 2430,
"s": 2321,
"text": "No, we need to authenticate the credentials via script. For that, we create an authentication variable auth."
},
{
"code": null,
"e": 2486,
"s": 2430,
"text": "auth =tweepy.OauthHandler(consumer_key,consumer_secret)"
},
{
"code": null,
"e": 2555,
"s": 2486,
"text": "now we set the access token with the help of authentication variable"
},
{
"code": null,
"e": 2611,
"s": 2555,
"text": "auth.set_access_token(access_token,access_token_secret)"
},
{
"code": null,
"e": 2667,
"s": 2611,
"text": "Now we create an API variable to perform our operations"
},
{
"code": null,
"e": 2688,
"s": 2667,
"text": "api=tweepy.API(auth)"
},
{
"code": null,
"e": 2775,
"s": 2688,
"text": "we need to get the public tweets via search method and store it in the form of a list."
},
{
"code": null,
"e": 2917,
"s": 2775,
"text": "public_tweet=api.search('Tutorialspoint')\nfor tweet in public_tweet:\n print(tweet.text)\n analysis=TextBlob(tweet.text)\n print(analysis)"
},
{
"code": null,
"e": 2988,
"s": 2917,
"text": "In the output, we observe to thing i.e. the polarity and subjectivity."
},
{
"code": null,
"e": 3045,
"s": 2988,
"text": "Polarity measures how positive or negative some text is."
},
{
"code": null,
"e": 3132,
"s": 3045,
"text": "Subjectivity measures the text that how much it is opinionated as compared to factual."
},
{
"code": null,
"e": 3244,
"s": 3132,
"text": "With the help of this sentiment analyzer, we are able to understand and extract human feelings out of the data."
}
]
|
Building Classification Models with Sklearn | by Sadrach Pierre, Ph.D. | Towards Data Science | Scikit-learn is an open-source machine learning library for python. It provides a variety of regression, classification, and clustering algorithms. In my previous post, A Brief Tour of Sklearn, I discussed several methods for regression using the machine learning package. In this post, we will go over some of the basic methods for building classification models. The documentation for this package is extensive and a fantastic resource for every data scientist. You can find the documentation here.
We will be using the Telco Customer Churn dataset. It can be found here
First, let’s import the data and print the first five rows:
import pandas as pd df = pd.read_csv("Customer_Churn.csv")print(df.head())
We will be using all of the categorical and numerical data to predict Churn. First, we need to convert the categorical columns into numerical values that the neural network can handle. For example, for gender we have:
df.gender = pd.Categorical(df.gender)df['gender_code'] = df.gender.cat.codes
Now, let’s define our input and output arrays:
import numpy as npfeatures = ['gender_code', 'SeniorCitizen_code', 'PhoneService_code', 'MultipleLines_code', 'InternetService_code', 'Partner_code', 'Dependents_code', 'PaymentMethod_code', 'PaymentMethod_code', 'PaperlessBilling_code','Contract_code', 'StreamingMovies_code', 'StreamingTV_code', 'TechSupport_code', 'DeviceProtection_code', 'OnlineBackup_code', 'OnlineSecurity_code', 'Dependents_code', 'Partner_code','tenure', 'MonthlyCharges']X = np.array(df[features])y = np.array(df['Churn_code'])
We will then split our data for training and testing:
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)
Now all of our necessary variables are defined. Let’s build some models!
LOGISTIC REGRESSION
Let’s start with logistic regression. Logistic regression uses a logistic function to predict a binary dependent variable.
We import the LogisticRegression package as follows:
from sklearn.linear_model import LogisticRegression
Let’s define a logistic regression object, fit our model, and evaluate performance:
reg_log = LogisticRegression()reg_log.fit(X_train, y_train)y_pred = reg_log.predict(X_test)
We can visualize the predictions using metrics classification report:
from sklearn import metricsprint(metrics.classification_report(y_test, y_pred))
We can also look at the ‘roc_auc_score’ and the ‘f1_score.’ The ‘roc_auc_score’ is the area under the receiving operating characteristic curve. It is a measure of how well the binary classification model can distinguish classes. A ‘roc_auc_score’ of 0.5 means the model is unable to distinguish between classes. Values close to 1.0 correspond to a strong separation between classes. The ‘f1_score’ is the harmonic mean of precision and recall. Similar to ‘roc_auc_score’, a perfect ‘f1_score’ is equal to 1.0:
print("roc_auc_score: ", roc_auc_score(y_test, y_pred))print("f1 score: ", f1_score(y_test, y_pred))
RANDOM FORESTS
Now let’s take a look at random forests. Random forest is a tree-based method that ensembles multiple individual decision trees.
We import the RandomForestClassifier package as follows:
from sklearn.ensemble import RandomForestClassifier
Let’s define a random forest classification object, fit our model, and evaluate performance:
reg_rf = RandomForestClassifier()reg_rf.fit(X_train, y_train)y_pred = reg_rf.predict(X_test)
And let’s take a look at the metrics classification report:
print(metrics.classification_report(y_test, y_pred))
print("roc_auc_score: ", roc_auc_score(y_test, y_pred))print("f1 score: ", f1_score(y_test, y_pred))
We see that the random forest has worse performance than logistic regression. We can also print the feature importance. This allows us to see which variables are most significant for temperature prediction:
feature_df = pd.DataFrame({'Importance':reg_rf.feature_importances_, 'Features': features })print(feature_df)
I’d like to point out that by not passing any parameters, like max_depth and n_estimators, I selected default random forest values (which are n_estimators = 10 and max_depth = 10 ). We can further improve performance by optimizing parameters in random forests. This can be done manually or in an automated way using grid search techniques. I will leave the matter of parameter optimization for another post.
SUPPORT VECTOR MACHINES
The next method I’ll discuss is called support vector regression. This is an extension of support vector machines (SVM). SVMs construct a set of hyperplanes in high dimensional feature space that can be used for regression and classification problems.
We import the SVC package as follows:
from sklearn.svm import SVC
Let’s define a support vector classification object, fit our model, and evaluate performance:
reg_svc = SVC()reg_svc.fit(X_train, y_train)y_pred = reg_svc.predict(X_test)
We can visualize the predictions using metrics classification report:
print(metrics.classification_report(y_test, y_pred))
We can also look at the roc_auc_score and the f1_scores:
print("roc_auc_score: ", roc_auc_score(y_test, y_pred))print("f1 score: ", f1_score(y_test, y_pred))
We see that support vector classification performance is slightly worse than logistic regression and slightly better than random forests. Similar to the random forest, SVC takes parameters that can be used to optimize performance. These include the regularization parameter (default C = 1.0), kernel (default kernel = ‘rbf’) and the kernel coefficient (default gamma = ‘scale’)
K-NEAREST NEIGHBORS
The final method I will discuss is k-nearest neighbor for classification. K-nearest neighbors use Euclidean distance calculations where the prediction is the average of the k nearest neighbors.
We import the KNeighborsClassifier package as follows:
from sklearn.neighbors import KNeighborsClassifier
Let’s define a k-nearest neighbor classification object, fit our model, and evaluate performance:
reg_knn = KNeighborsClassifier()reg_knn.fit(X_train, y_train)y_pred = reg_knn.predict(X_test)
And let’s take a look at the metrics classification report:
print(metrics.classification_report(y_test, y_pred))
We can also look at the roc_auc_score and the f1_scores:
print("roc_auc_score: ", roc_auc_score(y_test, y_pred))print("f1 score: ", f1_score(y_test, y_pred))
The K-nearest neighbor algorithm also takes hyper-parameters, specifically n_neighbors, which can be selected to minimized error.
CONCLUSIONS
I will stop here but feel free to play around with model feature selection to see if you can improve the performance of some of these models.
To recap, I outlined a brief introduction to classification using the python machine learning library. I went over how to define model objects, fit models to data, and predict output using logistic regression, random forest, support vector machine, and K-nearest neighbor models.
I hope this post was informative. The code from this post is available on GitHub. Thank you for reading and happy machine learning! | [
{
"code": null,
"e": 672,
"s": 171,
"text": "Scikit-learn is an open-source machine learning library for python. It provides a variety of regression, classification, and clustering algorithms. In my previous post, A Brief Tour of Sklearn, I discussed several methods for regression using the machine learning package. In this post, we will go over some of the basic methods for building classification models. The documentation for this package is extensive and a fantastic resource for every data scientist. You can find the documentation here."
},
{
"code": null,
"e": 744,
"s": 672,
"text": "We will be using the Telco Customer Churn dataset. It can be found here"
},
{
"code": null,
"e": 804,
"s": 744,
"text": "First, let’s import the data and print the first five rows:"
},
{
"code": null,
"e": 879,
"s": 804,
"text": "import pandas as pd df = pd.read_csv(\"Customer_Churn.csv\")print(df.head())"
},
{
"code": null,
"e": 1097,
"s": 879,
"text": "We will be using all of the categorical and numerical data to predict Churn. First, we need to convert the categorical columns into numerical values that the neural network can handle. For example, for gender we have:"
},
{
"code": null,
"e": 1174,
"s": 1097,
"text": "df.gender = pd.Categorical(df.gender)df['gender_code'] = df.gender.cat.codes"
},
{
"code": null,
"e": 1221,
"s": 1174,
"text": "Now, let’s define our input and output arrays:"
},
{
"code": null,
"e": 1792,
"s": 1221,
"text": "import numpy as npfeatures = ['gender_code', 'SeniorCitizen_code', 'PhoneService_code', 'MultipleLines_code', 'InternetService_code', 'Partner_code', 'Dependents_code', 'PaymentMethod_code', 'PaymentMethod_code', 'PaperlessBilling_code','Contract_code', 'StreamingMovies_code', 'StreamingTV_code', 'TechSupport_code', 'DeviceProtection_code', 'OnlineBackup_code', 'OnlineSecurity_code', 'Dependents_code', 'Partner_code','tenure', 'MonthlyCharges']X = np.array(df[features])y = np.array(df['Churn_code'])"
},
{
"code": null,
"e": 1846,
"s": 1792,
"text": "We will then split our data for training and testing:"
},
{
"code": null,
"e": 1992,
"s": 1846,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)"
},
{
"code": null,
"e": 2065,
"s": 1992,
"text": "Now all of our necessary variables are defined. Let’s build some models!"
},
{
"code": null,
"e": 2085,
"s": 2065,
"text": "LOGISTIC REGRESSION"
},
{
"code": null,
"e": 2208,
"s": 2085,
"text": "Let’s start with logistic regression. Logistic regression uses a logistic function to predict a binary dependent variable."
},
{
"code": null,
"e": 2261,
"s": 2208,
"text": "We import the LogisticRegression package as follows:"
},
{
"code": null,
"e": 2313,
"s": 2261,
"text": "from sklearn.linear_model import LogisticRegression"
},
{
"code": null,
"e": 2397,
"s": 2313,
"text": "Let’s define a logistic regression object, fit our model, and evaluate performance:"
},
{
"code": null,
"e": 2489,
"s": 2397,
"text": "reg_log = LogisticRegression()reg_log.fit(X_train, y_train)y_pred = reg_log.predict(X_test)"
},
{
"code": null,
"e": 2559,
"s": 2489,
"text": "We can visualize the predictions using metrics classification report:"
},
{
"code": null,
"e": 2639,
"s": 2559,
"text": "from sklearn import metricsprint(metrics.classification_report(y_test, y_pred))"
},
{
"code": null,
"e": 3149,
"s": 2639,
"text": "We can also look at the ‘roc_auc_score’ and the ‘f1_score.’ The ‘roc_auc_score’ is the area under the receiving operating characteristic curve. It is a measure of how well the binary classification model can distinguish classes. A ‘roc_auc_score’ of 0.5 means the model is unable to distinguish between classes. Values close to 1.0 correspond to a strong separation between classes. The ‘f1_score’ is the harmonic mean of precision and recall. Similar to ‘roc_auc_score’, a perfect ‘f1_score’ is equal to 1.0:"
},
{
"code": null,
"e": 3250,
"s": 3149,
"text": "print(\"roc_auc_score: \", roc_auc_score(y_test, y_pred))print(\"f1 score: \", f1_score(y_test, y_pred))"
},
{
"code": null,
"e": 3265,
"s": 3250,
"text": "RANDOM FORESTS"
},
{
"code": null,
"e": 3394,
"s": 3265,
"text": "Now let’s take a look at random forests. Random forest is a tree-based method that ensembles multiple individual decision trees."
},
{
"code": null,
"e": 3451,
"s": 3394,
"text": "We import the RandomForestClassifier package as follows:"
},
{
"code": null,
"e": 3503,
"s": 3451,
"text": "from sklearn.ensemble import RandomForestClassifier"
},
{
"code": null,
"e": 3596,
"s": 3503,
"text": "Let’s define a random forest classification object, fit our model, and evaluate performance:"
},
{
"code": null,
"e": 3689,
"s": 3596,
"text": "reg_rf = RandomForestClassifier()reg_rf.fit(X_train, y_train)y_pred = reg_rf.predict(X_test)"
},
{
"code": null,
"e": 3749,
"s": 3689,
"text": "And let’s take a look at the metrics classification report:"
},
{
"code": null,
"e": 3802,
"s": 3749,
"text": "print(metrics.classification_report(y_test, y_pred))"
},
{
"code": null,
"e": 3903,
"s": 3802,
"text": "print(\"roc_auc_score: \", roc_auc_score(y_test, y_pred))print(\"f1 score: \", f1_score(y_test, y_pred))"
},
{
"code": null,
"e": 4110,
"s": 3903,
"text": "We see that the random forest has worse performance than logistic regression. We can also print the feature importance. This allows us to see which variables are most significant for temperature prediction:"
},
{
"code": null,
"e": 4220,
"s": 4110,
"text": "feature_df = pd.DataFrame({'Importance':reg_rf.feature_importances_, 'Features': features })print(feature_df)"
},
{
"code": null,
"e": 4628,
"s": 4220,
"text": "I’d like to point out that by not passing any parameters, like max_depth and n_estimators, I selected default random forest values (which are n_estimators = 10 and max_depth = 10 ). We can further improve performance by optimizing parameters in random forests. This can be done manually or in an automated way using grid search techniques. I will leave the matter of parameter optimization for another post."
},
{
"code": null,
"e": 4652,
"s": 4628,
"text": "SUPPORT VECTOR MACHINES"
},
{
"code": null,
"e": 4904,
"s": 4652,
"text": "The next method I’ll discuss is called support vector regression. This is an extension of support vector machines (SVM). SVMs construct a set of hyperplanes in high dimensional feature space that can be used for regression and classification problems."
},
{
"code": null,
"e": 4942,
"s": 4904,
"text": "We import the SVC package as follows:"
},
{
"code": null,
"e": 4970,
"s": 4942,
"text": "from sklearn.svm import SVC"
},
{
"code": null,
"e": 5064,
"s": 4970,
"text": "Let’s define a support vector classification object, fit our model, and evaluate performance:"
},
{
"code": null,
"e": 5141,
"s": 5064,
"text": "reg_svc = SVC()reg_svc.fit(X_train, y_train)y_pred = reg_svc.predict(X_test)"
},
{
"code": null,
"e": 5211,
"s": 5141,
"text": "We can visualize the predictions using metrics classification report:"
},
{
"code": null,
"e": 5264,
"s": 5211,
"text": "print(metrics.classification_report(y_test, y_pred))"
},
{
"code": null,
"e": 5321,
"s": 5264,
"text": "We can also look at the roc_auc_score and the f1_scores:"
},
{
"code": null,
"e": 5422,
"s": 5321,
"text": "print(\"roc_auc_score: \", roc_auc_score(y_test, y_pred))print(\"f1 score: \", f1_score(y_test, y_pred))"
},
{
"code": null,
"e": 5800,
"s": 5422,
"text": "We see that support vector classification performance is slightly worse than logistic regression and slightly better than random forests. Similar to the random forest, SVC takes parameters that can be used to optimize performance. These include the regularization parameter (default C = 1.0), kernel (default kernel = ‘rbf’) and the kernel coefficient (default gamma = ‘scale’)"
},
{
"code": null,
"e": 5820,
"s": 5800,
"text": "K-NEAREST NEIGHBORS"
},
{
"code": null,
"e": 6014,
"s": 5820,
"text": "The final method I will discuss is k-nearest neighbor for classification. K-nearest neighbors use Euclidean distance calculations where the prediction is the average of the k nearest neighbors."
},
{
"code": null,
"e": 6069,
"s": 6014,
"text": "We import the KNeighborsClassifier package as follows:"
},
{
"code": null,
"e": 6120,
"s": 6069,
"text": "from sklearn.neighbors import KNeighborsClassifier"
},
{
"code": null,
"e": 6218,
"s": 6120,
"text": "Let’s define a k-nearest neighbor classification object, fit our model, and evaluate performance:"
},
{
"code": null,
"e": 6312,
"s": 6218,
"text": "reg_knn = KNeighborsClassifier()reg_knn.fit(X_train, y_train)y_pred = reg_knn.predict(X_test)"
},
{
"code": null,
"e": 6372,
"s": 6312,
"text": "And let’s take a look at the metrics classification report:"
},
{
"code": null,
"e": 6425,
"s": 6372,
"text": "print(metrics.classification_report(y_test, y_pred))"
},
{
"code": null,
"e": 6482,
"s": 6425,
"text": "We can also look at the roc_auc_score and the f1_scores:"
},
{
"code": null,
"e": 6583,
"s": 6482,
"text": "print(\"roc_auc_score: \", roc_auc_score(y_test, y_pred))print(\"f1 score: \", f1_score(y_test, y_pred))"
},
{
"code": null,
"e": 6713,
"s": 6583,
"text": "The K-nearest neighbor algorithm also takes hyper-parameters, specifically n_neighbors, which can be selected to minimized error."
},
{
"code": null,
"e": 6725,
"s": 6713,
"text": "CONCLUSIONS"
},
{
"code": null,
"e": 6867,
"s": 6725,
"text": "I will stop here but feel free to play around with model feature selection to see if you can improve the performance of some of these models."
},
{
"code": null,
"e": 7147,
"s": 6867,
"text": "To recap, I outlined a brief introduction to classification using the python machine learning library. I went over how to define model objects, fit models to data, and predict output using logistic regression, random forest, support vector machine, and K-nearest neighbor models."
}
]
|
Building a Neural Network with a Single Hidden Layer using Numpy | by Ramesh Paudel, Ph.D. | Towards Data Science | Implement a 2-class classification neural network with a single hidden layer using Numpy
In the previous post, we discussed how to make a simple neural network using NumPy. In this post, we will talk about how to make a deep neural network with a hidden layer.
Import Libraries
Import Libraries
We will import some basic python libraries like numpy, matplotlib (for plotting graphs), sklearn (for data mining and analysis tool), etc. that we will need.
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_split
2. Dataset
We will use the Banknote Dataset that involves predicting whether a given banknote is authentic given several measures taken from a photograph. It is a binary (2-class) classification problem. There are 1,372 observations with 4 input variables and 1 output variable. For more detail see the link.
data = np.genfromtxt(‘data_banknote_authentication.txt’, delimiter = ‘,’)X = data[:,:4]y = data[:, 4]
We can visualize the dataset using a scatter plot. We can see two classes (authentic and not authentic) are separable. Our goal is to build a model to fit this data i.e. we want to build a neural network model that defines regions as either authentic or unauthentic.
plt.scatter(X[:, 0], X[:, 1], alpha=0.2, c=y, cmap=’viridis’)plt.xlabel(‘variance of wavelet’)plt.ylabel(‘skewness of wavelet’);
Now, let us divide the data into a training set and test set. This can be accomplished using sklearn train_test_split() function. 20% of data is selected for test and 80% for train. Also, we will check the size of the training set and test set. This will be useful later to design our neural network model.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)X_train = X_train.Ty_train = y_train.reshape(1, y_train.shape[0])X_test = X_test.Ty_test = y_test.reshape(1, y_test.shape[0])print (‘Train X Shape: ‘, X_train.shape)print (‘Train Y Shape: ‘, y_train.shape)print (‘I have m = %d training examples!’ % (X_train.shape[1]))print ('\nTest X Shape: ', X_test.shape)
3. Neural Network Model
The general methodology to build a Neural Network is to:
1. Define the neural network structure ( # of input units, # of hidden units, etc). 2. Initialize the model's parameters3. Loop: - Implement forward propagation - Compute loss - Implement backward propagation to get the gradients - Update parameters (gradient descent)
We will build a Neural Network with a single hidden layer as shown in the following figure:
3.1 Define structure
We need to define the number of input units, the number of hidden units, and the output layer. The input units are equal to the number of features in the dataset (4), hidden layer is set to 4 (for this purpose), and the problem is the binary classification we will use a single layer output.
def define_structure(X, Y): input_unit = X.shape[0] # size of input layer hidden_unit = 4 #hidden layer of size 4 output_unit = Y.shape[0] # size of output layer return (input_unit, hidden_unit, output_unit)(input_unit, hidden_unit, output_unit) = define_structure(X_train, y_train)print("The size of the input layer is: = " + str(input_unit))print("The size of the hidden layer is: = " + str(hidden_unit))print("The size of the output layer is: = " + str(output_unit))
3.2 Initialize Model Parameter
We need to initialize the weight matrices and bias vectors. Weight is initialized randomly while bias is set to zeros. This can be done using the following function.
def parameters_initialization(input_unit, hidden_unit, output_unit): np.random.seed(2) W1 = np.random.randn(hidden_unit, input_unit)*0.01 b1 = np.zeros((hidden_unit, 1)) W2 = np.random.randn(output_unit, hidden_unit)*0.01 b2 = np.zeros((output_unit, 1)) parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} return parameters
3.3.1 Forward Propagation
For forward propagation, given the set of input features (X), we need to compute the activation function for each layer. For the hidden layer, we are using tanh activation function:
Similarly, for the output layer, we are using sigmoid activation function.
We can use the following code to implement forward propagation.
def sigmoid(z): return 1/(1+np.exp(-z))def forward_propagation(X, parameters): W1 = parameters['W1'] b1 = parameters['b1'] W2 = parameters['W2'] b2 = parameters['b2'] Z1 = np.dot(W1, X) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) cache = {"Z1": Z1,"A1": A1,"Z2": Z2,"A2": A2} return A2, cache
3.3.2 Compute Cost
We will compute the cross-entropy cost. In the above section, we calculated A2. Using A2 we can compute cross-entropy cost using the following formula.
def cross_entropy_cost(A2, Y, parameters): # number of training example m = Y.shape[1] # Compute the cross-entropy cost logprobs = np.multiply(np.log(A2), Y) + np.multiply((1-Y), np.log(1 - A2)) cost = - np.sum(logprobs) / m cost = float(np.squeeze(cost)) return cost
3.3.3 Backpropagation
We need to calculate the gradient with respect to different parameters as shown below.
def backward_propagation(parameters, cache, X, Y): #number of training example m = X.shape[1] W1 = parameters['W1'] W2 = parameters['W2'] A1 = cache['A1'] A2 = cache['A2'] dZ2 = A2-Y dW2 = (1/m) * np.dot(dZ2, A1.T) db2 = (1/m) * np.sum(dZ2, axis=1, keepdims=True) dZ1 = np.multiply(np.dot(W2.T, dZ2), 1 - np.power(A1, 2)) dW1 = (1/m) * np.dot(dZ1, X.T) db1 = (1/m)*np.sum(dZ1, axis=1, keepdims=True) grads = {"dW1": dW1, "db1": db1, "dW2": dW2,"db2": db2} return grads
3.3.4 Gradient Descent (update parameters)
We need to update the parameters using the gradient descent rule i.e.
where α is the learning rate and θ is the parameter.
def gradient_descent(parameters, grads, learning_rate = 0.01): W1 = parameters['W1'] b1 = parameters['b1'] W2 = parameters['W2'] b2 = parameters['b2'] dW1 = grads['dW1'] db1 = grads['db1'] dW2 = grads['dW2'] db2 = grads['db2'] W1 = W1 - learning_rate * dW1 b1 = b1 - learning_rate * db1 W2 = W2 - learning_rate * dW2 b2 = b2 - learning_rate * db2 parameters = {"W1": W1, "b1": b1,"W2": W2,"b2": b2} return parameters
4. Neural Network Model
Finally, putting together all the functions we can build a neural network model with a single hidden layer.
def neural_network_model(X, Y, hidden_unit, num_iterations = 1000): np.random.seed(3) input_unit = define_structure(X, Y)[0] output_unit = define_structure(X, Y)[2] parameters = parameters_initialization(input_unit, hidden_unit, output_unit) W1 = parameters['W1'] b1 = parameters['b1'] W2 = parameters['W2'] b2 = parameters['b2'] for i in range(0, num_iterations): A2, cache = forward_propagation(X, parameters) cost = cross_entropy_cost(A2, Y, parameters) grads = backward_propagation(parameters, cache, X, Y) parameters = gradient_descent(parameters, grads) if i % 5 == 0: print ("Cost after iteration %i: %f" %(i, cost)) return parametersparameters = neural_network_model(X_train, y_train, 4, num_iterations=1000)
5. Prediction
Using the learned parameter, we can predict the class for each example by using forward propagation.
def prediction(parameters, X): A2, cache = forward_propagation(X, parameters) predictions = np.round(A2) return predictions
If the activation > 0.5, then prediction is 1 otherwise 0.
predictions = prediction(parameters, X_train)print ('Accuracy Train: %d' % float((np.dot(y_train, predictions.T) + np.dot(1 - y_train, 1 - predictions.T))/float(y_train.size)*100) + '%')predictions = prediction(parameters, X_test)print ('Accuracy Test: %d' % float((np.dot(y_test, predictions.T) + np.dot(1 - y_test, 1 - predictions.T))/float(y_test.size)*100) + '%')
As we see, the training accuracy is around 97% which means that our model is working and fit the training data with high probability. The test accuracy is around 96%. Given the simple model and the small dataset, we can consider it as a good model.
Be a Medium member here and support independent writing for $5/month and get full access to every story on Medium. | [
{
"code": null,
"e": 261,
"s": 172,
"text": "Implement a 2-class classification neural network with a single hidden layer using Numpy"
},
{
"code": null,
"e": 433,
"s": 261,
"text": "In the previous post, we discussed how to make a simple neural network using NumPy. In this post, we will talk about how to make a deep neural network with a hidden layer."
},
{
"code": null,
"e": 450,
"s": 433,
"text": "Import Libraries"
},
{
"code": null,
"e": 467,
"s": 450,
"text": "Import Libraries"
},
{
"code": null,
"e": 625,
"s": 467,
"text": "We will import some basic python libraries like numpy, matplotlib (for plotting graphs), sklearn (for data mining and analysis tool), etc. that we will need."
},
{
"code": null,
"e": 727,
"s": 625,
"text": "import numpy as npimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_split"
},
{
"code": null,
"e": 738,
"s": 727,
"text": "2. Dataset"
},
{
"code": null,
"e": 1036,
"s": 738,
"text": "We will use the Banknote Dataset that involves predicting whether a given banknote is authentic given several measures taken from a photograph. It is a binary (2-class) classification problem. There are 1,372 observations with 4 input variables and 1 output variable. For more detail see the link."
},
{
"code": null,
"e": 1138,
"s": 1036,
"text": "data = np.genfromtxt(‘data_banknote_authentication.txt’, delimiter = ‘,’)X = data[:,:4]y = data[:, 4]"
},
{
"code": null,
"e": 1405,
"s": 1138,
"text": "We can visualize the dataset using a scatter plot. We can see two classes (authentic and not authentic) are separable. Our goal is to build a model to fit this data i.e. we want to build a neural network model that defines regions as either authentic or unauthentic."
},
{
"code": null,
"e": 1534,
"s": 1405,
"text": "plt.scatter(X[:, 0], X[:, 1], alpha=0.2, c=y, cmap=’viridis’)plt.xlabel(‘variance of wavelet’)plt.ylabel(‘skewness of wavelet’);"
},
{
"code": null,
"e": 1841,
"s": 1534,
"text": "Now, let us divide the data into a training set and test set. This can be accomplished using sklearn train_test_split() function. 20% of data is selected for test and 80% for train. Also, we will check the size of the training set and test set. This will be useful later to design our neural network model."
},
{
"code": null,
"e": 2239,
"s": 1841,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)X_train = X_train.Ty_train = y_train.reshape(1, y_train.shape[0])X_test = X_test.Ty_test = y_test.reshape(1, y_test.shape[0])print (‘Train X Shape: ‘, X_train.shape)print (‘Train Y Shape: ‘, y_train.shape)print (‘I have m = %d training examples!’ % (X_train.shape[1]))print ('\\nTest X Shape: ', X_test.shape)"
},
{
"code": null,
"e": 2263,
"s": 2239,
"text": "3. Neural Network Model"
},
{
"code": null,
"e": 2320,
"s": 2263,
"text": "The general methodology to build a Neural Network is to:"
},
{
"code": null,
"e": 2602,
"s": 2320,
"text": "1. Define the neural network structure ( # of input units, # of hidden units, etc). 2. Initialize the model's parameters3. Loop: - Implement forward propagation - Compute loss - Implement backward propagation to get the gradients - Update parameters (gradient descent)"
},
{
"code": null,
"e": 2694,
"s": 2602,
"text": "We will build a Neural Network with a single hidden layer as shown in the following figure:"
},
{
"code": null,
"e": 2715,
"s": 2694,
"text": "3.1 Define structure"
},
{
"code": null,
"e": 3007,
"s": 2715,
"text": "We need to define the number of input units, the number of hidden units, and the output layer. The input units are equal to the number of features in the dataset (4), hidden layer is set to 4 (for this purpose), and the problem is the binary classification we will use a single layer output."
},
{
"code": null,
"e": 3492,
"s": 3007,
"text": "def define_structure(X, Y): input_unit = X.shape[0] # size of input layer hidden_unit = 4 #hidden layer of size 4 output_unit = Y.shape[0] # size of output layer return (input_unit, hidden_unit, output_unit)(input_unit, hidden_unit, output_unit) = define_structure(X_train, y_train)print(\"The size of the input layer is: = \" + str(input_unit))print(\"The size of the hidden layer is: = \" + str(hidden_unit))print(\"The size of the output layer is: = \" + str(output_unit))"
},
{
"code": null,
"e": 3523,
"s": 3492,
"text": "3.2 Initialize Model Parameter"
},
{
"code": null,
"e": 3689,
"s": 3523,
"text": "We need to initialize the weight matrices and bias vectors. Weight is initialized randomly while bias is set to zeros. This can be done using the following function."
},
{
"code": null,
"e": 4092,
"s": 3689,
"text": "def parameters_initialization(input_unit, hidden_unit, output_unit): np.random.seed(2) W1 = np.random.randn(hidden_unit, input_unit)*0.01 b1 = np.zeros((hidden_unit, 1)) W2 = np.random.randn(output_unit, hidden_unit)*0.01 b2 = np.zeros((output_unit, 1)) parameters = {\"W1\": W1, \"b1\": b1, \"W2\": W2, \"b2\": b2} return parameters"
},
{
"code": null,
"e": 4118,
"s": 4092,
"text": "3.3.1 Forward Propagation"
},
{
"code": null,
"e": 4300,
"s": 4118,
"text": "For forward propagation, given the set of input features (X), we need to compute the activation function for each layer. For the hidden layer, we are using tanh activation function:"
},
{
"code": null,
"e": 4375,
"s": 4300,
"text": "Similarly, for the output layer, we are using sigmoid activation function."
},
{
"code": null,
"e": 4439,
"s": 4375,
"text": "We can use the following code to implement forward propagation."
},
{
"code": null,
"e": 4793,
"s": 4439,
"text": "def sigmoid(z): return 1/(1+np.exp(-z))def forward_propagation(X, parameters): W1 = parameters['W1'] b1 = parameters['b1'] W2 = parameters['W2'] b2 = parameters['b2'] Z1 = np.dot(W1, X) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) cache = {\"Z1\": Z1,\"A1\": A1,\"Z2\": Z2,\"A2\": A2} return A2, cache"
},
{
"code": null,
"e": 4812,
"s": 4793,
"text": "3.3.2 Compute Cost"
},
{
"code": null,
"e": 4964,
"s": 4812,
"text": "We will compute the cross-entropy cost. In the above section, we calculated A2. Using A2 we can compute cross-entropy cost using the following formula."
},
{
"code": null,
"e": 5290,
"s": 4964,
"text": "def cross_entropy_cost(A2, Y, parameters): # number of training example m = Y.shape[1] # Compute the cross-entropy cost logprobs = np.multiply(np.log(A2), Y) + np.multiply((1-Y), np.log(1 - A2)) cost = - np.sum(logprobs) / m cost = float(np.squeeze(cost)) return cost"
},
{
"code": null,
"e": 5312,
"s": 5290,
"text": "3.3.3 Backpropagation"
},
{
"code": null,
"e": 5399,
"s": 5312,
"text": "We need to calculate the gradient with respect to different parameters as shown below."
},
{
"code": null,
"e": 5926,
"s": 5399,
"text": "def backward_propagation(parameters, cache, X, Y): #number of training example m = X.shape[1] W1 = parameters['W1'] W2 = parameters['W2'] A1 = cache['A1'] A2 = cache['A2'] dZ2 = A2-Y dW2 = (1/m) * np.dot(dZ2, A1.T) db2 = (1/m) * np.sum(dZ2, axis=1, keepdims=True) dZ1 = np.multiply(np.dot(W2.T, dZ2), 1 - np.power(A1, 2)) dW1 = (1/m) * np.dot(dZ1, X.T) db1 = (1/m)*np.sum(dZ1, axis=1, keepdims=True) grads = {\"dW1\": dW1, \"db1\": db1, \"dW2\": dW2,\"db2\": db2} return grads"
},
{
"code": null,
"e": 5969,
"s": 5926,
"text": "3.3.4 Gradient Descent (update parameters)"
},
{
"code": null,
"e": 6039,
"s": 5969,
"text": "We need to update the parameters using the gradient descent rule i.e."
},
{
"code": null,
"e": 6092,
"s": 6039,
"text": "where α is the learning rate and θ is the parameter."
},
{
"code": null,
"e": 6562,
"s": 6092,
"text": "def gradient_descent(parameters, grads, learning_rate = 0.01): W1 = parameters['W1'] b1 = parameters['b1'] W2 = parameters['W2'] b2 = parameters['b2'] dW1 = grads['dW1'] db1 = grads['db1'] dW2 = grads['dW2'] db2 = grads['db2'] W1 = W1 - learning_rate * dW1 b1 = b1 - learning_rate * db1 W2 = W2 - learning_rate * dW2 b2 = b2 - learning_rate * db2 parameters = {\"W1\": W1, \"b1\": b1,\"W2\": W2,\"b2\": b2} return parameters"
},
{
"code": null,
"e": 6586,
"s": 6562,
"text": "4. Neural Network Model"
},
{
"code": null,
"e": 6694,
"s": 6586,
"text": "Finally, putting together all the functions we can build a neural network model with a single hidden layer."
},
{
"code": null,
"e": 7498,
"s": 6694,
"text": "def neural_network_model(X, Y, hidden_unit, num_iterations = 1000): np.random.seed(3) input_unit = define_structure(X, Y)[0] output_unit = define_structure(X, Y)[2] parameters = parameters_initialization(input_unit, hidden_unit, output_unit) W1 = parameters['W1'] b1 = parameters['b1'] W2 = parameters['W2'] b2 = parameters['b2'] for i in range(0, num_iterations): A2, cache = forward_propagation(X, parameters) cost = cross_entropy_cost(A2, Y, parameters) grads = backward_propagation(parameters, cache, X, Y) parameters = gradient_descent(parameters, grads) if i % 5 == 0: print (\"Cost after iteration %i: %f\" %(i, cost)) return parametersparameters = neural_network_model(X_train, y_train, 4, num_iterations=1000)"
},
{
"code": null,
"e": 7512,
"s": 7498,
"text": "5. Prediction"
},
{
"code": null,
"e": 7613,
"s": 7512,
"text": "Using the learned parameter, we can predict the class for each example by using forward propagation."
},
{
"code": null,
"e": 7750,
"s": 7613,
"text": "def prediction(parameters, X): A2, cache = forward_propagation(X, parameters) predictions = np.round(A2) return predictions"
},
{
"code": null,
"e": 7809,
"s": 7750,
"text": "If the activation > 0.5, then prediction is 1 otherwise 0."
},
{
"code": null,
"e": 8177,
"s": 7809,
"text": "predictions = prediction(parameters, X_train)print ('Accuracy Train: %d' % float((np.dot(y_train, predictions.T) + np.dot(1 - y_train, 1 - predictions.T))/float(y_train.size)*100) + '%')predictions = prediction(parameters, X_test)print ('Accuracy Test: %d' % float((np.dot(y_test, predictions.T) + np.dot(1 - y_test, 1 - predictions.T))/float(y_test.size)*100) + '%')"
},
{
"code": null,
"e": 8426,
"s": 8177,
"text": "As we see, the training accuracy is around 97% which means that our model is working and fit the training data with high probability. The test accuracy is around 96%. Given the simple model and the small dataset, we can consider it as a good model."
}
]
|
Image Segmentation (Part 1). Thresholding, Otsu’s and HSV... | by Ralph Caubalejo | Towards Data Science | One of the most important contributions of image processing to data science is the ability to use the processing technique to create different segmentation over the image. By segmentation, we mean segmenting different objects from their background. Normally if we have a raw image, and we want to create a dataset of the objects in the image, we would want to first isolate these objects. But how can we do that?
We use different image segmentation techniques to isolate these distinct objects.
There are a lot of segmentation techniques that are frequently used but for part 1 of this article, we will highlight and discuss the following:
Trial and Error ThresholdingOtsu’s MethodHSV Space Segmentation
Trial and Error Thresholding
Otsu’s Method
HSV Space Segmentation
Let us load a sample image:
Our sample image is a collection of small flowers on a plain brown background. Our challenge for this article is to be able to segment each of these flowers from the background. We will try to use the mention image segmentation and see if we are victorious at the end.
Trial and Error in image processing is always been the norm, especially when dealing with new images. This goes the same way as the thresholding method. We try to determine the best value where we can threshold the image and attenuate our desired objects.
Normally in thresholding, we try different thresholding values and compare and contrast which is the better results. An example below shows how we can do that:
#experimented threshold valuessample_t = sample_g>0.70sample_t1 = sample_g>0.50fig, ax = plt.subplots(1,3,figsize=(15,5))im = ax[0].imshow(sample_g,cmap='gray')fig.colorbar(im,ax=ax[0])ax[1].imshow(sample_t,cmap='gray')ax[0].set_title('Grayscale Image',fontsize=15)ax[1].set_title('Threshold at 0.70',fontsize=15)ax[2].imshow(sample_t1,cmap='gray')ax[2].set_title('Threshold at 0.50',fontsize=15)plt.show()
We can see in Figure, two different threshold values at 0.7 and 0.6. Notice that these threshold values are very near to each other but the results by using each one of them are evident. In the 0.70 value, we can clearly segment the white flower, while in the 0.50 value, we did segment the white flower but were joined by other pixel values between that range. If we would want only to segment the white flower, then the best thresholding value is around 0.7.
One thing to do to find the best thresholding value is by looking at the color bar beside the grayscale plot, from here we can choose what is the range that we can set to extract our needed objects.
The next technique is called Otsu’s Method and is actually almost the same with the trial and error but this time it is automated. This method is developed by Nobuyuki Otsu. The idea behind otsu’s method is that the method checks the pixel values and finds the best sweet spot where the two classes can be divided into two by minimizing the variance over the histogram of it.
There is already a predefined scikit-function that can be called upon for easier usage.
from skimage.filters import threshold_otsuthresh = threshold_otsu(sample_g)sample_ot = sample_g > thresh
From Figure 3, we can see the difference between using Otsu’s Method and using a trial and error thresholding. Notice that the result of otsu’s has a more defined blob object compared to the 0.7 threshold graph, this means that it was able to segment and see the entirety of the white flower.
Notice that from the two segmentation techniques above, it is easy to distinguish the bright and dark pixel value because we are dealing with the grayscale image dimension. In terms of doing in the RGB Color Channel dimension, we use HSV or Hue, Saturation, and Value Space to properly segment the flowers.
Let us first show how the sample image looks like in the HSV Values.
from skimage.color import rgb2hsv#convert to hsv scalesample_h= rgb2hsv(sample)#graph per HSV Channelfig, ax = plt.subplots(1, 3, figsize=(15,5))ax[0].imshow(sample_h[:,:,0], cmap='hsv')ax[0].set_title('Hue',fontsize=15)ax[1].imshow(sample_h[:,:,1], cmap='hsv')ax[1].set_title('Saturation',fontsize=15)ax[2].imshow(sample_h[:,:,2], cmap='hsv')ax[2].set_title('Value',fontsize=15);plt.show()
The figure shows the different channels of the HSV Color space, and notice that from this different channel we can identify the needed segmentation objects. From the Value Graph, we can see the white flowers to be having a different intensity from the background.
Using HSV Color Space, we can actually segment the flowers more appropriately compared to the first two techniques. Sample code as follows:
fig, ax = plt.subplots(1,3,figsize=(15,5))im = ax[0].imshow(sample_h[:,:,0],cmap='hsv')fig.colorbar(im,ax=ax[0])ax[0].set_title('Hue Graph',fontsize=15)#set the lower and upper mask based on hue colorbar value of the desired fruitlower_mask = sample_h[:,:,0] > 0.11upper_mask = sample_h[:,:,0] < 0.3mask = upper_mask*lower_mask# get the desired mask and show in original imagered = sample[:,:,0]*maskgreen = sample[:,:,1]*maskblue = sample[:,:,2]*maskmask2 = np.dstack((red,green,blue))ax[1].imshow(mask)ax[2].imshow(mask2)ax[1].set_title('Mask',fontsize=15)ax[2].set_title('Final Image',fontsize=15)plt.tight_layout()plt.show()
From our code, notice that we first defined a lower and upper mask for the intended object. The value of the mask is derived from the color bar value at the side of the Hue Graph. Notice that the flower has a hue that is really different from the background. Using the Value we can already segment the small flower bouquets as a whole.
We also showed the resulting final image when we multiplied the mask to the original image. Notice how defined the segment flowers are from the background. We were able to segment each one of them!
From the results, we can see that we were victorious in segmenting the white flowers from the image by using a trial and error thresholding and also by using otsu’s method. By using also the HSV Color Channel, we were able to segment the flower bouquets much more precisely compared to the other two techniques. To conclude, it is important to note that these technologies have different advantages and disadvantages and can be used simultaneously to suit your needs.
Stay Tuned for Part 2! | [
{
"code": null,
"e": 585,
"s": 172,
"text": "One of the most important contributions of image processing to data science is the ability to use the processing technique to create different segmentation over the image. By segmentation, we mean segmenting different objects from their background. Normally if we have a raw image, and we want to create a dataset of the objects in the image, we would want to first isolate these objects. But how can we do that?"
},
{
"code": null,
"e": 667,
"s": 585,
"text": "We use different image segmentation techniques to isolate these distinct objects."
},
{
"code": null,
"e": 812,
"s": 667,
"text": "There are a lot of segmentation techniques that are frequently used but for part 1 of this article, we will highlight and discuss the following:"
},
{
"code": null,
"e": 876,
"s": 812,
"text": "Trial and Error ThresholdingOtsu’s MethodHSV Space Segmentation"
},
{
"code": null,
"e": 905,
"s": 876,
"text": "Trial and Error Thresholding"
},
{
"code": null,
"e": 919,
"s": 905,
"text": "Otsu’s Method"
},
{
"code": null,
"e": 942,
"s": 919,
"text": "HSV Space Segmentation"
},
{
"code": null,
"e": 970,
"s": 942,
"text": "Let us load a sample image:"
},
{
"code": null,
"e": 1239,
"s": 970,
"text": "Our sample image is a collection of small flowers on a plain brown background. Our challenge for this article is to be able to segment each of these flowers from the background. We will try to use the mention image segmentation and see if we are victorious at the end."
},
{
"code": null,
"e": 1495,
"s": 1239,
"text": "Trial and Error in image processing is always been the norm, especially when dealing with new images. This goes the same way as the thresholding method. We try to determine the best value where we can threshold the image and attenuate our desired objects."
},
{
"code": null,
"e": 1655,
"s": 1495,
"text": "Normally in thresholding, we try different thresholding values and compare and contrast which is the better results. An example below shows how we can do that:"
},
{
"code": null,
"e": 2062,
"s": 1655,
"text": "#experimented threshold valuessample_t = sample_g>0.70sample_t1 = sample_g>0.50fig, ax = plt.subplots(1,3,figsize=(15,5))im = ax[0].imshow(sample_g,cmap='gray')fig.colorbar(im,ax=ax[0])ax[1].imshow(sample_t,cmap='gray')ax[0].set_title('Grayscale Image',fontsize=15)ax[1].set_title('Threshold at 0.70',fontsize=15)ax[2].imshow(sample_t1,cmap='gray')ax[2].set_title('Threshold at 0.50',fontsize=15)plt.show()"
},
{
"code": null,
"e": 2523,
"s": 2062,
"text": "We can see in Figure, two different threshold values at 0.7 and 0.6. Notice that these threshold values are very near to each other but the results by using each one of them are evident. In the 0.70 value, we can clearly segment the white flower, while in the 0.50 value, we did segment the white flower but were joined by other pixel values between that range. If we would want only to segment the white flower, then the best thresholding value is around 0.7."
},
{
"code": null,
"e": 2722,
"s": 2523,
"text": "One thing to do to find the best thresholding value is by looking at the color bar beside the grayscale plot, from here we can choose what is the range that we can set to extract our needed objects."
},
{
"code": null,
"e": 3098,
"s": 2722,
"text": "The next technique is called Otsu’s Method and is actually almost the same with the trial and error but this time it is automated. This method is developed by Nobuyuki Otsu. The idea behind otsu’s method is that the method checks the pixel values and finds the best sweet spot where the two classes can be divided into two by minimizing the variance over the histogram of it."
},
{
"code": null,
"e": 3186,
"s": 3098,
"text": "There is already a predefined scikit-function that can be called upon for easier usage."
},
{
"code": null,
"e": 3292,
"s": 3186,
"text": "from skimage.filters import threshold_otsuthresh = threshold_otsu(sample_g)sample_ot = sample_g > thresh"
},
{
"code": null,
"e": 3585,
"s": 3292,
"text": "From Figure 3, we can see the difference between using Otsu’s Method and using a trial and error thresholding. Notice that the result of otsu’s has a more defined blob object compared to the 0.7 threshold graph, this means that it was able to segment and see the entirety of the white flower."
},
{
"code": null,
"e": 3892,
"s": 3585,
"text": "Notice that from the two segmentation techniques above, it is easy to distinguish the bright and dark pixel value because we are dealing with the grayscale image dimension. In terms of doing in the RGB Color Channel dimension, we use HSV or Hue, Saturation, and Value Space to properly segment the flowers."
},
{
"code": null,
"e": 3961,
"s": 3892,
"text": "Let us first show how the sample image looks like in the HSV Values."
},
{
"code": null,
"e": 4352,
"s": 3961,
"text": "from skimage.color import rgb2hsv#convert to hsv scalesample_h= rgb2hsv(sample)#graph per HSV Channelfig, ax = plt.subplots(1, 3, figsize=(15,5))ax[0].imshow(sample_h[:,:,0], cmap='hsv')ax[0].set_title('Hue',fontsize=15)ax[1].imshow(sample_h[:,:,1], cmap='hsv')ax[1].set_title('Saturation',fontsize=15)ax[2].imshow(sample_h[:,:,2], cmap='hsv')ax[2].set_title('Value',fontsize=15);plt.show()"
},
{
"code": null,
"e": 4616,
"s": 4352,
"text": "The figure shows the different channels of the HSV Color space, and notice that from this different channel we can identify the needed segmentation objects. From the Value Graph, we can see the white flowers to be having a different intensity from the background."
},
{
"code": null,
"e": 4756,
"s": 4616,
"text": "Using HSV Color Space, we can actually segment the flowers more appropriately compared to the first two techniques. Sample code as follows:"
},
{
"code": null,
"e": 5385,
"s": 4756,
"text": "fig, ax = plt.subplots(1,3,figsize=(15,5))im = ax[0].imshow(sample_h[:,:,0],cmap='hsv')fig.colorbar(im,ax=ax[0])ax[0].set_title('Hue Graph',fontsize=15)#set the lower and upper mask based on hue colorbar value of the desired fruitlower_mask = sample_h[:,:,0] > 0.11upper_mask = sample_h[:,:,0] < 0.3mask = upper_mask*lower_mask# get the desired mask and show in original imagered = sample[:,:,0]*maskgreen = sample[:,:,1]*maskblue = sample[:,:,2]*maskmask2 = np.dstack((red,green,blue))ax[1].imshow(mask)ax[2].imshow(mask2)ax[1].set_title('Mask',fontsize=15)ax[2].set_title('Final Image',fontsize=15)plt.tight_layout()plt.show()"
},
{
"code": null,
"e": 5721,
"s": 5385,
"text": "From our code, notice that we first defined a lower and upper mask for the intended object. The value of the mask is derived from the color bar value at the side of the Hue Graph. Notice that the flower has a hue that is really different from the background. Using the Value we can already segment the small flower bouquets as a whole."
},
{
"code": null,
"e": 5919,
"s": 5721,
"text": "We also showed the resulting final image when we multiplied the mask to the original image. Notice how defined the segment flowers are from the background. We were able to segment each one of them!"
},
{
"code": null,
"e": 6387,
"s": 5919,
"text": "From the results, we can see that we were victorious in segmenting the white flowers from the image by using a trial and error thresholding and also by using otsu’s method. By using also the HSV Color Channel, we were able to segment the flower bouquets much more precisely compared to the other two techniques. To conclude, it is important to note that these technologies have different advantages and disadvantages and can be used simultaneously to suit your needs."
}
]
|
Golang Program to reverse a given linked list. | Approach to solve this problem
Step 1 − Define a method that accepts the head of a linked list.
Step 2 − If head == nil, return; else, call ReverseLinkedList, recursively.
Step 3 − Print head.value at the end.
Live Demo
package main
import "fmt"
type Node struct {
value int
next *Node
}
func NewNode(value int, next *Node) *Node{
var n Node
n.value = value
n.next = next
return &n
}
func TraverseLinkedList(head *Node){
fmt.Printf("Input Linked List is: ")
temp := head
for temp != nil {
fmt.Printf("%d ", temp.value)
temp = temp.next
}
fmt.Println()
}
func ReverseLinkedList(head *Node){
if head == nil{
return
}
ReverseLinkedList(head.next)
fmt.Printf("%d ", head.value)
}
func main(){
head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
TraverseLinkedList(head)
fmt.Printf("Reversal of the input linked list is: ")
ReverseLinkedList(head)
}
Input Linked List is: 30 10 40 40
Reversal of the input linked list is: 40 40 10 30 | [
{
"code": null,
"e": 1093,
"s": 1062,
"text": "Approach to solve this problem"
},
{
"code": null,
"e": 1158,
"s": 1093,
"text": "Step 1 − Define a method that accepts the head of a linked list."
},
{
"code": null,
"e": 1234,
"s": 1158,
"text": "Step 2 − If head == nil, return; else, call ReverseLinkedList, recursively."
},
{
"code": null,
"e": 1272,
"s": 1234,
"text": "Step 3 − Print head.value at the end."
},
{
"code": null,
"e": 1283,
"s": 1272,
"text": " Live Demo"
},
{
"code": null,
"e": 1995,
"s": 1283,
"text": "package main\nimport \"fmt\"\ntype Node struct {\n value int\n next *Node\n}\nfunc NewNode(value int, next *Node) *Node{\n var n Node\n n.value = value\n n.next = next\n return &n\n}\nfunc TraverseLinkedList(head *Node){\n fmt.Printf(\"Input Linked List is: \")\n temp := head\n for temp != nil {\n fmt.Printf(\"%d \", temp.value)\n temp = temp.next\n }\n fmt.Println()\n}\nfunc ReverseLinkedList(head *Node){\n if head == nil{\n return\n }\n ReverseLinkedList(head.next)\n fmt.Printf(\"%d \", head.value)\n}\nfunc main(){\n head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))\n TraverseLinkedList(head)\n fmt.Printf(\"Reversal of the input linked list is: \")\n ReverseLinkedList(head)\n}"
},
{
"code": null,
"e": 2079,
"s": 1995,
"text": "Input Linked List is: 30 10 40 40\nReversal of the input linked list is: 40 40 10 30"
}
]
|
dir() Method in Python | The dir() function returns list of the attributes and methods of any object like functions , modules, strings, lists, dictionaries etc. In this article we will see how to use the dir() in different ways in a program and for different requirements.
When we print the value of the dir() without importing any other module into the program, we get the list of methods and attributes that are available as part of the standard library that is available when a python program is initialized.
Print(dir())
Running the above code gives us the following result −
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
As we import additional modules and create variables, they get added to the current environment. Then those methods and attributes also become available in the print statement woth dir().
import math
x = math.ceil(10.03)
print(dir())
Running the above code gives us the following result −
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'math', 'x']
For specific modules we can find the methods and attributes contained in that module by passing it as parameter to the dir(). In the below example we see the methods available in the math module.
import math
print(dir(math))
Running the above code gives us the following result −
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', ...., 'nan', ... 'trunc']
We can also apply the dir() to a class which was user created rather than in-bulit and gets its attributes listed through dir().
Live Demo
class moviecount:
def __dir__(self):
return ['Red Man','Hello Boy','Happy Monday']
movie_dtls = moviecount()
print(dir(movie_dtls))
Running the above code gives us the following result −
['Happy Monday', 'Hello Boy', 'Red Man'] | [
{
"code": null,
"e": 1310,
"s": 1062,
"text": "The dir() function returns list of the attributes and methods of any object like functions , modules, strings, lists, dictionaries etc. In this article we will see how to use the dir() in different ways in a program and for different requirements."
},
{
"code": null,
"e": 1549,
"s": 1310,
"text": "When we print the value of the dir() without importing any other module into the program, we get the list of methods and attributes that are available as part of the standard library that is available when a python program is initialized."
},
{
"code": null,
"e": 1562,
"s": 1549,
"text": "Print(dir())"
},
{
"code": null,
"e": 1617,
"s": 1562,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1743,
"s": 1617,
"text": "['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']"
},
{
"code": null,
"e": 1931,
"s": 1743,
"text": "As we import additional modules and create variables, they get added to the current environment. Then those methods and attributes also become available in the print statement woth dir()."
},
{
"code": null,
"e": 1978,
"s": 1931,
"text": "import math\n\nx = math.ceil(10.03)\nprint(dir())"
},
{
"code": null,
"e": 2033,
"s": 1978,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2172,
"s": 2033,
"text": "['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'math', 'x']"
},
{
"code": null,
"e": 2368,
"s": 2172,
"text": "For specific modules we can find the methods and attributes contained in that module by passing it as parameter to the dir(). In the below example we see the methods available in the math module."
},
{
"code": null,
"e": 2398,
"s": 2368,
"text": "import math\n\nprint(dir(math))"
},
{
"code": null,
"e": 2453,
"s": 2398,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2624,
"s": 2453,
"text": "['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', ...., 'nan', ... 'trunc']"
},
{
"code": null,
"e": 2753,
"s": 2624,
"text": "We can also apply the dir() to a class which was user created rather than in-bulit and gets its attributes listed through dir()."
},
{
"code": null,
"e": 2764,
"s": 2753,
"text": " Live Demo"
},
{
"code": null,
"e": 2908,
"s": 2764,
"text": "class moviecount:\n\n def __dir__(self):\n return ['Red Man','Hello Boy','Happy Monday']\n\nmovie_dtls = moviecount()\n\nprint(dir(movie_dtls))"
},
{
"code": null,
"e": 2963,
"s": 2908,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3004,
"s": 2963,
"text": "['Happy Monday', 'Hello Boy', 'Red Man']"
}
]
|
VBScript Mid Function | The Mid Function returns a specified number of characters from a given input string.
Mid(String,start[,Length])
String, a Required Parameter. Input String from which the specified number of characters to be returned.
String, a Required Parameter. Input String from which the specified number of characters to be returned.
Start, a Required Parameter. An Integer, which Specifies starting position of the string.
Start, a Required Parameter. An Integer, which Specifies starting position of the string.
Length, an Optional Parameter. An Integer, which specifies the number of characters to be returned.
Length, an Optional Parameter. An Integer, which specifies the number of characters to be returned.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
var = "Microsoft VBScript"
document.write("Line 1 : " & Mid(var,2) & "<br />")
document.write("Line 2 : " & Mid(var,2,5) & "<br />")
document.write("Line 3 : " & Mid(var,5,7) & "<br />")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Line 1 : icrosoft VBScript
Line 2 : icros
Line 3 : osoft V
63 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2165,
"s": 2080,
"text": "The Mid Function returns a specified number of characters from a given input string."
},
{
"code": null,
"e": 2193,
"s": 2165,
"text": "Mid(String,start[,Length])\n"
},
{
"code": null,
"e": 2298,
"s": 2193,
"text": "String, a Required Parameter. Input String from which the specified number of characters to be returned."
},
{
"code": null,
"e": 2403,
"s": 2298,
"text": "String, a Required Parameter. Input String from which the specified number of characters to be returned."
},
{
"code": null,
"e": 2493,
"s": 2403,
"text": "Start, a Required Parameter. An Integer, which Specifies starting position of the string."
},
{
"code": null,
"e": 2583,
"s": 2493,
"text": "Start, a Required Parameter. An Integer, which Specifies starting position of the string."
},
{
"code": null,
"e": 2683,
"s": 2583,
"text": "Length, an Optional Parameter. An Integer, which specifies the number of characters to be returned."
},
{
"code": null,
"e": 2783,
"s": 2683,
"text": "Length, an Optional Parameter. An Integer, which specifies the number of characters to be returned."
},
{
"code": null,
"e": 3135,
"s": 2783,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n var = \"Microsoft VBScript\"\n document.write(\"Line 1 : \" & Mid(var,2) & \"<br />\")\n document.write(\"Line 2 : \" & Mid(var,2,5) & \"<br />\")\n document.write(\"Line 3 : \" & Mid(var,5,7) & \"<br />\")\n\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 3256,
"s": 3135,
"text": "When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −"
},
{
"code": null,
"e": 3316,
"s": 3256,
"text": "Line 1 : icrosoft VBScript\nLine 2 : icros\nLine 3 : osoft V\n"
},
{
"code": null,
"e": 3349,
"s": 3316,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3366,
"s": 3349,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3373,
"s": 3366,
"text": " Print"
},
{
"code": null,
"e": 3384,
"s": 3373,
"text": " Add Notes"
}
]
|
Classification Algorithms - Decision Tree | In general, Decision tree analysis is a predictive modelling tool that can be applied across many areas. Decision trees can be constructed by an algorithmic approach that can split the dataset in different ways based on different conditions. Decisions trees are the most powerful algorithms that falls under the category of supervised algorithms.
They can be used for both classification and regression tasks. The two main entities of a tree are decision nodes, where the data is split and leaves, where we got outcome. The example of a binary tree for predicting whether a person is fit or unfit providing various information like age, eating habits and exercise habits, is given below −
In the above decision tree, the question are decision nodes and final outcomes are leaves. We have the following two types of decision trees.
Classification decision trees − In this kind of decision trees, the decision variable is categorical. The above decision tree is an example of classification decision tree.
Classification decision trees − In this kind of decision trees, the decision variable is categorical. The above decision tree is an example of classification decision tree.
Regression decision trees − In this kind of decision trees, the decision variable is continuous.
Regression decision trees − In this kind of decision trees, the decision variable is continuous.
It is the name of the cost function that is used to evaluate the binary splits in the dataset and works with the categorial target variable “Success” or “Failure”.
Higher the value of Gini index, higher the homogeneity. A perfect Gini index value is 0 and worst is 0.5 (for 2 class problem). Gini index for a split can be calculated with the help of following steps −
First, calculate Gini index for sub-nodes by using the formula p^2+q^2, which is the sum of the square of probability for success and failure.
First, calculate Gini index for sub-nodes by using the formula p^2+q^2, which is the sum of the square of probability for success and failure.
Next, calculate Gini index for split using weighted Gini score of each node of that split.
Next, calculate Gini index for split using weighted Gini score of each node of that split.
Classification and Regression Tree (CART) algorithm uses Gini method to generate binary splits.
A split is basically including an attribute in the dataset and a value. We can create a split in dataset with the help of following three parts −
Part 1: Calculating Gini Score − We have just discussed this part in the previous section.
Part 1: Calculating Gini Score − We have just discussed this part in the previous section.
Part 2: Splitting a dataset − It may be defined as separating a dataset into two lists of rows having index of an attribute and a split value of that attribute. After getting the two groups - right and left, from the dataset, we can calculate the value of split by using Gini score calculated in first part. Split value will decide in which group the attribute will reside.
Part 2: Splitting a dataset − It may be defined as separating a dataset into two lists of rows having index of an attribute and a split value of that attribute. After getting the two groups - right and left, from the dataset, we can calculate the value of split by using Gini score calculated in first part. Split value will decide in which group the attribute will reside.
Part 3: Evaluating all splits − Next part after finding Gini score and splitting dataset is the evaluation of all splits. For this purpose, first, we must check every value associated with each attribute as a candidate split. Then we need to find the best possible split by evaluating the cost of the split. The best split will be used as a node in the decision tree.
Part 3: Evaluating all splits − Next part after finding Gini score and splitting dataset is the evaluation of all splits. For this purpose, first, we must check every value associated with each attribute as a candidate split. Then we need to find the best possible split by evaluating the cost of the split. The best split will be used as a node in the decision tree.
As we know that a tree has root node and terminal nodes. After creating the root node, we can build the tree by following two parts −
While creating terminal nodes of decision tree, one important point is to decide when to stop growing tree or creating further terminal nodes. It can be done by using two criteria namely maximum tree depth and minimum node records as follows −
Maximum Tree Depth − As name suggests, this is the maximum number of the nodes in a tree after root node. We must stop adding terminal nodes once a tree reached at maximum depth i.e. once a tree got maximum number of terminal nodes.
Maximum Tree Depth − As name suggests, this is the maximum number of the nodes in a tree after root node. We must stop adding terminal nodes once a tree reached at maximum depth i.e. once a tree got maximum number of terminal nodes.
Minimum Node Records − It may be defined as the minimum number of training patterns that a given node is responsible for. We must stop adding terminal nodes once tree reached at these minimum node records or below this minimum.
Minimum Node Records − It may be defined as the minimum number of training patterns that a given node is responsible for. We must stop adding terminal nodes once tree reached at these minimum node records or below this minimum.
Terminal node is used to make a final prediction.
As we understood about when to create terminal nodes, now we can start building our tree. Recursive splitting is a method to build the tree. In this method, once a node is created, we can create the child nodes (nodes added to an existing node) recursively on each group of data, generated by splitting the dataset, by calling the same function again and again.
After building a decision tree, we need to make a prediction about it. Basically, prediction involves navigating the decision tree with the specifically provided row of data.
We can make a prediction with the help of recursive function, as did above. The same prediction routine is called again with the left or the child right nodes.
The following are some of the assumptions we make while creating decision tree −
While preparing decision trees, the training set is as root node.
While preparing decision trees, the training set is as root node.
Decision tree classifier prefers the features values to be categorical. In case if you want to use continuous values then they must be done discretized prior to model building.
Decision tree classifier prefers the features values to be categorical. In case if you want to use continuous values then they must be done discretized prior to model building.
Based on the attribute’s values, the records are recursively distributed.
Based on the attribute’s values, the records are recursively distributed.
Statistical approach will be used to place attributes at any node position i.e.as root node or internal node.
Statistical approach will be used to place attributes at any node position i.e.as root node or internal node.
In the following example, we are going to implement Decision Tree classifier on Pima Indian Diabetes −
First, start with importing necessary python packages −
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
Next, download the iris dataset from its weblink as follows −
col_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label']
pima = pd.read_csv(r"C:\pima-indians-diabetes.csv", header = None, names = col_names)
pima.head()
Now, split the dataset into features and target variable as follows −
feature_cols = ['pregnant', 'insulin', 'bmi', 'age','glucose','bp','pedigree']
X = pima[feature_cols] # Features
y = pima.label # Target variable
Next, we will divide the data into train and test split. The following code will split the dataset into 70% training data and 30% of testing data −
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)
Next, train the model with the help of DecisionTreeClassifier class of sklearn as follows −
clf = DecisionTreeClassifier()
clf = clf.fit(X_train,y_train)
At last we need to make prediction. It can be done with the help of following script −
y_pred = clf.predict(X_test)
Next, we can get the accuracy score, confusion matrix and classification report as follows −
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
result = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(result)
result1 = classification_report(y_test, y_pred)
print("Classification Report:",)
print (result1)
result2 = accuracy_score(y_test,y_pred)
print("Accuracy:",result2)
Output
Confusion Matrix:
[[116 30]
[ 46 39]]
Classification Report:
precision recall f1-score support
0 0.72 0.79 0.75 146
1 0.57 0.46 0.51 85
micro avg 0.67 0.67 0.67 231
macro avg 0.64 0.63 0.63 231
weighted avg 0.66 0.67 0.66 231
Accuracy: 0.670995670995671
The above decision tree can be visualized with the help of following code −
from sklearn.tree import export_graphviz
from sklearn.externals.six import StringIO
from IPython.display import Image
import pydotplus
dot_data = StringIO()
export_graphviz(clf, out_file=dot_data, filled=True, rounded=True,
special_characters=True,feature_names = feature_cols,class_names=['0','1'])
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
graph.write_png('Pima_diabetes_Tree.png')
Image(graph.create_png())
168 Lectures
13.5 hours
Er. Himanshu Vasishta
64 Lectures
10.5 hours
Eduonix Learning Solutions
91 Lectures
10 hours
Abhilash Nelson
54 Lectures
6 hours
Abhishek And Pukhraj
49 Lectures
5 hours
Abhishek And Pukhraj
35 Lectures
4 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2651,
"s": 2304,
"text": "In general, Decision tree analysis is a predictive modelling tool that can be applied across many areas. Decision trees can be constructed by an algorithmic approach that can split the dataset in different ways based on different conditions. Decisions trees are the most powerful algorithms that falls under the category of supervised algorithms."
},
{
"code": null,
"e": 2993,
"s": 2651,
"text": "They can be used for both classification and regression tasks. The two main entities of a tree are decision nodes, where the data is split and leaves, where we got outcome. The example of a binary tree for predicting whether a person is fit or unfit providing various information like age, eating habits and exercise habits, is given below −"
},
{
"code": null,
"e": 3135,
"s": 2993,
"text": "In the above decision tree, the question are decision nodes and final outcomes are leaves. We have the following two types of decision trees."
},
{
"code": null,
"e": 3308,
"s": 3135,
"text": "Classification decision trees − In this kind of decision trees, the decision variable is categorical. The above decision tree is an example of classification decision tree."
},
{
"code": null,
"e": 3481,
"s": 3308,
"text": "Classification decision trees − In this kind of decision trees, the decision variable is categorical. The above decision tree is an example of classification decision tree."
},
{
"code": null,
"e": 3578,
"s": 3481,
"text": "Regression decision trees − In this kind of decision trees, the decision variable is continuous."
},
{
"code": null,
"e": 3675,
"s": 3578,
"text": "Regression decision trees − In this kind of decision trees, the decision variable is continuous."
},
{
"code": null,
"e": 3839,
"s": 3675,
"text": "It is the name of the cost function that is used to evaluate the binary splits in the dataset and works with the categorial target variable “Success” or “Failure”."
},
{
"code": null,
"e": 4043,
"s": 3839,
"text": "Higher the value of Gini index, higher the homogeneity. A perfect Gini index value is 0 and worst is 0.5 (for 2 class problem). Gini index for a split can be calculated with the help of following steps −"
},
{
"code": null,
"e": 4186,
"s": 4043,
"text": "First, calculate Gini index for sub-nodes by using the formula p^2+q^2, which is the sum of the square of probability for success and failure."
},
{
"code": null,
"e": 4329,
"s": 4186,
"text": "First, calculate Gini index for sub-nodes by using the formula p^2+q^2, which is the sum of the square of probability for success and failure."
},
{
"code": null,
"e": 4420,
"s": 4329,
"text": "Next, calculate Gini index for split using weighted Gini score of each node of that split."
},
{
"code": null,
"e": 4511,
"s": 4420,
"text": "Next, calculate Gini index for split using weighted Gini score of each node of that split."
},
{
"code": null,
"e": 4607,
"s": 4511,
"text": "Classification and Regression Tree (CART) algorithm uses Gini method to generate binary splits."
},
{
"code": null,
"e": 4753,
"s": 4607,
"text": "A split is basically including an attribute in the dataset and a value. We can create a split in dataset with the help of following three parts −"
},
{
"code": null,
"e": 4844,
"s": 4753,
"text": "Part 1: Calculating Gini Score − We have just discussed this part in the previous section."
},
{
"code": null,
"e": 4935,
"s": 4844,
"text": "Part 1: Calculating Gini Score − We have just discussed this part in the previous section."
},
{
"code": null,
"e": 5309,
"s": 4935,
"text": "Part 2: Splitting a dataset − It may be defined as separating a dataset into two lists of rows having index of an attribute and a split value of that attribute. After getting the two groups - right and left, from the dataset, we can calculate the value of split by using Gini score calculated in first part. Split value will decide in which group the attribute will reside."
},
{
"code": null,
"e": 5683,
"s": 5309,
"text": "Part 2: Splitting a dataset − It may be defined as separating a dataset into two lists of rows having index of an attribute and a split value of that attribute. After getting the two groups - right and left, from the dataset, we can calculate the value of split by using Gini score calculated in first part. Split value will decide in which group the attribute will reside."
},
{
"code": null,
"e": 6051,
"s": 5683,
"text": "Part 3: Evaluating all splits − Next part after finding Gini score and splitting dataset is the evaluation of all splits. For this purpose, first, we must check every value associated with each attribute as a candidate split. Then we need to find the best possible split by evaluating the cost of the split. The best split will be used as a node in the decision tree."
},
{
"code": null,
"e": 6419,
"s": 6051,
"text": "Part 3: Evaluating all splits − Next part after finding Gini score and splitting dataset is the evaluation of all splits. For this purpose, first, we must check every value associated with each attribute as a candidate split. Then we need to find the best possible split by evaluating the cost of the split. The best split will be used as a node in the decision tree."
},
{
"code": null,
"e": 6553,
"s": 6419,
"text": "As we know that a tree has root node and terminal nodes. After creating the root node, we can build the tree by following two parts −"
},
{
"code": null,
"e": 6797,
"s": 6553,
"text": "While creating terminal nodes of decision tree, one important point is to decide when to stop growing tree or creating further terminal nodes. It can be done by using two criteria namely maximum tree depth and minimum node records as follows −"
},
{
"code": null,
"e": 7030,
"s": 6797,
"text": "Maximum Tree Depth − As name suggests, this is the maximum number of the nodes in a tree after root node. We must stop adding terminal nodes once a tree reached at maximum depth i.e. once a tree got maximum number of terminal nodes."
},
{
"code": null,
"e": 7263,
"s": 7030,
"text": "Maximum Tree Depth − As name suggests, this is the maximum number of the nodes in a tree after root node. We must stop adding terminal nodes once a tree reached at maximum depth i.e. once a tree got maximum number of terminal nodes."
},
{
"code": null,
"e": 7491,
"s": 7263,
"text": "Minimum Node Records − It may be defined as the minimum number of training patterns that a given node is responsible for. We must stop adding terminal nodes once tree reached at these minimum node records or below this minimum."
},
{
"code": null,
"e": 7719,
"s": 7491,
"text": "Minimum Node Records − It may be defined as the minimum number of training patterns that a given node is responsible for. We must stop adding terminal nodes once tree reached at these minimum node records or below this minimum."
},
{
"code": null,
"e": 7769,
"s": 7719,
"text": "Terminal node is used to make a final prediction."
},
{
"code": null,
"e": 8131,
"s": 7769,
"text": "As we understood about when to create terminal nodes, now we can start building our tree. Recursive splitting is a method to build the tree. In this method, once a node is created, we can create the child nodes (nodes added to an existing node) recursively on each group of data, generated by splitting the dataset, by calling the same function again and again."
},
{
"code": null,
"e": 8306,
"s": 8131,
"text": "After building a decision tree, we need to make a prediction about it. Basically, prediction involves navigating the decision tree with the specifically provided row of data."
},
{
"code": null,
"e": 8466,
"s": 8306,
"text": "We can make a prediction with the help of recursive function, as did above. The same prediction routine is called again with the left or the child right nodes."
},
{
"code": null,
"e": 8547,
"s": 8466,
"text": "The following are some of the assumptions we make while creating decision tree −"
},
{
"code": null,
"e": 8613,
"s": 8547,
"text": "While preparing decision trees, the training set is as root node."
},
{
"code": null,
"e": 8679,
"s": 8613,
"text": "While preparing decision trees, the training set is as root node."
},
{
"code": null,
"e": 8856,
"s": 8679,
"text": "Decision tree classifier prefers the features values to be categorical. In case if you want to use continuous values then they must be done discretized prior to model building."
},
{
"code": null,
"e": 9033,
"s": 8856,
"text": "Decision tree classifier prefers the features values to be categorical. In case if you want to use continuous values then they must be done discretized prior to model building."
},
{
"code": null,
"e": 9107,
"s": 9033,
"text": "Based on the attribute’s values, the records are recursively distributed."
},
{
"code": null,
"e": 9181,
"s": 9107,
"text": "Based on the attribute’s values, the records are recursively distributed."
},
{
"code": null,
"e": 9291,
"s": 9181,
"text": "Statistical approach will be used to place attributes at any node position i.e.as root node or internal node."
},
{
"code": null,
"e": 9401,
"s": 9291,
"text": "Statistical approach will be used to place attributes at any node position i.e.as root node or internal node."
},
{
"code": null,
"e": 9504,
"s": 9401,
"text": "In the following example, we are going to implement Decision Tree classifier on Pima Indian Diabetes −"
},
{
"code": null,
"e": 9560,
"s": 9504,
"text": "First, start with importing necessary python packages −"
},
{
"code": null,
"e": 9682,
"s": 9560,
"text": "import pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\n"
},
{
"code": null,
"e": 9744,
"s": 9682,
"text": "Next, download the iris dataset from its weblink as follows −"
},
{
"code": null,
"e": 9938,
"s": 9744,
"text": "col_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label']\npima = pd.read_csv(r\"C:\\pima-indians-diabetes.csv\", header = None, names = col_names)\npima.head()"
},
{
"code": null,
"e": 10008,
"s": 9938,
"text": "Now, split the dataset into features and target variable as follows −"
},
{
"code": null,
"e": 10155,
"s": 10008,
"text": "feature_cols = ['pregnant', 'insulin', 'bmi', 'age','glucose','bp','pedigree']\nX = pima[feature_cols] # Features\ny = pima.label # Target variable\n"
},
{
"code": null,
"e": 10303,
"s": 10155,
"text": "Next, we will divide the data into train and test split. The following code will split the dataset into 70% training data and 30% of testing data −"
},
{
"code": null,
"e": 10397,
"s": 10303,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)\n"
},
{
"code": null,
"e": 10489,
"s": 10397,
"text": "Next, train the model with the help of DecisionTreeClassifier class of sklearn as follows −"
},
{
"code": null,
"e": 10552,
"s": 10489,
"text": "clf = DecisionTreeClassifier()\nclf = clf.fit(X_train,y_train)\n"
},
{
"code": null,
"e": 10639,
"s": 10552,
"text": "At last we need to make prediction. It can be done with the help of following script −"
},
{
"code": null,
"e": 10669,
"s": 10639,
"text": "y_pred = clf.predict(X_test)\n"
},
{
"code": null,
"e": 10762,
"s": 10669,
"text": "Next, we can get the accuracy score, confusion matrix and classification report as follows −"
},
{
"code": null,
"e": 11093,
"s": 10762,
"text": "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\nresult = confusion_matrix(y_test, y_pred)\nprint(\"Confusion Matrix:\")\nprint(result)\nresult1 = classification_report(y_test, y_pred)\nprint(\"Classification Report:\",)\nprint (result1)\nresult2 = accuracy_score(y_test,y_pred)\nprint(\"Accuracy:\",result2)"
},
{
"code": null,
"e": 11100,
"s": 11093,
"text": "Output"
},
{
"code": null,
"e": 11563,
"s": 11100,
"text": "Confusion Matrix:\n [[116 30]\n [ 46 39]]\nClassification Report:\n precision recall f1-score support\n 0 0.72 0.79 0.75 146\n 1 0.57 0.46 0.51 85\nmicro avg 0.67 0.67 0.67 231\nmacro avg 0.64 0.63 0.63 231\nweighted avg 0.66 0.67 0.66 231\n\nAccuracy: 0.670995670995671\n"
},
{
"code": null,
"e": 11639,
"s": 11563,
"text": "The above decision tree can be visualized with the help of following code −"
},
{
"code": null,
"e": 12071,
"s": 11639,
"text": "from sklearn.tree import export_graphviz\nfrom sklearn.externals.six import StringIO\nfrom IPython.display import Image\nimport pydotplus\ndot_data = StringIO()\nexport_graphviz(clf, out_file=dot_data, filled=True, rounded=True,\n special_characters=True,feature_names = feature_cols,class_names=['0','1'])\n\ngraph = pydotplus.graph_from_dot_data(dot_data.getvalue())\ngraph.write_png('Pima_diabetes_Tree.png')\nImage(graph.create_png())\n"
},
{
"code": null,
"e": 12108,
"s": 12071,
"text": "\n 168 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 12131,
"s": 12108,
"text": " Er. Himanshu Vasishta"
},
{
"code": null,
"e": 12167,
"s": 12131,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 12195,
"s": 12167,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12229,
"s": 12195,
"text": "\n 91 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 12246,
"s": 12229,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12279,
"s": 12246,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 12301,
"s": 12279,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 12334,
"s": 12301,
"text": "\n 49 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 12356,
"s": 12334,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 12389,
"s": 12356,
"text": "\n 35 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12411,
"s": 12389,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 12418,
"s": 12411,
"text": " Print"
},
{
"code": null,
"e": 12429,
"s": 12418,
"text": " Add Notes"
}
]
|
MySQL - SIGNAL Statement | While working with stored procedures in MySQL if an exception or occurs the execution of the procedure terminates abruptly, to avoid this you need to handle the exceptions in MYSQL.
MySQL provides a handler to handle the exceptions in the stored procedures. You can handle these exceptions by declaring a handler using the MySQL DECLARE ... HANDLER Statement.
The SIGNAL in MySQL is used provide error information to a handler, application or a client.
Following is the syntax of the MySQL SIGNAL Statement −
SIGNAL condition_value [SET signal_information_item]
Where, condition_value represents the error value to be returned, which can be sqlstate_value or, condition_name, and signal_information_item which is one of the following: CLASS_ORIGIN, SUBCLASS_ORIGIN, MESSAGE_TEXT, MYSQL_ERRNO, CONSTRAINT_CATALOG, CONSTRAINT_SCHEMA, CONSTRAINT_NAME, CATALOG_NAME, SCHEMA_NAME, TABLE_NAME, COLUMN_NAME, CURSOR_NAME
Following procedure accepts the short form of the degrees and returns the full forms of them. If we pass a value other than B-Tech, M-Tech, BSC, MSC it generates an error message.
Here we are using the SIGNAL Statement to generate the error message −
DELIMITER //
CREATE PROCEDURE example(IN degree VARCHAR(20), OUT full_form Varchar(50))
BEGIN
IF degree='B-Tech' THEN SET full_form = 'Bachelor of Technology';
ELSEIF degree='M-Tech' THEN SET full_form = 'Master of Technology';
ELSEIF degree='BSC' THEN SET full_form = 'Bachelor of Science';
ELSEIF degree='MSC' THEN SET full_form = 'Master of Science';
ELSE
SIGNAL SQLSTATE '01000'
SET MESSAGE_TEXT = 'Choose from the existing values', MYSQL_ERRNO = 12121;
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Given degree is not valid', MYSQL_ERRNO = 1001;
END IF;
END //
DELIMITER ;
You can call the above procedure as shown below −
CALL example('BSC', @fullform);
You can retrieve the value of the variable using SELECT statement −
mysql> SELECT @fullform;
+---------------------+
| @fullform |
+---------------------+
| Bachelor of Science |
+---------------------+
1 row in set (0.00 sec)
If you pass an invalid value to the procedure, it will generate an error message as follow −
mysql> CALL procedureEx ('BBC', @fullform);
ERROR 1001 (45000): Given degree is not valid
Following is another example demonstrating the usage of the SIGNAL Statement −
DELIMITER //
CREATE PROCEDURE example (num INT)
BEGIN
DECLARE testCondition CONDITION FOR SQLSTATE '45000';
IF num < 0 THEN
SIGNAL SQLSTATE '01000';
ELSEIF num > 150 THEN
SIGNAL SQLSTATE '45000';
END IF;
END //
DELIMITER ;
You can call the above procedure by passing two values as shown below −
mysql> DELIMITER ;
mysql> CALL example(15);
Query OK, 0 rows affected (0.00 sec)
mysql> CALL example(160);
ERROR 1644 (45000): Unhandled user-defined exception condition
31 Lectures
6 hours
Eduonix Learning Solutions
84 Lectures
5.5 hours
Frahaan Hussain
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
60 Lectures
10 hours
Vijay Kumar Parvatha Reddy
10 Lectures
1 hours
Harshit Srivastava
25 Lectures
4 hours
Trevoir Williams
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2515,
"s": 2333,
"text": "While working with stored procedures in MySQL if an exception or occurs the execution of the procedure terminates abruptly, to avoid this you need to handle the exceptions in MYSQL."
},
{
"code": null,
"e": 2693,
"s": 2515,
"text": "MySQL provides a handler to handle the exceptions in the stored procedures. You can handle these exceptions by declaring a handler using the MySQL DECLARE ... HANDLER Statement."
},
{
"code": null,
"e": 2786,
"s": 2693,
"text": "The SIGNAL in MySQL is used provide error information to a handler, application or a client."
},
{
"code": null,
"e": 2842,
"s": 2786,
"text": "Following is the syntax of the MySQL SIGNAL Statement −"
},
{
"code": null,
"e": 2896,
"s": 2842,
"text": "SIGNAL condition_value [SET signal_information_item]\n"
},
{
"code": null,
"e": 3247,
"s": 2896,
"text": "Where, condition_value represents the error value to be returned, which can be sqlstate_value or, condition_name, and signal_information_item which is one of the following: CLASS_ORIGIN, SUBCLASS_ORIGIN, MESSAGE_TEXT, MYSQL_ERRNO, CONSTRAINT_CATALOG, CONSTRAINT_SCHEMA, CONSTRAINT_NAME, CATALOG_NAME, SCHEMA_NAME, TABLE_NAME, COLUMN_NAME, CURSOR_NAME"
},
{
"code": null,
"e": 3427,
"s": 3247,
"text": "Following procedure accepts the short form of the degrees and returns the full forms of them. If we pass a value other than B-Tech, M-Tech, BSC, MSC it generates an error message."
},
{
"code": null,
"e": 3498,
"s": 3427,
"text": "Here we are using the SIGNAL Statement to generate the error message −"
},
{
"code": null,
"e": 4149,
"s": 3498,
"text": "DELIMITER //\nCREATE PROCEDURE example(IN degree VARCHAR(20), OUT full_form Varchar(50))\n BEGIN\n IF degree='B-Tech' THEN SET full_form = 'Bachelor of Technology'; \n ELSEIF degree='M-Tech' THEN SET full_form = 'Master of Technology'; \n ELSEIF degree='BSC' THEN SET full_form = 'Bachelor of Science';\n ELSEIF degree='MSC' THEN SET full_form = 'Master of Science';\n ELSE\n SIGNAL SQLSTATE '01000'\n SET MESSAGE_TEXT = 'Choose from the existing values', MYSQL_ERRNO = 12121;\n SIGNAL SQLSTATE '45000'\n SET MESSAGE_TEXT = 'Given degree is not valid', MYSQL_ERRNO = 1001;\n END IF;\n END //\nDELIMITER ;"
},
{
"code": null,
"e": 4199,
"s": 4149,
"text": "You can call the above procedure as shown below −"
},
{
"code": null,
"e": 4231,
"s": 4199,
"text": "CALL example('BSC', @fullform);"
},
{
"code": null,
"e": 4299,
"s": 4231,
"text": "You can retrieve the value of the variable using SELECT statement −"
},
{
"code": null,
"e": 4469,
"s": 4299,
"text": "mysql> SELECT @fullform;\n+---------------------+\n| @fullform |\n+---------------------+\n| Bachelor of Science |\n+---------------------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 4562,
"s": 4469,
"text": "If you pass an invalid value to the procedure, it will generate an error message as follow −"
},
{
"code": null,
"e": 4652,
"s": 4562,
"text": "mysql> CALL procedureEx ('BBC', @fullform);\nERROR 1001 (45000): Given degree is not valid"
},
{
"code": null,
"e": 4731,
"s": 4652,
"text": "Following is another example demonstrating the usage of the SIGNAL Statement −"
},
{
"code": null,
"e": 5002,
"s": 4731,
"text": "DELIMITER //\nCREATE PROCEDURE example (num INT)\n BEGIN\n DECLARE testCondition CONDITION FOR SQLSTATE '45000';\n IF num < 0 THEN\n SIGNAL SQLSTATE '01000';\n ELSEIF num > 150 THEN\n SIGNAL SQLSTATE '45000';\n END IF;\n END //\nDELIMITER ;"
},
{
"code": null,
"e": 5074,
"s": 5002,
"text": "You can call the above procedure by passing two values as shown below −"
},
{
"code": null,
"e": 5245,
"s": 5074,
"text": "mysql> DELIMITER ;\nmysql> CALL example(15);\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> CALL example(160);\nERROR 1644 (45000): Unhandled user-defined exception condition"
},
{
"code": null,
"e": 5278,
"s": 5245,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5306,
"s": 5278,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5341,
"s": 5306,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5358,
"s": 5341,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5392,
"s": 5358,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5427,
"s": 5392,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 5461,
"s": 5427,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 5489,
"s": 5461,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 5522,
"s": 5489,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5542,
"s": 5522,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 5575,
"s": 5542,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5593,
"s": 5575,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 5600,
"s": 5593,
"text": " Print"
},
{
"code": null,
"e": 5611,
"s": 5600,
"text": " Add Notes"
}
]
|
Connecting to and Disconnecting from the MySQL Server | A MySQL user name needs to be provided when ‘mysql’ is invoked. Next a password has to be entered. If the server runs on a system which is not the same as that on which the user logs in, the host name also needs to be provided while trying to log in.
It is suggested to contact the administrator to find out the parameters that are required to connect to the server.
Once the parameters are determined, the below lines need to be sued to connect to the server −
shell> mysql −h host −u user −p
Enter the password: ***
Here, ‘host’ represents the name of the host where the MySQL server is running. The ‘user’ represents the user name of the MySQL account. The appropriate values are substituted in these places. The *** represents the password. This is entered when ‘mysql’ prompts ‘Enter the password’.
Once this is successful, some introductory information is displayed, and this is followed by ‘mysql>’ prompt.
shell> mysql −h host −u user −p
Enter password: ********
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 25338 to server version: 8.0.25-standard
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
The ‘mysql’ prompt tells that ‘mysql’ is ready for the user to enter their SQL commands and execute it.
Note: If the user is trying to log in from the same machine where MySQL is running, the host name can be omitted, and the below line can be run instead:
shell> mysql −u user −p
When trying to connect, if a message like ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2), shows up, it indicates that the MySQL server daemon (Unix) or service (Windows) is not running currently. When this happens, the administrator has to be contacted.
Once the connection is successful, and you wish to disconnect, run the below lines of code −
mysql> QUIT
Bye | [
{
"code": null,
"e": 1313,
"s": 1062,
"text": "A MySQL user name needs to be provided when ‘mysql’ is invoked. Next a password has to be entered. If the server runs on a system which is not the same as that on which the user logs in, the host name also needs to be provided while trying to log in."
},
{
"code": null,
"e": 1429,
"s": 1313,
"text": "It is suggested to contact the administrator to find out the parameters that are required to connect to the server."
},
{
"code": null,
"e": 1524,
"s": 1429,
"text": "Once the parameters are determined, the below lines need to be sued to connect to the server −"
},
{
"code": null,
"e": 1580,
"s": 1524,
"text": "shell> mysql −h host −u user −p\nEnter the password: ***"
},
{
"code": null,
"e": 1866,
"s": 1580,
"text": "Here, ‘host’ represents the name of the host where the MySQL server is running. The ‘user’ represents the user name of the MySQL account. The appropriate values are substituted in these places. The *** represents the password. This is entered when ‘mysql’ prompts ‘Enter the password’."
},
{
"code": null,
"e": 1976,
"s": 1866,
"text": "Once this is successful, some introductory information is displayed, and this is followed by ‘mysql>’ prompt."
},
{
"code": null,
"e": 2230,
"s": 1976,
"text": "shell> mysql −h host −u user −p\nEnter password: ********\nWelcome to the MySQL monitor. Commands end with ; or \\g.\nYour MySQL connection id is 25338 to server version: 8.0.25-standard\n\nType 'help;' or '\\h' for help. Type '\\c' to clear the buffer.\n\nmysql>"
},
{
"code": null,
"e": 2334,
"s": 2230,
"text": "The ‘mysql’ prompt tells that ‘mysql’ is ready for the user to enter their SQL commands and execute it."
},
{
"code": null,
"e": 2487,
"s": 2334,
"text": "Note: If the user is trying to log in from the same machine where MySQL is running, the host name can be omitted, and the below line can be run instead:"
},
{
"code": null,
"e": 2511,
"s": 2487,
"text": "shell> mysql −u user −p"
},
{
"code": null,
"e": 2811,
"s": 2511,
"text": "When trying to connect, if a message like ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2), shows up, it indicates that the MySQL server daemon (Unix) or service (Windows) is not running currently. When this happens, the administrator has to be contacted."
},
{
"code": null,
"e": 2904,
"s": 2811,
"text": "Once the connection is successful, and you wish to disconnect, run the below lines of code −"
},
{
"code": null,
"e": 2920,
"s": 2904,
"text": "mysql> QUIT\nBye"
}
]
|
JavaScript String - constructor Property | A constructor returns a reference to the string function that created the instance's prototype.
Its syntax is as follows −
string.constructor
Returns the function that created this object's instance.
Try the following example.
<html>
<head>
<title>JavaScript String constructor Method</title>
</head>
<body>
<script type = "text/javascript">
var str = new String( "This is string" );
document.write("str.constructor is:" + str.constructor);
</script>
</body>
</html>
str.constructor is: function String() { [native code] }
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2562,
"s": 2466,
"text": "A constructor returns a reference to the string function that created the instance's prototype."
},
{
"code": null,
"e": 2589,
"s": 2562,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2609,
"s": 2589,
"text": "string.constructor\n"
},
{
"code": null,
"e": 2667,
"s": 2609,
"text": "Returns the function that created this object's instance."
},
{
"code": null,
"e": 2694,
"s": 2667,
"text": "Try the following example."
},
{
"code": null,
"e": 2996,
"s": 2694,
"text": "<html>\n <head>\n <title>JavaScript String constructor Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var str = new String( \"This is string\" );\n document.write(\"str.constructor is:\" + str.constructor); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3054,
"s": 2996,
"text": "str.constructor is: function String() { [native code] } \n"
},
{
"code": null,
"e": 3089,
"s": 3054,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3103,
"s": 3089,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3137,
"s": 3103,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3151,
"s": 3137,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3186,
"s": 3151,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3203,
"s": 3186,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3238,
"s": 3203,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3255,
"s": 3238,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3288,
"s": 3255,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3316,
"s": 3288,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3350,
"s": 3316,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3378,
"s": 3350,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3385,
"s": 3378,
"text": " Print"
},
{
"code": null,
"e": 3396,
"s": 3385,
"text": " Add Notes"
}
]
|
Accuracy Visualisation In Deep Learning — Part 1 | by Kaushik Choudhury | Towards Data Science | “One look is worth a thousand words.”
We all want to train the deep learning models in the most optimum way to increase even the last two decimal of the prediction accuracy. We have so many parameters to tweak in the deep learning model starting from the optimiser and its parameters, activation function, number of layers/filters etc. that finding the right combinations of all these parameters is like finding a needle in the haystack.
Fortunately, we can leverage hyperparameters to tune the performance and accuracy of the model, but we need to have a broad sense of the parameter combination to try and test.
Tensor board is one of the most powerful inbuilt tool available to visualise individual model’s performance based on different metrics and also for comparison among different models. It can guide in ascertaining the ballpark parameter combinations which we can further try with hyperparameter tuning.
In this article, I will discuss the deep learning model visualisation with a combination of optimisers and activation function for simple regression. It will enable us to learn how we can discard unsuitable combinations quickly and focus our performance tuning efforts on a few potential parameters.
Step 1: We will use the Scikit learn make_regression method to generate a random dataset for regression testing and train_test_split to divide the datasets into training and testing set.
from sklearn.datasets import make_regressionfrom sklearn.model_selection import train_test_split
Step 2: In the code below, we have imported the Tensor Board and deep learning Keras package. We will use Keras for modelling and Tensor Board for visualisation.
from tensorflow.keras.callbacks import TensorBoardfrom keras.models import Sequentialfrom keras.layers import Dense
Step 3: In this article, we will work with “adam” and “RMSprop” optimiser, and GlorotUniform” and “normal” weight initializer. We have mentioned these in a list and will call the combination in sequence for training the model.
optimizers=["adam","RMSprop"] #Optimisersinitializers=["GlorotUniform","normal"] # Activation function
Step 5: In the below code, we have nested FOR loop to train the deep learning model with different combinations of optimisers and weight initialiser, and record the result for analysis in Tensor board.
Each model is named with weight initialiser and optimiser name to identify each model’s result and graph.
As the main objective of this article is to learn the visualisation of deep learning model results, hence we will work with a very simple model with one input, hidden and output layer.
We will use mean square error as a loss function for all the model and measure the mean absolute percentage error. If you do not know these statistical metrics, then I will suggest referring Wikipedia for detail explanation.
Step 6: We can view the results and analyse after the code is executed. We need to open the command prompt in windows or terminal in mac to start the Tensor Board. Navigate to the folder directory in where logs are saved via command prompt/terminal and then type the below command.
tensorboard --logdir=logs/
It will instantiate the tensor board and will show the address which we need to type in the browser to view the results.
In the current example, we can access the Tensor board by typing http://localhost:6006/ in the browser.
In one consolidated graph, we can view the change in the mean square error as the number of iterations progresses for a different combination of optimizers and weight initializers.
It indicates the optimizers and weight initializers which are unsuitable for the current datasets and modelling. In the current example, the mean squared loss is decreasing way slower for “RMSprop” and “normal” optimiser combination than other combinations. Based on this knowledge from the visualisation, we can focus our energy in fine-tuning the remaining combinations and save time by not tweaking the combination which is not performing well on a broad level.
In the same way, we can view the change in mean absolute percentage error for different combinations as the number of iterations progresses.
We can also use filters to view the graphs of one or more combination of the models.
It is important to give meaningful names to the model as it helps to put the filter correctly and avoid confusion during the analysis. In the current example, the combination of weight initializer and optimiser is the name of the model.
We can also download the graphs, and loss function data SVG and CSV format respectively. Loss function data in CSV format enables us to perform advanced analysis quickly with excel.
Besides visualising the result in terms of epochs progression, we can also view the relative performance of the model with a single click of a mouse.
In this article, we have learnt the basics of the tensor board and seen a few visualisation options available to grasp the finer details about different models in an instant. We also saw the way we can use the tensor board visualisation to focus on fine-tuning potential models. In the next article, we will see a few advanced visualisations for deep learning models.
If you would like to learn Exploratory data analysis (EDA) with visualisation then read by article 5 Advanced Visualisation for Exploratory data analysis (EDA)
If you are a big fan of pandas like me then you will find the article 5 Powerful Visualisation with Pandas for Data Preprocessing interesting to read and learn. | [
{
"code": null,
"e": 210,
"s": 172,
"text": "“One look is worth a thousand words.”"
},
{
"code": null,
"e": 610,
"s": 210,
"text": "We all want to train the deep learning models in the most optimum way to increase even the last two decimal of the prediction accuracy. We have so many parameters to tweak in the deep learning model starting from the optimiser and its parameters, activation function, number of layers/filters etc. that finding the right combinations of all these parameters is like finding a needle in the haystack."
},
{
"code": null,
"e": 786,
"s": 610,
"text": "Fortunately, we can leverage hyperparameters to tune the performance and accuracy of the model, but we need to have a broad sense of the parameter combination to try and test."
},
{
"code": null,
"e": 1087,
"s": 786,
"text": "Tensor board is one of the most powerful inbuilt tool available to visualise individual model’s performance based on different metrics and also for comparison among different models. It can guide in ascertaining the ballpark parameter combinations which we can further try with hyperparameter tuning."
},
{
"code": null,
"e": 1387,
"s": 1087,
"text": "In this article, I will discuss the deep learning model visualisation with a combination of optimisers and activation function for simple regression. It will enable us to learn how we can discard unsuitable combinations quickly and focus our performance tuning efforts on a few potential parameters."
},
{
"code": null,
"e": 1574,
"s": 1387,
"text": "Step 1: We will use the Scikit learn make_regression method to generate a random dataset for regression testing and train_test_split to divide the datasets into training and testing set."
},
{
"code": null,
"e": 1671,
"s": 1574,
"text": "from sklearn.datasets import make_regressionfrom sklearn.model_selection import train_test_split"
},
{
"code": null,
"e": 1833,
"s": 1671,
"text": "Step 2: In the code below, we have imported the Tensor Board and deep learning Keras package. We will use Keras for modelling and Tensor Board for visualisation."
},
{
"code": null,
"e": 1949,
"s": 1833,
"text": "from tensorflow.keras.callbacks import TensorBoardfrom keras.models import Sequentialfrom keras.layers import Dense"
},
{
"code": null,
"e": 2176,
"s": 1949,
"text": "Step 3: In this article, we will work with “adam” and “RMSprop” optimiser, and GlorotUniform” and “normal” weight initializer. We have mentioned these in a list and will call the combination in sequence for training the model."
},
{
"code": null,
"e": 2279,
"s": 2176,
"text": "optimizers=[\"adam\",\"RMSprop\"] #Optimisersinitializers=[\"GlorotUniform\",\"normal\"] # Activation function"
},
{
"code": null,
"e": 2481,
"s": 2279,
"text": "Step 5: In the below code, we have nested FOR loop to train the deep learning model with different combinations of optimisers and weight initialiser, and record the result for analysis in Tensor board."
},
{
"code": null,
"e": 2587,
"s": 2481,
"text": "Each model is named with weight initialiser and optimiser name to identify each model’s result and graph."
},
{
"code": null,
"e": 2772,
"s": 2587,
"text": "As the main objective of this article is to learn the visualisation of deep learning model results, hence we will work with a very simple model with one input, hidden and output layer."
},
{
"code": null,
"e": 2997,
"s": 2772,
"text": "We will use mean square error as a loss function for all the model and measure the mean absolute percentage error. If you do not know these statistical metrics, then I will suggest referring Wikipedia for detail explanation."
},
{
"code": null,
"e": 3279,
"s": 2997,
"text": "Step 6: We can view the results and analyse after the code is executed. We need to open the command prompt in windows or terminal in mac to start the Tensor Board. Navigate to the folder directory in where logs are saved via command prompt/terminal and then type the below command."
},
{
"code": null,
"e": 3306,
"s": 3279,
"text": "tensorboard --logdir=logs/"
},
{
"code": null,
"e": 3427,
"s": 3306,
"text": "It will instantiate the tensor board and will show the address which we need to type in the browser to view the results."
},
{
"code": null,
"e": 3531,
"s": 3427,
"text": "In the current example, we can access the Tensor board by typing http://localhost:6006/ in the browser."
},
{
"code": null,
"e": 3712,
"s": 3531,
"text": "In one consolidated graph, we can view the change in the mean square error as the number of iterations progresses for a different combination of optimizers and weight initializers."
},
{
"code": null,
"e": 4177,
"s": 3712,
"text": "It indicates the optimizers and weight initializers which are unsuitable for the current datasets and modelling. In the current example, the mean squared loss is decreasing way slower for “RMSprop” and “normal” optimiser combination than other combinations. Based on this knowledge from the visualisation, we can focus our energy in fine-tuning the remaining combinations and save time by not tweaking the combination which is not performing well on a broad level."
},
{
"code": null,
"e": 4318,
"s": 4177,
"text": "In the same way, we can view the change in mean absolute percentage error for different combinations as the number of iterations progresses."
},
{
"code": null,
"e": 4403,
"s": 4318,
"text": "We can also use filters to view the graphs of one or more combination of the models."
},
{
"code": null,
"e": 4640,
"s": 4403,
"text": "It is important to give meaningful names to the model as it helps to put the filter correctly and avoid confusion during the analysis. In the current example, the combination of weight initializer and optimiser is the name of the model."
},
{
"code": null,
"e": 4822,
"s": 4640,
"text": "We can also download the graphs, and loss function data SVG and CSV format respectively. Loss function data in CSV format enables us to perform advanced analysis quickly with excel."
},
{
"code": null,
"e": 4972,
"s": 4822,
"text": "Besides visualising the result in terms of epochs progression, we can also view the relative performance of the model with a single click of a mouse."
},
{
"code": null,
"e": 5340,
"s": 4972,
"text": "In this article, we have learnt the basics of the tensor board and seen a few visualisation options available to grasp the finer details about different models in an instant. We also saw the way we can use the tensor board visualisation to focus on fine-tuning potential models. In the next article, we will see a few advanced visualisations for deep learning models."
},
{
"code": null,
"e": 5500,
"s": 5340,
"text": "If you would like to learn Exploratory data analysis (EDA) with visualisation then read by article 5 Advanced Visualisation for Exploratory data analysis (EDA)"
}
]
|
How do you automatically download a Pdf with Selenium Webdriver in Python? | We can automatically download a pdf with the Selenium webdriver in Python. A file is downloaded in the default path set in the Chrome browser. However, we can modify the path of the downloaded file programmatically in Selenium.
This is done with the help of the Options class. We have to create an object of this class and apply the add_experimental_option. We have to pass the parameters - prefs and the path where the pdf is to be downloaded to this method. Finally, this information has to be sent to the webdriver object.
Syntax
op = Options()
p = {"download.default_directory": "../pdf"}
op.add_experimental_option("prefs", p)
Code Implementation
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#Options instance
op = Options()
#configure path of downloaded pdf file
p = {"download.default_directory": "../pdf"}
op.add_experimental_option("prefs", p)
#send browser option to webdriver object
driver = webdriver.Chrome(executable_path='../drivers/chromedriver', options=op)
#implicit wait
driver.implicitly_wait(0.8)
#url launch
driver.get("http://demo.automationtesting.in/FileDownload.html")
#browser maximize
driver.maximize_window()
#identify element
m = driver.find_element_by_id('pdfbox')
m.send_keys("infotest")
t = driver.find_element_by_id('createPdf')
t.click()
e = driver.find_element_by_id('pdf-link-to-download')
e.click()
#driver close
driver.close() | [
{
"code": null,
"e": 1290,
"s": 1062,
"text": "We can automatically download a pdf with the Selenium webdriver in Python. A file is downloaded in the default path set in the Chrome browser. However, we can modify the path of the downloaded file programmatically in Selenium."
},
{
"code": null,
"e": 1588,
"s": 1290,
"text": "This is done with the help of the Options class. We have to create an object of this class and apply the add_experimental_option. We have to pass the parameters - prefs and the path where the pdf is to be downloaded to this method. Finally, this information has to be sent to the webdriver object."
},
{
"code": null,
"e": 1595,
"s": 1588,
"text": "Syntax"
},
{
"code": null,
"e": 1694,
"s": 1595,
"text": "op = Options()\np = {\"download.default_directory\": \"../pdf\"}\nop.add_experimental_option(\"prefs\", p)"
},
{
"code": null,
"e": 1714,
"s": 1694,
"text": "Code Implementation"
},
{
"code": null,
"e": 2468,
"s": 1714,
"text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n#Options instance\nop = Options()\n#configure path of downloaded pdf file\np = {\"download.default_directory\": \"../pdf\"}\nop.add_experimental_option(\"prefs\", p)\n#send browser option to webdriver object\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver', options=op)\n#implicit wait\ndriver.implicitly_wait(0.8)\n#url launch\ndriver.get(\"http://demo.automationtesting.in/FileDownload.html\")\n#browser maximize\ndriver.maximize_window()\n#identify element\nm = driver.find_element_by_id('pdfbox')\nm.send_keys(\"infotest\")\nt = driver.find_element_by_id('createPdf')\nt.click()\ne = driver.find_element_by_id('pdf-link-to-download')\ne.click()\n#driver close\ndriver.close()"
}
]
|
Introduction to Random Forest Classifiers from sklearn | by Philip Wilkinson | Towards Data Science | Admittedly I am a huge fan of the NBA even though I am based in the UK so I don’t get to see much of the games. This means that I get my fix mostly from following the stats and the highlights after the games. Although I regret that I don’t get to watch as many games as I like, the analytical side of me enjoys being able to watch and follow the stats, usually being able to roll them off my tongue to any unsuspecting victim that engages me on the topic. Given this though, I thought it would be good to combine my love of basketball and analytics to integrate them into my learning of Data Science. One of my projects therefore is being able to predict the position of NBA players based on their stats in an attempt to answer the question of whether we are witnessing a truly ‘positionless’ league.
The data for this comes from the Basketball Reference website [1], which lists every NBA players stats for the 2018–2019 season. This season was used because of the limited games played in the 2019–2020 season which may affect any analysis that would have been performed. Data on each player included: Games played, minutes played, field goals, field goal attempts etc. which are typical of an NBA stat sheet. Of course, as part of any data analysis, the data had to be cleaned first. The data I extracted was the total stats for the season for all players and had some duplicates from when players were traded mid-season. The first thing to do was to remove these duplicates and convert the totals into per minute stats, so as to not allow difference in total amount influence the analysis. Of course, this may indicate efficiency rather than anything else (i.e. points per minute), but it was taken as the best non biased indicator of performance. This left me with 22 independent variables from which to identify position from, which, using a correlation plot, several variables were removed that were seen as highly correlated or may bias the results:
corrMatrix = NBA.corr()f, (ax) = plt.subplots(figsize=(15,15))sns.heatmap(corrMatrix, annot=True, ax=ax)plt.show()
Dropping columns of Field Goals, Field Goals attempted, Field Goal percentage because they were aggregates of the 2-point and 3-point variables, and free throw attempts, two point attempts and three point attempts were removed as these could also be represented in free throw percentage, 2 point percentage and three point percentage.
After that, the analysis could proceed. This included splitting the data into our independent variables and the dependent variable and creating a train test split so that the model could be validated.
X = NBA.drop(columns = ["Pos"])y = NBA.Posfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state=42)
The Random Forest Classifier algorithm is an ensemble method in that it utilises the Decision Tree Classifier method but instead of creating just a single Decision Tree, multiple are created. In doing so, it takes advantage of random sampling of the data as each tree learns from a random sample of the data points which are drawn without replacement, and uses a subset of the features considered when splitting nodes. This randomness in generating individual trees minimises the potential for over-fitting and improves the overall predictive accuracy of the model. This is because the final predictions are made by averaging the predictions of each individual tree, thus following the logic that the performance of the crowd is better than the performance of the individual.
The advantages of this are that:
The potential for overfitting is removed by the randomness
The results can be seen as highly accurate and robust
We can extract feature importance, which tells us which variables contribute to the results the most
Of course, there are also disadvantages:
The model can take longer than any decision tree because of the increased complexity
The model may be difficult to interpret in comparison to a single decision tree because of the combination of many decision trees
For this application however the Random Forest Algorithm is a suitable algorithm because of its complexity, its ability to be highly accurate and robust, and the potential to extract feature importance given the high number of independent variables included in the model.
In using the Random Forest Classifier we also want to test the results against a baseline, which we can do by creating a dummy classifier which makes decisions based on simple rules, such as putting all players into the largest category, which in this case is the shooting guard position:
from sklearn.dummy import DummyClassifierfrom sklearn.metrics import accuracy_scorefrom sklearn import metricsdc = DummyClassifier(strategy='most_frequent')dc.fit(X_train,y_train) dc_preds = dc.predict(X_test)print (metrics.classification_report(y_test, dc_preds))
Now, we actually want to generate the model for our data and see how it compares. First thing is to therefore import the Random Forest Classifier algorithm, taken from the sklearn.ensemble module. There are a variety of parameters for this that could be altered depending on what we want from our decision tree, with explanations from here and here. For our purpose, we will still with the default gini criterion for splitting, set the number of estimates at 100 to create 100 individual decision trees, set the oob_score as True and set the max_depth as 3 so that we can later visualise some of the individual trees:
#import the classifierfrom sklearn.ensemble import RandomForestClassifierclf = RandomForestClassifier(n_estimators =100, oob_score=True, max_depth =3)#fit it to the training dataclf.fit(X_train, y_train)#extract the predictionstest_pred_random_forest = clf.predict(X_test)
Once this is fitted, we can then generate the confusion matrix based on the predictions generated by the model. Here, the true label is given on the Y axis, while the predicted label is given on the X-axis:
# get the confusion matrixconfusion_matrix2 = metrics.confusion_matrix(y_test, test_pred_random_forest)#conevrt the matrix to a dataframematrix2_df = pd.DataFrame(confusion_matrix2)# set axis to add title and axis labels laterax = plt.axes()sns.set(font_scale=1.3) # for label sizeplt.figure(figsize=(12,12))plot = sns.heatmap(matrix2_df, annot=True, fmt='g', ax=ax, cmap = "magma") #fmt so that numbers aren't scientific#axis labels and titleax.set_title('Confusion Matrix - Random Forest', fontsize = 17)ax.set_xlabel('Predicted Label', fontsize = 15)ax.set_ylabel('True Label' , fontsize = 15)# change tick labels from 0-4 to 1-5labels = ("C", "PF", "PG", "SF", "SG")ax.set_xticklabels(labels)ax.set_yticklabels(labels)plt.show()fig = plot.get_figure()
From this we can see that the model has done relatively well at predicting Centres and Power Forwards with the main issues being predicting that they are each other, with small forwards often being confused with power forwards and some confusion between point guards and shooting guards. Of course, we can quantify this through the precision, recall, f1-score and accuracy metrics as we did for the dummy classifier:
print (metrics.classification_report(y_test, test_pred_random_forest))
For descriptions of each metric please see here, but we can see that compared to the dummy classifier, the overall accuracy of the model has greatly increased from 0.28 to 0.63 indicating that our model is better than a simple decision rule. However, with only a 63 percent accuracy we are still incorrectly predicting 37 percent, which suggests that our model is not perfect. We can therefore consider how we may be able to improve our model fit.
What is good about the Random Forest Classifier, as compared to a single Decision Tree, is that we can examine the feature importance more closely. This is because while a single decision tree may focus on a particular part of the data and thus associate high importance with that feature even if it doesn’t necessarily have high importance, random sampling and feature selection across multiple decision trees allows us to identify which features consistently have high importance. By creating multiple trees, we can use the average predictive ability of the features in order to reduce the variance that would be associated with feature importance if we were using an individual tree.
From this understanding, we can remove features that are not important and re-run the models again, or use the information simply to understand which features are not important for the model. Removing features will reduce the complexity of the model and thus reduce the compute time, so the trade off is the information gained from features against compute time.
fi = pd.DataFrame({'feature': list(X.columns), 'importance': clf.feature_importances_}).\ sort_values('importance', ascending=True)plot = fi.plot.barh(x = 'feature', y = 'importance', figsize=(15,15))fig = plot.get_figure()
Our results show that 6 features are highly informative while the remaining 11 are less so. The decision to remove these features, if at all, is often based on a threshold (such as 1%) or we could compare them against a random feature (i.e. random set of numbers) which if they perform worse than they would be removed as they simply represent noise.
The alternative measure for this is the permutation importance, which uses random re-shuffling to see how each individual variable influences the model outcome. This does so by training the baseline model, recording the score (in this case the R2 score, then reshuffling the values from one feature in the dataset and rerun the predictions. The feature importance here is the difference between the benchmark score and the modified score, thus the higher the value the more important the feature is for the model:
from sklearn.metrics import r2_scorefrom sklearn.inspection import permutation_importanceresult = permutation_importance(clf, X_test, y_test, n_repeats=10, random_state=42, n_jobs=2)sorted_idx = result.importances_mean.argsort()fig, ax = plt.subplots(figsize=(15,15))ax.boxplot(result.importances[sorted_idx].T, vert=False, labels=X_test.columns[sorted_idx])ax.set_title("Permutation Importances (test set)")fig.tight_layout()plt.show()
From this we can see similar results to the feature importance results, showing essentially that free throws attempted and personal fouls add no information to the model.
Using this, we can create a decision rule to drop results from the model, which we will use if a feature contributes less than 1% feature importance. Which influence the results:
#extracting unimportant featuresUIF = list(fi[fi.importance <= 0.01].feature)X_trainIF = X_train.drop(columns = UIF)X_testIF = X_test.drop(columns = UIF)clf.fit(X_trainIF, y_train)test_pred_random_forest_IF = clf.predict(X_testIF)train_accuracy = clf.score(X_trainIF, y_train)test_accuracy = clf.score(X_testIF, y_test)oob_score = clf.oob_score_print(f"The training score of the random forest classifier is : {train_accuracy:.3f}")print(f"The out of basket score is: {oob_score:.3f}")print(f"The test score of the random forest classifier is {test_accuracy:.3f}")print (metrics.classification_report(y_test, test_pred_random_forest_IF))
Which, after dropping points, three point percentage, free throw percentage and free throws, the accuracy of the model has not changed overall! Thus reducing the complexity of the model while not changing the accuracy of the model. There is one more way of improving the model.
The final way we are going to attempt to improve the model is by tuning the hyperparameters, which are the parameters that influence how the model works and the random forest is created. For this we will select max_depth and min_samples_split which each influence how far each decision tree can go which would increase complexity, and how many samples are required before a branch can split. Increasing max depth increases complexity but could improve our model, and similarly with reducing the min samples split. Given that we want to be able to see whether we accurately predict NBA positions, our metric that we will train against, using grid search, is overall accuracy:
from sklearn.model_selection import GridSearchCVtuned_parameters = [{'max_depth': [4,5,6,7,8], 'min_samples_split': [1,3,5,7,9]}]scores = ['accuracy']for score in scores: print() print(f"Tuning hyperparameters for {score}") print() clf = GridSearchCV( RandomForestClassifier(), tuned_parameters, scoring = f'{score}' ) clf.fit(X_trainIF, y_train) print("Best parameters set found on development set:") print() print(clf.best_params_) print() print("Grid scores on development set:") means = clf.cv_results_["mean_test_score"] stds = clf.cv_results_["std_test_score"] for mean, std, params in zip(means, stds, clf.cv_results_['params']): print(f"{mean:0.3f} (+/-{std*2:0.03f}) for {params}")
Which the results suggest that the best parameters for this is max_depth =7 and min_samples_split =9. Inputting these back into the model results in:
clf = RandomForestClassifier(n_estimators =100, oob_score=True, max_depth =6, min_samples_split = 7)clf.fit(X_trainIF, y_train)test_pred_random_forest = clf.predict(X_testIF)print (metrics.classification_report(y_test, test_pred_random_forest))
Which results in an overall increase in accuracy, but only a small one from 0.63 to 0.64.
Thus, using a Random Forest Classifier, an accuracy of only 0.64 suggests that using these statistics, we can predict position to a degree, however there may be some overlap in certain positions i.e. centre and power forward, point guard and shooting guard. This may suggest that there is a degree of positionlessness in the league, but the fact that the confusion matrix created in the first instance showed that no power forwards or centres were confused with point guards may suggest we are not in a truly positionless league where positions don’t matter at all.
This conclusion of course could also be influenced by the teams themselves, with the rise of small ball meaning that a traditional centre is not needed, such as Houston (Although they have issues of their own at the moment). There could also be more accurate statistics, such as advanced stats, that could be used to inform this and hence may suggest that each position may still be quite clearly defined, or indeed even other methods for classifying positions! Analysis could always be improved and in the future I hope to redo this analysis with different methods and potentially more stats, even comparing how the positions have changed over the years!
For full code see here | [
{
"code": null,
"e": 973,
"s": 172,
"text": "Admittedly I am a huge fan of the NBA even though I am based in the UK so I don’t get to see much of the games. This means that I get my fix mostly from following the stats and the highlights after the games. Although I regret that I don’t get to watch as many games as I like, the analytical side of me enjoys being able to watch and follow the stats, usually being able to roll them off my tongue to any unsuspecting victim that engages me on the topic. Given this though, I thought it would be good to combine my love of basketball and analytics to integrate them into my learning of Data Science. One of my projects therefore is being able to predict the position of NBA players based on their stats in an attempt to answer the question of whether we are witnessing a truly ‘positionless’ league."
},
{
"code": null,
"e": 2129,
"s": 973,
"text": "The data for this comes from the Basketball Reference website [1], which lists every NBA players stats for the 2018–2019 season. This season was used because of the limited games played in the 2019–2020 season which may affect any analysis that would have been performed. Data on each player included: Games played, minutes played, field goals, field goal attempts etc. which are typical of an NBA stat sheet. Of course, as part of any data analysis, the data had to be cleaned first. The data I extracted was the total stats for the season for all players and had some duplicates from when players were traded mid-season. The first thing to do was to remove these duplicates and convert the totals into per minute stats, so as to not allow difference in total amount influence the analysis. Of course, this may indicate efficiency rather than anything else (i.e. points per minute), but it was taken as the best non biased indicator of performance. This left me with 22 independent variables from which to identify position from, which, using a correlation plot, several variables were removed that were seen as highly correlated or may bias the results:"
},
{
"code": null,
"e": 2244,
"s": 2129,
"text": "corrMatrix = NBA.corr()f, (ax) = plt.subplots(figsize=(15,15))sns.heatmap(corrMatrix, annot=True, ax=ax)plt.show()"
},
{
"code": null,
"e": 2579,
"s": 2244,
"text": "Dropping columns of Field Goals, Field Goals attempted, Field Goal percentage because they were aggregates of the 2-point and 3-point variables, and free throw attempts, two point attempts and three point attempts were removed as these could also be represented in free throw percentage, 2 point percentage and three point percentage."
},
{
"code": null,
"e": 2780,
"s": 2579,
"text": "After that, the analysis could proceed. This included splitting the data into our independent variables and the dependent variable and creating a train test split so that the model could be validated."
},
{
"code": null,
"e": 2967,
"s": 2780,
"text": "X = NBA.drop(columns = [\"Pos\"])y = NBA.Posfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state=42)"
},
{
"code": null,
"e": 3743,
"s": 2967,
"text": "The Random Forest Classifier algorithm is an ensemble method in that it utilises the Decision Tree Classifier method but instead of creating just a single Decision Tree, multiple are created. In doing so, it takes advantage of random sampling of the data as each tree learns from a random sample of the data points which are drawn without replacement, and uses a subset of the features considered when splitting nodes. This randomness in generating individual trees minimises the potential for over-fitting and improves the overall predictive accuracy of the model. This is because the final predictions are made by averaging the predictions of each individual tree, thus following the logic that the performance of the crowd is better than the performance of the individual."
},
{
"code": null,
"e": 3776,
"s": 3743,
"text": "The advantages of this are that:"
},
{
"code": null,
"e": 3835,
"s": 3776,
"text": "The potential for overfitting is removed by the randomness"
},
{
"code": null,
"e": 3889,
"s": 3835,
"text": "The results can be seen as highly accurate and robust"
},
{
"code": null,
"e": 3990,
"s": 3889,
"text": "We can extract feature importance, which tells us which variables contribute to the results the most"
},
{
"code": null,
"e": 4031,
"s": 3990,
"text": "Of course, there are also disadvantages:"
},
{
"code": null,
"e": 4116,
"s": 4031,
"text": "The model can take longer than any decision tree because of the increased complexity"
},
{
"code": null,
"e": 4246,
"s": 4116,
"text": "The model may be difficult to interpret in comparison to a single decision tree because of the combination of many decision trees"
},
{
"code": null,
"e": 4518,
"s": 4246,
"text": "For this application however the Random Forest Algorithm is a suitable algorithm because of its complexity, its ability to be highly accurate and robust, and the potential to extract feature importance given the high number of independent variables included in the model."
},
{
"code": null,
"e": 4807,
"s": 4518,
"text": "In using the Random Forest Classifier we also want to test the results against a baseline, which we can do by creating a dummy classifier which makes decisions based on simple rules, such as putting all players into the largest category, which in this case is the shooting guard position:"
},
{
"code": null,
"e": 5072,
"s": 4807,
"text": "from sklearn.dummy import DummyClassifierfrom sklearn.metrics import accuracy_scorefrom sklearn import metricsdc = DummyClassifier(strategy='most_frequent')dc.fit(X_train,y_train) dc_preds = dc.predict(X_test)print (metrics.classification_report(y_test, dc_preds))"
},
{
"code": null,
"e": 5690,
"s": 5072,
"text": "Now, we actually want to generate the model for our data and see how it compares. First thing is to therefore import the Random Forest Classifier algorithm, taken from the sklearn.ensemble module. There are a variety of parameters for this that could be altered depending on what we want from our decision tree, with explanations from here and here. For our purpose, we will still with the default gini criterion for splitting, set the number of estimates at 100 to create 100 individual decision trees, set the oob_score as True and set the max_depth as 3 so that we can later visualise some of the individual trees:"
},
{
"code": null,
"e": 5963,
"s": 5690,
"text": "#import the classifierfrom sklearn.ensemble import RandomForestClassifierclf = RandomForestClassifier(n_estimators =100, oob_score=True, max_depth =3)#fit it to the training dataclf.fit(X_train, y_train)#extract the predictionstest_pred_random_forest = clf.predict(X_test)"
},
{
"code": null,
"e": 6170,
"s": 5963,
"text": "Once this is fitted, we can then generate the confusion matrix based on the predictions generated by the model. Here, the true label is given on the Y axis, while the predicted label is given on the X-axis:"
},
{
"code": null,
"e": 6930,
"s": 6170,
"text": "# get the confusion matrixconfusion_matrix2 = metrics.confusion_matrix(y_test, test_pred_random_forest)#conevrt the matrix to a dataframematrix2_df = pd.DataFrame(confusion_matrix2)# set axis to add title and axis labels laterax = plt.axes()sns.set(font_scale=1.3) # for label sizeplt.figure(figsize=(12,12))plot = sns.heatmap(matrix2_df, annot=True, fmt='g', ax=ax, cmap = \"magma\") #fmt so that numbers aren't scientific#axis labels and titleax.set_title('Confusion Matrix - Random Forest', fontsize = 17)ax.set_xlabel('Predicted Label', fontsize = 15)ax.set_ylabel('True Label' , fontsize = 15)# change tick labels from 0-4 to 1-5labels = (\"C\", \"PF\", \"PG\", \"SF\", \"SG\")ax.set_xticklabels(labels)ax.set_yticklabels(labels)plt.show()fig = plot.get_figure()"
},
{
"code": null,
"e": 7347,
"s": 6930,
"text": "From this we can see that the model has done relatively well at predicting Centres and Power Forwards with the main issues being predicting that they are each other, with small forwards often being confused with power forwards and some confusion between point guards and shooting guards. Of course, we can quantify this through the precision, recall, f1-score and accuracy metrics as we did for the dummy classifier:"
},
{
"code": null,
"e": 7418,
"s": 7347,
"text": "print (metrics.classification_report(y_test, test_pred_random_forest))"
},
{
"code": null,
"e": 7866,
"s": 7418,
"text": "For descriptions of each metric please see here, but we can see that compared to the dummy classifier, the overall accuracy of the model has greatly increased from 0.28 to 0.63 indicating that our model is better than a simple decision rule. However, with only a 63 percent accuracy we are still incorrectly predicting 37 percent, which suggests that our model is not perfect. We can therefore consider how we may be able to improve our model fit."
},
{
"code": null,
"e": 8553,
"s": 7866,
"text": "What is good about the Random Forest Classifier, as compared to a single Decision Tree, is that we can examine the feature importance more closely. This is because while a single decision tree may focus on a particular part of the data and thus associate high importance with that feature even if it doesn’t necessarily have high importance, random sampling and feature selection across multiple decision trees allows us to identify which features consistently have high importance. By creating multiple trees, we can use the average predictive ability of the features in order to reduce the variance that would be associated with feature importance if we were using an individual tree."
},
{
"code": null,
"e": 8916,
"s": 8553,
"text": "From this understanding, we can remove features that are not important and re-run the models again, or use the information simply to understand which features are not important for the model. Removing features will reduce the complexity of the model and thus reduce the compute time, so the trade off is the information gained from features against compute time."
},
{
"code": null,
"e": 9176,
"s": 8916,
"text": "fi = pd.DataFrame({'feature': list(X.columns), 'importance': clf.feature_importances_}).\\ sort_values('importance', ascending=True)plot = fi.plot.barh(x = 'feature', y = 'importance', figsize=(15,15))fig = plot.get_figure()"
},
{
"code": null,
"e": 9527,
"s": 9176,
"text": "Our results show that 6 features are highly informative while the remaining 11 are less so. The decision to remove these features, if at all, is often based on a threshold (such as 1%) or we could compare them against a random feature (i.e. random set of numbers) which if they perform worse than they would be removed as they simply represent noise."
},
{
"code": null,
"e": 10041,
"s": 9527,
"text": "The alternative measure for this is the permutation importance, which uses random re-shuffling to see how each individual variable influences the model outcome. This does so by training the baseline model, recording the score (in this case the R2 score, then reshuffling the values from one feature in the dataset and rerun the predictions. The feature importance here is the difference between the benchmark score and the modified score, thus the higher the value the more important the feature is for the model:"
},
{
"code": null,
"e": 10519,
"s": 10041,
"text": "from sklearn.metrics import r2_scorefrom sklearn.inspection import permutation_importanceresult = permutation_importance(clf, X_test, y_test, n_repeats=10, random_state=42, n_jobs=2)sorted_idx = result.importances_mean.argsort()fig, ax = plt.subplots(figsize=(15,15))ax.boxplot(result.importances[sorted_idx].T, vert=False, labels=X_test.columns[sorted_idx])ax.set_title(\"Permutation Importances (test set)\")fig.tight_layout()plt.show()"
},
{
"code": null,
"e": 10690,
"s": 10519,
"text": "From this we can see similar results to the feature importance results, showing essentially that free throws attempted and personal fouls add no information to the model."
},
{
"code": null,
"e": 10869,
"s": 10690,
"text": "Using this, we can create a decision rule to drop results from the model, which we will use if a feature contributes less than 1% feature importance. Which influence the results:"
},
{
"code": null,
"e": 11506,
"s": 10869,
"text": "#extracting unimportant featuresUIF = list(fi[fi.importance <= 0.01].feature)X_trainIF = X_train.drop(columns = UIF)X_testIF = X_test.drop(columns = UIF)clf.fit(X_trainIF, y_train)test_pred_random_forest_IF = clf.predict(X_testIF)train_accuracy = clf.score(X_trainIF, y_train)test_accuracy = clf.score(X_testIF, y_test)oob_score = clf.oob_score_print(f\"The training score of the random forest classifier is : {train_accuracy:.3f}\")print(f\"The out of basket score is: {oob_score:.3f}\")print(f\"The test score of the random forest classifier is {test_accuracy:.3f}\")print (metrics.classification_report(y_test, test_pred_random_forest_IF))"
},
{
"code": null,
"e": 11784,
"s": 11506,
"text": "Which, after dropping points, three point percentage, free throw percentage and free throws, the accuracy of the model has not changed overall! Thus reducing the complexity of the model while not changing the accuracy of the model. There is one more way of improving the model."
},
{
"code": null,
"e": 12459,
"s": 11784,
"text": "The final way we are going to attempt to improve the model is by tuning the hyperparameters, which are the parameters that influence how the model works and the random forest is created. For this we will select max_depth and min_samples_split which each influence how far each decision tree can go which would increase complexity, and how many samples are required before a branch can split. Increasing max depth increases complexity but could improve our model, and similarly with reducing the min samples split. Given that we want to be able to see whether we accurately predict NBA positions, our metric that we will train against, using grid search, is overall accuracy:"
},
{
"code": null,
"e": 13246,
"s": 12459,
"text": "from sklearn.model_selection import GridSearchCVtuned_parameters = [{'max_depth': [4,5,6,7,8], 'min_samples_split': [1,3,5,7,9]}]scores = ['accuracy']for score in scores: print() print(f\"Tuning hyperparameters for {score}\") print() clf = GridSearchCV( RandomForestClassifier(), tuned_parameters, scoring = f'{score}' ) clf.fit(X_trainIF, y_train) print(\"Best parameters set found on development set:\") print() print(clf.best_params_) print() print(\"Grid scores on development set:\") means = clf.cv_results_[\"mean_test_score\"] stds = clf.cv_results_[\"std_test_score\"] for mean, std, params in zip(means, stds, clf.cv_results_['params']): print(f\"{mean:0.3f} (+/-{std*2:0.03f}) for {params}\")"
},
{
"code": null,
"e": 13396,
"s": 13246,
"text": "Which the results suggest that the best parameters for this is max_depth =7 and min_samples_split =9. Inputting these back into the model results in:"
},
{
"code": null,
"e": 13641,
"s": 13396,
"text": "clf = RandomForestClassifier(n_estimators =100, oob_score=True, max_depth =6, min_samples_split = 7)clf.fit(X_trainIF, y_train)test_pred_random_forest = clf.predict(X_testIF)print (metrics.classification_report(y_test, test_pred_random_forest))"
},
{
"code": null,
"e": 13731,
"s": 13641,
"text": "Which results in an overall increase in accuracy, but only a small one from 0.63 to 0.64."
},
{
"code": null,
"e": 14297,
"s": 13731,
"text": "Thus, using a Random Forest Classifier, an accuracy of only 0.64 suggests that using these statistics, we can predict position to a degree, however there may be some overlap in certain positions i.e. centre and power forward, point guard and shooting guard. This may suggest that there is a degree of positionlessness in the league, but the fact that the confusion matrix created in the first instance showed that no power forwards or centres were confused with point guards may suggest we are not in a truly positionless league where positions don’t matter at all."
},
{
"code": null,
"e": 14953,
"s": 14297,
"text": "This conclusion of course could also be influenced by the teams themselves, with the rise of small ball meaning that a traditional centre is not needed, such as Houston (Although they have issues of their own at the moment). There could also be more accurate statistics, such as advanced stats, that could be used to inform this and hence may suggest that each position may still be quite clearly defined, or indeed even other methods for classifying positions! Analysis could always be improved and in the future I hope to redo this analysis with different methods and potentially more stats, even comparing how the positions have changed over the years!"
}
]
|
Introducing Hiveplotlib. Better Network Visualization in Python... | by Gary Koplik | Towards Data Science | Introducing hiveplotlib— a new, open-source Python package for generating Hive Plots. Originally developed by Martin Krzywinski, Hive Plots generate well-defined figures that allow for interpretable, visual explorations of network data.
The hiveplotlib repository is visible to all on Gitlab, with documentation including further explanation of Hive Plots, examples (both toy data and real data), and full documentation of the code.
Hiveplotlib can be installed via pip:
$ pip install hiveplotlib
Currently, we only support matplotlib-based visualization, but we plan to extend hiveplotlib for use with interactive Python viz packages like bokeh, plotly, and holoviews.
hiveplotlib scales nicely to large network datasets. As a demonstration on synthetic data, let’s build a Hive Plot similar to the “o” in the hiveplotlib logo:
from hiveplotlib import hive_plot_n_axes, Nodefrom hiveplotlib.viz import hive_plot_viz_mplimport numpy as npimport matplotlib.pyplot as pltnum_nodes = 20num_edges = 80np.random.seed(0)# build node datanodes = []for i in range(num_nodes): temp_node = Node(unique_id=i, data={'a': np.random.uniform(), 'b': np.random.uniform(), 'c': np.random.uniform()}) nodes.append(temp_node)# give the nodes simple int IDsnode_ids = np.arange(num_nodes)# build random edgesedges = np.random.choice(np.arange(num_nodes), size=num_edges*2).reshape(-1, 2)# construct HivePlot instance, evenly spacing out nodes over 3 axeshp = hive_plot_n_axes(node_list=nodes, edges=edges, axes_assignments=[ node_ids[:num_nodes//3], node_ids[num_nodes//3:2*num_nodes//3], node_ids[2*num_nodes//3:] ], sorting_variables=["a", "b", "c"], axes_names=["A", "B", "C"], vmins=[0, 0, 0], vmaxes=[1, 1, 1], orient_angle=-30)# change the line kwargs for edges in plothp.add_edge_kwargs(axis_id_1="A", axis_id_2="B", c=f"C0", lw=3, alpha=1, zorder=1.5)hp.add_edge_kwargs(axis_id_1="B", axis_id_2="C", c=f"C2", lw=3, alpha=1, zorder=1.5)hp.add_edge_kwargs(axis_id_1="A", axis_id_2="C", c=f"C1", lw=3, alpha=1, zorder=1.5)fig, ax = hive_plot_viz_mpl(hive_plot=hp)plt.show()
This code (minus the import statements) runs on a laptop in ~200 ms. If we scale up by changing only the above code to num_nodes = 10000 and num_edges = 10000, the runtime goes up to ~1 second. 100,000 nodes and edges runs in ~10 seconds.
In order to use hiveplotlib, we need to wrangle two sources of data, nodes and edges.
Setting up a node in our framework simply requires a dictionary of data and a unique_id to go along with it. This will play particularly nicely with any json output from a database query (for example, queries from a Mongo database through pymongo). pandas dataframes can also easily be converted into this format with df.to_dict(orient="records").
Edges are stored as an (n, 2) numpy.ndarray, where the edges (if directed) move from the first column to the second column.
To demonstrate the code in action with real data, let’s look at a small but popular example: Zachary’s Karate Club.
From 1970–1972, Wayne W. Zachary observed a karate club split into two factions, those that supported the Club President, referred to as “John A,” and those that supported one of the instructors, referred to as “Mr. Hi.” Eventually, the two factions formally split into two clubs.
This frequently-used dataset contains 34 club members (nodes) and a record of who socialized with whom outside of the class (edges) right before the formal split of the club.
Let’s start by putting all our imports for the below work in one place:
from hiveplotlib import Axis, Node, HivePlotfrom hiveplotlib.viz import axes_viz_mpl, node_viz_mpl, edge_viz_mplfrom matplotlib.lines import Line2Dimport matplotlib.pyplot as pltimport networkx as nximport numpy as np# if you're in a jupyter notebook%matplotlib inline
Grabbing the Karate Club dataset is convenient through networkx:
G = nx.karate_club_graph()
The visualizations of this network — in the original paper, networkx, and even Wikipedia — are always done with a circular graph, so let’s use that as a starting point:
# color the nodes by factioncolor = []for node in G.nodes(): if G.nodes.data()[node]['club'] == "Mr. Hi": color.append("C0") else: color.append("C1")fig, ax = plt.subplots(figsize=(10, 10))plt.axis("equal")nx.draw_circular(G, with_labels=True, node_color=color, ax=ax, node_size=1000)ax.set_title("Zachary's Karate Club\nCircular Network Plot", fontsize=20)# legendjohn_a_legend = Line2D([], [], markerfacecolor="C1", markeredgecolor='C1', marker='o', linestyle='None', markersize=10)mr_hi_legend = Line2D([], [], markerfacecolor="C0", markeredgecolor='C0', marker='o', linestyle='None', markersize=10)ax.legend([mr_hi_legend, john_a_legend], ["Mr. Hi", "John A."], loc='upper left', bbox_to_anchor=(1, 1), title="Faction")plt.show()
One clear and unsurprising conclusion from this graph is that Mr. Hi (node 0) and John A. (node 33) were popular, but it’s hard to conclude much else.
Look at the above figure for roughly 10 seconds, then ask yourself the following questions:
How socially separated are the two factions? How long does it take to confirm there exists a connection between blue and orange?
Are the connections between the two groups from people who are generally more social?
To answer the first question, we could certainly be more careful in ordering these nodes in our plot, partitioning orange from blue, but the second question would still be difficult.
Hive Plots allow us to carefully choose both the axes on which to place nodes and how to align the nodes on those axes.
There is thus a lot of necessary declaration, but with the payoff of a far more interpretable network visualization.
To answer our above questions, we will structure our Hive Plot in the following way:
We will construct a total of 4 axes — 2 axes for the John A. faction, and 2 axes for the Mr. Hi Faction. This use of repeat axes allows us to see the intra-faction behavior in a well-defined way in our resulting visualization.
We will look at 3 sets of edges — edges within the John A. faction, edges within the Mr. Hi faction, and edges between the two factions. This will give us a clear answer to our first question above.
We will sort one axis for each faction by node degree. This allows us to nicely answer our second question above, but more on this later.
Let’s first calculate degree for all of our nodes, and simultaneously build the necessary data structures for hiveplotlib:
edges = np.array(G.edges)# pull out degree information from nodes for later usenode_ids, degrees = np.unique(edges, return_counts=True)nodes = []for node_id, degree in zip(node_ids, degrees): # store the index number as a way to align the nodes on axes G.nodes.data()[node_id]['loc'] = node_id # also store the degree of each node as another way to # align nodes on axes G.nodes.data()[node_id]['degree'] = degree temp_node = Node(unique_id=node_id, data=G.nodes.data()[node_id]) nodes.append(temp_node)
Next, the hiveplotlib component. Let’s build out a HivePlot() instance:
karate_hp = HivePlot()### nodes ###karate_hp.add_nodes(nodes)### axes ###axis0 = Axis(axis_id="hi_id", start=1, end=5, angle=-30, long_name="Mr. Hi Faction\n(Sorted by ID)")axis1 = Axis(axis_id="hi_degree", start=1, end=5, angle=30, long_name="Mr. Hi Faction\n(Sorted by Degree)")axis2 = Axis(axis_id="john_degree", start=1, end=5, angle=180 - 30, long_name="John A. Faction\n(Sorted by Degree)")axis3 = Axis(axis_id="john_id", start=1, end=5, angle=180 + 30, long_name="John A. Faction\n(Sorted by ID)")axes = [axis0, axis1, axis2, axis3]karate_hp.add_axes(axes)### node assignments #### partition the nodes into "Mr. Hi" nodes and "John A." nodeshi_nodes = [node.unique_id for node in nodes if node.data['club'] == "Mr. Hi"]john_a_nodes = [node.unique_id for node in nodes if node.data['club'] == "Officer"]# assign nodes and sorting procedure to position nodes on axiskarate_hp.place_nodes_on_axis(axis_id="hi_id", unique_ids=hi_nodes, sorting_feature_to_use="loc", vmin=0, vmax=33)karate_hp.place_nodes_on_axis(axis_id="hi_degree", unique_ids=hi_nodes, sorting_feature_to_use="degree", vmin=0, vmax=17)karate_hp.place_nodes_on_axis(axis_id="john_degree", unique_ids=john_a_nodes, sorting_feature_to_use="degree", vmin=0, vmax=17)karate_hp.place_nodes_on_axis(axis_id="john_id", unique_ids=john_a_nodes, sorting_feature_to_use="loc", vmin=0, vmax=33)### edges ###karate_hp.connect_axes(edges=edges, axis_id_1="hi_degree", axis_id_2="hi_id", c="C0")karate_hp.connect_axes(edges=edges, axis_id_1="john_degree", axis_id_2="john_id", c="C1")karate_hp.connect_axes(edges=edges, axis_id_1="hi_degree", axis_id_2="john_degree", c="C2")
As an extension of the hiveplotlib visualization, we will also pull out the John A. and Mr. Hi node placements to plot them in different colors in the final figure.
# pull out the location of the John A. and Mr. Hi nodes# for visual emphasis laterjohn_a_degree_locations = \ karate_hp.axes["john_degree"].node_placementsjohn_a_node = \ john_a_degree_locations\ .loc[john_a_degree_locations.loc[:, 'unique_id'] == 33, ['x', 'y']].values.flatten()mr_hi_degree_locations = \ karate_hp.axes["hi_degree"].node_placementsmr_hi_node = \ mr_hi_degree_locations\ .loc[mr_hi_degree_locations.loc[:, 'unique_id'] == 0, ['x', 'y']].values.flatten()
We’re now ready to plot:
# plot axesfig, ax = axes_viz_mpl(karate_hp, axes_labels_buffer=1.4)# plot nodesnode_viz_mpl(karate_hp, fig=fig, ax=ax, s=80, c="black")# plot edgesedge_viz_mpl(hive_plot=karate_hp, fig=fig, ax=ax, alpha=0.7, zorder=-1) ax.set_title("Zachary’s Karate Club\nHive Plot", fontsize=20, y=0.9)
We’ll also add in a the highlighting nodes for Mr. Hi and John A. and a custom legend for reference, all using standard matplotlib:
# highlight Mr. Hi and John. A on the degree axesax.scatter(john_a_node[0], john_a_node[1], facecolor="red", edgecolor="black", s=150, lw=2)ax.scatter(mr_hi_node[0], mr_hi_node[1], facecolor="yellow", edgecolor="black", s=150, lw=2)### legend #### edgescustom_lines = [Line2D([0], [0], color=f'C{i}', lw=3, linestyle='-') for i in range(3)]# John A. and Mr. Hi nodesjohn_a_legend = Line2D([], [], markerfacecolor="red", markeredgecolor='black', marker='o', linestyle='None', markersize=10)custom_lines.append(john_a_legend)mr_hi_legend = Line2D([], [], markerfacecolor="yellow", markeredgecolor='black', marker='o', linestyle='None', markersize=10)custom_lines.append(mr_hi_legend)ax.legend(custom_lines, ["Within Mr. Hi Faction", "Within John A. Faction", "Between Factions", "John A.", "Mr. Hi"], loc='upper left', bbox_to_anchor=(0.37, 0.35), title="Social Connections")plt.show()
Let’s revisit our questions from earlier:
How socially separated are the two factions? How long does it take to confirm there exists a connection between blue and orange?
From this figure, there appear to be far more intra-faction connections than inter-faction connections, but we can clearly see inter-faction connections in green.
Are the connections between the two groups from people who are more generally social?
There does not appear to be a particularly strong correlation between inter-faction connections and general sociability. Otherwise, there would be green connections only between nodes high on each of the degree axes.
The setup costs are of course higher to generate this Hive Plot visualization than the circular layout — we had to make the axes and sorting decisions.
As a reward, however, we can generate unambiguous visualizations that can serve as first steps in answering genuine research questions.
We’re excited to continue development on this project going forward. Some of our planned next steps include, but are not limited to:
Extending the package to work with interactive Python visualization packages.
Extending sorting procedures (scale by monotonic functions, sorting on categorical data).
Manipulation of individual edge weights in the resulting visualization.
“Binned Hive Plots” — drawing connections between binnings of nodes on edges rather than individual node-to-node edges.
Thanks to Geometric Data Analytics for supporting the development and open-sourcing of this project.
We’d also like to thank Rodrigo Garcia-Herrera for his work on pyveplot, which we referenced as a starting point for our structural design. We also translated some of his utility methods for use in this repository.
Our documentation can be found at: https://geomdata.gitlab.io/hiveplotlib/index.html
The Hiveplotlib Gitlab repository: https://gitlab.com/geomdata/hiveplotlib
PyPI: https://pypi.org/project/hiveplotlib/
Another excellent resource on Hive Plots: http://www.hiveplot.com/
If you’re looking for network data to play with, the Stanford Large Network Dataset Collection is an excellent resource: https://snap.stanford.edu/data/
Krzywinski M, Birol I, Jones S, Marra M (2011). Hive Plots — Rational Approach to Visualizing Networks. Briefings in Bioinformatics (early access 9 December 2011, doi: 10.1093/bib/bbr069).
Zachary W. (1977). An information flow model for conflict and fission in small groups. Journal of Anthropological Research, 33, 452–473. | [
{
"code": null,
"e": 409,
"s": 172,
"text": "Introducing hiveplotlib— a new, open-source Python package for generating Hive Plots. Originally developed by Martin Krzywinski, Hive Plots generate well-defined figures that allow for interpretable, visual explorations of network data."
},
{
"code": null,
"e": 605,
"s": 409,
"text": "The hiveplotlib repository is visible to all on Gitlab, with documentation including further explanation of Hive Plots, examples (both toy data and real data), and full documentation of the code."
},
{
"code": null,
"e": 643,
"s": 605,
"text": "Hiveplotlib can be installed via pip:"
},
{
"code": null,
"e": 669,
"s": 643,
"text": "$ pip install hiveplotlib"
},
{
"code": null,
"e": 842,
"s": 669,
"text": "Currently, we only support matplotlib-based visualization, but we plan to extend hiveplotlib for use with interactive Python viz packages like bokeh, plotly, and holoviews."
},
{
"code": null,
"e": 1001,
"s": 842,
"text": "hiveplotlib scales nicely to large network datasets. As a demonstration on synthetic data, let’s build a Hive Plot similar to the “o” in the hiveplotlib logo:"
},
{
"code": null,
"e": 2567,
"s": 1001,
"text": "from hiveplotlib import hive_plot_n_axes, Nodefrom hiveplotlib.viz import hive_plot_viz_mplimport numpy as npimport matplotlib.pyplot as pltnum_nodes = 20num_edges = 80np.random.seed(0)# build node datanodes = []for i in range(num_nodes): temp_node = Node(unique_id=i, data={'a': np.random.uniform(), 'b': np.random.uniform(), 'c': np.random.uniform()}) nodes.append(temp_node)# give the nodes simple int IDsnode_ids = np.arange(num_nodes)# build random edgesedges = np.random.choice(np.arange(num_nodes), size=num_edges*2).reshape(-1, 2)# construct HivePlot instance, evenly spacing out nodes over 3 axeshp = hive_plot_n_axes(node_list=nodes, edges=edges, axes_assignments=[ node_ids[:num_nodes//3], node_ids[num_nodes//3:2*num_nodes//3], node_ids[2*num_nodes//3:] ], sorting_variables=[\"a\", \"b\", \"c\"], axes_names=[\"A\", \"B\", \"C\"], vmins=[0, 0, 0], vmaxes=[1, 1, 1], orient_angle=-30)# change the line kwargs for edges in plothp.add_edge_kwargs(axis_id_1=\"A\", axis_id_2=\"B\", c=f\"C0\", lw=3, alpha=1, zorder=1.5)hp.add_edge_kwargs(axis_id_1=\"B\", axis_id_2=\"C\", c=f\"C2\", lw=3, alpha=1, zorder=1.5)hp.add_edge_kwargs(axis_id_1=\"A\", axis_id_2=\"C\", c=f\"C1\", lw=3, alpha=1, zorder=1.5)fig, ax = hive_plot_viz_mpl(hive_plot=hp)plt.show()"
},
{
"code": null,
"e": 2806,
"s": 2567,
"text": "This code (minus the import statements) runs on a laptop in ~200 ms. If we scale up by changing only the above code to num_nodes = 10000 and num_edges = 10000, the runtime goes up to ~1 second. 100,000 nodes and edges runs in ~10 seconds."
},
{
"code": null,
"e": 2892,
"s": 2806,
"text": "In order to use hiveplotlib, we need to wrangle two sources of data, nodes and edges."
},
{
"code": null,
"e": 3240,
"s": 2892,
"text": "Setting up a node in our framework simply requires a dictionary of data and a unique_id to go along with it. This will play particularly nicely with any json output from a database query (for example, queries from a Mongo database through pymongo). pandas dataframes can also easily be converted into this format with df.to_dict(orient=\"records\")."
},
{
"code": null,
"e": 3364,
"s": 3240,
"text": "Edges are stored as an (n, 2) numpy.ndarray, where the edges (if directed) move from the first column to the second column."
},
{
"code": null,
"e": 3480,
"s": 3364,
"text": "To demonstrate the code in action with real data, let’s look at a small but popular example: Zachary’s Karate Club."
},
{
"code": null,
"e": 3761,
"s": 3480,
"text": "From 1970–1972, Wayne W. Zachary observed a karate club split into two factions, those that supported the Club President, referred to as “John A,” and those that supported one of the instructors, referred to as “Mr. Hi.” Eventually, the two factions formally split into two clubs."
},
{
"code": null,
"e": 3936,
"s": 3761,
"text": "This frequently-used dataset contains 34 club members (nodes) and a record of who socialized with whom outside of the class (edges) right before the formal split of the club."
},
{
"code": null,
"e": 4008,
"s": 3936,
"text": "Let’s start by putting all our imports for the below work in one place:"
},
{
"code": null,
"e": 4277,
"s": 4008,
"text": "from hiveplotlib import Axis, Node, HivePlotfrom hiveplotlib.viz import axes_viz_mpl, node_viz_mpl, edge_viz_mplfrom matplotlib.lines import Line2Dimport matplotlib.pyplot as pltimport networkx as nximport numpy as np# if you're in a jupyter notebook%matplotlib inline"
},
{
"code": null,
"e": 4342,
"s": 4277,
"text": "Grabbing the Karate Club dataset is convenient through networkx:"
},
{
"code": null,
"e": 4369,
"s": 4342,
"text": "G = nx.karate_club_graph()"
},
{
"code": null,
"e": 4538,
"s": 4369,
"text": "The visualizations of this network — in the original paper, networkx, and even Wikipedia — are always done with a circular graph, so let’s use that as a starting point:"
},
{
"code": null,
"e": 5354,
"s": 4538,
"text": "# color the nodes by factioncolor = []for node in G.nodes(): if G.nodes.data()[node]['club'] == \"Mr. Hi\": color.append(\"C0\") else: color.append(\"C1\")fig, ax = plt.subplots(figsize=(10, 10))plt.axis(\"equal\")nx.draw_circular(G, with_labels=True, node_color=color, ax=ax, node_size=1000)ax.set_title(\"Zachary's Karate Club\\nCircular Network Plot\", fontsize=20)# legendjohn_a_legend = Line2D([], [], markerfacecolor=\"C1\", markeredgecolor='C1', marker='o', linestyle='None', markersize=10)mr_hi_legend = Line2D([], [], markerfacecolor=\"C0\", markeredgecolor='C0', marker='o', linestyle='None', markersize=10)ax.legend([mr_hi_legend, john_a_legend], [\"Mr. Hi\", \"John A.\"], loc='upper left', bbox_to_anchor=(1, 1), title=\"Faction\")plt.show()"
},
{
"code": null,
"e": 5505,
"s": 5354,
"text": "One clear and unsurprising conclusion from this graph is that Mr. Hi (node 0) and John A. (node 33) were popular, but it’s hard to conclude much else."
},
{
"code": null,
"e": 5597,
"s": 5505,
"text": "Look at the above figure for roughly 10 seconds, then ask yourself the following questions:"
},
{
"code": null,
"e": 5726,
"s": 5597,
"text": "How socially separated are the two factions? How long does it take to confirm there exists a connection between blue and orange?"
},
{
"code": null,
"e": 5812,
"s": 5726,
"text": "Are the connections between the two groups from people who are generally more social?"
},
{
"code": null,
"e": 5995,
"s": 5812,
"text": "To answer the first question, we could certainly be more careful in ordering these nodes in our plot, partitioning orange from blue, but the second question would still be difficult."
},
{
"code": null,
"e": 6115,
"s": 5995,
"text": "Hive Plots allow us to carefully choose both the axes on which to place nodes and how to align the nodes on those axes."
},
{
"code": null,
"e": 6232,
"s": 6115,
"text": "There is thus a lot of necessary declaration, but with the payoff of a far more interpretable network visualization."
},
{
"code": null,
"e": 6317,
"s": 6232,
"text": "To answer our above questions, we will structure our Hive Plot in the following way:"
},
{
"code": null,
"e": 6544,
"s": 6317,
"text": "We will construct a total of 4 axes — 2 axes for the John A. faction, and 2 axes for the Mr. Hi Faction. This use of repeat axes allows us to see the intra-faction behavior in a well-defined way in our resulting visualization."
},
{
"code": null,
"e": 6743,
"s": 6544,
"text": "We will look at 3 sets of edges — edges within the John A. faction, edges within the Mr. Hi faction, and edges between the two factions. This will give us a clear answer to our first question above."
},
{
"code": null,
"e": 6881,
"s": 6743,
"text": "We will sort one axis for each faction by node degree. This allows us to nicely answer our second question above, but more on this later."
},
{
"code": null,
"e": 7004,
"s": 6881,
"text": "Let’s first calculate degree for all of our nodes, and simultaneously build the necessary data structures for hiveplotlib:"
},
{
"code": null,
"e": 7550,
"s": 7004,
"text": "edges = np.array(G.edges)# pull out degree information from nodes for later usenode_ids, degrees = np.unique(edges, return_counts=True)nodes = []for node_id, degree in zip(node_ids, degrees): # store the index number as a way to align the nodes on axes G.nodes.data()[node_id]['loc'] = node_id # also store the degree of each node as another way to # align nodes on axes G.nodes.data()[node_id]['degree'] = degree temp_node = Node(unique_id=node_id, data=G.nodes.data()[node_id]) nodes.append(temp_node)"
},
{
"code": null,
"e": 7622,
"s": 7550,
"text": "Next, the hiveplotlib component. Let’s build out a HivePlot() instance:"
},
{
"code": null,
"e": 9714,
"s": 7622,
"text": "karate_hp = HivePlot()### nodes ###karate_hp.add_nodes(nodes)### axes ###axis0 = Axis(axis_id=\"hi_id\", start=1, end=5, angle=-30, long_name=\"Mr. Hi Faction\\n(Sorted by ID)\")axis1 = Axis(axis_id=\"hi_degree\", start=1, end=5, angle=30, long_name=\"Mr. Hi Faction\\n(Sorted by Degree)\")axis2 = Axis(axis_id=\"john_degree\", start=1, end=5, angle=180 - 30, long_name=\"John A. Faction\\n(Sorted by Degree)\")axis3 = Axis(axis_id=\"john_id\", start=1, end=5, angle=180 + 30, long_name=\"John A. Faction\\n(Sorted by ID)\")axes = [axis0, axis1, axis2, axis3]karate_hp.add_axes(axes)### node assignments #### partition the nodes into \"Mr. Hi\" nodes and \"John A.\" nodeshi_nodes = [node.unique_id for node in nodes if node.data['club'] == \"Mr. Hi\"]john_a_nodes = [node.unique_id for node in nodes if node.data['club'] == \"Officer\"]# assign nodes and sorting procedure to position nodes on axiskarate_hp.place_nodes_on_axis(axis_id=\"hi_id\", unique_ids=hi_nodes, sorting_feature_to_use=\"loc\", vmin=0, vmax=33)karate_hp.place_nodes_on_axis(axis_id=\"hi_degree\", unique_ids=hi_nodes, sorting_feature_to_use=\"degree\", vmin=0, vmax=17)karate_hp.place_nodes_on_axis(axis_id=\"john_degree\", unique_ids=john_a_nodes, sorting_feature_to_use=\"degree\", vmin=0, vmax=17)karate_hp.place_nodes_on_axis(axis_id=\"john_id\", unique_ids=john_a_nodes, sorting_feature_to_use=\"loc\", vmin=0, vmax=33)### edges ###karate_hp.connect_axes(edges=edges, axis_id_1=\"hi_degree\", axis_id_2=\"hi_id\", c=\"C0\")karate_hp.connect_axes(edges=edges, axis_id_1=\"john_degree\", axis_id_2=\"john_id\", c=\"C1\")karate_hp.connect_axes(edges=edges, axis_id_1=\"hi_degree\", axis_id_2=\"john_degree\", c=\"C2\")"
},
{
"code": null,
"e": 9879,
"s": 9714,
"text": "As an extension of the hiveplotlib visualization, we will also pull out the John A. and Mr. Hi node placements to plot them in different colors in the final figure."
},
{
"code": null,
"e": 10402,
"s": 9879,
"text": "# pull out the location of the John A. and Mr. Hi nodes# for visual emphasis laterjohn_a_degree_locations = \\ karate_hp.axes[\"john_degree\"].node_placementsjohn_a_node = \\ john_a_degree_locations\\ .loc[john_a_degree_locations.loc[:, 'unique_id'] == 33, ['x', 'y']].values.flatten()mr_hi_degree_locations = \\ karate_hp.axes[\"hi_degree\"].node_placementsmr_hi_node = \\ mr_hi_degree_locations\\ .loc[mr_hi_degree_locations.loc[:, 'unique_id'] == 0, ['x', 'y']].values.flatten()"
},
{
"code": null,
"e": 10427,
"s": 10402,
"text": "We’re now ready to plot:"
},
{
"code": null,
"e": 10765,
"s": 10427,
"text": "# plot axesfig, ax = axes_viz_mpl(karate_hp, axes_labels_buffer=1.4)# plot nodesnode_viz_mpl(karate_hp, fig=fig, ax=ax, s=80, c=\"black\")# plot edgesedge_viz_mpl(hive_plot=karate_hp, fig=fig, ax=ax, alpha=0.7, zorder=-1) ax.set_title(\"Zachary’s Karate Club\\nHive Plot\", fontsize=20, y=0.9)"
},
{
"code": null,
"e": 10897,
"s": 10765,
"text": "We’ll also add in a the highlighting nodes for Mr. Hi and John A. and a custom legend for reference, all using standard matplotlib:"
},
{
"code": null,
"e": 12017,
"s": 10897,
"text": "# highlight Mr. Hi and John. A on the degree axesax.scatter(john_a_node[0], john_a_node[1], facecolor=\"red\", edgecolor=\"black\", s=150, lw=2)ax.scatter(mr_hi_node[0], mr_hi_node[1], facecolor=\"yellow\", edgecolor=\"black\", s=150, lw=2)### legend #### edgescustom_lines = [Line2D([0], [0], color=f'C{i}', lw=3, linestyle='-') for i in range(3)]# John A. and Mr. Hi nodesjohn_a_legend = Line2D([], [], markerfacecolor=\"red\", markeredgecolor='black', marker='o', linestyle='None', markersize=10)custom_lines.append(john_a_legend)mr_hi_legend = Line2D([], [], markerfacecolor=\"yellow\", markeredgecolor='black', marker='o', linestyle='None', markersize=10)custom_lines.append(mr_hi_legend)ax.legend(custom_lines, [\"Within Mr. Hi Faction\", \"Within John A. Faction\", \"Between Factions\", \"John A.\", \"Mr. Hi\"], loc='upper left', bbox_to_anchor=(0.37, 0.35), title=\"Social Connections\")plt.show()"
},
{
"code": null,
"e": 12059,
"s": 12017,
"text": "Let’s revisit our questions from earlier:"
},
{
"code": null,
"e": 12188,
"s": 12059,
"text": "How socially separated are the two factions? How long does it take to confirm there exists a connection between blue and orange?"
},
{
"code": null,
"e": 12351,
"s": 12188,
"text": "From this figure, there appear to be far more intra-faction connections than inter-faction connections, but we can clearly see inter-faction connections in green."
},
{
"code": null,
"e": 12437,
"s": 12351,
"text": "Are the connections between the two groups from people who are more generally social?"
},
{
"code": null,
"e": 12654,
"s": 12437,
"text": "There does not appear to be a particularly strong correlation between inter-faction connections and general sociability. Otherwise, there would be green connections only between nodes high on each of the degree axes."
},
{
"code": null,
"e": 12806,
"s": 12654,
"text": "The setup costs are of course higher to generate this Hive Plot visualization than the circular layout — we had to make the axes and sorting decisions."
},
{
"code": null,
"e": 12942,
"s": 12806,
"text": "As a reward, however, we can generate unambiguous visualizations that can serve as first steps in answering genuine research questions."
},
{
"code": null,
"e": 13075,
"s": 12942,
"text": "We’re excited to continue development on this project going forward. Some of our planned next steps include, but are not limited to:"
},
{
"code": null,
"e": 13153,
"s": 13075,
"text": "Extending the package to work with interactive Python visualization packages."
},
{
"code": null,
"e": 13243,
"s": 13153,
"text": "Extending sorting procedures (scale by monotonic functions, sorting on categorical data)."
},
{
"code": null,
"e": 13315,
"s": 13243,
"text": "Manipulation of individual edge weights in the resulting visualization."
},
{
"code": null,
"e": 13435,
"s": 13315,
"text": "“Binned Hive Plots” — drawing connections between binnings of nodes on edges rather than individual node-to-node edges."
},
{
"code": null,
"e": 13536,
"s": 13435,
"text": "Thanks to Geometric Data Analytics for supporting the development and open-sourcing of this project."
},
{
"code": null,
"e": 13751,
"s": 13536,
"text": "We’d also like to thank Rodrigo Garcia-Herrera for his work on pyveplot, which we referenced as a starting point for our structural design. We also translated some of his utility methods for use in this repository."
},
{
"code": null,
"e": 13836,
"s": 13751,
"text": "Our documentation can be found at: https://geomdata.gitlab.io/hiveplotlib/index.html"
},
{
"code": null,
"e": 13911,
"s": 13836,
"text": "The Hiveplotlib Gitlab repository: https://gitlab.com/geomdata/hiveplotlib"
},
{
"code": null,
"e": 13955,
"s": 13911,
"text": "PyPI: https://pypi.org/project/hiveplotlib/"
},
{
"code": null,
"e": 14022,
"s": 13955,
"text": "Another excellent resource on Hive Plots: http://www.hiveplot.com/"
},
{
"code": null,
"e": 14175,
"s": 14022,
"text": "If you’re looking for network data to play with, the Stanford Large Network Dataset Collection is an excellent resource: https://snap.stanford.edu/data/"
},
{
"code": null,
"e": 14364,
"s": 14175,
"text": "Krzywinski M, Birol I, Jones S, Marra M (2011). Hive Plots — Rational Approach to Visualizing Networks. Briefings in Bioinformatics (early access 9 December 2011, doi: 10.1093/bib/bbr069)."
}
]
|
How to update MongoDB Object? | To update MongoDB object, use UPDATE(). Let us create a collection with documents −
> db.demo77.insertOne({"Details" : { "Score" : 78 } });
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2bd6f371bf0181ecc4228a")
}
Display all documents from a collection with the help of find() method −
> db.demo77.find();
This will produce the following output −
{ "_id" : ObjectId("5e2bd6f371bf0181ecc4228a"), "Details" : { "Score" : 78 } }
Following is the query to update MongoDB object −
> db.demo77.update({'Details.Score':78},{$set:{'Details.Score':89}},{multi:true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo77.find();
This will produce the following output −
{ "_id" : ObjectId("5e2bd6f371bf0181ecc4228a"), "Details" : { "Score" : 89 } } | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "To update MongoDB object, use UPDATE(). Let us create a collection with documents −"
},
{
"code": null,
"e": 1287,
"s": 1146,
"text": "> db.demo77.insertOne({\"Details\" : { \"Score\" : 78 } });\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2bd6f371bf0181ecc4228a\")\n}"
},
{
"code": null,
"e": 1360,
"s": 1287,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1380,
"s": 1360,
"text": "> db.demo77.find();"
},
{
"code": null,
"e": 1421,
"s": 1380,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1500,
"s": 1421,
"text": "{ \"_id\" : ObjectId(\"5e2bd6f371bf0181ecc4228a\"), \"Details\" : { \"Score\" : 78 } }"
},
{
"code": null,
"e": 1550,
"s": 1500,
"text": "Following is the query to update MongoDB object −"
},
{
"code": null,
"e": 1699,
"s": 1550,
"text": "> db.demo77.update({'Details.Score':78},{$set:{'Details.Score':89}},{multi:true});\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 1772,
"s": 1699,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1792,
"s": 1772,
"text": "> db.demo77.find();"
},
{
"code": null,
"e": 1833,
"s": 1792,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1912,
"s": 1833,
"text": "{ \"_id\" : ObjectId(\"5e2bd6f371bf0181ecc4228a\"), \"Details\" : { \"Score\" : 89 } }"
}
]
|
Generalized Linear Models — Introduction | by Deepak Khandelwal | Towards Data Science | What is Linear Model in Machine Learning?
To illustrate the topic with an example, I have taken this dataset which has one predictor/feature/independent/explanatory variable namely Brain Weight and one response/target/dependent variable namely Body Weight .
Index Brain Weight Body Weight 1 3.385 44.500 2 0.480 15.500 3 1.350 8.100 4 465.000 423.000 5 36.330 119.500 6 27.660 115.000...
The response variable Body Wight is having a continuous distribution. We can model this distribution as a linear combination of predictors — Brain Weight,which is only one in this dataset, and a intercept term. Here, model is essentially trying to learn the weights/parameter associated with each features. Mathematically, we have to model the following linear equation —
y = Body Weight [Response]X = Brain Weight [Predictor]We are interested to model the following equation y_hat y_hat = W1*X1 + W0 y = y_hat + e
In the above equation, W1 and W0 are generally called parameters of model. In the context of linear models, W1 and W0 are referred as coefficients and intercept respectively. W0 represents the situation where all the X1 predictors will be zero, W0 is the value our model will predict.
e is called error term. This is the error which cannot be predicted from the knowledge of the predictors. It is the difference between what is observed i.e y, and what our model has predicted i.e. W1*X1 + W0.
The regression function tells us that how much the response variable y changes on average for a unit change (increase or decrease) in the value of X1.
The following plot is the hyper plane (line in this case) that fits the data.
We will take one more example to illustrate the idea of linear model more concretely.In this example, we have this dataset which contains two predictors and one continuous response variable. In this case, we have following situation —
y = Fish Length [Response]X1 = Age [Predictor]X2 = Water Temperature[Predictor]We are interested to model the following equation y_hat y_hat = W1*X1 + W2*X2 + W0 y = y_hat + e
The following hyper plane (plane in this case) is drawn using the parameters i.e. W1, W2, W0 learned by the model. Although it is not the best fit to the data but our focus is on the underlying concept of linear model, not on the model predictive power.
We can compare and cross-check the equation y = y_hat + e by putting the learned parameters in the equation - y_hat = W1*X1 + W2*X2 + W0 . For the sake of brevity, I have taken first ten rows of the dataset.
We can clearly see that y is very closely equal to the summation of y_hat and error term e .
Following the above discussion, we can conclude that Linear Model means that a distribution of a random variable is modeled as a linear combination of the features/predictors.
What is ‘linear’ in linear models?
When we say — ‘linear combination of features’ — it means that it is the model parameters Wi that are linear, having degree 1, not the features. We estimate linear parameters, we don’t estimate something like — W12, W1*W2 in case of linear models. Moreover, Features can have different varieties of terms such as — X1, X1*X2, X22 etc.
Now we can write a general equation for linear model as follows —
y = W0 + W1*X1 + W2*X2 + W3*X3 + ... + Wn*Xn + e
But while we perform linear regression, we make certain assumptions such as: 1. Distribution of response variable is normal i.e. Y_i ~ N(μ_i, σ2)2. Function of the predictors/explanatory variables Xi is W0 + Wi*Xi 3. Connection/Link between the explanatory variables and the the distribution of Yi is the mean of the response variable.The predicted value for each data point would be distributed around that mean with variance σ2.
μ_i = E(Y_i) = W0 + Wi*Xi
Limitations with linear models -1. The assumption of normality does not hold all the time, we may have our categorical features such as — gender, profession type etc. or we may have time series data which are not normally distributed.2. Linear model cannot fit a data with categorical response variable such as iris flower dataset, MNIST dataset etc.
3. Even if the response variable is a continuous random variable but takes its values within a range such as probability between 0 and 1. A traditional linear model will fail to predict a value between 0 and 1 because our features can take any value in the range (-∞, ∞).
Now we have learnt that linear models are not always right choice to model different than continuous response data and may provide rather strange results. Now what we are going to do is to generalize this model to overcome such problems. This results in GLMs which provides a unified framework for modelling data originating from the exponential family of probability distributions such as Normal, Binomial, Poisson among others.
There are 3 components of GLM.
Random Component — Which defines the response variable y and its probability distribution. One important assumption is that the responses from y1 to yn are independent to each other.Systematic Component — Which defines which explanatory variables we want to include in our model. It also allows the interactions among explanatory variables such as — X1*X2, X12 etc.That is the part that we model. It is also called linear predictor of covariates i.e. X1, X2, ... , Xn and coefficients i.e W1, W2, ... , Wn.Link Component — Which connects Random and Systematic component. It is the function of expected value of response variable i.e. E(Y) which enables linearity in the parameters and allows E(Y) to be non-linearly related to the explanatory variables. It is the link function that generalizes the linear models.
Random Component — Which defines the response variable y and its probability distribution. One important assumption is that the responses from y1 to yn are independent to each other.
Systematic Component — Which defines which explanatory variables we want to include in our model. It also allows the interactions among explanatory variables such as — X1*X2, X12 etc.That is the part that we model. It is also called linear predictor of covariates i.e. X1, X2, ... , Xn and coefficients i.e W1, W2, ... , Wn.
Link Component — Which connects Random and Systematic component. It is the function of expected value of response variable i.e. E(Y) which enables linearity in the parameters and allows E(Y) to be non-linearly related to the explanatory variables. It is the link function that generalizes the linear models.
Note that choice of link function is separate from the choice of random component.
Now we can say that the simple linear regression model is a special case of GLM, wherein the random component has Normal distribution and it takes the continuous values in the range (-∞, ∞). The systematic component is X.The link function is an identity function.
Y ~ N(μ, σ2) E(Y) = μ g(E(Y)) = μ = W1*X1 + e
What do we generalize in GLMs?
We generalize the distribution of response variable, that is y , can take.We generalize the link function between explanatory variables Xi and response variable Yi.
We generalize the distribution of response variable, that is y , can take.
We generalize the link function between explanatory variables Xi and response variable Yi.
Below table contains the commonly used link functions.
Let’s summarize what we have discussed so far — 1. Linear models are good to model continuous response variable but they have certain limitations.2. Generalized linear models unify many different types of response variable distributions that belong to exponential family of density.3. Link function is the key component in the GLM which enable linearity in the parameters and it is the one that generalizes the linear model.
References:[1] B. Caffo, 03 01 Part 1 of 1 Generalized Linear Models (2015)[2] R. Cooksey, Logic of the General Linear Model (GLM) (2013)[3] Actuarial Education, CT6 Introduction to generalized linear models (GLMs) (2012) | [
{
"code": null,
"e": 214,
"s": 172,
"text": "What is Linear Model in Machine Learning?"
},
{
"code": null,
"e": 430,
"s": 214,
"text": "To illustrate the topic with an example, I have taken this dataset which has one predictor/feature/independent/explanatory variable namely Brain Weight and one response/target/dependent variable namely Body Weight ."
},
{
"code": null,
"e": 632,
"s": 430,
"text": "Index Brain Weight Body Weight 1 3.385 44.500 2 0.480 15.500 3 1.350 8.100 4 465.000 423.000 5 36.330 119.500 6 27.660 115.000..."
},
{
"code": null,
"e": 1004,
"s": 632,
"text": "The response variable Body Wight is having a continuous distribution. We can model this distribution as a linear combination of predictors — Brain Weight,which is only one in this dataset, and a intercept term. Here, model is essentially trying to learn the weights/parameter associated with each features. Mathematically, we have to model the following linear equation —"
},
{
"code": null,
"e": 1155,
"s": 1004,
"text": "y = Body Weight [Response]X = Brain Weight [Predictor]We are interested to model the following equation y_hat y_hat = W1*X1 + W0 y = y_hat + e"
},
{
"code": null,
"e": 1440,
"s": 1155,
"text": "In the above equation, W1 and W0 are generally called parameters of model. In the context of linear models, W1 and W0 are referred as coefficients and intercept respectively. W0 represents the situation where all the X1 predictors will be zero, W0 is the value our model will predict."
},
{
"code": null,
"e": 1649,
"s": 1440,
"text": "e is called error term. This is the error which cannot be predicted from the knowledge of the predictors. It is the difference between what is observed i.e y, and what our model has predicted i.e. W1*X1 + W0."
},
{
"code": null,
"e": 1800,
"s": 1649,
"text": "The regression function tells us that how much the response variable y changes on average for a unit change (increase or decrease) in the value of X1."
},
{
"code": null,
"e": 1878,
"s": 1800,
"text": "The following plot is the hyper plane (line in this case) that fits the data."
},
{
"code": null,
"e": 2113,
"s": 1878,
"text": "We will take one more example to illustrate the idea of linear model more concretely.In this example, we have this dataset which contains two predictors and one continuous response variable. In this case, we have following situation —"
},
{
"code": null,
"e": 2297,
"s": 2113,
"text": "y = Fish Length [Response]X1 = Age [Predictor]X2 = Water Temperature[Predictor]We are interested to model the following equation y_hat y_hat = W1*X1 + W2*X2 + W0 y = y_hat + e"
},
{
"code": null,
"e": 2551,
"s": 2297,
"text": "The following hyper plane (plane in this case) is drawn using the parameters i.e. W1, W2, W0 learned by the model. Although it is not the best fit to the data but our focus is on the underlying concept of linear model, not on the model predictive power."
},
{
"code": null,
"e": 2759,
"s": 2551,
"text": "We can compare and cross-check the equation y = y_hat + e by putting the learned parameters in the equation - y_hat = W1*X1 + W2*X2 + W0 . For the sake of brevity, I have taken first ten rows of the dataset."
},
{
"code": null,
"e": 2852,
"s": 2759,
"text": "We can clearly see that y is very closely equal to the summation of y_hat and error term e ."
},
{
"code": null,
"e": 3028,
"s": 2852,
"text": "Following the above discussion, we can conclude that Linear Model means that a distribution of a random variable is modeled as a linear combination of the features/predictors."
},
{
"code": null,
"e": 3063,
"s": 3028,
"text": "What is ‘linear’ in linear models?"
},
{
"code": null,
"e": 3398,
"s": 3063,
"text": "When we say — ‘linear combination of features’ — it means that it is the model parameters Wi that are linear, having degree 1, not the features. We estimate linear parameters, we don’t estimate something like — W12, W1*W2 in case of linear models. Moreover, Features can have different varieties of terms such as — X1, X1*X2, X22 etc."
},
{
"code": null,
"e": 3464,
"s": 3398,
"text": "Now we can write a general equation for linear model as follows —"
},
{
"code": null,
"e": 3513,
"s": 3464,
"text": "y = W0 + W1*X1 + W2*X2 + W3*X3 + ... + Wn*Xn + e"
},
{
"code": null,
"e": 3944,
"s": 3513,
"text": "But while we perform linear regression, we make certain assumptions such as: 1. Distribution of response variable is normal i.e. Y_i ~ N(μ_i, σ2)2. Function of the predictors/explanatory variables Xi is W0 + Wi*Xi 3. Connection/Link between the explanatory variables and the the distribution of Yi is the mean of the response variable.The predicted value for each data point would be distributed around that mean with variance σ2."
},
{
"code": null,
"e": 3992,
"s": 3944,
"text": " μ_i = E(Y_i) = W0 + Wi*Xi"
},
{
"code": null,
"e": 4343,
"s": 3992,
"text": "Limitations with linear models -1. The assumption of normality does not hold all the time, we may have our categorical features such as — gender, profession type etc. or we may have time series data which are not normally distributed.2. Linear model cannot fit a data with categorical response variable such as iris flower dataset, MNIST dataset etc."
},
{
"code": null,
"e": 4615,
"s": 4343,
"text": "3. Even if the response variable is a continuous random variable but takes its values within a range such as probability between 0 and 1. A traditional linear model will fail to predict a value between 0 and 1 because our features can take any value in the range (-∞, ∞)."
},
{
"code": null,
"e": 5045,
"s": 4615,
"text": "Now we have learnt that linear models are not always right choice to model different than continuous response data and may provide rather strange results. Now what we are going to do is to generalize this model to overcome such problems. This results in GLMs which provides a unified framework for modelling data originating from the exponential family of probability distributions such as Normal, Binomial, Poisson among others."
},
{
"code": null,
"e": 5076,
"s": 5045,
"text": "There are 3 components of GLM."
},
{
"code": null,
"e": 5890,
"s": 5076,
"text": "Random Component — Which defines the response variable y and its probability distribution. One important assumption is that the responses from y1 to yn are independent to each other.Systematic Component — Which defines which explanatory variables we want to include in our model. It also allows the interactions among explanatory variables such as — X1*X2, X12 etc.That is the part that we model. It is also called linear predictor of covariates i.e. X1, X2, ... , Xn and coefficients i.e W1, W2, ... , Wn.Link Component — Which connects Random and Systematic component. It is the function of expected value of response variable i.e. E(Y) which enables linearity in the parameters and allows E(Y) to be non-linearly related to the explanatory variables. It is the link function that generalizes the linear models."
},
{
"code": null,
"e": 6073,
"s": 5890,
"text": "Random Component — Which defines the response variable y and its probability distribution. One important assumption is that the responses from y1 to yn are independent to each other."
},
{
"code": null,
"e": 6398,
"s": 6073,
"text": "Systematic Component — Which defines which explanatory variables we want to include in our model. It also allows the interactions among explanatory variables such as — X1*X2, X12 etc.That is the part that we model. It is also called linear predictor of covariates i.e. X1, X2, ... , Xn and coefficients i.e W1, W2, ... , Wn."
},
{
"code": null,
"e": 6706,
"s": 6398,
"text": "Link Component — Which connects Random and Systematic component. It is the function of expected value of response variable i.e. E(Y) which enables linearity in the parameters and allows E(Y) to be non-linearly related to the explanatory variables. It is the link function that generalizes the linear models."
},
{
"code": null,
"e": 6789,
"s": 6706,
"text": "Note that choice of link function is separate from the choice of random component."
},
{
"code": null,
"e": 7053,
"s": 6789,
"text": "Now we can say that the simple linear regression model is a special case of GLM, wherein the random component has Normal distribution and it takes the continuous values in the range (-∞, ∞). The systematic component is X.The link function is an identity function."
},
{
"code": null,
"e": 7169,
"s": 7053,
"text": " Y ~ N(μ, σ2) E(Y) = μ g(E(Y)) = μ = W1*X1 + e"
},
{
"code": null,
"e": 7200,
"s": 7169,
"text": "What do we generalize in GLMs?"
},
{
"code": null,
"e": 7365,
"s": 7200,
"text": "We generalize the distribution of response variable, that is y , can take.We generalize the link function between explanatory variables Xi and response variable Yi."
},
{
"code": null,
"e": 7440,
"s": 7365,
"text": "We generalize the distribution of response variable, that is y , can take."
},
{
"code": null,
"e": 7531,
"s": 7440,
"text": "We generalize the link function between explanatory variables Xi and response variable Yi."
},
{
"code": null,
"e": 7586,
"s": 7531,
"text": "Below table contains the commonly used link functions."
},
{
"code": null,
"e": 8011,
"s": 7586,
"text": "Let’s summarize what we have discussed so far — 1. Linear models are good to model continuous response variable but they have certain limitations.2. Generalized linear models unify many different types of response variable distributions that belong to exponential family of density.3. Link function is the key component in the GLM which enable linearity in the parameters and it is the one that generalizes the linear model."
}
]
|
How to destroy an object in Python? | A class implements the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance.
This __del__() destructor prints the class name of an instance that is about to be destroyed −
#!/usr/bin/python
class Point:
def __init__( self, x=0, y=0):
self.x = x self.y = y def __del__(self):
class_name = self.__class__.__name__ print class_name, "destroyed"
pt1 = Point()
pt2 = pt1 pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
When the above code is executed, it produces following result −
3083401324 3083401324 3083401324
Point destroyed | [
{
"code": null,
"e": 1276,
"s": 1062,
"text": "A class implements the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance."
},
{
"code": null,
"e": 1371,
"s": 1276,
"text": "This __del__() destructor prints the class name of an instance that is about to be destroyed −"
},
{
"code": null,
"e": 1695,
"s": 1371,
"text": "#!/usr/bin/python\n\nclass Point:\n def __init__( self, x=0, y=0):\n self.x = x self.y = y def __del__(self):\n class_name = self.__class__.__name__ print class_name, \"destroyed\"\n pt1 = Point()\npt2 = pt1 pt3 = pt1\nprint id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts\ndel pt1\ndel pt2\ndel pt3"
},
{
"code": null,
"e": 1759,
"s": 1695,
"text": "When the above code is executed, it produces following result −"
},
{
"code": null,
"e": 1808,
"s": 1759,
"text": "3083401324 3083401324 3083401324\nPoint destroyed"
}
]
|
How to Filter Rows Based on Column Values with query function in Pandas? - GeeksforGeeks | 11 Dec, 2020
In this article, let’s see how to filter rows based on column values. Query function can be used to filter rows based on column values.
Consider below Dataframe:
Python3
import pandas as pd data = [['A', 10], ['B', 15], ['C', 14], ['D', 12]] df = pd.DataFrame(data, columns = ['Name', 'Age'])df
Output:
Our DataFrame
Now, Suppose You want to get only persons that have Age >13. We can use Query function of Pandas.
Python3
df.query("Age>13")
Output:
Using Query with only 1 Column
Now, If you want multiple columns. For example, you want to have Age >13 and Name = C. Then,
Python3
df.query("Age>13 and Name=='C'")
Output:
Using multiple cols filter
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 24038,
"s": 23901,
"text": "In this article, let’s see how to filter rows based on column values. Query function can be used to filter rows based on column values. "
},
{
"code": null,
"e": 24064,
"s": 24038,
"text": "Consider below Dataframe:"
},
{
"code": null,
"e": 24072,
"s": 24064,
"text": "Python3"
},
{
"code": "import pandas as pd data = [['A', 10], ['B', 15], ['C', 14], ['D', 12]] df = pd.DataFrame(data, columns = ['Name', 'Age'])df",
"e": 24200,
"s": 24072,
"text": null
},
{
"code": null,
"e": 24209,
"s": 24200,
"text": "Output: "
},
{
"code": null,
"e": 24224,
"s": 24209,
"text": "Our DataFrame "
},
{
"code": null,
"e": 24323,
"s": 24224,
"text": "Now, Suppose You want to get only persons that have Age >13. We can use Query function of Pandas."
},
{
"code": null,
"e": 24331,
"s": 24323,
"text": "Python3"
},
{
"code": "df.query(\"Age>13\")",
"e": 24350,
"s": 24331,
"text": null
},
{
"code": null,
"e": 24359,
"s": 24350,
"text": "Output: "
},
{
"code": null,
"e": 24390,
"s": 24359,
"text": "Using Query with only 1 Column"
},
{
"code": null,
"e": 24483,
"s": 24390,
"text": "Now, If you want multiple columns. For example, you want to have Age >13 and Name = C. Then,"
},
{
"code": null,
"e": 24491,
"s": 24483,
"text": "Python3"
},
{
"code": "df.query(\"Age>13 and Name=='C'\")",
"e": 24524,
"s": 24491,
"text": null
},
{
"code": null,
"e": 24532,
"s": 24524,
"text": "Output:"
},
{
"code": null,
"e": 24559,
"s": 24532,
"text": "Using multiple cols filter"
},
{
"code": null,
"e": 24582,
"s": 24559,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 24596,
"s": 24582,
"text": "Python-pandas"
},
{
"code": null,
"e": 24603,
"s": 24596,
"text": "Python"
},
{
"code": null,
"e": 24701,
"s": 24603,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24710,
"s": 24701,
"text": "Comments"
},
{
"code": null,
"e": 24723,
"s": 24710,
"text": "Old Comments"
},
{
"code": null,
"e": 24755,
"s": 24723,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 24811,
"s": 24755,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 24853,
"s": 24811,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 24895,
"s": 24853,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 24931,
"s": 24895,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 24970,
"s": 24931,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 24992,
"s": 24970,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25023,
"s": 24992,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25050,
"s": 25023,
"text": "Python Classes and Objects"
}
]
|
Central Limit Theorem: a real-life application | by Carolina Bento | Towards Data Science | The Central Limit Theorem (CLT) is one of the most popular theorems in statistics and it’s very useful in real world problems. In this article we’ll see why the Central Limit Theorem is so useful and how to apply it.
In a lot of situations where you use statistics, the ultimate goal is to identify the characteristics of a population.
Central Limit Theorem is an approximation you can use when the population you’re studying is so big, it would take a long time to gather data about each individual that’s part of it.
Population is the group of individuals that you are studying. And even though they are referred to as individuals, the elements that make a population don’t need to be people.
If you’re a regional manager at a grocery chain and you’re trying to be more efficient at re-stocking the seltzer water section every week in every store, so you sell as much seltzer as possible and avoid ending up with a lot of unsold inventory, all the cases of seltzer sold in that particular store represent the population.
If you’re a poultry farmer and want to put in an order for chicken feed, you’ll need to know how many pounds of grain your hens typically eat. So here, the chickens are your population.
Depending on the problem you’re solving, it will be extremely hard to gather data for the entire population.
If a company like Coca-Cola wants to know if their US customers will like the new product they are developing, they can’t send an army of researchers to talk to every single person in the US. Well, they probably could, but it would be very expensive and would take a long time to collect all the data 😀
That’s why companies do user studies with several groups of people that represent of their product’s audience, their population, so they can gather data and determine if it’s worth moving forward with product development. All of this, without talking to the entire population.
So, in statistical terms, you’re going to collect samples from your population, and by combining the information from the samples you can draw conclusions about your population.
A good sample must be:
Representative of the population,
Big enough to draw conclusions from, which in statistics is a sample size greater or equal to 30.
Picked at random, so you’re not biased towards certain characteristics in the population.
A representative sample must showcase all the different characteristics of the population.
If you want to know who is more likely to win the Super Bowl and decide to poll the US population, i.e., take a sample from the US population, you need to make sure to talk to people from:
All the different states about who they think is going to win,
Different age groups and different genders,
And only include in your study the people that have interest in sports or in the event itself otherwise, they will not be part of the population that is interested in what you’re studying.
You’re the regional manager at a grocery chain, in charge of 350 stores in the region, and the next project you’re going to take on is to optimize the weekly re-stocking of seltzer water.
You want to know many cases of seltzer water to order weekly, for each store, so you minimize the amount of inventory that ends up sitting idle in store shelves.
You know there has to be a better way to get to a plausible answer that doesn’t involve visiting every single store in your region and get their sales numbers every single week.
Since you’ve taken a few statistics classes, the Central Limit Theorem comes to mind. You know that, applied to real-world problems, the Central Limit Theorem helps you balance the time and cost of collecting all the data you need to draw conclusions about the population.
You remember the definition of Central Limit Theorem for sample means[1]:
When we collect a sufficiently large sample of n independent observations from a population with mean μ and standard deviation σ, the sampling distribution the sample means will be nearly normal with mean = μ and standard error = σ/ √n
The Central Limit Theorem tells you that we don’t have to visit every single store in the region and get their seltzer sales numbers for the week to know how many cases to put in the next order. What you can do is collect many samples from weekly sales in your stores (the population), calculate their mean (the average number of seltzer cases sold) and build the distribution of the sample means. This distribution is also referred to as sampling distribution.
If these samples meet Central Limit Theorem’s criteria, you can assume the distribution of the sample means can be approximated to the Normal distribution. So now you can use all the statistical tools the Normal distribution provides.
From this point on, since you know the distribution at hand, you can calculate probabilities and confidence intervals, and perform statistical tests.
But before you use the Central Limit Theorem and use the Normal distribution approximation, your samples must meet a specific set of criteria that extends the characteristics of what is a good sample.
Your samples should be:
Picked at random, so you’re not biased towards certain characteristics in the population and you guarantee each observation in the sample is independent of all other observations. This also helps enforce that each observation in the sample is independent.
Representative of the population.
Big enough to draw conclusions from, which in statistics is a sample size greater or equal to 30.
Include less than 10% of the population, if you’re sampling without replacement. Since observations in the population are not all independent of each other, if you collect a sample that is too big you may end up collect observations that are not independent of each other. Even if those observations were picked at random.
If you want to use any kind inferential statistical methods, i.e., understand the characteristics of probability distribution of your data, you need to know the distribution your data follows. Otherwise, you might end up using the wrong tools for the job.
So one question that comes to mind is Do I need to know the distribution of my population to use the Central Limit Theorem?
The short answer is No 😁
What is really powerful about the Central Limit Theorem is that you don’t need to know the distribution your population in advance. All you need to do is collect enough samples that follow the criteria and you can be sure that the distribution of the sample means will follow a Normal distribution.
To answer this question let’s generate a random dataset to represents the population, where each data point is the total number of seltzer cases sold per week in each store of the region you supervise.
import pandas as pdimport randomimport globdef create_dataset(dataset_size): """ Creating the population dataset """ dataset = [] while dataset_size > 0: dataset.append(random.randrange(3, 100)) dataset_size -= 1 return dataset# Initializing the random number generatorrandom.seed(1234)# Reading the output directory in case we've already generated the population datasetdataset_file_list = glob.glob("output/sales_dataset.csv")sales_data = None# Creating the population dataset and saving it to avoid always recreating the datasetif len(dataset_file_list) == 0: sales_data = pd.DataFrame(data=create_dataset(4200)) sales_data.columns = ['sales'] sales_data.to_csv("output/sales_dataset.csv", index=False)else: sales_data = pd.read_csv('output/sales_dataset.csv')
Then you can take a different number of samples, all with the same size, and plot the sales data just to see how it looks like.
The distribution of the sample data by itself doesn’t necessarily have the shape of a Normal Distribution. Also, the Central Limit Theorem doesn’t require you to know the distribution of the population.
In this example, each chart has a different numbers of samples, all with size 30, and none of the distributions look like the classic Bell curve. Not even close.
That doesn’t change much when you take another set of samples, this time with 100 data points each.
import numpy as npimport matplotlib.pyplot as pltdef picking_n_samples(population, number_samples, sample_size): """ Sampling without replacement with fixed size Returning the array of sample and array with their respective mean """ results = [] sample_mean = [] while number_samples > 0: new_sample = random.sample(population, sample_size) results += new_sample sample_mean += [np.mean(new_sample)] number_samples -= 1 return [results, sample_mean]def generate_sample_sets(dataset, number_samples, sample_size): """ Generate multiple sets samples with fixed size Returns all sample sets and their corresponding set of means """ samples_array = [] sample_means_array = [] for sample_count in number_samples: new_sample, sample_mean = picking_n_samples(dataset, sample_count, sample_size) samples_array.append(new_sample) sample_means_array.append(sample_mean) return [samples_array, sample_means_array]def plot_samples(sample_array, number_samples, default_size, plot_color='#6689F2', title='', x_axis_title='', filename='plot'): fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 7), constrained_layout=True) fig.suptitle(title, fontsize=16) ax1.hist(sample_array[0], color=plot_color) ax1.set_title("Taking " + str(number_samples[0]) + " samples of size=" + str(default_size), fontsize=10) ax1.set_xlabel(x_axis_title) ax3.hist(sample_array[2], color=plot_color) ax3.set_title("Taking " + str(number_samples[2]) + " samples of size=" + str(default_size), fontsize=10) ax3.set_xlabel(x_axis_title) ax2.hist(sample_array[1], color=plot_color) ax2.set_title("Taking " + str(number_samples[1]) + " samples of size=" + str(default_size), fontsize=10) ax2.set_xlabel(x_axis_title) ax4.hist(sample_array[3], color=plot_color) ax4.set_title("Taking " + str(number_samples[3]) + " samples of size=" + str(default_size), fontsize=10) ax4.set_xlabel(x_axis_title) fig.savefig("output/" + filename)######################### Example 1####################### Setting the defaults for this exampleexample1_number_of_samples_array = [5, 50, 100, 1000, 10000]example1_default_sample_size = 30# Picking multiple samples of size 30example_1_samples, example_1_means = generate_sample_sets(list(sales_data['sales'].values), example1_number_of_samples_array, example1_default_sample_size)# Plot the different sets of samplesplot_title = 'Distribution of sales from different samples of size ' + str(example1_default_sample_size)plot_samples(example_1_samples, example1_number_of_samples_array, example1_default_sample_size, title=plot_title, filename="example_1_samples_distribution")########################## Example 2######################## Setting the defaults for this exampleexample_2_number_of_samples_array = [5, 50, 100, 1000, 10000]example_2_default_sample_size = 100example_2_samples, example_2_means = generate_sample_sets(list(sales_data['sales'].values), example_2_number_of_samples_array, example_2_default_sample_size)# Plot the different sets of samplesplot_title = 'Distribution of sales from different samples of size ' + str(example_2_default_sample_size)plot_samples(example_2_samples, example_2_number_of_samples_array, example_2_default_sample_size, title=plot_title, filename="example_2_samples_distribution", plot_color="#96D2D9")
Because the key is to take a sample and the calculate the mean!
Looking at the distribution of sample means of the previous examples it becomes clear. As the number of samples taken increases, the closer you get to the shape of a Normal distribution.
The higher number samples will also reduce the variability in the sampling distribution.
If you look at the distributions that have 5 and 50 samples, you’ll notice the latter has a smaller standard deviation.
If you collect a bigger sample you’ll have fewer chances of getting extreme values, so your values will be more clustered together. Therefore the standard deviation, or the distance from the mean, will be smaller.
To approach it from formulaic way, looking back to the definition of the Central Limit Theorem, the standard deviation of the sampling distribution, also called standard error, is equal to σ/ √n. So, as the sample size increases the denominator also increases, and makes the overall standard value smaller.
example_1_sampling_distribution_5_samples = pd.Series(example_1_means[0])print("Example 1: Summary statistics for sampling distribution with " + str(len(example_1_sampling_distribution_5_samples)) + " samples taken (size= " + str(example1_default_sample_size) + ")")print(example_1_sampling_distribution_5_samples.describe())example_1_sampling_distribution_5_samples = pd.Series(example_1_means[1])print("Example 1: Summary statistics for sampling distribution with " + str(len(example_1_sampling_distribution_5_samples)) + " samples taken (size= " + str(example1_default_sample_size) + ")")print(example_1_sampling_distribution_5_samples.describe())
And if you take 10,000 samples of size 100 from the randomly generated sales dataset, you’ll get a sampling distribution that resembles the bell curve characteristic of the Normal distribution.
def plot_sample_means(sample_means_array, plot_color='#A9CBD9', title='', filename='plot'): fig, ax = plt.subplots(figsize=(12, 7)) fig.suptitle(title, fontsize=16) ax.hist(sample_means_array, color=plot_color) # removing to and right border ax.spines['top'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) # adding major gridlines ax.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5) ax.set_xlabel("Average number of seltzer cases sold") fig.savefig("output/" + filename)plot_title = 'Sampling distribution from taking 10,000 samples of size 30 ' + str(example1_default_sample_size)plot_sample_means(example_1_means[4], title=plot_title, filename="example_1_sampling_dist_10ksamples")
Back to the original, if you want to know how many cases of seltzer water you need to re-stock every week, take a look at the summary statistics of this last sampling distribution, the one with 10,000 samples.
The mean of the sampling distribution is 51, so you’ll need an average of 51 cases per store per week.
example_2_sampling_distribution = pd.Series(example_2_means[4])print("Summary statistics for sampling distribution with " + str(example_2_number_of_samples_array[4]) + " samples taken (size= "+ str(example_2_default_sample_size) + ")")print(example_2_sampling_distribution.describe())
This is the average across all stores in your region. If you wanted a more precise number per store, you’d have to do this process for each of them. Each store becomes the population, and you only take samples from that that are from that store.
Since you generated the sales dataset, you can do another interesting check. See how far the mean of sampling distribution is from the real population mean.
The average of the population is 51!
# Population summary statisticsprint("Summary statistics for the population (sales dataset)")print(sales_data['sales'].describe())
We just experienced the power of the Central Limit Theorem!
With a randomly generated set and not knowing any details about the original distribution (you only checked at the very end 😀) you:
Took an increasing number of samples and saw the distribution of the sample means becoming closer and closer to the shape of a Normal Distribution.Confirmed that the average of the sampling distribution was very close to the population distribution, with a small margin of error.Used the Central Limit Theorem to solve a real life problem.
Took an increasing number of samples and saw the distribution of the sample means becoming closer and closer to the shape of a Normal Distribution.
Confirmed that the average of the sampling distribution was very close to the population distribution, with a small margin of error.
Used the Central Limit Theorem to solve a real life problem.
Hope you enjoyed this article, thanks for reading!
[1]OpenIntro Statistics — Fourth Edition (2019) | [
{
"code": null,
"e": 389,
"s": 172,
"text": "The Central Limit Theorem (CLT) is one of the most popular theorems in statistics and it’s very useful in real world problems. In this article we’ll see why the Central Limit Theorem is so useful and how to apply it."
},
{
"code": null,
"e": 508,
"s": 389,
"text": "In a lot of situations where you use statistics, the ultimate goal is to identify the characteristics of a population."
},
{
"code": null,
"e": 691,
"s": 508,
"text": "Central Limit Theorem is an approximation you can use when the population you’re studying is so big, it would take a long time to gather data about each individual that’s part of it."
},
{
"code": null,
"e": 867,
"s": 691,
"text": "Population is the group of individuals that you are studying. And even though they are referred to as individuals, the elements that make a population don’t need to be people."
},
{
"code": null,
"e": 1195,
"s": 867,
"text": "If you’re a regional manager at a grocery chain and you’re trying to be more efficient at re-stocking the seltzer water section every week in every store, so you sell as much seltzer as possible and avoid ending up with a lot of unsold inventory, all the cases of seltzer sold in that particular store represent the population."
},
{
"code": null,
"e": 1381,
"s": 1195,
"text": "If you’re a poultry farmer and want to put in an order for chicken feed, you’ll need to know how many pounds of grain your hens typically eat. So here, the chickens are your population."
},
{
"code": null,
"e": 1490,
"s": 1381,
"text": "Depending on the problem you’re solving, it will be extremely hard to gather data for the entire population."
},
{
"code": null,
"e": 1793,
"s": 1490,
"text": "If a company like Coca-Cola wants to know if their US customers will like the new product they are developing, they can’t send an army of researchers to talk to every single person in the US. Well, they probably could, but it would be very expensive and would take a long time to collect all the data 😀"
},
{
"code": null,
"e": 2070,
"s": 1793,
"text": "That’s why companies do user studies with several groups of people that represent of their product’s audience, their population, so they can gather data and determine if it’s worth moving forward with product development. All of this, without talking to the entire population."
},
{
"code": null,
"e": 2248,
"s": 2070,
"text": "So, in statistical terms, you’re going to collect samples from your population, and by combining the information from the samples you can draw conclusions about your population."
},
{
"code": null,
"e": 2271,
"s": 2248,
"text": "A good sample must be:"
},
{
"code": null,
"e": 2305,
"s": 2271,
"text": "Representative of the population,"
},
{
"code": null,
"e": 2403,
"s": 2305,
"text": "Big enough to draw conclusions from, which in statistics is a sample size greater or equal to 30."
},
{
"code": null,
"e": 2493,
"s": 2403,
"text": "Picked at random, so you’re not biased towards certain characteristics in the population."
},
{
"code": null,
"e": 2584,
"s": 2493,
"text": "A representative sample must showcase all the different characteristics of the population."
},
{
"code": null,
"e": 2773,
"s": 2584,
"text": "If you want to know who is more likely to win the Super Bowl and decide to poll the US population, i.e., take a sample from the US population, you need to make sure to talk to people from:"
},
{
"code": null,
"e": 2836,
"s": 2773,
"text": "All the different states about who they think is going to win,"
},
{
"code": null,
"e": 2880,
"s": 2836,
"text": "Different age groups and different genders,"
},
{
"code": null,
"e": 3069,
"s": 2880,
"text": "And only include in your study the people that have interest in sports or in the event itself otherwise, they will not be part of the population that is interested in what you’re studying."
},
{
"code": null,
"e": 3257,
"s": 3069,
"text": "You’re the regional manager at a grocery chain, in charge of 350 stores in the region, and the next project you’re going to take on is to optimize the weekly re-stocking of seltzer water."
},
{
"code": null,
"e": 3419,
"s": 3257,
"text": "You want to know many cases of seltzer water to order weekly, for each store, so you minimize the amount of inventory that ends up sitting idle in store shelves."
},
{
"code": null,
"e": 3597,
"s": 3419,
"text": "You know there has to be a better way to get to a plausible answer that doesn’t involve visiting every single store in your region and get their sales numbers every single week."
},
{
"code": null,
"e": 3870,
"s": 3597,
"text": "Since you’ve taken a few statistics classes, the Central Limit Theorem comes to mind. You know that, applied to real-world problems, the Central Limit Theorem helps you balance the time and cost of collecting all the data you need to draw conclusions about the population."
},
{
"code": null,
"e": 3944,
"s": 3870,
"text": "You remember the definition of Central Limit Theorem for sample means[1]:"
},
{
"code": null,
"e": 4180,
"s": 3944,
"text": "When we collect a sufficiently large sample of n independent observations from a population with mean μ and standard deviation σ, the sampling distribution the sample means will be nearly normal with mean = μ and standard error = σ/ √n"
},
{
"code": null,
"e": 4642,
"s": 4180,
"text": "The Central Limit Theorem tells you that we don’t have to visit every single store in the region and get their seltzer sales numbers for the week to know how many cases to put in the next order. What you can do is collect many samples from weekly sales in your stores (the population), calculate their mean (the average number of seltzer cases sold) and build the distribution of the sample means. This distribution is also referred to as sampling distribution."
},
{
"code": null,
"e": 4877,
"s": 4642,
"text": "If these samples meet Central Limit Theorem’s criteria, you can assume the distribution of the sample means can be approximated to the Normal distribution. So now you can use all the statistical tools the Normal distribution provides."
},
{
"code": null,
"e": 5027,
"s": 4877,
"text": "From this point on, since you know the distribution at hand, you can calculate probabilities and confidence intervals, and perform statistical tests."
},
{
"code": null,
"e": 5228,
"s": 5027,
"text": "But before you use the Central Limit Theorem and use the Normal distribution approximation, your samples must meet a specific set of criteria that extends the characteristics of what is a good sample."
},
{
"code": null,
"e": 5252,
"s": 5228,
"text": "Your samples should be:"
},
{
"code": null,
"e": 5508,
"s": 5252,
"text": "Picked at random, so you’re not biased towards certain characteristics in the population and you guarantee each observation in the sample is independent of all other observations. This also helps enforce that each observation in the sample is independent."
},
{
"code": null,
"e": 5542,
"s": 5508,
"text": "Representative of the population."
},
{
"code": null,
"e": 5640,
"s": 5542,
"text": "Big enough to draw conclusions from, which in statistics is a sample size greater or equal to 30."
},
{
"code": null,
"e": 5963,
"s": 5640,
"text": "Include less than 10% of the population, if you’re sampling without replacement. Since observations in the population are not all independent of each other, if you collect a sample that is too big you may end up collect observations that are not independent of each other. Even if those observations were picked at random."
},
{
"code": null,
"e": 6219,
"s": 5963,
"text": "If you want to use any kind inferential statistical methods, i.e., understand the characteristics of probability distribution of your data, you need to know the distribution your data follows. Otherwise, you might end up using the wrong tools for the job."
},
{
"code": null,
"e": 6343,
"s": 6219,
"text": "So one question that comes to mind is Do I need to know the distribution of my population to use the Central Limit Theorem?"
},
{
"code": null,
"e": 6368,
"s": 6343,
"text": "The short answer is No 😁"
},
{
"code": null,
"e": 6667,
"s": 6368,
"text": "What is really powerful about the Central Limit Theorem is that you don’t need to know the distribution your population in advance. All you need to do is collect enough samples that follow the criteria and you can be sure that the distribution of the sample means will follow a Normal distribution."
},
{
"code": null,
"e": 6869,
"s": 6667,
"text": "To answer this question let’s generate a random dataset to represents the population, where each data point is the total number of seltzer cases sold per week in each store of the region you supervise."
},
{
"code": null,
"e": 7675,
"s": 6869,
"text": "import pandas as pdimport randomimport globdef create_dataset(dataset_size): \"\"\" Creating the population dataset \"\"\" dataset = [] while dataset_size > 0: dataset.append(random.randrange(3, 100)) dataset_size -= 1 return dataset# Initializing the random number generatorrandom.seed(1234)# Reading the output directory in case we've already generated the population datasetdataset_file_list = glob.glob(\"output/sales_dataset.csv\")sales_data = None# Creating the population dataset and saving it to avoid always recreating the datasetif len(dataset_file_list) == 0: sales_data = pd.DataFrame(data=create_dataset(4200)) sales_data.columns = ['sales'] sales_data.to_csv(\"output/sales_dataset.csv\", index=False)else: sales_data = pd.read_csv('output/sales_dataset.csv')"
},
{
"code": null,
"e": 7803,
"s": 7675,
"text": "Then you can take a different number of samples, all with the same size, and plot the sales data just to see how it looks like."
},
{
"code": null,
"e": 8006,
"s": 7803,
"text": "The distribution of the sample data by itself doesn’t necessarily have the shape of a Normal Distribution. Also, the Central Limit Theorem doesn’t require you to know the distribution of the population."
},
{
"code": null,
"e": 8168,
"s": 8006,
"text": "In this example, each chart has a different numbers of samples, all with size 30, and none of the distributions look like the classic Bell curve. Not even close."
},
{
"code": null,
"e": 8268,
"s": 8168,
"text": "That doesn’t change much when you take another set of samples, this time with 100 data points each."
},
{
"code": null,
"e": 11675,
"s": 8268,
"text": "import numpy as npimport matplotlib.pyplot as pltdef picking_n_samples(population, number_samples, sample_size): \"\"\" Sampling without replacement with fixed size Returning the array of sample and array with their respective mean \"\"\" results = [] sample_mean = [] while number_samples > 0: new_sample = random.sample(population, sample_size) results += new_sample sample_mean += [np.mean(new_sample)] number_samples -= 1 return [results, sample_mean]def generate_sample_sets(dataset, number_samples, sample_size): \"\"\" Generate multiple sets samples with fixed size Returns all sample sets and their corresponding set of means \"\"\" samples_array = [] sample_means_array = [] for sample_count in number_samples: new_sample, sample_mean = picking_n_samples(dataset, sample_count, sample_size) samples_array.append(new_sample) sample_means_array.append(sample_mean) return [samples_array, sample_means_array]def plot_samples(sample_array, number_samples, default_size, plot_color='#6689F2', title='', x_axis_title='', filename='plot'): fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 7), constrained_layout=True) fig.suptitle(title, fontsize=16) ax1.hist(sample_array[0], color=plot_color) ax1.set_title(\"Taking \" + str(number_samples[0]) + \" samples of size=\" + str(default_size), fontsize=10) ax1.set_xlabel(x_axis_title) ax3.hist(sample_array[2], color=plot_color) ax3.set_title(\"Taking \" + str(number_samples[2]) + \" samples of size=\" + str(default_size), fontsize=10) ax3.set_xlabel(x_axis_title) ax2.hist(sample_array[1], color=plot_color) ax2.set_title(\"Taking \" + str(number_samples[1]) + \" samples of size=\" + str(default_size), fontsize=10) ax2.set_xlabel(x_axis_title) ax4.hist(sample_array[3], color=plot_color) ax4.set_title(\"Taking \" + str(number_samples[3]) + \" samples of size=\" + str(default_size), fontsize=10) ax4.set_xlabel(x_axis_title) fig.savefig(\"output/\" + filename)######################### Example 1####################### Setting the defaults for this exampleexample1_number_of_samples_array = [5, 50, 100, 1000, 10000]example1_default_sample_size = 30# Picking multiple samples of size 30example_1_samples, example_1_means = generate_sample_sets(list(sales_data['sales'].values), example1_number_of_samples_array, example1_default_sample_size)# Plot the different sets of samplesplot_title = 'Distribution of sales from different samples of size ' + str(example1_default_sample_size)plot_samples(example_1_samples, example1_number_of_samples_array, example1_default_sample_size, title=plot_title, filename=\"example_1_samples_distribution\")########################## Example 2######################## Setting the defaults for this exampleexample_2_number_of_samples_array = [5, 50, 100, 1000, 10000]example_2_default_sample_size = 100example_2_samples, example_2_means = generate_sample_sets(list(sales_data['sales'].values), example_2_number_of_samples_array, example_2_default_sample_size)# Plot the different sets of samplesplot_title = 'Distribution of sales from different samples of size ' + str(example_2_default_sample_size)plot_samples(example_2_samples, example_2_number_of_samples_array, example_2_default_sample_size, title=plot_title, filename=\"example_2_samples_distribution\", plot_color=\"#96D2D9\")"
},
{
"code": null,
"e": 11739,
"s": 11675,
"text": "Because the key is to take a sample and the calculate the mean!"
},
{
"code": null,
"e": 11926,
"s": 11739,
"text": "Looking at the distribution of sample means of the previous examples it becomes clear. As the number of samples taken increases, the closer you get to the shape of a Normal distribution."
},
{
"code": null,
"e": 12015,
"s": 11926,
"text": "The higher number samples will also reduce the variability in the sampling distribution."
},
{
"code": null,
"e": 12135,
"s": 12015,
"text": "If you look at the distributions that have 5 and 50 samples, you’ll notice the latter has a smaller standard deviation."
},
{
"code": null,
"e": 12349,
"s": 12135,
"text": "If you collect a bigger sample you’ll have fewer chances of getting extreme values, so your values will be more clustered together. Therefore the standard deviation, or the distance from the mean, will be smaller."
},
{
"code": null,
"e": 12656,
"s": 12349,
"text": "To approach it from formulaic way, looking back to the definition of the Central Limit Theorem, the standard deviation of the sampling distribution, also called standard error, is equal to σ/ √n. So, as the sample size increases the denominator also increases, and makes the overall standard value smaller."
},
{
"code": null,
"e": 13307,
"s": 12656,
"text": "example_1_sampling_distribution_5_samples = pd.Series(example_1_means[0])print(\"Example 1: Summary statistics for sampling distribution with \" + str(len(example_1_sampling_distribution_5_samples)) + \" samples taken (size= \" + str(example1_default_sample_size) + \")\")print(example_1_sampling_distribution_5_samples.describe())example_1_sampling_distribution_5_samples = pd.Series(example_1_means[1])print(\"Example 1: Summary statistics for sampling distribution with \" + str(len(example_1_sampling_distribution_5_samples)) + \" samples taken (size= \" + str(example1_default_sample_size) + \")\")print(example_1_sampling_distribution_5_samples.describe())"
},
{
"code": null,
"e": 13501,
"s": 13307,
"text": "And if you take 10,000 samples of size 100 from the randomly generated sales dataset, you’ll get a sampling distribution that resembles the bell curve characteristic of the Normal distribution."
},
{
"code": null,
"e": 14282,
"s": 13501,
"text": "def plot_sample_means(sample_means_array, plot_color='#A9CBD9', title='', filename='plot'): fig, ax = plt.subplots(figsize=(12, 7)) fig.suptitle(title, fontsize=16) ax.hist(sample_means_array, color=plot_color) # removing to and right border ax.spines['top'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) # adding major gridlines ax.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5) ax.set_xlabel(\"Average number of seltzer cases sold\") fig.savefig(\"output/\" + filename)plot_title = 'Sampling distribution from taking 10,000 samples of size 30 ' + str(example1_default_sample_size)plot_sample_means(example_1_means[4], title=plot_title, filename=\"example_1_sampling_dist_10ksamples\")"
},
{
"code": null,
"e": 14492,
"s": 14282,
"text": "Back to the original, if you want to know how many cases of seltzer water you need to re-stock every week, take a look at the summary statistics of this last sampling distribution, the one with 10,000 samples."
},
{
"code": null,
"e": 14595,
"s": 14492,
"text": "The mean of the sampling distribution is 51, so you’ll need an average of 51 cases per store per week."
},
{
"code": null,
"e": 14880,
"s": 14595,
"text": "example_2_sampling_distribution = pd.Series(example_2_means[4])print(\"Summary statistics for sampling distribution with \" + str(example_2_number_of_samples_array[4]) + \" samples taken (size= \"+ str(example_2_default_sample_size) + \")\")print(example_2_sampling_distribution.describe())"
},
{
"code": null,
"e": 15126,
"s": 14880,
"text": "This is the average across all stores in your region. If you wanted a more precise number per store, you’d have to do this process for each of them. Each store becomes the population, and you only take samples from that that are from that store."
},
{
"code": null,
"e": 15283,
"s": 15126,
"text": "Since you generated the sales dataset, you can do another interesting check. See how far the mean of sampling distribution is from the real population mean."
},
{
"code": null,
"e": 15320,
"s": 15283,
"text": "The average of the population is 51!"
},
{
"code": null,
"e": 15451,
"s": 15320,
"text": "# Population summary statisticsprint(\"Summary statistics for the population (sales dataset)\")print(sales_data['sales'].describe())"
},
{
"code": null,
"e": 15511,
"s": 15451,
"text": "We just experienced the power of the Central Limit Theorem!"
},
{
"code": null,
"e": 15643,
"s": 15511,
"text": "With a randomly generated set and not knowing any details about the original distribution (you only checked at the very end 😀) you:"
},
{
"code": null,
"e": 15983,
"s": 15643,
"text": "Took an increasing number of samples and saw the distribution of the sample means becoming closer and closer to the shape of a Normal Distribution.Confirmed that the average of the sampling distribution was very close to the population distribution, with a small margin of error.Used the Central Limit Theorem to solve a real life problem."
},
{
"code": null,
"e": 16131,
"s": 15983,
"text": "Took an increasing number of samples and saw the distribution of the sample means becoming closer and closer to the shape of a Normal Distribution."
},
{
"code": null,
"e": 16264,
"s": 16131,
"text": "Confirmed that the average of the sampling distribution was very close to the population distribution, with a small margin of error."
},
{
"code": null,
"e": 16325,
"s": 16264,
"text": "Used the Central Limit Theorem to solve a real life problem."
},
{
"code": null,
"e": 16376,
"s": 16325,
"text": "Hope you enjoyed this article, thanks for reading!"
}
]
|
Manufacturing simulation using SimPy | by Juan Horgan | Towards Data Science | Hi there! In this tutorial we are going to build a guitar factory using SimPy! Even though this is a toy example, we are going to cover some pretty cool things that you can use for your own simulations. We are going to go throw the code here, but if you want to see the final version, it’s on my GitHub.
First of all, what is SimPy? In the documentation, they define it as: “SimPy is a process-based discrete-event simulation framework based on standard Python”. You can see the full documentation here, which I strongly recommend. There you can find not only the things you can do, but also a lot of simple but very helpful tutorials. If you don’t have SimPy installed, a simple pip will do the trick:
pip install simpy
We are going to build a guitar factory from scratch, starting from something very simple into a more complex system. In this example, we are building one type of guitar. The body and the neck are build separately, but from the same type of wood. Then they are pass to a painting area. After that, a body, a neck and the electronic components are combined, so the guitar is made.
Let’s have a look:
Let me explain that flowchart:
There are 2 main containers. Wood and Electronic. Those containers have an N amount of wood/electronic components that going to be use in the process.The body make get a piece of wood from the container and transform it into a body, which will be stored in the Body storage. The same thing happen with the neck builder, but from one piece of wood, he will get two necks. The necks are stored in the Neck storage.Painter pick necks and bodies, paint them, and store them in Body storage 2 and Neck storage 2.Assembler picks a body, a neck and one piece of electronics, and assemble the guitar, which will be store in the Dispatch container.After an N amount of guitars are made, store send someone to pick them up.When Wood or Electronic are bellow a certain level of raw material, a call to the Supplier is made. After T days, supplier arrives to the factory and refill the container with raw material.
There are 2 main containers. Wood and Electronic. Those containers have an N amount of wood/electronic components that going to be use in the process.
The body make get a piece of wood from the container and transform it into a body, which will be stored in the Body storage. The same thing happen with the neck builder, but from one piece of wood, he will get two necks. The necks are stored in the Neck storage.
Painter pick necks and bodies, paint them, and store them in Body storage 2 and Neck storage 2.
Assembler picks a body, a neck and one piece of electronics, and assemble the guitar, which will be store in the Dispatch container.
After an N amount of guitars are made, store send someone to pick them up.
When Wood or Electronic are bellow a certain level of raw material, a call to the Supplier is made. After T days, supplier arrives to the factory and refill the container with raw material.
Part 1: Simple model
Let’s start our model from the simplest form:
We start importing SimPy. After that we will create the class Guitar_Factory and add the first two containers. Notice that we set the capacity of our containers as the variables shown above. Of course, dispatch will start empty. If we run out of wood, process will not stop, but it won’t create any more guitars either. The same thing happen if dispatch is full. Note the env argument. This is simply the SimPy environment where this are happening. We will define this later in our code.
Now we will add the Body maker and the Neck maker:
We start creating our first two employees. The function take two arguments: The SimPy environment and the guitar_factory class (note that guitar_factory is different from the Guitar_Factory we define as our class in the previous Gist). What is happening there is pretty straight forward:
While the simulation is running, the maker will take one piece of wood (yield guitar_factory.wood.get(1)).
It will keep that wood piece for one time period (that’s what the env.timeout function does). This simulate the time it takes to transform a piece of wood into a guitar body/neck.
After that time unit (1 in our case) has pass, the maker will put that piece into a container named dispatch. Please note that from one piece of wood, the body maker will make one guitar body. Instead, the neck maker, will make two necks from one piece of wood. So, you have the flexibility to take the number of raw material you want, and deliver as much other thing as you want, simply by changing that numbers.
And finally:
Our simulation will run for 40 hours (8 hours per business day * 5 business days), which is defined in the until = total_time argument passed to the env.run function. The body_maker_process and neck_maker_process will create our “employees”. And finally, we added a print so we can know how much bodies and neck’s we’ve make. Note that we get that result with the guitar_factory.dispatch.level. That’s equivalent to say “return the amount of things that are in the dispatch container”:
If you want the full code of part 1, is here.
Now we are going to add paint and assembling to our model. For that purpose, we will add:
Pre paint and post paint containers, and the painter.
Electronic container and assembler.
Nothing new here. We add electronic, pre_paint and post_paint containers, and set their capacities.
As we’ve done with body and neck makers, we create the painter and the assembler. Note that painting takes 4 hours, but it works over 10 pieces at the same time, while assembling use 2 post paint pieces (1 body and 1 neck) plus 1 electronic piece, and deliver a guitar after an hour of work.
Then we add some prints, environment process creation and run the simulation! Again, part 2 full code is here.
Now we are going to add some very cool stuff. Fasten your seat belts!
Until now, we have set a fixed time for our employees activity. For example, we have said that assembler takes 1 hour to make a guitar. With that parameter, it will always takes one hour, and not a minute more and not a minute less. We all now that’s not true. Activities takes different times, even do they are repeated along time. Here we will asume that the distribution of time is normal, but you can use any distribution you want. Also note that we are defining how many employees of each kind we want. We will start this part by importing the random library and defining the parameters needed to make the changes:
Lets explain this:
num_body set the number of body makers we are going to use (in this case, 2)
mean_body its the mean time needed for a body maker to make a body out of a piece of wood.
std_body is the standard error.
Now we are going to make a change to the function that creates our employees:
It is simple to note that now, body_time will not always be 1. In fact it will be a random number taken from a normal distribution with (in this case) mean 1 and standard error 0.1. Also note the assembling_time: we are taking the maximum number between the random one and 1. In other words, we are saying that assembling a guitar will never take less than one hour.
We have to change the creating process of our employees, by creating a new function that allow us to create more than one employee for each kind:
Of course, this will be the same code for neck_maker_gen, paint_maker_gen and assembler_maker_gen. With that for loop we will be creating 2 body makers (remember that we define the variable num_body = 2). So, we are going to have 2 body makers, 1 neck maker, 1 painter and 4 assemblers.
Now we are going to create stock alarms and suppliers calls. This is how it will work:
Our alarm will be constantly monitoring the amount of stock (level) of a container.
If the current level is bellow a critical level that we’ll define, it will make a call to the supplier.
After a T amount of time, supplier will arrive to our factory and refill our container with an N amount of raw material.
First, we need to define our critical levels:
As we can see, wood supplier takes 2 business days to arrive. Then for critical level I define depends on the mean time it takes to create a body or a neck, the amount of body makers and neck makers, the 2 business days it takes to the supplier to arrive, and 1 margin day just to be sure. We do not want to be over stocked. Stock is money that just sit there, and that’s not good. But we don’t want to run out of stock either, because if that happens we are going to keep paying salaries for people that cannot work. The critical level is a trade off between that two things that you will need to define by your self. Each business if different.
Let’s add the alarm:
We made some changes in the __init__ function, by adding the wood_control and electronic_control processes. Before we take a look at the wood_stock_control, please notice that the electronic_stock_control function is not there. That function is pretty much the same as the wood_stock_control, so you can try to create it yourself. If you can’t or don’t want to, the complete code will be at the end of this part.
So, the first yield env.timeout(0) means that this process will start executing as soon as the simulation start. We can change that value (0) to, for example, an 8. That way, the process will start 8 time units later.
The while True, as we explain earlier, mean that the process will execute for all the time the simulation es running.
Then, it would check if the stock level is equal or minor than the critical level defined earlier. If stock es greater than that level, it would shut down for 1 time unit (see the else statement).
Of the stock level is equal or lower than the critical level, the print will be executed, informing that the level is N at a certain day and hour and the supplier call has been made.
After 2 days (16 hours), supplier arrives and it would refill the wood container with 300 units. That is what the yield self.wood.put(300) means.
Finally, the new stock level is printed and the alarm will be off for 1 day (yield env.timeout(8)).
We run this simulation for 5 days:
Part 3 complete code can be found here.
To be honest, until now we have been cheating somehow. After bodies and necks were made, they were store in the same container (prepaint) and we were treating them as the some thing. Now we are going to implement separe container for each piece, so we can treat them properly:
We already now how to make a container. Just notice two things here: the guitars_made variable, and the dispatch_control. Of course, we need to modify the body_maker and neck_maker processes:
Now we are storing the bodies in the body_pre_paint container. The same thing happens with the neck_maker. Painter also needs a modification:
We are now going to build a control process as we did on electronic or wood. This process will track the stock level of guitars ready to ship, and call the shop to let them now they can come to pick them up. For tracking purpose, we create a global variable call guitars_made, so we can store the number of guitars the shop has taken:
The first thing we do here is call the global variable guitars_made, with the statement global. If dispatch stock level is equal or higher than 50 guitars, we call the shop. After 4 hours, they come to pick the guitars and they take all the guitars available, not only the, for example, 50 that were ready when we call. So, when they take the guitars, we sum than level to our guitars_made variable with the statement guitars_made += self.dispatch.level. Then, the control process goes off for 8 hours. Assembler will need to be modified too, you can try to do it yourself, or take it from the full code.
Finally, add some prints and run the simulation:
And we are done! Of course, part 4 full code is in the link at the beginning. Thank you so much for reading my articule, hope you enjoy it and you could get something useful from it.
Until next time! | [
{
"code": null,
"e": 476,
"s": 172,
"text": "Hi there! In this tutorial we are going to build a guitar factory using SimPy! Even though this is a toy example, we are going to cover some pretty cool things that you can use for your own simulations. We are going to go throw the code here, but if you want to see the final version, it’s on my GitHub."
},
{
"code": null,
"e": 875,
"s": 476,
"text": "First of all, what is SimPy? In the documentation, they define it as: “SimPy is a process-based discrete-event simulation framework based on standard Python”. You can see the full documentation here, which I strongly recommend. There you can find not only the things you can do, but also a lot of simple but very helpful tutorials. If you don’t have SimPy installed, a simple pip will do the trick:"
},
{
"code": null,
"e": 893,
"s": 875,
"text": "pip install simpy"
},
{
"code": null,
"e": 1272,
"s": 893,
"text": "We are going to build a guitar factory from scratch, starting from something very simple into a more complex system. In this example, we are building one type of guitar. The body and the neck are build separately, but from the same type of wood. Then they are pass to a painting area. After that, a body, a neck and the electronic components are combined, so the guitar is made."
},
{
"code": null,
"e": 1291,
"s": 1272,
"text": "Let’s have a look:"
},
{
"code": null,
"e": 1322,
"s": 1291,
"text": "Let me explain that flowchart:"
},
{
"code": null,
"e": 2225,
"s": 1322,
"text": "There are 2 main containers. Wood and Electronic. Those containers have an N amount of wood/electronic components that going to be use in the process.The body make get a piece of wood from the container and transform it into a body, which will be stored in the Body storage. The same thing happen with the neck builder, but from one piece of wood, he will get two necks. The necks are stored in the Neck storage.Painter pick necks and bodies, paint them, and store them in Body storage 2 and Neck storage 2.Assembler picks a body, a neck and one piece of electronics, and assemble the guitar, which will be store in the Dispatch container.After an N amount of guitars are made, store send someone to pick them up.When Wood or Electronic are bellow a certain level of raw material, a call to the Supplier is made. After T days, supplier arrives to the factory and refill the container with raw material."
},
{
"code": null,
"e": 2376,
"s": 2225,
"text": "There are 2 main containers. Wood and Electronic. Those containers have an N amount of wood/electronic components that going to be use in the process."
},
{
"code": null,
"e": 2639,
"s": 2376,
"text": "The body make get a piece of wood from the container and transform it into a body, which will be stored in the Body storage. The same thing happen with the neck builder, but from one piece of wood, he will get two necks. The necks are stored in the Neck storage."
},
{
"code": null,
"e": 2735,
"s": 2639,
"text": "Painter pick necks and bodies, paint them, and store them in Body storage 2 and Neck storage 2."
},
{
"code": null,
"e": 2868,
"s": 2735,
"text": "Assembler picks a body, a neck and one piece of electronics, and assemble the guitar, which will be store in the Dispatch container."
},
{
"code": null,
"e": 2943,
"s": 2868,
"text": "After an N amount of guitars are made, store send someone to pick them up."
},
{
"code": null,
"e": 3133,
"s": 2943,
"text": "When Wood or Electronic are bellow a certain level of raw material, a call to the Supplier is made. After T days, supplier arrives to the factory and refill the container with raw material."
},
{
"code": null,
"e": 3154,
"s": 3133,
"text": "Part 1: Simple model"
},
{
"code": null,
"e": 3200,
"s": 3154,
"text": "Let’s start our model from the simplest form:"
},
{
"code": null,
"e": 3688,
"s": 3200,
"text": "We start importing SimPy. After that we will create the class Guitar_Factory and add the first two containers. Notice that we set the capacity of our containers as the variables shown above. Of course, dispatch will start empty. If we run out of wood, process will not stop, but it won’t create any more guitars either. The same thing happen if dispatch is full. Note the env argument. This is simply the SimPy environment where this are happening. We will define this later in our code."
},
{
"code": null,
"e": 3739,
"s": 3688,
"text": "Now we will add the Body maker and the Neck maker:"
},
{
"code": null,
"e": 4027,
"s": 3739,
"text": "We start creating our first two employees. The function take two arguments: The SimPy environment and the guitar_factory class (note that guitar_factory is different from the Guitar_Factory we define as our class in the previous Gist). What is happening there is pretty straight forward:"
},
{
"code": null,
"e": 4134,
"s": 4027,
"text": "While the simulation is running, the maker will take one piece of wood (yield guitar_factory.wood.get(1))."
},
{
"code": null,
"e": 4314,
"s": 4134,
"text": "It will keep that wood piece for one time period (that’s what the env.timeout function does). This simulate the time it takes to transform a piece of wood into a guitar body/neck."
},
{
"code": null,
"e": 4728,
"s": 4314,
"text": "After that time unit (1 in our case) has pass, the maker will put that piece into a container named dispatch. Please note that from one piece of wood, the body maker will make one guitar body. Instead, the neck maker, will make two necks from one piece of wood. So, you have the flexibility to take the number of raw material you want, and deliver as much other thing as you want, simply by changing that numbers."
},
{
"code": null,
"e": 4741,
"s": 4728,
"text": "And finally:"
},
{
"code": null,
"e": 5227,
"s": 4741,
"text": "Our simulation will run for 40 hours (8 hours per business day * 5 business days), which is defined in the until = total_time argument passed to the env.run function. The body_maker_process and neck_maker_process will create our “employees”. And finally, we added a print so we can know how much bodies and neck’s we’ve make. Note that we get that result with the guitar_factory.dispatch.level. That’s equivalent to say “return the amount of things that are in the dispatch container”:"
},
{
"code": null,
"e": 5273,
"s": 5227,
"text": "If you want the full code of part 1, is here."
},
{
"code": null,
"e": 5363,
"s": 5273,
"text": "Now we are going to add paint and assembling to our model. For that purpose, we will add:"
},
{
"code": null,
"e": 5417,
"s": 5363,
"text": "Pre paint and post paint containers, and the painter."
},
{
"code": null,
"e": 5453,
"s": 5417,
"text": "Electronic container and assembler."
},
{
"code": null,
"e": 5553,
"s": 5453,
"text": "Nothing new here. We add electronic, pre_paint and post_paint containers, and set their capacities."
},
{
"code": null,
"e": 5845,
"s": 5553,
"text": "As we’ve done with body and neck makers, we create the painter and the assembler. Note that painting takes 4 hours, but it works over 10 pieces at the same time, while assembling use 2 post paint pieces (1 body and 1 neck) plus 1 electronic piece, and deliver a guitar after an hour of work."
},
{
"code": null,
"e": 5956,
"s": 5845,
"text": "Then we add some prints, environment process creation and run the simulation! Again, part 2 full code is here."
},
{
"code": null,
"e": 6026,
"s": 5956,
"text": "Now we are going to add some very cool stuff. Fasten your seat belts!"
},
{
"code": null,
"e": 6646,
"s": 6026,
"text": "Until now, we have set a fixed time for our employees activity. For example, we have said that assembler takes 1 hour to make a guitar. With that parameter, it will always takes one hour, and not a minute more and not a minute less. We all now that’s not true. Activities takes different times, even do they are repeated along time. Here we will asume that the distribution of time is normal, but you can use any distribution you want. Also note that we are defining how many employees of each kind we want. We will start this part by importing the random library and defining the parameters needed to make the changes:"
},
{
"code": null,
"e": 6665,
"s": 6646,
"text": "Lets explain this:"
},
{
"code": null,
"e": 6742,
"s": 6665,
"text": "num_body set the number of body makers we are going to use (in this case, 2)"
},
{
"code": null,
"e": 6833,
"s": 6742,
"text": "mean_body its the mean time needed for a body maker to make a body out of a piece of wood."
},
{
"code": null,
"e": 6865,
"s": 6833,
"text": "std_body is the standard error."
},
{
"code": null,
"e": 6943,
"s": 6865,
"text": "Now we are going to make a change to the function that creates our employees:"
},
{
"code": null,
"e": 7310,
"s": 6943,
"text": "It is simple to note that now, body_time will not always be 1. In fact it will be a random number taken from a normal distribution with (in this case) mean 1 and standard error 0.1. Also note the assembling_time: we are taking the maximum number between the random one and 1. In other words, we are saying that assembling a guitar will never take less than one hour."
},
{
"code": null,
"e": 7456,
"s": 7310,
"text": "We have to change the creating process of our employees, by creating a new function that allow us to create more than one employee for each kind:"
},
{
"code": null,
"e": 7743,
"s": 7456,
"text": "Of course, this will be the same code for neck_maker_gen, paint_maker_gen and assembler_maker_gen. With that for loop we will be creating 2 body makers (remember that we define the variable num_body = 2). So, we are going to have 2 body makers, 1 neck maker, 1 painter and 4 assemblers."
},
{
"code": null,
"e": 7830,
"s": 7743,
"text": "Now we are going to create stock alarms and suppliers calls. This is how it will work:"
},
{
"code": null,
"e": 7914,
"s": 7830,
"text": "Our alarm will be constantly monitoring the amount of stock (level) of a container."
},
{
"code": null,
"e": 8018,
"s": 7914,
"text": "If the current level is bellow a critical level that we’ll define, it will make a call to the supplier."
},
{
"code": null,
"e": 8139,
"s": 8018,
"text": "After a T amount of time, supplier will arrive to our factory and refill our container with an N amount of raw material."
},
{
"code": null,
"e": 8185,
"s": 8139,
"text": "First, we need to define our critical levels:"
},
{
"code": null,
"e": 8832,
"s": 8185,
"text": "As we can see, wood supplier takes 2 business days to arrive. Then for critical level I define depends on the mean time it takes to create a body or a neck, the amount of body makers and neck makers, the 2 business days it takes to the supplier to arrive, and 1 margin day just to be sure. We do not want to be over stocked. Stock is money that just sit there, and that’s not good. But we don’t want to run out of stock either, because if that happens we are going to keep paying salaries for people that cannot work. The critical level is a trade off between that two things that you will need to define by your self. Each business if different."
},
{
"code": null,
"e": 8853,
"s": 8832,
"text": "Let’s add the alarm:"
},
{
"code": null,
"e": 9266,
"s": 8853,
"text": "We made some changes in the __init__ function, by adding the wood_control and electronic_control processes. Before we take a look at the wood_stock_control, please notice that the electronic_stock_control function is not there. That function is pretty much the same as the wood_stock_control, so you can try to create it yourself. If you can’t or don’t want to, the complete code will be at the end of this part."
},
{
"code": null,
"e": 9484,
"s": 9266,
"text": "So, the first yield env.timeout(0) means that this process will start executing as soon as the simulation start. We can change that value (0) to, for example, an 8. That way, the process will start 8 time units later."
},
{
"code": null,
"e": 9602,
"s": 9484,
"text": "The while True, as we explain earlier, mean that the process will execute for all the time the simulation es running."
},
{
"code": null,
"e": 9799,
"s": 9602,
"text": "Then, it would check if the stock level is equal or minor than the critical level defined earlier. If stock es greater than that level, it would shut down for 1 time unit (see the else statement)."
},
{
"code": null,
"e": 9982,
"s": 9799,
"text": "Of the stock level is equal or lower than the critical level, the print will be executed, informing that the level is N at a certain day and hour and the supplier call has been made."
},
{
"code": null,
"e": 10128,
"s": 9982,
"text": "After 2 days (16 hours), supplier arrives and it would refill the wood container with 300 units. That is what the yield self.wood.put(300) means."
},
{
"code": null,
"e": 10228,
"s": 10128,
"text": "Finally, the new stock level is printed and the alarm will be off for 1 day (yield env.timeout(8))."
},
{
"code": null,
"e": 10263,
"s": 10228,
"text": "We run this simulation for 5 days:"
},
{
"code": null,
"e": 10303,
"s": 10263,
"text": "Part 3 complete code can be found here."
},
{
"code": null,
"e": 10580,
"s": 10303,
"text": "To be honest, until now we have been cheating somehow. After bodies and necks were made, they were store in the same container (prepaint) and we were treating them as the some thing. Now we are going to implement separe container for each piece, so we can treat them properly:"
},
{
"code": null,
"e": 10772,
"s": 10580,
"text": "We already now how to make a container. Just notice two things here: the guitars_made variable, and the dispatch_control. Of course, we need to modify the body_maker and neck_maker processes:"
},
{
"code": null,
"e": 10914,
"s": 10772,
"text": "Now we are storing the bodies in the body_pre_paint container. The same thing happens with the neck_maker. Painter also needs a modification:"
},
{
"code": null,
"e": 11249,
"s": 10914,
"text": "We are now going to build a control process as we did on electronic or wood. This process will track the stock level of guitars ready to ship, and call the shop to let them now they can come to pick them up. For tracking purpose, we create a global variable call guitars_made, so we can store the number of guitars the shop has taken:"
},
{
"code": null,
"e": 11854,
"s": 11249,
"text": "The first thing we do here is call the global variable guitars_made, with the statement global. If dispatch stock level is equal or higher than 50 guitars, we call the shop. After 4 hours, they come to pick the guitars and they take all the guitars available, not only the, for example, 50 that were ready when we call. So, when they take the guitars, we sum than level to our guitars_made variable with the statement guitars_made += self.dispatch.level. Then, the control process goes off for 8 hours. Assembler will need to be modified too, you can try to do it yourself, or take it from the full code."
},
{
"code": null,
"e": 11903,
"s": 11854,
"text": "Finally, add some prints and run the simulation:"
},
{
"code": null,
"e": 12086,
"s": 11903,
"text": "And we are done! Of course, part 4 full code is in the link at the beginning. Thank you so much for reading my articule, hope you enjoy it and you could get something useful from it."
}
]
|
Finding difference in Timestamps – Python Pandas | To find the difference in timestamps, we can use index operator i.e. the square brackets to find the difference. For timestamps, we need to also use abs(). At first, import the required library −
import pandas as pd
Create a DataFrame with 3 columns. We have two date columns with timestamp −
dataFrame = pd.DataFrame(
{
"Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW"],
"Date_of_Purchase": [
pd.Timestamp("2021-06-10"),
pd.Timestamp("2021-07-11"),
pd.Timestamp("2021-06-25"),
pd.Timestamp("2021-06-29"),
pd.Timestamp("2021-03-20"),
],
"Date_of_Service": [
pd.Timestamp("2021-11-10"),
pd.Timestamp("2021-12-11"),
pd.Timestamp("2021-11-25"),
pd.Timestamp("2021-11-29"),
pd.Timestamp("2021-08-20"),
]
})
Let us now find the difference between timestamps from both the date columns −
timestamp_diff = abs(dataFrame['Date_of_Purchase']-dataFrame['Date_of_Service'])
Following is the code −
import pandas as pd
# create a dataframe with 3 columns
dataFrame = pd.DataFrame(
{
"Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW"],
"Date_of_Purchase": [
pd.Timestamp("2021-06-10"),
pd.Timestamp("2021-07-11"),
pd.Timestamp("2021-06-25"),
pd.Timestamp("2021-06-29"),
pd.Timestamp("2021-03-20"),
],
"Date_of_Service": [
pd.Timestamp("2021-11-10"),
pd.Timestamp("2021-12-11"),
pd.Timestamp("2021-11-25"),
pd.Timestamp("2021-11-29"),
pd.Timestamp("2021-08-20"),
]
})
print"DataFrame...\n", dataFrame
# find difference in timestamps
timestamp_diff = abs(dataFrame['Date_of_Purchase']-dataFrame['Date_of_Service'])
print"\nDifference between two Timestamps: \n",timestamp_diff
This will produce the following output −
DataFrame...
Car Date_of_Purchase Date_of_Service
0 Audi 2021-06-10 2021-11-10
1 Lexus 2021-07-11 2021-12-11
2 Tesla 2021-06-25 2021-11-25
3 Mercedes 2021-06-29 2021-11-29
4 BMW 2021-03-20 2021-08-20
Difference between two Timestamps:
0 153 days
1 153 days
2 153 days
3 153 days
4 153 days
dtype: timedelta64[ns] | [
{
"code": null,
"e": 1258,
"s": 1062,
"text": "To find the difference in timestamps, we can use index operator i.e. the square brackets to find the difference. For timestamps, we need to also use abs(). At first, import the required library −"
},
{
"code": null,
"e": 1278,
"s": 1258,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1355,
"s": 1278,
"text": "Create a DataFrame with 3 columns. We have two date columns with timestamp −"
},
{
"code": null,
"e": 1897,
"s": 1355,
"text": "dataFrame = pd.DataFrame(\n {\n \"Car\": [\"Audi\", \"Lexus\", \"Tesla\", \"Mercedes\", \"BMW\"],\n\n \"Date_of_Purchase\": [\n pd.Timestamp(\"2021-06-10\"),\n pd.Timestamp(\"2021-07-11\"),\n pd.Timestamp(\"2021-06-25\"),\n pd.Timestamp(\"2021-06-29\"),\n pd.Timestamp(\"2021-03-20\"),\n ],\n \"Date_of_Service\": [\n pd.Timestamp(\"2021-11-10\"),\n pd.Timestamp(\"2021-12-11\"),\n pd.Timestamp(\"2021-11-25\"),\n pd.Timestamp(\"2021-11-29\"),\n pd.Timestamp(\"2021-08-20\"),\n ]\n })\n\n"
},
{
"code": null,
"e": 1976,
"s": 1897,
"text": "Let us now find the difference between timestamps from both the date columns −"
},
{
"code": null,
"e": 2057,
"s": 1976,
"text": "timestamp_diff = abs(dataFrame['Date_of_Purchase']-dataFrame['Date_of_Service'])"
},
{
"code": null,
"e": 2081,
"s": 2057,
"text": "Following is the code −"
},
{
"code": null,
"e": 2888,
"s": 2081,
"text": "import pandas as pd\n\n# create a dataframe with 3 columns\ndataFrame = pd.DataFrame(\n {\n \"Car\": [\"Audi\", \"Lexus\", \"Tesla\", \"Mercedes\", \"BMW\"],\n\n \"Date_of_Purchase\": [\n pd.Timestamp(\"2021-06-10\"),\n pd.Timestamp(\"2021-07-11\"),\n pd.Timestamp(\"2021-06-25\"),\n pd.Timestamp(\"2021-06-29\"),\n pd.Timestamp(\"2021-03-20\"),\n ],\n \"Date_of_Service\": [\n pd.Timestamp(\"2021-11-10\"),\n pd.Timestamp(\"2021-12-11\"),\n pd.Timestamp(\"2021-11-25\"),\n pd.Timestamp(\"2021-11-29\"),\n pd.Timestamp(\"2021-08-20\"),\n ]\n })\n\nprint\"DataFrame...\\n\", dataFrame\n\n# find difference in timestamps\ntimestamp_diff = abs(dataFrame['Date_of_Purchase']-dataFrame['Date_of_Service'])\nprint\"\\nDifference between two Timestamps: \\n\",timestamp_diff"
},
{
"code": null,
"e": 2929,
"s": 2888,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3360,
"s": 2929,
"text": "DataFrame...\n Car Date_of_Purchase Date_of_Service\n0 Audi 2021-06-10 2021-11-10\n1 Lexus 2021-07-11 2021-12-11\n2 Tesla 2021-06-25 2021-11-25\n3 Mercedes 2021-06-29 2021-11-29\n4 BMW 2021-03-20 2021-08-20\n\nDifference between two Timestamps:\n0 153 days\n1 153 days\n2 153 days\n3 153 days\n4 153 days\ndtype: timedelta64[ns]"
}
]
|
Adding Multiple Backgrounds with CSS3 | To add multiple backgrounds, use the background-image property in CSS. Following is the code for adding multiple backgrounds −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
div {
background-image:
url("http://pngimg.com/uploads/autumn_leaves/autumn_leaves_PNG3613.png"),
url("https://i.picsum.photos/id/256/1200/300.jpg");
background-position: left bottom, left top;
background-repeat: repeat, repeat;
padding: 15px;
}
p {
font-size: 18px;
}
</style>
</head>
<body>
<h1>Multiple Backgrounds using CSS</h1>
<div>
<h1>Some Sample Text</h1>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem, ipsum
dolorem? Adipisci accusantium eveniet necessitatibus beatae est, dolorum
nobis minima aliquam atque id at sapiente culpa, alias nulla rem.
Aliquam, modi repellendus fugiat dolore, blanditiis praesentium quam
doloribus possimus doloremque reprehenderit corporis enim distinctio,
ducimus nisi. Voluptatum vel repudiandae omnis.
</p>
</div>
</body>
</html>
The above code will produce the following output − | [
{
"code": null,
"e": 1189,
"s": 1062,
"text": "To add multiple backgrounds, use the background-image property in CSS. Following is the code for adding multiple backgrounds −"
},
{
"code": null,
"e": 1200,
"s": 1189,
"text": " Live Demo"
},
{
"code": null,
"e": 2127,
"s": 1200,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nbody {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n}\ndiv {\n background-image:\n url(\"http://pngimg.com/uploads/autumn_leaves/autumn_leaves_PNG3613.png\"),\n url(\"https://i.picsum.photos/id/256/1200/300.jpg\");\n background-position: left bottom, left top;\n background-repeat: repeat, repeat;\n padding: 15px;\n}\np {\n font-size: 18px;\n}\n</style>\n</head>\n<body>\n<h1>Multiple Backgrounds using CSS</h1>\n<div>\n<h1>Some Sample Text</h1>\n<p>\nLorem ipsum dolor sit amet consectetur adipisicing elit. Quidem, ipsum\ndolorem? Adipisci accusantium eveniet necessitatibus beatae est, dolorum\nnobis minima aliquam atque id at sapiente culpa, alias nulla rem.\nAliquam, modi repellendus fugiat dolore, blanditiis praesentium quam\ndoloribus possimus doloremque reprehenderit corporis enim distinctio,\nducimus nisi. Voluptatum vel repudiandae omnis.\n</p>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 2178,
"s": 2127,
"text": "The above code will produce the following output −"
}
]
|
Matplotlib Plot Lines with Colors through Colormap | To plot lines with colors through colormap, we can take the following steps−
Create x and y data points using numpy
Plot x and y data points using plot() method.
Count n finds, number of color lines has to be plotted.
Iterate in a range (n) and plot the lines.
Limit the x ticks range.
Use show() method to display the figure.
import numpy as np
import matplotlib.pylab as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(0, 2 * np.pi, 64)
y = np.exp(x)
plt.plot(x, y)
n = 20
colors = plt.cm.rainbow(np.linspace(0, 1, n))
for i in range(n):
plt.plot(x, i * y, color=colors[i])
plt.xlim(4, 6)
plt.show() | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To plot lines with colors through colormap, we can take the following steps−"
},
{
"code": null,
"e": 1178,
"s": 1139,
"text": "Create x and y data points using numpy"
},
{
"code": null,
"e": 1224,
"s": 1178,
"text": "Plot x and y data points using plot() method."
},
{
"code": null,
"e": 1280,
"s": 1224,
"text": "Count n finds, number of color lines has to be plotted."
},
{
"code": null,
"e": 1323,
"s": 1280,
"text": "Iterate in a range (n) and plot the lines."
},
{
"code": null,
"e": 1348,
"s": 1323,
"text": "Limit the x ticks range."
},
{
"code": null,
"e": 1389,
"s": 1348,
"text": "Use show() method to display the figure."
},
{
"code": null,
"e": 1723,
"s": 1389,
"text": "import numpy as np\nimport matplotlib.pylab as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(0, 2 * np.pi, 64)\ny = np.exp(x)\nplt.plot(x, y)\nn = 20\ncolors = plt.cm.rainbow(np.linspace(0, 1, n))\nfor i in range(n):\nplt.plot(x, i * y, color=colors[i])\nplt.xlim(4, 6)\nplt.show()"
}
]
|
Scraping Reddit data. How to scrape data from Reddit using... | by Gilbert Tanner | Towards Data Science | As its name suggests PRAW is a Python wrapper for the Reddit API, which enables you to scrape data from subreddits, create a bot and much more.
In this article, we will learn how to use PRAW to scrape posts from different subreddits as well as how to get comments from a specific post.
PRAW can be installed using pip or conda:
Now PRAW can be imported by writting:
import praw
Before it can be used to scrape data we need to authenticate ourselves. For this we need to create a Reddit instance and provide it with a client_id , client_secret and a user_agent .
To get the authentication information we need to create a reddit app by navigating to this page and clicking create app or create another app.
This will open a form where you need to fill in a name, description and redirect uri. For the redirect uri you should choose http://localhost:8080 as described in the excellent PRAW documentation.
After pressing create app a new application will appear. Here you can find the authentication information needed to create the praw.Reddit instance.
Now that we have a praw.Reddit instance we can access all available functions and use it, to for example get the 10 “hottest” posts from the Machine Learning subreddit.
Output:
[D] What is the best ML paper you read in 2018 and why?[D] Machine Learning - WAYR (What Are You Reading) - Week 53[R] A Geometric Theory of Higher-Order Automatic DifferentiationUC Berkeley and Berkeley AI Research published all materials of CS 188: Introduction to Artificial Intelligence, Fall 2018[Research] Accurate, Data-Efficient, Unconstrained Text Recognition with Convolutional Neural Networks...
We can also get the 10 “hottest” posts of all subreddits combined by specifying “all” as the subreddit name.
Output:
I've been lying to my wife about film plots for years.I don’t care if this gets downvoted into oblivion! I DID IT REDDIT!!I’ve had enough of your shit, KarenStranger Things 3: Coming July 4th, 2019...
This variable can be iterated over and features including the post title, id and url can be extracted and saved into an .csv file.
General information about the subreddit can be obtained using the .description function on the subreddit object.
Output:
**[Rules For Posts](https://www.reddit.com/r/MachineLearning/about/rules/)**--------+[Research](https://www.reddit.com/r/MachineLearning/search?sort=new&restrict_sr=on&q=flair%3AResearch)--------+[Discussion](https://www.reddit.com/r/MachineLearning/search?sort=new&restrict_sr=on&q=flair%3ADiscussion)--------+[Project](https://www.reddit.com/r/MachineLearning/search?sort=new&restrict_sr=on&q=flair%3AProject)--------+[News](https://www.reddit.com/r/MachineLearning/search?sort=new&restrict_sr=on&q=flair%3ANews)--------...
You can get the comments for a post/submission by creating/obtaining a Submission object and looping through the comments attribute. To get a post/submission we can either iterate through the submissions of a subreddit or specify a specific submission using reddit.submission and passing it the submission url or id.
To get the top-level comments we only need to iterate over submission.comments .
This will work for some submission, but for others that have more comments this code will throw an AttributeError saying:
AttributeError: 'MoreComments' object has no attribute 'body'
These MoreComments object represent the “load more comments” and “continue this thread” links encountered on the websites, as described in more detail in the comment documentation.
There get rid of the MoreComments objects, we can check the datatype of each comment before printing the body.
But Praw already provides a method called replace_more , which replaces or removes the MoreComments . The method takes an argument called limit, which when set to 0 will remove all MoreComments.
Both of the above code blocks successfully iterate over all the top-level comments and print their body. The output can be seen below.
Source: [https://www.facebook.com/VoyageursWolfProject/](https://www.facebook.com/VoyageursWolfProject/)I thought this was a shit post made in paint before I read the titleWow, that’s very cool. To think how keen their senses must be to recognize and avoid each other and their territories. Plus, I like to think that there’s one from the white colored clan who just goes way into the other territories because, well, he’s a badass.That’s really cool. The edges are surprisingly defined....
However, the comment section can be arbitrarily deep and most of the time we surely also want to get the comments of the comments. CommentForest provides the .list method, which can be used for getting all comments inside the comment section.
The above code will first of output all the top-level comments, followed by the second-level comments and so on until there are no comments left.
towardsdatascience.com
Praw is a Python wrapper for the Reddit API, which enables us to use the Reddit API with a clean Python interface. The API can be used for webscraping, creating a bot as well as many others.
This article covered authentication, getting posts from a subreddit and getting comments. To learn more about the API I suggest to take a look at their excellent documentation.
If you liked this article consider subscribing on my Youtube Channel and following me on social media.
The code covered in this article is available as a Github Repository.
If you have any questions, recommendations or critiques, I can be reached via Twitter or the comment section. | [
{
"code": null,
"e": 315,
"s": 171,
"text": "As its name suggests PRAW is a Python wrapper for the Reddit API, which enables you to scrape data from subreddits, create a bot and much more."
},
{
"code": null,
"e": 457,
"s": 315,
"text": "In this article, we will learn how to use PRAW to scrape posts from different subreddits as well as how to get comments from a specific post."
},
{
"code": null,
"e": 499,
"s": 457,
"text": "PRAW can be installed using pip or conda:"
},
{
"code": null,
"e": 537,
"s": 499,
"text": "Now PRAW can be imported by writting:"
},
{
"code": null,
"e": 549,
"s": 537,
"text": "import praw"
},
{
"code": null,
"e": 733,
"s": 549,
"text": "Before it can be used to scrape data we need to authenticate ourselves. For this we need to create a Reddit instance and provide it with a client_id , client_secret and a user_agent ."
},
{
"code": null,
"e": 876,
"s": 733,
"text": "To get the authentication information we need to create a reddit app by navigating to this page and clicking create app or create another app."
},
{
"code": null,
"e": 1073,
"s": 876,
"text": "This will open a form where you need to fill in a name, description and redirect uri. For the redirect uri you should choose http://localhost:8080 as described in the excellent PRAW documentation."
},
{
"code": null,
"e": 1222,
"s": 1073,
"text": "After pressing create app a new application will appear. Here you can find the authentication information needed to create the praw.Reddit instance."
},
{
"code": null,
"e": 1391,
"s": 1222,
"text": "Now that we have a praw.Reddit instance we can access all available functions and use it, to for example get the 10 “hottest” posts from the Machine Learning subreddit."
},
{
"code": null,
"e": 1399,
"s": 1391,
"text": "Output:"
},
{
"code": null,
"e": 1806,
"s": 1399,
"text": "[D] What is the best ML paper you read in 2018 and why?[D] Machine Learning - WAYR (What Are You Reading) - Week 53[R] A Geometric Theory of Higher-Order Automatic DifferentiationUC Berkeley and Berkeley AI Research published all materials of CS 188: Introduction to Artificial Intelligence, Fall 2018[Research] Accurate, Data-Efficient, Unconstrained Text Recognition with Convolutional Neural Networks..."
},
{
"code": null,
"e": 1915,
"s": 1806,
"text": "We can also get the 10 “hottest” posts of all subreddits combined by specifying “all” as the subreddit name."
},
{
"code": null,
"e": 1923,
"s": 1915,
"text": "Output:"
},
{
"code": null,
"e": 2124,
"s": 1923,
"text": "I've been lying to my wife about film plots for years.I don’t care if this gets downvoted into oblivion! I DID IT REDDIT!!I’ve had enough of your shit, KarenStranger Things 3: Coming July 4th, 2019..."
},
{
"code": null,
"e": 2255,
"s": 2124,
"text": "This variable can be iterated over and features including the post title, id and url can be extracted and saved into an .csv file."
},
{
"code": null,
"e": 2368,
"s": 2255,
"text": "General information about the subreddit can be obtained using the .description function on the subreddit object."
},
{
"code": null,
"e": 2376,
"s": 2368,
"text": "Output:"
},
{
"code": null,
"e": 2902,
"s": 2376,
"text": "**[Rules For Posts](https://www.reddit.com/r/MachineLearning/about/rules/)**--------+[Research](https://www.reddit.com/r/MachineLearning/search?sort=new&restrict_sr=on&q=flair%3AResearch)--------+[Discussion](https://www.reddit.com/r/MachineLearning/search?sort=new&restrict_sr=on&q=flair%3ADiscussion)--------+[Project](https://www.reddit.com/r/MachineLearning/search?sort=new&restrict_sr=on&q=flair%3AProject)--------+[News](https://www.reddit.com/r/MachineLearning/search?sort=new&restrict_sr=on&q=flair%3ANews)--------..."
},
{
"code": null,
"e": 3219,
"s": 2902,
"text": "You can get the comments for a post/submission by creating/obtaining a Submission object and looping through the comments attribute. To get a post/submission we can either iterate through the submissions of a subreddit or specify a specific submission using reddit.submission and passing it the submission url or id."
},
{
"code": null,
"e": 3300,
"s": 3219,
"text": "To get the top-level comments we only need to iterate over submission.comments ."
},
{
"code": null,
"e": 3422,
"s": 3300,
"text": "This will work for some submission, but for others that have more comments this code will throw an AttributeError saying:"
},
{
"code": null,
"e": 3484,
"s": 3422,
"text": "AttributeError: 'MoreComments' object has no attribute 'body'"
},
{
"code": null,
"e": 3665,
"s": 3484,
"text": "These MoreComments object represent the “load more comments” and “continue this thread” links encountered on the websites, as described in more detail in the comment documentation."
},
{
"code": null,
"e": 3776,
"s": 3665,
"text": "There get rid of the MoreComments objects, we can check the datatype of each comment before printing the body."
},
{
"code": null,
"e": 3971,
"s": 3776,
"text": "But Praw already provides a method called replace_more , which replaces or removes the MoreComments . The method takes an argument called limit, which when set to 0 will remove all MoreComments."
},
{
"code": null,
"e": 4106,
"s": 3971,
"text": "Both of the above code blocks successfully iterate over all the top-level comments and print their body. The output can be seen below."
},
{
"code": null,
"e": 4599,
"s": 4106,
"text": "Source: [https://www.facebook.com/VoyageursWolfProject/](https://www.facebook.com/VoyageursWolfProject/)I thought this was a shit post made in paint before I read the titleWow, that’s very cool. To think how keen their senses must be to recognize and avoid each other and their territories. Plus, I like to think that there’s one from the white colored clan who just goes way into the other territories because, well, he’s a badass.That’s really cool. The edges are surprisingly defined...."
},
{
"code": null,
"e": 4842,
"s": 4599,
"text": "However, the comment section can be arbitrarily deep and most of the time we surely also want to get the comments of the comments. CommentForest provides the .list method, which can be used for getting all comments inside the comment section."
},
{
"code": null,
"e": 4988,
"s": 4842,
"text": "The above code will first of output all the top-level comments, followed by the second-level comments and so on until there are no comments left."
},
{
"code": null,
"e": 5011,
"s": 4988,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5202,
"s": 5011,
"text": "Praw is a Python wrapper for the Reddit API, which enables us to use the Reddit API with a clean Python interface. The API can be used for webscraping, creating a bot as well as many others."
},
{
"code": null,
"e": 5379,
"s": 5202,
"text": "This article covered authentication, getting posts from a subreddit and getting comments. To learn more about the API I suggest to take a look at their excellent documentation."
},
{
"code": null,
"e": 5482,
"s": 5379,
"text": "If you liked this article consider subscribing on my Youtube Channel and following me on social media."
},
{
"code": null,
"e": 5552,
"s": 5482,
"text": "The code covered in this article is available as a Github Repository."
}
]
|
C Program for Rat in a Maze | Backtracking-2 - GeeksforGeeks | 02 Aug, 2021
We have discussed Backtracking and Knight’s tour problem in Set 1. Let us discuss Rat in a Maze as another example problem that can be solved using Backtracking.
A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach the destination. The rat can move only in two directions: forward and down.In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with a limited number of moves.
Following is an example maze.
Gray blocks are dead ends (value = 0).
Following is binary matrix representation of the above maze.
{1, 0, 0, 0}
{1, 1, 0, 1}
{0, 1, 0, 0}
{1, 1, 1, 1}
Following is a maze with highlighted solution path.
Following is the solution matrix (output of program) for the above input matrix.
{1, 0, 0, 0}
{1, 1, 0, 0}
{0, 1, 0, 0}
{0, 1, 1, 1}
All entries in solution path are marked as 1.
C/C++
/* C/C++ program to solve Rat in a Maze problem using backtracking */#include <stdio.h> // Maze size#define N 4 bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]); /* A utility function to print solution matrix sol[N][N] */void printSolution(int sol[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(" %d ", sol[i][j]); printf("\n"); }} /* A utility function to check if x, y is valid index for N*N maze */bool isSafe(int maze[N][N], int x, int y){ // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) return true; return false;} /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/bool solveMaze(int maze[N][N]){ int sol[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveMazeUtil(maze, 0, 0, sol) == false) { printf("Solution doesn't exist"); return false; } printSolution(sol); return true;} /* A recursive utility function to solve Maze problem */bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]){ // if (x, y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol) == true) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + 1, sol) == true) return true; /* If none of the above movements work then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false;} // driver program to test above functionint main(){ int maze[N][N] = { { 1, 0, 0, 0 }, { 1, 1, 0, 1 }, { 0, 1, 0, 0 }, { 1, 1, 1, 1 } }; solveMaze(maze); return 0;}
1 0 0 0
1 1 0 0
0 1 0 0
0 1 1 1
Please refer complete article on Rat in a Maze | Backtracking-2 for more details!
as5853535
sweetyty
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Regular expressions in C
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Hamming code Implementation in C/C++
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Difference between break and continue statement in C
C Hello World Program | [
{
"code": null,
"e": 24955,
"s": 24927,
"text": "\n02 Aug, 2021"
},
{
"code": null,
"e": 25117,
"s": 24955,
"text": "We have discussed Backtracking and Knight’s tour problem in Set 1. Let us discuss Rat in a Maze as another example problem that can be solved using Backtracking."
},
{
"code": null,
"e": 25752,
"s": 25117,
"text": "A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach the destination. The rat can move only in two directions: forward and down.In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with a limited number of moves."
},
{
"code": null,
"e": 25782,
"s": 25752,
"text": "Following is an example maze."
},
{
"code": null,
"e": 25823,
"s": 25782,
"text": " Gray blocks are dead ends (value = 0). "
},
{
"code": null,
"e": 25884,
"s": 25823,
"text": "Following is binary matrix representation of the above maze."
},
{
"code": null,
"e": 26001,
"s": 25884,
"text": " {1, 0, 0, 0}\n {1, 1, 0, 1}\n {0, 1, 0, 0}\n {1, 1, 1, 1}\n"
},
{
"code": null,
"e": 26053,
"s": 26001,
"text": "Following is a maze with highlighted solution path."
},
{
"code": null,
"e": 26134,
"s": 26053,
"text": "Following is the solution matrix (output of program) for the above input matrix."
},
{
"code": null,
"e": 26298,
"s": 26134,
"text": " {1, 0, 0, 0}\n {1, 1, 0, 0}\n {0, 1, 0, 0}\n {0, 1, 1, 1}\n All entries in solution path are marked as 1.\n"
},
{
"code": null,
"e": 26304,
"s": 26298,
"text": "C/C++"
},
{
"code": "/* C/C++ program to solve Rat in a Maze problem using backtracking */#include <stdio.h> // Maze size#define N 4 bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]); /* A utility function to print solution matrix sol[N][N] */void printSolution(int sol[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(\" %d \", sol[i][j]); printf(\"\\n\"); }} /* A utility function to check if x, y is valid index for N*N maze */bool isSafe(int maze[N][N], int x, int y){ // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) return true; return false;} /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/bool solveMaze(int maze[N][N]){ int sol[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveMazeUtil(maze, 0, 0, sol) == false) { printf(\"Solution doesn't exist\"); return false; } printSolution(sol); return true;} /* A recursive utility function to solve Maze problem */bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]){ // if (x, y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol) == true) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + 1, sol) == true) return true; /* If none of the above movements work then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false;} // driver program to test above functionint main(){ int maze[N][N] = { { 1, 0, 0, 0 }, { 1, 1, 0, 1 }, { 0, 1, 0, 0 }, { 1, 1, 1, 1 } }; solveMaze(maze); return 0;}",
"e": 28742,
"s": 26304,
"text": null
},
{
"code": null,
"e": 28790,
"s": 28742,
"text": "1 0 0 0 \n1 1 0 0 \n0 1 0 0 \n0 1 1 1\n"
},
{
"code": null,
"e": 28872,
"s": 28790,
"text": "Please refer complete article on Rat in a Maze | Backtracking-2 for more details!"
},
{
"code": null,
"e": 28882,
"s": 28872,
"text": "as5853535"
},
{
"code": null,
"e": 28891,
"s": 28882,
"text": "sweetyty"
},
{
"code": null,
"e": 28902,
"s": 28891,
"text": "C Programs"
},
{
"code": null,
"e": 29000,
"s": 28902,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29041,
"s": 29000,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29072,
"s": 29041,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 29113,
"s": 29072,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 29147,
"s": 29113,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 29172,
"s": 29147,
"text": "Regular expressions in C"
},
{
"code": null,
"e": 29243,
"s": 29172,
"text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 29280,
"s": 29243,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 29370,
"s": 29280,
"text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++"
},
{
"code": null,
"e": 29423,
"s": 29370,
"text": "Difference between break and continue statement in C"
}
]
|
Find the k most frequent words from data set in Python | If there is a need to find 10 most frequent words in a data set, python can help us find it using the collections module. The collections module has a counter class which gives the count of the words after we supply a list of words to it. We also use the most_common method to find out the number of such words as needed by the program input.
In the below example we take a paragraph, and then first create a list of words applying split(). We will then apply the counter() to find the count of all the words. Finally the most_common function will give us the appropriate result of how many such words with highest frequency we want.
from collections import Counter
word_set = " This is a series of strings to count " \
"many words . They sometime hurt and words sometime inspire "\
"Also sometime fewer words convey more meaning than a bag of words "\
"Be careful what you speak or what you write or even what you think of. "\
# Create list of all the words in the string
word_list = word_set.split()
# Get the count of each word.
word_count = Counter(word_list)
# Use most_common() method from Counter subclass
print(word_count.most_common(3))
Running the above code gives us the following result −
[('words', 4), ('sometime', 3), ('what', 3)] | [
{
"code": null,
"e": 1405,
"s": 1062,
"text": "If there is a need to find 10 most frequent words in a data set, python can help us find it using the collections module. The collections module has a counter class which gives the count of the words after we supply a list of words to it. We also use the most_common method to find out the number of such words as needed by the program input."
},
{
"code": null,
"e": 1696,
"s": 1405,
"text": "In the below example we take a paragraph, and then first create a list of words applying split(). We will then apply the counter() to find the count of all the words. Finally the most_common function will give us the appropriate result of how many such words with highest frequency we want."
},
{
"code": null,
"e": 2219,
"s": 1696,
"text": "from collections import Counter\nword_set = \" This is a series of strings to count \" \\\n \"many words . They sometime hurt and words sometime inspire \"\\\n \"Also sometime fewer words convey more meaning than a bag of words \"\\\n \"Be careful what you speak or what you write or even what you think of. \"\\\n# Create list of all the words in the string\nword_list = word_set.split()\n\n# Get the count of each word.\nword_count = Counter(word_list)\n\n# Use most_common() method from Counter subclass\nprint(word_count.most_common(3))"
},
{
"code": null,
"e": 2274,
"s": 2219,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2319,
"s": 2274,
"text": "[('words', 4), ('sometime', 3), ('what', 3)]"
}
]
|
Hamming Code implementation in Python - GeeksforGeeks | 25 Aug, 2021
Pre-requisite: Hamming Code
Hamming code is a set of error-correction codes that can be used to detect and correct the errors that can occur when the data is moved or stored from the sender to the receiver. It is a technique developed by R.W. Hamming for error correction.
Steps:
Enter the Data to be transmittedCalculate the no of redundant bits requiredDetermine the parity bitsCreate error data for testingCheck for errors
Enter the Data to be transmitted
Calculate the no of redundant bits required
Determine the parity bits
Create error data for testing
Check for errors
Examples:
Input:
1011001
Output:
Data transferred is 10101001110
Error Data is 11101001110
The position of error is 10
Input:
10101111010
Output:
Data transferred is 101011111010000
Error Data is 101011111010100
The position of error is 3
Python3
# Python program to demonstrate# hamming code def calcRedundantBits(m): # Use the formula 2 ^ r >= m + r + 1 # to calculate the no of redundant bits. # Iterate over 0 .. m and return the value # that satisfies the equation for i in range(m): if(2**i >= m + i + 1): return i def posRedundantBits(data, r): # Redundancy bits are placed at the positions # which correspond to the power of 2. j = 0 k = 1 m = len(data) res = '' # If position is power of 2 then insert '0' # Else append the data for i in range(1, m + r+1): if(i == 2**j): res = res + '0' j += 1 else: res = res + data[-1 * k] k += 1 # The result is reversed since positions are # counted backwards. (m + r+1 ... 1) return res[::-1] def calcParityBits(arr, r): n = len(arr) # For finding rth parity bit, iterate over # 0 to r - 1 for i in range(r): val = 0 for j in range(1, n + 1): # If position has 1 in ith significant # position then Bitwise OR the array value # to find parity bit value. if(j & (2**i) == (2**i)): val = val ^ int(arr[-1 * j]) # -1 * j is given since array is reversed # String Concatenation # (0 to n - 2^r) + parity bit + (n - 2^r + 1 to n) arr = arr[:n-(2**i)] + str(val) + arr[n-(2**i)+1:] return arr def detectError(arr, nr): n = len(arr) res = 0 # Calculate parity bits again for i in range(nr): val = 0 for j in range(1, n + 1): if(j & (2**i) == (2**i)): val = val ^ int(arr[-1 * j]) # Create a binary no by appending # parity bits together. res = res + val*(10**i) # Convert binary to decimal return int(str(res), 2) # Enter the data to be transmitteddata = '1011001' # Calculate the no of Redundant Bits Requiredm = len(data)r = calcRedundantBits(m) # Determine the positions of Redundant Bitsarr = posRedundantBits(data, r) # Determine the parity bitsarr = calcParityBits(arr, r) # Data to be transferredprint("Data transferred is " + arr) # Stimulate error in transmission by changing# a bit value.# 10101001110 -> 11101001110, error in 10th position. arr = '11101001110'print("Error Data is " + arr)correction = detectError(arr, r)print("The position of error is " + str(correction))
Output:
Data transferred is 10101001110
Error Data is 11101001110
The position of error is 2
siddharthx_07
sagar0719kumar
Python-Miscellaneous
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 24045,
"s": 24017,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 24073,
"s": 24045,
"text": "Pre-requisite: Hamming Code"
},
{
"code": null,
"e": 24319,
"s": 24073,
"text": "Hamming code is a set of error-correction codes that can be used to detect and correct the errors that can occur when the data is moved or stored from the sender to the receiver. It is a technique developed by R.W. Hamming for error correction. "
},
{
"code": null,
"e": 24326,
"s": 24319,
"text": "Steps:"
},
{
"code": null,
"e": 24472,
"s": 24326,
"text": "Enter the Data to be transmittedCalculate the no of redundant bits requiredDetermine the parity bitsCreate error data for testingCheck for errors"
},
{
"code": null,
"e": 24505,
"s": 24472,
"text": "Enter the Data to be transmitted"
},
{
"code": null,
"e": 24549,
"s": 24505,
"text": "Calculate the no of redundant bits required"
},
{
"code": null,
"e": 24575,
"s": 24549,
"text": "Determine the parity bits"
},
{
"code": null,
"e": 24605,
"s": 24575,
"text": "Create error data for testing"
},
{
"code": null,
"e": 24622,
"s": 24605,
"text": "Check for errors"
},
{
"code": null,
"e": 24633,
"s": 24622,
"text": "Examples: "
},
{
"code": null,
"e": 24867,
"s": 24633,
"text": "Input: \n1011001\n\nOutput:\nData transferred is 10101001110\nError Data is 11101001110\nThe position of error is 10\n\n\nInput:\n10101111010\n\nOutput:\nData transferred is 101011111010000\nError Data is 101011111010100\nThe position of error is 3"
},
{
"code": null,
"e": 24877,
"s": 24869,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# hamming code def calcRedundantBits(m): # Use the formula 2 ^ r >= m + r + 1 # to calculate the no of redundant bits. # Iterate over 0 .. m and return the value # that satisfies the equation for i in range(m): if(2**i >= m + i + 1): return i def posRedundantBits(data, r): # Redundancy bits are placed at the positions # which correspond to the power of 2. j = 0 k = 1 m = len(data) res = '' # If position is power of 2 then insert '0' # Else append the data for i in range(1, m + r+1): if(i == 2**j): res = res + '0' j += 1 else: res = res + data[-1 * k] k += 1 # The result is reversed since positions are # counted backwards. (m + r+1 ... 1) return res[::-1] def calcParityBits(arr, r): n = len(arr) # For finding rth parity bit, iterate over # 0 to r - 1 for i in range(r): val = 0 for j in range(1, n + 1): # If position has 1 in ith significant # position then Bitwise OR the array value # to find parity bit value. if(j & (2**i) == (2**i)): val = val ^ int(arr[-1 * j]) # -1 * j is given since array is reversed # String Concatenation # (0 to n - 2^r) + parity bit + (n - 2^r + 1 to n) arr = arr[:n-(2**i)] + str(val) + arr[n-(2**i)+1:] return arr def detectError(arr, nr): n = len(arr) res = 0 # Calculate parity bits again for i in range(nr): val = 0 for j in range(1, n + 1): if(j & (2**i) == (2**i)): val = val ^ int(arr[-1 * j]) # Create a binary no by appending # parity bits together. res = res + val*(10**i) # Convert binary to decimal return int(str(res), 2) # Enter the data to be transmitteddata = '1011001' # Calculate the no of Redundant Bits Requiredm = len(data)r = calcRedundantBits(m) # Determine the positions of Redundant Bitsarr = posRedundantBits(data, r) # Determine the parity bitsarr = calcParityBits(arr, r) # Data to be transferredprint(\"Data transferred is \" + arr) # Stimulate error in transmission by changing# a bit value.# 10101001110 -> 11101001110, error in 10th position. arr = '11101001110'print(\"Error Data is \" + arr)correction = detectError(arr, r)print(\"The position of error is \" + str(correction))",
"e": 27303,
"s": 24877,
"text": null
},
{
"code": null,
"e": 27311,
"s": 27303,
"text": "Output:"
},
{
"code": null,
"e": 27396,
"s": 27311,
"text": "Data transferred is 10101001110\nError Data is 11101001110\nThe position of error is 2"
},
{
"code": null,
"e": 27410,
"s": 27396,
"text": "siddharthx_07"
},
{
"code": null,
"e": 27425,
"s": 27410,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 27446,
"s": 27425,
"text": "Python-Miscellaneous"
},
{
"code": null,
"e": 27453,
"s": 27446,
"text": "Python"
},
{
"code": null,
"e": 27472,
"s": 27453,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27570,
"s": 27472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27579,
"s": 27570,
"text": "Comments"
},
{
"code": null,
"e": 27592,
"s": 27579,
"text": "Old Comments"
},
{
"code": null,
"e": 27610,
"s": 27592,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27645,
"s": 27610,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27667,
"s": 27645,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27699,
"s": 27667,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27729,
"s": 27699,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27771,
"s": 27729,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27797,
"s": 27771,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27840,
"s": 27797,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27884,
"s": 27840,
"text": "Reading and Writing to text files in Python"
}
]
|
How to build a smart search engine (Part II) | by Josh Taylor | Towards Data Science | In the first post within this series, we built a search engine in just a few lines of code which was powered by the BM25 algorithm used in many of the largest enterprise search engines today.
In this post, we want to go beyond this and create a truly smart search engine. This post will describe the process to do this and also provide template code to achieve this on any dataset.
But what do we mean by ‘smart’? We are defining this as a search engine which is able to:
Return relevant results to a user even if they have not searched for the specific words within these results.
Be location aware; understand UK postcodes and the geographic relationship of towns and cities in the UK.
Be able to scale up to larger datasets (we will be moving to a larger dataset than in our previous example with 212k records but we need to be able to scale to much larger data).
Be orders of magnitude faster than our last implementation, even when searching over large datasets.
Handle spelling mistakes, typos and previously ‘unseen’ words in an intelligent way.
In order to achieve this, we will need to combine a number of techniques:
fastText Word vectors. We will train a model on our data set to create vector representations of words (more information on this here).
BM25. We will still be using this algorithm to power our search but we will need apply this to our word vector results.
Superfast searching of our results using the lightweight and highly efficient Non-Metric Space Library (NMSLIB).
This will look something like the below:
This article will walk through each of these areas and describe how they can be brought together to create a smart search engine.
The first step in creating a search engine is splitting our documents into individual words or ‘tokens’. The spaCy library makes this both very simple and very fast to achieve. As a reminder, the example we are using in this article is the same as the one in the previous article. It contains UK public sector contract notices, published on the Contracts Finder platform. However, for the purposes of this exercise, we have increased the dataset size (it is now 212k records, previously it was only 50k). In addition to this, we have also brought through location data into our dataset. Prior to any processing, the data frame we are using looks like the below:
The column we will be using for our search engine is the ‘Text’ column which is an amalgamation of the free text and location fields for each notice.
We can take this column, clean it and tokenise it all using the spaCy library. The below code does this by using a spaCy pipe, this makes the processing as efficient as possible and also allows us to choose only the parts of the tokenizer engine that we want to use (again ensuring that the process is as fast as possible):
The above code splits our documents into a list of tokens whilst performing some basic cleaning operations to remove punctuation, white space and convert the text to lowercase. Running on a Colab notebook, this can process over 1,800 notices a second.
Why word vectors? Why not BERT/GPT-3/[latest SOTA NLP model]?
Since the introduction of sophisticated transformer models like BERT, word vector models can seem quite old fashioned. However they are still relevant today for the following reasons:
They are ‘lightweight’ when compared to transformer models in all areas that matter when creating scalable services (model size, training times, inference speed).
Due to the above point they can be trained from scratch on domain specific texts. In addition to this they can be trained on relatively small data sets (i.e. thousands of documents rather than the many millions typically used to train transformer models).
They are easier to interpret due to the fact that a word vector will remain consistent and will not change based on the context of the surrounding text (both an advantage and a disadvantage, more on this later).
In addition to the above they are super simple to implement using the Gensim library. Here we are building a fastText model:
Reviewing performance:
Now that we have trained up our model, let's see how it performs.
It never ceases to amaze me just how effective fastText can be at capturing the relationships between words within a corpus. This is best demonstrated with a few examples:
Most similar words to ‘m4’:
ft_model.wv.most_similar("m4", topn=20, restrict_vocab=5000)
This really is quite astounding, the model has clearly learned that M4 relates to the UK motorway and understands that other large UK motorways are similar to this (M1, M5, M3, M60).
It has also learned that LRN is also closely related (this stands for Local Road Network) I did not even know this myself!
The ‘9AT’ token looks quite odd however a quick search reveals that this is the postcode of Highways England.
Including postcode and location information in our word vector model was a deliberate design choice. The rationale was that the model will understand how UK postcodes and locations relate to one another. Let’s put this to the test:
Most similar words to ‘Yorkshire’:
The model has learned that Yorkshire is a region in the UK (in the north west) and the major cities and towns within it. It also understands the relationship between this region and its sub regions; ‘Riding’ here refers to the North/East/West Ridings which sit within the Yorkshire county. But what about post codes?
Most similar words to ‘RG9’:
RG9 is a postcode (zip code) within the UK which relates to the town of Henley. This is a tricky example as Henley is quite a small town and the RG postcode is also used for other, larger nearby towns (such as Reading). Will the model be able to correctly associate this post code with Henley?
It passes with flying colours! Henley is the most similar word and the other results are also highly relevant, representing neighbouring towns and postcodes.
Clearly our word vector model is performing well, in the next step we will supercharge our word embeddings using the BM25 algorithm.
Now that we have our word vectors, we need to find a way of combining these for each document in our search engine.
The simplest way of doing this would be to average the word vectors for each document (and this would work) however it has been shown that combining word vectors with the BM25 algorithm can produce much higher quality search results[1]
A simple recap of BM25 is below but please review my first post for more details on its inner workings:
Whilst this looks complex, implementing this with our word vectors is actually very simple and requires just a few lines of code(just like all of the other steps in this article!)
The output from this will give us a single vector per document in our search engine.
We have now have a list of vectors for each document in our data set. We can also use the techniques outlined above to create a vector for a search query from a user.
But how do we return relevant results based on this search query? We need to be able to find the closest vectors to our search vector. Given the high number of dimensions (100) in our vectors this is where things could start to fall down with our approach. Search engines need to be fast and searching over 100 dimensions across a data set of over 200k records is very resource intensive.
NMSLIB:
Thankfully this is a fairly common challenge within computer science and solutions exist to massively speed up similarity search problems. NMSLIB is one of the fastest solutions out there [2]. Using this library we can create a search index which will be orders of magnitude faster than finding similar vectors using a brute force approach:
Now that we have our search index, it is simply a matter of creating a search vector and returning the closest matches from the index:
Using the same query of ‘flood defences’ as in our previous article we now get the following results (top 5):
Searched 212,447 records in 0.0005 seconds:Q3172 PROPERTY FLOOD MITIGATION SCHEME WASH GREEN, WIRKSWORTH, DERBYSHIRE SUPPLY AND INSTALL CERTIFIED FLOOD PROTECTION PRODUCTS INCLUDING FLOOD DOORS, FLOOD BARRIERS, AIR BRICKS AND OTHER WORKS IDENTIFIED IN THE PROPERTY LEVEL FLOOD PROTECTION SURVEY REPORTS, AS WELL AS SKIMMER PUMPS AND HOSES. Matlock DE4 3AG WHIMPLE FLOOD DEFENCE IMPROVEMENTS CONSULTANCY SERVICES FOR PREPARATION OF CONTRACT FOR CONSTRUCTION OF FLOOD ALLEVIATION SCHEME. Sidmouth EX10 8HL FLOOD RISK ASSESSMENT FLOOD RISK ASSESSMENT Woolwich SE186HQ PAPERMILL DYKE FLOOD DEFENCE WALL CONSTRUCTION OF FLOOD DEFENCE Doncaster DN1 3BU MVDC - JS - LEVEL 2 STRATEGIC FLOOD RISK ASSESSMENT LEVEL 2 STRATEGIC FLOOD RISK ASSESSMENT TO SUPPORT PREPARATION OF THE FUTURE MOLE VALLEY LOCAL PLAN Surrey RH4 1SJ
Some great results. Also, the search is performed in 0.0005 seconds. This is 122 times faster than our previous search engine despite the dataset being more than 4 times the size.
It is also worth highlighting that a number of the results, whilst highly relevant, do not contain the word ‘defences’. The approach of using word vectors means that exact word matches are now no longer required to return relevant results.
Given that geographic information should also be encoded within the search index, let's try searching for a contract that has been awarded in a specific area. To do this we will search using the NR2 postcode to find Notices in Norwich: ‘audit services NR2'. Here are the top 3 results:
Searched 212,447 records in 0.0004 secondsPROVISION OF EXTERNAL AUDIT SERVICES THE CONTRACT IS A SINGLE LOT FOR THE PROVISION OF EXTERNAL AUDIT SERVICES. Norwich NR4 6TJGB-NORWICH: EXTERNAL AUDIT ANNUAL AUDIT OF TRUST FINANCIAL & QUALITY ACCOUNTS AND ANNUAL REPORT. Norwich NR6 5BEGB-NORWICH: 18-022 - INTERNAL AUDIT SERVICES BROADLAND HOUSING GROUP WISHES TO ENTER INTO A CONTRACT FOR INTERNAL AUDITING. Norwich NR1 1HU
It works! Returning all results for both internal and external audit services in Norwich, note that even though we searched with the NR2 postcode, it knows that that this is also similar to the other Norwich postcodes of NR4, NR6 and NR1... pretty smart!
Finally, let's feed it a typo and see if it can still handle this in an intelligent way. ‘audit services in Norwic’:
Searched 212447 records in 0.0005 secondsPROVISION OF EXTERNAL AUDIT SERVICES THE CONTRACT IS A SINGLE LOT FOR THE PROVISION OF EXTERNAL AUDIT SERVICES. Norwich NR4 6TJGB-NORWICH: EXTERNAL AUDIT ANNUAL AUDIT OF TRUST FINANCIAL & QUALITY ACCOUNTS AND ANNUAL REPORT. Norwich NR6 5BEGB-NORWICH: 18-022 - INTERNAL AUDIT SERVICES BROADLAND HOUSING GROUP WISHES TO ENTER INTO A CONTRACT FOR INTERNAL AUDITING. Norwich NR1 1HU 0.13
Same results again, despite the misspelling of the town name.
In this article we have seen how combining word vectors to BM25 and supercharging this with a fast similarity search index can create a smart, scalable and performant search engine.
Despite this, it is always important to consider whether this will be of benefit to the end user. For example, we may find that users prefer a simple key word search as they can easily interpret the results. This also highlights one of the biggest risks of creating ‘smarter’ services; they can often become:
less predictable,
learn biases that exist within the search data, and;
can be far more difficult to debug due to the increased complexity.
For these reasons they require a significant amount of testing to ensure they behave as expected once in production.
As the search continues to get more sophisticated, we will no doubt see even more complex solutions emerging over time. Whilst it is great to see such rapid development in this area, it is also important to remember that often the simplest solution to a problem is the best.
colab.research.google.com
[1] Word Embeddings in Search Engines, Quality Evaluation https://ad-publications.cs.uni-freiburg.de/theses/Bachelor_Eneko_Pinzolas_2017.pdf
[2] Benchmark of similarity search libraries https://github.com/erikbern/ann-benchmarks
Link to the first part of this series:
towardsdatascience.com
As always, a big thanks to the TDS editorial team! | [
{
"code": null,
"e": 364,
"s": 172,
"text": "In the first post within this series, we built a search engine in just a few lines of code which was powered by the BM25 algorithm used in many of the largest enterprise search engines today."
},
{
"code": null,
"e": 554,
"s": 364,
"text": "In this post, we want to go beyond this and create a truly smart search engine. This post will describe the process to do this and also provide template code to achieve this on any dataset."
},
{
"code": null,
"e": 644,
"s": 554,
"text": "But what do we mean by ‘smart’? We are defining this as a search engine which is able to:"
},
{
"code": null,
"e": 754,
"s": 644,
"text": "Return relevant results to a user even if they have not searched for the specific words within these results."
},
{
"code": null,
"e": 860,
"s": 754,
"text": "Be location aware; understand UK postcodes and the geographic relationship of towns and cities in the UK."
},
{
"code": null,
"e": 1039,
"s": 860,
"text": "Be able to scale up to larger datasets (we will be moving to a larger dataset than in our previous example with 212k records but we need to be able to scale to much larger data)."
},
{
"code": null,
"e": 1140,
"s": 1039,
"text": "Be orders of magnitude faster than our last implementation, even when searching over large datasets."
},
{
"code": null,
"e": 1225,
"s": 1140,
"text": "Handle spelling mistakes, typos and previously ‘unseen’ words in an intelligent way."
},
{
"code": null,
"e": 1299,
"s": 1225,
"text": "In order to achieve this, we will need to combine a number of techniques:"
},
{
"code": null,
"e": 1435,
"s": 1299,
"text": "fastText Word vectors. We will train a model on our data set to create vector representations of words (more information on this here)."
},
{
"code": null,
"e": 1555,
"s": 1435,
"text": "BM25. We will still be using this algorithm to power our search but we will need apply this to our word vector results."
},
{
"code": null,
"e": 1668,
"s": 1555,
"text": "Superfast searching of our results using the lightweight and highly efficient Non-Metric Space Library (NMSLIB)."
},
{
"code": null,
"e": 1709,
"s": 1668,
"text": "This will look something like the below:"
},
{
"code": null,
"e": 1839,
"s": 1709,
"text": "This article will walk through each of these areas and describe how they can be brought together to create a smart search engine."
},
{
"code": null,
"e": 2501,
"s": 1839,
"text": "The first step in creating a search engine is splitting our documents into individual words or ‘tokens’. The spaCy library makes this both very simple and very fast to achieve. As a reminder, the example we are using in this article is the same as the one in the previous article. It contains UK public sector contract notices, published on the Contracts Finder platform. However, for the purposes of this exercise, we have increased the dataset size (it is now 212k records, previously it was only 50k). In addition to this, we have also brought through location data into our dataset. Prior to any processing, the data frame we are using looks like the below:"
},
{
"code": null,
"e": 2651,
"s": 2501,
"text": "The column we will be using for our search engine is the ‘Text’ column which is an amalgamation of the free text and location fields for each notice."
},
{
"code": null,
"e": 2975,
"s": 2651,
"text": "We can take this column, clean it and tokenise it all using the spaCy library. The below code does this by using a spaCy pipe, this makes the processing as efficient as possible and also allows us to choose only the parts of the tokenizer engine that we want to use (again ensuring that the process is as fast as possible):"
},
{
"code": null,
"e": 3227,
"s": 2975,
"text": "The above code splits our documents into a list of tokens whilst performing some basic cleaning operations to remove punctuation, white space and convert the text to lowercase. Running on a Colab notebook, this can process over 1,800 notices a second."
},
{
"code": null,
"e": 3289,
"s": 3227,
"text": "Why word vectors? Why not BERT/GPT-3/[latest SOTA NLP model]?"
},
{
"code": null,
"e": 3473,
"s": 3289,
"text": "Since the introduction of sophisticated transformer models like BERT, word vector models can seem quite old fashioned. However they are still relevant today for the following reasons:"
},
{
"code": null,
"e": 3636,
"s": 3473,
"text": "They are ‘lightweight’ when compared to transformer models in all areas that matter when creating scalable services (model size, training times, inference speed)."
},
{
"code": null,
"e": 3892,
"s": 3636,
"text": "Due to the above point they can be trained from scratch on domain specific texts. In addition to this they can be trained on relatively small data sets (i.e. thousands of documents rather than the many millions typically used to train transformer models)."
},
{
"code": null,
"e": 4104,
"s": 3892,
"text": "They are easier to interpret due to the fact that a word vector will remain consistent and will not change based on the context of the surrounding text (both an advantage and a disadvantage, more on this later)."
},
{
"code": null,
"e": 4229,
"s": 4104,
"text": "In addition to the above they are super simple to implement using the Gensim library. Here we are building a fastText model:"
},
{
"code": null,
"e": 4252,
"s": 4229,
"text": "Reviewing performance:"
},
{
"code": null,
"e": 4318,
"s": 4252,
"text": "Now that we have trained up our model, let's see how it performs."
},
{
"code": null,
"e": 4490,
"s": 4318,
"text": "It never ceases to amaze me just how effective fastText can be at capturing the relationships between words within a corpus. This is best demonstrated with a few examples:"
},
{
"code": null,
"e": 4518,
"s": 4490,
"text": "Most similar words to ‘m4’:"
},
{
"code": null,
"e": 4579,
"s": 4518,
"text": "ft_model.wv.most_similar(\"m4\", topn=20, restrict_vocab=5000)"
},
{
"code": null,
"e": 4762,
"s": 4579,
"text": "This really is quite astounding, the model has clearly learned that M4 relates to the UK motorway and understands that other large UK motorways are similar to this (M1, M5, M3, M60)."
},
{
"code": null,
"e": 4885,
"s": 4762,
"text": "It has also learned that LRN is also closely related (this stands for Local Road Network) I did not even know this myself!"
},
{
"code": null,
"e": 4995,
"s": 4885,
"text": "The ‘9AT’ token looks quite odd however a quick search reveals that this is the postcode of Highways England."
},
{
"code": null,
"e": 5227,
"s": 4995,
"text": "Including postcode and location information in our word vector model was a deliberate design choice. The rationale was that the model will understand how UK postcodes and locations relate to one another. Let’s put this to the test:"
},
{
"code": null,
"e": 5262,
"s": 5227,
"text": "Most similar words to ‘Yorkshire’:"
},
{
"code": null,
"e": 5579,
"s": 5262,
"text": "The model has learned that Yorkshire is a region in the UK (in the north west) and the major cities and towns within it. It also understands the relationship between this region and its sub regions; ‘Riding’ here refers to the North/East/West Ridings which sit within the Yorkshire county. But what about post codes?"
},
{
"code": null,
"e": 5608,
"s": 5579,
"text": "Most similar words to ‘RG9’:"
},
{
"code": null,
"e": 5902,
"s": 5608,
"text": "RG9 is a postcode (zip code) within the UK which relates to the town of Henley. This is a tricky example as Henley is quite a small town and the RG postcode is also used for other, larger nearby towns (such as Reading). Will the model be able to correctly associate this post code with Henley?"
},
{
"code": null,
"e": 6060,
"s": 5902,
"text": "It passes with flying colours! Henley is the most similar word and the other results are also highly relevant, representing neighbouring towns and postcodes."
},
{
"code": null,
"e": 6193,
"s": 6060,
"text": "Clearly our word vector model is performing well, in the next step we will supercharge our word embeddings using the BM25 algorithm."
},
{
"code": null,
"e": 6309,
"s": 6193,
"text": "Now that we have our word vectors, we need to find a way of combining these for each document in our search engine."
},
{
"code": null,
"e": 6545,
"s": 6309,
"text": "The simplest way of doing this would be to average the word vectors for each document (and this would work) however it has been shown that combining word vectors with the BM25 algorithm can produce much higher quality search results[1]"
},
{
"code": null,
"e": 6649,
"s": 6545,
"text": "A simple recap of BM25 is below but please review my first post for more details on its inner workings:"
},
{
"code": null,
"e": 6829,
"s": 6649,
"text": "Whilst this looks complex, implementing this with our word vectors is actually very simple and requires just a few lines of code(just like all of the other steps in this article!)"
},
{
"code": null,
"e": 6914,
"s": 6829,
"text": "The output from this will give us a single vector per document in our search engine."
},
{
"code": null,
"e": 7081,
"s": 6914,
"text": "We have now have a list of vectors for each document in our data set. We can also use the techniques outlined above to create a vector for a search query from a user."
},
{
"code": null,
"e": 7470,
"s": 7081,
"text": "But how do we return relevant results based on this search query? We need to be able to find the closest vectors to our search vector. Given the high number of dimensions (100) in our vectors this is where things could start to fall down with our approach. Search engines need to be fast and searching over 100 dimensions across a data set of over 200k records is very resource intensive."
},
{
"code": null,
"e": 7478,
"s": 7470,
"text": "NMSLIB:"
},
{
"code": null,
"e": 7819,
"s": 7478,
"text": "Thankfully this is a fairly common challenge within computer science and solutions exist to massively speed up similarity search problems. NMSLIB is one of the fastest solutions out there [2]. Using this library we can create a search index which will be orders of magnitude faster than finding similar vectors using a brute force approach:"
},
{
"code": null,
"e": 7954,
"s": 7819,
"text": "Now that we have our search index, it is simply a matter of creating a search vector and returning the closest matches from the index:"
},
{
"code": null,
"e": 8064,
"s": 7954,
"text": "Using the same query of ‘flood defences’ as in our previous article we now get the following results (top 5):"
},
{
"code": null,
"e": 8879,
"s": 8064,
"text": "Searched 212,447 records in 0.0005 seconds:Q3172 PROPERTY FLOOD MITIGATION SCHEME WASH GREEN, WIRKSWORTH, DERBYSHIRE SUPPLY AND INSTALL CERTIFIED FLOOD PROTECTION PRODUCTS INCLUDING FLOOD DOORS, FLOOD BARRIERS, AIR BRICKS AND OTHER WORKS IDENTIFIED IN THE PROPERTY LEVEL FLOOD PROTECTION SURVEY REPORTS, AS WELL AS SKIMMER PUMPS AND HOSES. Matlock DE4 3AG WHIMPLE FLOOD DEFENCE IMPROVEMENTS CONSULTANCY SERVICES FOR PREPARATION OF CONTRACT FOR CONSTRUCTION OF FLOOD ALLEVIATION SCHEME. Sidmouth EX10 8HL FLOOD RISK ASSESSMENT FLOOD RISK ASSESSMENT Woolwich SE186HQ PAPERMILL DYKE FLOOD DEFENCE WALL CONSTRUCTION OF FLOOD DEFENCE Doncaster DN1 3BU MVDC - JS - LEVEL 2 STRATEGIC FLOOD RISK ASSESSMENT LEVEL 2 STRATEGIC FLOOD RISK ASSESSMENT TO SUPPORT PREPARATION OF THE FUTURE MOLE VALLEY LOCAL PLAN Surrey RH4 1SJ"
},
{
"code": null,
"e": 9059,
"s": 8879,
"text": "Some great results. Also, the search is performed in 0.0005 seconds. This is 122 times faster than our previous search engine despite the dataset being more than 4 times the size."
},
{
"code": null,
"e": 9299,
"s": 9059,
"text": "It is also worth highlighting that a number of the results, whilst highly relevant, do not contain the word ‘defences’. The approach of using word vectors means that exact word matches are now no longer required to return relevant results."
},
{
"code": null,
"e": 9585,
"s": 9299,
"text": "Given that geographic information should also be encoded within the search index, let's try searching for a contract that has been awarded in a specific area. To do this we will search using the NR2 postcode to find Notices in Norwich: ‘audit services NR2'. Here are the top 3 results:"
},
{
"code": null,
"e": 10006,
"s": 9585,
"text": "Searched 212,447 records in 0.0004 secondsPROVISION OF EXTERNAL AUDIT SERVICES THE CONTRACT IS A SINGLE LOT FOR THE PROVISION OF EXTERNAL AUDIT SERVICES. Norwich NR4 6TJGB-NORWICH: EXTERNAL AUDIT ANNUAL AUDIT OF TRUST FINANCIAL & QUALITY ACCOUNTS AND ANNUAL REPORT. Norwich NR6 5BEGB-NORWICH: 18-022 - INTERNAL AUDIT SERVICES BROADLAND HOUSING GROUP WISHES TO ENTER INTO A CONTRACT FOR INTERNAL AUDITING. Norwich NR1 1HU"
},
{
"code": null,
"e": 10261,
"s": 10006,
"text": "It works! Returning all results for both internal and external audit services in Norwich, note that even though we searched with the NR2 postcode, it knows that that this is also similar to the other Norwich postcodes of NR4, NR6 and NR1... pretty smart!"
},
{
"code": null,
"e": 10378,
"s": 10261,
"text": "Finally, let's feed it a typo and see if it can still handle this in an intelligent way. ‘audit services in Norwic’:"
},
{
"code": null,
"e": 10803,
"s": 10378,
"text": "Searched 212447 records in 0.0005 secondsPROVISION OF EXTERNAL AUDIT SERVICES THE CONTRACT IS A SINGLE LOT FOR THE PROVISION OF EXTERNAL AUDIT SERVICES. Norwich NR4 6TJGB-NORWICH: EXTERNAL AUDIT ANNUAL AUDIT OF TRUST FINANCIAL & QUALITY ACCOUNTS AND ANNUAL REPORT. Norwich NR6 5BEGB-NORWICH: 18-022 - INTERNAL AUDIT SERVICES BROADLAND HOUSING GROUP WISHES TO ENTER INTO A CONTRACT FOR INTERNAL AUDITING. Norwich NR1 1HU 0.13"
},
{
"code": null,
"e": 10865,
"s": 10803,
"text": "Same results again, despite the misspelling of the town name."
},
{
"code": null,
"e": 11047,
"s": 10865,
"text": "In this article we have seen how combining word vectors to BM25 and supercharging this with a fast similarity search index can create a smart, scalable and performant search engine."
},
{
"code": null,
"e": 11356,
"s": 11047,
"text": "Despite this, it is always important to consider whether this will be of benefit to the end user. For example, we may find that users prefer a simple key word search as they can easily interpret the results. This also highlights one of the biggest risks of creating ‘smarter’ services; they can often become:"
},
{
"code": null,
"e": 11374,
"s": 11356,
"text": "less predictable,"
},
{
"code": null,
"e": 11427,
"s": 11374,
"text": "learn biases that exist within the search data, and;"
},
{
"code": null,
"e": 11495,
"s": 11427,
"text": "can be far more difficult to debug due to the increased complexity."
},
{
"code": null,
"e": 11612,
"s": 11495,
"text": "For these reasons they require a significant amount of testing to ensure they behave as expected once in production."
},
{
"code": null,
"e": 11887,
"s": 11612,
"text": "As the search continues to get more sophisticated, we will no doubt see even more complex solutions emerging over time. Whilst it is great to see such rapid development in this area, it is also important to remember that often the simplest solution to a problem is the best."
},
{
"code": null,
"e": 11913,
"s": 11887,
"text": "colab.research.google.com"
},
{
"code": null,
"e": 12054,
"s": 11913,
"text": "[1] Word Embeddings in Search Engines, Quality Evaluation https://ad-publications.cs.uni-freiburg.de/theses/Bachelor_Eneko_Pinzolas_2017.pdf"
},
{
"code": null,
"e": 12142,
"s": 12054,
"text": "[2] Benchmark of similarity search libraries https://github.com/erikbern/ann-benchmarks"
},
{
"code": null,
"e": 12181,
"s": 12142,
"text": "Link to the first part of this series:"
},
{
"code": null,
"e": 12204,
"s": 12181,
"text": "towardsdatascience.com"
}
]
|
Queries for counts of array elements with values in given range | 09 Jun, 2022
Given an unsorted array of size n, find no of elements between two elements i and j (both inclusive).Examples:
Input : arr = [1 3 3 9 10 4]
i1 = 1, j1 = 4
i2 = 9, j2 = 12
Output : 4
2
The numbers are: 1 3 3 4 for first query
The numbers are: 9 10 for second query
Source: Amazon Interview Experience
A simple approach will be to run a for loop to check if each element is in the given range and maintain their count. Time complexity for running each query will be O(n).
C++
Java
Python3
C#
PHP
Javascript
// Simple C++ program to count number of elements// with values in given range.#include <bits/stdc++.h>using namespace std; // function to count elements within given rangeint countInRange(int arr[], int n, int x, int y){ // initialize result int count = 0; for (int i = 0; i < n; i++) { // check if element is in range if (arr[i] >= x && arr[i] <= y) count++; } return count;} // driver functionint main(){ int arr[] = { 1, 3, 4, 9, 10, 3 }; int n = sizeof(arr) / sizeof(arr[0]); // Answer queries int i = 1, j = 4; cout << countInRange(arr, n, i, j) << endl; i = 9, j = 12; cout << countInRange(arr, n, i, j) << endl; return 0;}
// Simple java program to count// number of elements with// values in given range.import java.io.*; class GFG{ // function to count elements within given range static int countInRange(int arr[], int n, int x, int y) { // initialize result int count = 0; for (int i = 0; i < n; i++) { // check if element is in range if (arr[i] >= x && arr[i] <= y) count++; } return count; } // driver function public static void main (String[] args) { int arr[] = { 1, 3, 4, 9, 10, 3 }; int n = arr.length; // Answer queries int i = 1, j = 4; System.out.println ( countInRange(arr, n, i, j)) ; i = 9; j = 12; System.out.println ( countInRange(arr, n, i, j)) ; }} // This article is contributed by vt_m
# function to count elements within given rangedef countInRange(arr, n, x, y): # initialize result count = 0; for i in range(n): # check if element is in range if (arr[i] >= x and arr[i] <= y): count += 1 return count # driver functionarr = [1, 3, 4, 9, 10, 3]n = len(arr) # Answer queriesi = 1j = 4print(countInRange(arr, n, i, j))i = 9j = 12print(countInRange(arr, n, i, j))
// Simple C# program to count// number of elements with// values in given range.using System; class GFG { // function to count elements // within given range static int countInRange(int []arr, int n, int x, int y) { // initialize result int count = 0; for (int i = 0; i < n; i++) { // check if element is in range if (arr[i] >= x && arr[i] <= y) count++; } return count; } // Driver Code public static void Main () { int[]arr = {1, 3, 4, 9, 10, 3}; int n = arr.Length; // Answer queries int i = 1, j = 4; Console.WriteLine( countInRange(arr, n, i, j)) ; i = 9; j = 12; Console.WriteLine( countInRange(arr, n, i, j)) ; }} // This code is contributed by vt_m.
<?php// Simple PHP program to count// number of elements with// values in given range. // function to count elements// within given rangefunction countInRange($arr, $n, $x, $y){ // initialize result $count = 0; for ($i = 0; $i < $n; $i++) { // check if element is in range if ($arr[$i] >= $x && $arr[$i] <= $y) $count++; } return $count;} // Driver Code $arr = array(1, 3, 4, 9, 10, 3); $n = count($arr); // Answer queries $i = 1; $j = 4; echo countInRange($arr, $n, $i, $j)."\n"; $i = 9; $j = 12; echo countInRange($arr, $n, $i, $j)."\n"; // This code is contributed by Sam007?>
<script> // Simple JavaScript program to count // number of elements with // values in given range. // function to count elements // within given range function countInRange(arr, n, x, y) { // initialize result let count = 0; for (let i = 0; i < n; i++) { // check if element is in range if (arr[i] >= x && arr[i] <= y) count++; } return count; } let arr = [1, 3, 4, 9, 10, 3]; let n = arr.length; // Answer queries let i = 1, j = 4; document.write( countInRange(arr, n, i, j) + "</br>") ; i = 9; j = 12; document.write( countInRange(arr, n, i, j)) ; </script>
Output:
4
2
Time Complexity: O(n),Auxiliary Space: O(1)
An Efficient Approach will be to first sort the array and then using a modified binary search function find two indices, one of first element greater than or equal to lower bound of range and the other of the last element less than or equal to upperbound. Time for running each query will be O(logn) and for sorting the array once will be O(nlogn).
C++
Java
Python3
C#
PHP
Javascript
// Efficient C++ program to count number of elements// with values in given range.#include <bits/stdc++.h>using namespace std; // function to find first index >= xint lowerIndex(int arr[], int n, int x){ int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l;} // function to find last index <= yint upperIndex(int arr[], int n, int y){ int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h;} // function to count elements within given rangeint countInRange(int arr[], int n, int x, int y){ // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count;} // driver functionint main(){ int arr[] = { 1, 4, 4, 9, 10, 3 }; int n = sizeof(arr) / sizeof(arr[0]); // Preprocess array sort(arr, arr + n); // Answer queries int i = 1, j = 4; cout << countInRange(arr, n, i, j) << endl; i = 9, j = 12; cout << countInRange(arr, n, i, j) << endl; return 0;}
// Efficient C++ program to count number// of elements with values in given range.import java.io.*;import java.util.Arrays; class GFG{ // function to find first index >= x static int lowerIndex(int arr[], int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y static int upperIndex(int arr[], int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements within given range static int countInRange(int arr[], int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } // Driver function public static void main (String[] args) { int arr[] = { 1, 4, 4, 9, 10, 3 }; int n = arr.length; // Preprocess array Arrays.sort(arr); // Answer queries int i = 1, j = 4; System.out.println( countInRange(arr, n, i, j)); ; i = 9; j = 12; System.out.println( countInRange(arr, n, i, j)); }} // This article is contributed by vt_m.
# function to find first index >= xdef lowerIndex(arr, n, x): l = 0 h = n-1 while (l <= h): mid = int((l + h)//2) if (arr[mid] >= x): h = mid - 1 else: l = mid + 1 return l # function to find last index <= xdef upperIndex(arr, n, x): l = 0 h = n-1 while (l <= h): mid = int((l + h)//2) if (arr[mid] <= x): l = mid + 1 else: h = mid - 1 return h # function to count elements within given rangedef countInRange(arr, n, x, y): # initialize result count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count # driver functionarr = [1, 3, 4, 9, 10, 3] # Preprocess arrayarr.sort()n = len(arr) # Answer queriesi = 1j = 4print(countInRange(arr, n, i, j))i = 9j = 12print(countInRange(arr, n, i, j))
// Efficient C# program to count number// of elements with values in given range.using System; class GFG{ // function to find first index >= x static int lowerIndex(int []arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y static int upperIndex(int []arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements // within given range static int countInRange(int []arr, int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } // Driver code public static void Main () { int []arr = {1, 4, 4, 9, 10, 3}; int n = arr.Length; // Preprocess array Array.Sort(arr); // Answer queries int i = 1, j = 4; Console.WriteLine(countInRange(arr, n, i, j)); ; i = 9; j = 12; Console.WriteLine(countInRange(arr, n, i, j)); }} // This code is contributed by vt_m.
<?php// Efficient PHP program to count// number of elements with values// in given range. // function to find first index >= xfunction lowerIndex($arr, $n, $x){ $l = 0; $h = $n - 1; while ($l <= $h) { $mid = ($l + $h) / 2; if ($arr[$mid] >= $x) $h = $mid - 1; else $l = $mid + 1; } return $l;} // function to find last index <= yfunction upperIndex($arr, $n, $y){ $l = 0; $h = $n - 1; while ($l <= $h) { $mid = ($l + $h) / 2; if ($arr[$mid] <= $y) $l = $mid + 1; else $h = $mid - 1; } return $h;} // function to count elements// within given rangefunction countInRange($arr, $n, $x, $y){ // initialize result $count = 0; $count = (upperIndex($arr, $n, $y) - lowerIndex($arr, $n, $x) + 1); $t = floor($count); return $t;} // Driver Code $arr = array( 1, 4, 4, 9, 10, 3 );$n = sizeof($arr); // Preprocess arraysort($arr); // Answer queries$i = 1; $j = 4;echo countInRange($arr, $n, $i, $j), "\n"; $i = 9; $j = 12;echo countInRange($arr, $n, $i, $j), "\n"; // This code is contributed by Sachin?>
<script> // Efficient Javascript program to count number // of elements with values in given range. // function to find first index >= x function lowerIndex(arr, n, x) { let l = 0, h = n - 1; while (l <= h) { let mid = parseInt((l + h) / 2, 10); if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y function upperIndex(arr, n, y) { let l = 0, h = n - 1; while (l <= h) { let mid = parseInt((l + h) / 2, 10); if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements // within given range function countInRange(arr, n, x, y) { // initialize result let count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } let arr = [1, 4, 4, 9, 10, 3]; let n = arr.length; // Preprocess array arr.sort(function(a, b){return a - b}); // Answer queries let i = 1, j = 4; document.write(countInRange(arr, n, i, j) + "</br>"); ; i = 9; j = 12; document.write(countInRange(arr, n, i, j)); </script>
Output:
4
2
Time Complexity: O(n log n),Auxiliary Space: O(1)
This article is contributed by Aditi Sharma. 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.
vt_m
Sam007
Sach_Code
Shivam Mohan
suresh07
divyeshrabadiya07
amartyaghoshgfg
sachinvinod1904
Amazon
array-range-queries
Binary Search
Arrays
Amazon
Arrays
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Introduction to Data Structures | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 167,
"s": 54,
"text": "Given an unsorted array of size n, find no of elements between two elements i and j (both inclusive).Examples: "
},
{
"code": null,
"e": 349,
"s": 167,
"text": "Input : arr = [1 3 3 9 10 4] \n i1 = 1, j1 = 4\n i2 = 9, j2 = 12\nOutput : 4\n 2\nThe numbers are: 1 3 3 4 for first query\nThe numbers are: 9 10 for second query"
},
{
"code": null,
"e": 386,
"s": 349,
"text": "Source: Amazon Interview Experience "
},
{
"code": null,
"e": 557,
"s": 386,
"text": "A simple approach will be to run a for loop to check if each element is in the given range and maintain their count. Time complexity for running each query will be O(n). "
},
{
"code": null,
"e": 561,
"s": 557,
"text": "C++"
},
{
"code": null,
"e": 566,
"s": 561,
"text": "Java"
},
{
"code": null,
"e": 574,
"s": 566,
"text": "Python3"
},
{
"code": null,
"e": 577,
"s": 574,
"text": "C#"
},
{
"code": null,
"e": 581,
"s": 577,
"text": "PHP"
},
{
"code": null,
"e": 592,
"s": 581,
"text": "Javascript"
},
{
"code": "// Simple C++ program to count number of elements// with values in given range.#include <bits/stdc++.h>using namespace std; // function to count elements within given rangeint countInRange(int arr[], int n, int x, int y){ // initialize result int count = 0; for (int i = 0; i < n; i++) { // check if element is in range if (arr[i] >= x && arr[i] <= y) count++; } return count;} // driver functionint main(){ int arr[] = { 1, 3, 4, 9, 10, 3 }; int n = sizeof(arr) / sizeof(arr[0]); // Answer queries int i = 1, j = 4; cout << countInRange(arr, n, i, j) << endl; i = 9, j = 12; cout << countInRange(arr, n, i, j) << endl; return 0;}",
"e": 1290,
"s": 592,
"text": null
},
{
"code": "// Simple java program to count// number of elements with// values in given range.import java.io.*; class GFG{ // function to count elements within given range static int countInRange(int arr[], int n, int x, int y) { // initialize result int count = 0; for (int i = 0; i < n; i++) { // check if element is in range if (arr[i] >= x && arr[i] <= y) count++; } return count; } // driver function public static void main (String[] args) { int arr[] = { 1, 3, 4, 9, 10, 3 }; int n = arr.length; // Answer queries int i = 1, j = 4; System.out.println ( countInRange(arr, n, i, j)) ; i = 9; j = 12; System.out.println ( countInRange(arr, n, i, j)) ; }} // This article is contributed by vt_m",
"e": 2158,
"s": 1290,
"text": null
},
{
"code": "# function to count elements within given rangedef countInRange(arr, n, x, y): # initialize result count = 0; for i in range(n): # check if element is in range if (arr[i] >= x and arr[i] <= y): count += 1 return count # driver functionarr = [1, 3, 4, 9, 10, 3]n = len(arr) # Answer queriesi = 1j = 4print(countInRange(arr, n, i, j))i = 9j = 12print(countInRange(arr, n, i, j))",
"e": 2575,
"s": 2158,
"text": null
},
{
"code": "// Simple C# program to count// number of elements with// values in given range.using System; class GFG { // function to count elements // within given range static int countInRange(int []arr, int n, int x, int y) { // initialize result int count = 0; for (int i = 0; i < n; i++) { // check if element is in range if (arr[i] >= x && arr[i] <= y) count++; } return count; } // Driver Code public static void Main () { int[]arr = {1, 3, 4, 9, 10, 3}; int n = arr.Length; // Answer queries int i = 1, j = 4; Console.WriteLine( countInRange(arr, n, i, j)) ; i = 9; j = 12; Console.WriteLine( countInRange(arr, n, i, j)) ; }} // This code is contributed by vt_m.",
"e": 3460,
"s": 2575,
"text": null
},
{
"code": "<?php// Simple PHP program to count// number of elements with// values in given range. // function to count elements// within given rangefunction countInRange($arr, $n, $x, $y){ // initialize result $count = 0; for ($i = 0; $i < $n; $i++) { // check if element is in range if ($arr[$i] >= $x && $arr[$i] <= $y) $count++; } return $count;} // Driver Code $arr = array(1, 3, 4, 9, 10, 3); $n = count($arr); // Answer queries $i = 1; $j = 4; echo countInRange($arr, $n, $i, $j).\"\\n\"; $i = 9; $j = 12; echo countInRange($arr, $n, $i, $j).\"\\n\"; // This code is contributed by Sam007?>",
"e": 4160,
"s": 3460,
"text": null
},
{
"code": "<script> // Simple JavaScript program to count // number of elements with // values in given range. // function to count elements // within given range function countInRange(arr, n, x, y) { // initialize result let count = 0; for (let i = 0; i < n; i++) { // check if element is in range if (arr[i] >= x && arr[i] <= y) count++; } return count; } let arr = [1, 3, 4, 9, 10, 3]; let n = arr.length; // Answer queries let i = 1, j = 4; document.write( countInRange(arr, n, i, j) + \"</br>\") ; i = 9; j = 12; document.write( countInRange(arr, n, i, j)) ; </script>",
"e": 4876,
"s": 4160,
"text": null
},
{
"code": null,
"e": 4886,
"s": 4876,
"text": "Output: "
},
{
"code": null,
"e": 4890,
"s": 4886,
"text": "4\n2"
},
{
"code": null,
"e": 4934,
"s": 4890,
"text": "Time Complexity: O(n),Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5284,
"s": 4934,
"text": "An Efficient Approach will be to first sort the array and then using a modified binary search function find two indices, one of first element greater than or equal to lower bound of range and the other of the last element less than or equal to upperbound. Time for running each query will be O(logn) and for sorting the array once will be O(nlogn). "
},
{
"code": null,
"e": 5288,
"s": 5284,
"text": "C++"
},
{
"code": null,
"e": 5293,
"s": 5288,
"text": "Java"
},
{
"code": null,
"e": 5301,
"s": 5293,
"text": "Python3"
},
{
"code": null,
"e": 5304,
"s": 5301,
"text": "C#"
},
{
"code": null,
"e": 5308,
"s": 5304,
"text": "PHP"
},
{
"code": null,
"e": 5319,
"s": 5308,
"text": "Javascript"
},
{
"code": "// Efficient C++ program to count number of elements// with values in given range.#include <bits/stdc++.h>using namespace std; // function to find first index >= xint lowerIndex(int arr[], int n, int x){ int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l;} // function to find last index <= yint upperIndex(int arr[], int n, int y){ int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h;} // function to count elements within given rangeint countInRange(int arr[], int n, int x, int y){ // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count;} // driver functionint main(){ int arr[] = { 1, 4, 4, 9, 10, 3 }; int n = sizeof(arr) / sizeof(arr[0]); // Preprocess array sort(arr, arr + n); // Answer queries int i = 1, j = 4; cout << countInRange(arr, n, i, j) << endl; i = 9, j = 12; cout << countInRange(arr, n, i, j) << endl; return 0;}",
"e": 6505,
"s": 5319,
"text": null
},
{
"code": "// Efficient C++ program to count number// of elements with values in given range.import java.io.*;import java.util.Arrays; class GFG{ // function to find first index >= x static int lowerIndex(int arr[], int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y static int upperIndex(int arr[], int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements within given range static int countInRange(int arr[], int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } // Driver function public static void main (String[] args) { int arr[] = { 1, 4, 4, 9, 10, 3 }; int n = arr.length; // Preprocess array Arrays.sort(arr); // Answer queries int i = 1, j = 4; System.out.println( countInRange(arr, n, i, j)); ; i = 9; j = 12; System.out.println( countInRange(arr, n, i, j)); }} // This article is contributed by vt_m.",
"e": 8022,
"s": 6505,
"text": null
},
{
"code": "# function to find first index >= xdef lowerIndex(arr, n, x): l = 0 h = n-1 while (l <= h): mid = int((l + h)//2) if (arr[mid] >= x): h = mid - 1 else: l = mid + 1 return l # function to find last index <= xdef upperIndex(arr, n, x): l = 0 h = n-1 while (l <= h): mid = int((l + h)//2) if (arr[mid] <= x): l = mid + 1 else: h = mid - 1 return h # function to count elements within given rangedef countInRange(arr, n, x, y): # initialize result count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count # driver functionarr = [1, 3, 4, 9, 10, 3] # Preprocess arrayarr.sort()n = len(arr) # Answer queriesi = 1j = 4print(countInRange(arr, n, i, j))i = 9j = 12print(countInRange(arr, n, i, j))",
"e": 8789,
"s": 8022,
"text": null
},
{
"code": "// Efficient C# program to count number// of elements with values in given range.using System; class GFG{ // function to find first index >= x static int lowerIndex(int []arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y static int upperIndex(int []arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements // within given range static int countInRange(int []arr, int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } // Driver code public static void Main () { int []arr = {1, 4, 4, 9, 10, 3}; int n = arr.Length; // Preprocess array Array.Sort(arr); // Answer queries int i = 1, j = 4; Console.WriteLine(countInRange(arr, n, i, j)); ; i = 9; j = 12; Console.WriteLine(countInRange(arr, n, i, j)); }} // This code is contributed by vt_m.",
"e": 10356,
"s": 8789,
"text": null
},
{
"code": "<?php// Efficient PHP program to count// number of elements with values// in given range. // function to find first index >= xfunction lowerIndex($arr, $n, $x){ $l = 0; $h = $n - 1; while ($l <= $h) { $mid = ($l + $h) / 2; if ($arr[$mid] >= $x) $h = $mid - 1; else $l = $mid + 1; } return $l;} // function to find last index <= yfunction upperIndex($arr, $n, $y){ $l = 0; $h = $n - 1; while ($l <= $h) { $mid = ($l + $h) / 2; if ($arr[$mid] <= $y) $l = $mid + 1; else $h = $mid - 1; } return $h;} // function to count elements// within given rangefunction countInRange($arr, $n, $x, $y){ // initialize result $count = 0; $count = (upperIndex($arr, $n, $y) - lowerIndex($arr, $n, $x) + 1); $t = floor($count); return $t;} // Driver Code $arr = array( 1, 4, 4, 9, 10, 3 );$n = sizeof($arr); // Preprocess arraysort($arr); // Answer queries$i = 1; $j = 4;echo countInRange($arr, $n, $i, $j), \"\\n\"; $i = 9; $j = 12;echo countInRange($arr, $n, $i, $j), \"\\n\"; // This code is contributed by Sachin?>",
"e": 11494,
"s": 10356,
"text": null
},
{
"code": "<script> // Efficient Javascript program to count number // of elements with values in given range. // function to find first index >= x function lowerIndex(arr, n, x) { let l = 0, h = n - 1; while (l <= h) { let mid = parseInt((l + h) / 2, 10); if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y function upperIndex(arr, n, y) { let l = 0, h = n - 1; while (l <= h) { let mid = parseInt((l + h) / 2, 10); if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements // within given range function countInRange(arr, n, x, y) { // initialize result let count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } let arr = [1, 4, 4, 9, 10, 3]; let n = arr.length; // Preprocess array arr.sort(function(a, b){return a - b}); // Answer queries let i = 1, j = 4; document.write(countInRange(arr, n, i, j) + \"</br>\"); ; i = 9; j = 12; document.write(countInRange(arr, n, i, j)); </script>",
"e": 12854,
"s": 11494,
"text": null
},
{
"code": null,
"e": 12864,
"s": 12854,
"text": "Output: "
},
{
"code": null,
"e": 12868,
"s": 12864,
"text": "4\n2"
},
{
"code": null,
"e": 12918,
"s": 12868,
"text": "Time Complexity: O(n log n),Auxiliary Space: O(1)"
},
{
"code": null,
"e": 13339,
"s": 12918,
"text": "This article is contributed by Aditi Sharma. 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": 13344,
"s": 13339,
"text": "vt_m"
},
{
"code": null,
"e": 13351,
"s": 13344,
"text": "Sam007"
},
{
"code": null,
"e": 13361,
"s": 13351,
"text": "Sach_Code"
},
{
"code": null,
"e": 13374,
"s": 13361,
"text": "Shivam Mohan"
},
{
"code": null,
"e": 13383,
"s": 13374,
"text": "suresh07"
},
{
"code": null,
"e": 13401,
"s": 13383,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 13417,
"s": 13401,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 13433,
"s": 13417,
"text": "sachinvinod1904"
},
{
"code": null,
"e": 13440,
"s": 13433,
"text": "Amazon"
},
{
"code": null,
"e": 13460,
"s": 13440,
"text": "array-range-queries"
},
{
"code": null,
"e": 13474,
"s": 13460,
"text": "Binary Search"
},
{
"code": null,
"e": 13481,
"s": 13474,
"text": "Arrays"
},
{
"code": null,
"e": 13488,
"s": 13481,
"text": "Amazon"
},
{
"code": null,
"e": 13495,
"s": 13488,
"text": "Arrays"
},
{
"code": null,
"e": 13509,
"s": 13495,
"text": "Binary Search"
},
{
"code": null,
"e": 13607,
"s": 13509,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13675,
"s": 13607,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 13719,
"s": 13675,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 13751,
"s": 13719,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 13799,
"s": 13751,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 13813,
"s": 13799,
"text": "Linear Search"
},
{
"code": null,
"e": 13898,
"s": 13813,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 13921,
"s": 13898,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 13977,
"s": 13921,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 14004,
"s": 13977,
"text": "Subset Sum Problem | DP-25"
}
]
|
Python program to find second largest number in a list | 01 Jul, 2022
Given a list of numbers, the task is to write a Python program to find the second largest number in the given list.
Examples:
Input: list1 = [10, 20, 4]
Output: 10
Input: list2 = [70, 11, 20, 4, 100]
Output: 70
Method 1: Sorting is an easier but less optimal method. Given below is an O(n) algorithm to do the same.
Python3
# Python program to find second largest# number in a list # list of numbers - length of# list should be at least 2list1 = [10, 20, 4, 45, 99] mx = max(list1[0], list1[1])secondmax = min(list1[0], list1[1])n = len(list1)for i in range(2,n): if list1[i] > mx: secondmax = mx mx = list1[i] elif list1[i] > secondmax and \ mx != list1[i]: secondmax = list1[i] elif mx == secondmax and \ secondmax != list1[i]: secondmax = list1[i] print("Second highest number is : ",\ str(secondmax))
Second highest number is : 45
Method 2: Sort the list in ascending order and print the second last element in the list.
Python3
# Python program to find largest number# in a list # List of numberslist1 = [10, 20, 20, 4, 45, 45, 45, 99, 99] # Removing duplicates from the listlist2 = list(set(list1)) # Sorting the listlist2.sort() # Printing the second last elementprint("Second largest element is:", list2[-2])
Second largest element is: 45
Method 3: By removing the max element from the list
Python3
# Python program to find second largest number# in a list # List of numberslist1 = [10, 20, 4, 45, 99] # new_list is a set of list1new_list = set(list1) # Removing the largest element from temp listnew_list.remove(max(new_list)) # Elements in original list are not changed# print(list1)print(max(new_list))
45
Method 4: Find the max list element on inputs provided by the user
Python3
# Python program to find second largest# number in a list # creating list of integer typelist1 = [10, 20, 4, 45, 99] '''# sort the list list1.sort() # print second maximum elementprint("Second largest element is:", list1[-2]) ''' # print second maximum element using sorted() methodprint("Second largest element is:", sorted(list1)[-2])
Second largest element is: 45
Method 5: Traverse once to find the largest and then once again to find the second largest.
Python3
def findLargest(arr): secondLargest = arr[0] largest = arr[0] for i in range(len(arr)): if arr[i] > largest: largest = arr[i] for i in range(len(arr)): if arr[i] > secondLargest and arr[i] != largest: secondLargest = arr[i] # Returning second largest element return secondLargest # Calling above method over this array setprint(findLargest([10, 20, 4, 45, 99]))
45
Method 6: Using list comprehension
Python3
def secondmax(arr): sublist = [x for x in arr if x < max(arr)] return max(sublist) if __name__ == '__main__': arr = [10, 20, 4, 45, 99] print(secondmax(arr))
45
saurabh3299
RahulJain29
planetside2psc
tommybhatt
huzaifamalik47
hirendrakoche1
beheraprabirkumar
nagpal_chi
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jul, 2022"
},
{
"code": null,
"e": 168,
"s": 52,
"text": "Given a list of numbers, the task is to write a Python program to find the second largest number in the given list."
},
{
"code": null,
"e": 179,
"s": 168,
"text": "Examples: "
},
{
"code": null,
"e": 217,
"s": 179,
"text": "Input: list1 = [10, 20, 4]\nOutput: 10"
},
{
"code": null,
"e": 264,
"s": 217,
"text": "Input: list2 = [70, 11, 20, 4, 100]\nOutput: 70"
},
{
"code": null,
"e": 370,
"s": 264,
"text": "Method 1: Sorting is an easier but less optimal method. Given below is an O(n) algorithm to do the same. "
},
{
"code": null,
"e": 378,
"s": 370,
"text": "Python3"
},
{
"code": "# Python program to find second largest# number in a list # list of numbers - length of# list should be at least 2list1 = [10, 20, 4, 45, 99] mx = max(list1[0], list1[1])secondmax = min(list1[0], list1[1])n = len(list1)for i in range(2,n): if list1[i] > mx: secondmax = mx mx = list1[i] elif list1[i] > secondmax and \\ mx != list1[i]: secondmax = list1[i] elif mx == secondmax and \\ secondmax != list1[i]: secondmax = list1[i] print(\"Second highest number is : \",\\ str(secondmax))",
"e": 917,
"s": 378,
"text": null
},
{
"code": null,
"e": 948,
"s": 917,
"text": "Second highest number is : 45"
},
{
"code": null,
"e": 1038,
"s": 948,
"text": "Method 2: Sort the list in ascending order and print the second last element in the list."
},
{
"code": null,
"e": 1046,
"s": 1038,
"text": "Python3"
},
{
"code": "# Python program to find largest number# in a list # List of numberslist1 = [10, 20, 20, 4, 45, 45, 45, 99, 99] # Removing duplicates from the listlist2 = list(set(list1)) # Sorting the listlist2.sort() # Printing the second last elementprint(\"Second largest element is:\", list2[-2])",
"e": 1331,
"s": 1046,
"text": null
},
{
"code": null,
"e": 1361,
"s": 1331,
"text": "Second largest element is: 45"
},
{
"code": null,
"e": 1414,
"s": 1361,
"text": "Method 3: By removing the max element from the list "
},
{
"code": null,
"e": 1422,
"s": 1414,
"text": "Python3"
},
{
"code": "# Python program to find second largest number# in a list # List of numberslist1 = [10, 20, 4, 45, 99] # new_list is a set of list1new_list = set(list1) # Removing the largest element from temp listnew_list.remove(max(new_list)) # Elements in original list are not changed# print(list1)print(max(new_list))",
"e": 1729,
"s": 1422,
"text": null
},
{
"code": null,
"e": 1732,
"s": 1729,
"text": "45"
},
{
"code": null,
"e": 1800,
"s": 1732,
"text": "Method 4: Find the max list element on inputs provided by the user "
},
{
"code": null,
"e": 1808,
"s": 1800,
"text": "Python3"
},
{
"code": "# Python program to find second largest# number in a list # creating list of integer typelist1 = [10, 20, 4, 45, 99] '''# sort the list list1.sort() # print second maximum elementprint(\"Second largest element is:\", list1[-2]) ''' # print second maximum element using sorted() methodprint(\"Second largest element is:\", sorted(list1)[-2])",
"e": 2151,
"s": 1808,
"text": null
},
{
"code": null,
"e": 2181,
"s": 2151,
"text": "Second largest element is: 45"
},
{
"code": null,
"e": 2274,
"s": 2181,
"text": "Method 5: Traverse once to find the largest and then once again to find the second largest. "
},
{
"code": null,
"e": 2282,
"s": 2274,
"text": "Python3"
},
{
"code": "def findLargest(arr): secondLargest = arr[0] largest = arr[0] for i in range(len(arr)): if arr[i] > largest: largest = arr[i] for i in range(len(arr)): if arr[i] > secondLargest and arr[i] != largest: secondLargest = arr[i] # Returning second largest element return secondLargest # Calling above method over this array setprint(findLargest([10, 20, 4, 45, 99]))",
"e": 2701,
"s": 2282,
"text": null
},
{
"code": null,
"e": 2704,
"s": 2701,
"text": "45"
},
{
"code": null,
"e": 2739,
"s": 2704,
"text": "Method 6: Using list comprehension"
},
{
"code": null,
"e": 2747,
"s": 2739,
"text": "Python3"
},
{
"code": "def secondmax(arr): sublist = [x for x in arr if x < max(arr)] return max(sublist) if __name__ == '__main__': arr = [10, 20, 4, 45, 99] print(secondmax(arr))",
"e": 2909,
"s": 2747,
"text": null
},
{
"code": null,
"e": 2912,
"s": 2909,
"text": "45"
},
{
"code": null,
"e": 2924,
"s": 2912,
"text": "saurabh3299"
},
{
"code": null,
"e": 2936,
"s": 2924,
"text": "RahulJain29"
},
{
"code": null,
"e": 2951,
"s": 2936,
"text": "planetside2psc"
},
{
"code": null,
"e": 2962,
"s": 2951,
"text": "tommybhatt"
},
{
"code": null,
"e": 2977,
"s": 2962,
"text": "huzaifamalik47"
},
{
"code": null,
"e": 2992,
"s": 2977,
"text": "hirendrakoche1"
},
{
"code": null,
"e": 3010,
"s": 2992,
"text": "beheraprabirkumar"
},
{
"code": null,
"e": 3021,
"s": 3010,
"text": "nagpal_chi"
},
{
"code": null,
"e": 3042,
"s": 3021,
"text": "Python list-programs"
},
{
"code": null,
"e": 3054,
"s": 3042,
"text": "python-list"
},
{
"code": null,
"e": 3061,
"s": 3054,
"text": "Python"
},
{
"code": null,
"e": 3077,
"s": 3061,
"text": "Python Programs"
},
{
"code": null,
"e": 3089,
"s": 3077,
"text": "python-list"
},
{
"code": null,
"e": 3187,
"s": 3089,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3229,
"s": 3187,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3251,
"s": 3229,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3277,
"s": 3251,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3309,
"s": 3277,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3338,
"s": 3309,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3360,
"s": 3338,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3399,
"s": 3360,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3437,
"s": 3399,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3486,
"s": 3437,
"text": "Python | Convert string dictionary to dictionary"
}
]
|
How to Append Values to Vector Using Loop in R? | 28 Nov, 2021
In this article, we will discuss how to append values to a vector using a loop in R Programming Language.
Here we are going to append the values using for loop to the empty vector.
Syntax:
for(iterator in range) {
vector = c(vector, iterator)
}
where,
range is the range of values
iterator is to iterate the range of values
c(vector,iterator) is an append function which will append values to the vector
Example:
R
# create empty vectorvector1 = c() # displayprint(vector1) # use for loop to add elements from 1 to 5for(i in 1: 5) { vector1 = c(vector1, i)} # displayvector1
Output:
NULL
[1] 1 2 3 4 5
Here we are going to perform some numeric operations and append values to the empty vector. We can perform cube operation and append to empty vector.
Syntax:
for(iterator in range) {
vector = c(vector, operation(iterator))
}
where,
range is the range of values
iterator is to iterate the range of values
c(vector,operation(iterator) ) is an append function which will append values to the vector by performing some operation
Here we are going to append the cube values to the vector
Example:
R
# create empty vectorvector1 = c() # displayprint(vector1) # use for loop to add elements from # 1 to 5 with cube valuesfor(i in 1: 5) { vector1 = c(vector1, i*i*i)} # displayvector1
Output:
NULL
[1] 1 8 27 64 125
Here we are going to append a value for an existing vector.
Syntax:
c(existing_vector,new)
where,
existing_vector is the vector
new is the values to be appended
Example:
R
# create vectorvector1 = c(1, 2, 3, 4, 5) # displayprint(vector1) # append 34vector1 = c(vector1, 34) # displayvector1
Output:
[1] 1 2 3 4 5
[1] 1 2 3 4 5 34
Here we are going to append multiple values to the existing vector using for loop.
Syntax:
for(iterator in range) {
vector = c(existing_vector, iterator)
}
where,
range is the range of values
iterator is to iterate the range of values
c(existing_vector,iterator) is an append function which will append values to the existing vector
Example:
R
# create vectorvector1 = c(6, 7, 8, 9, 10) # displayprint(vector1) # use for loop to add elements from 1 to 5for(i in 1: 5) { vector1 = c(vector1, i)} # displayvector1
Output:
[1] 6 7 8 9 10
[1] 6 7 8 9 10 1 2 3 4 5
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 135,
"s": 28,
"text": "In this article, we will discuss how to append values to a vector using a loop in R Programming Language. "
},
{
"code": null,
"e": 210,
"s": 135,
"text": "Here we are going to append the values using for loop to the empty vector."
},
{
"code": null,
"e": 218,
"s": 210,
"text": "Syntax:"
},
{
"code": null,
"e": 276,
"s": 218,
"text": "for(iterator in range) {\n vector = c(vector, iterator)\n}"
},
{
"code": null,
"e": 283,
"s": 276,
"text": "where,"
},
{
"code": null,
"e": 312,
"s": 283,
"text": "range is the range of values"
},
{
"code": null,
"e": 355,
"s": 312,
"text": "iterator is to iterate the range of values"
},
{
"code": null,
"e": 435,
"s": 355,
"text": "c(vector,iterator) is an append function which will append values to the vector"
},
{
"code": null,
"e": 444,
"s": 435,
"text": "Example:"
},
{
"code": null,
"e": 446,
"s": 444,
"text": "R"
},
{
"code": "# create empty vectorvector1 = c() # displayprint(vector1) # use for loop to add elements from 1 to 5for(i in 1: 5) { vector1 = c(vector1, i)} # displayvector1",
"e": 612,
"s": 446,
"text": null
},
{
"code": null,
"e": 620,
"s": 612,
"text": "Output:"
},
{
"code": null,
"e": 639,
"s": 620,
"text": "NULL\n[1] 1 2 3 4 5"
},
{
"code": null,
"e": 789,
"s": 639,
"text": "Here we are going to perform some numeric operations and append values to the empty vector. We can perform cube operation and append to empty vector."
},
{
"code": null,
"e": 797,
"s": 789,
"text": "Syntax:"
},
{
"code": null,
"e": 865,
"s": 797,
"text": "for(iterator in range) {\n vector = c(vector, operation(iterator))\n}"
},
{
"code": null,
"e": 872,
"s": 865,
"text": "where,"
},
{
"code": null,
"e": 901,
"s": 872,
"text": "range is the range of values"
},
{
"code": null,
"e": 944,
"s": 901,
"text": "iterator is to iterate the range of values"
},
{
"code": null,
"e": 1065,
"s": 944,
"text": "c(vector,operation(iterator) ) is an append function which will append values to the vector by performing some operation"
},
{
"code": null,
"e": 1123,
"s": 1065,
"text": "Here we are going to append the cube values to the vector"
},
{
"code": null,
"e": 1132,
"s": 1123,
"text": "Example:"
},
{
"code": null,
"e": 1134,
"s": 1132,
"text": "R"
},
{
"code": "# create empty vectorvector1 = c() # displayprint(vector1) # use for loop to add elements from # 1 to 5 with cube valuesfor(i in 1: 5) { vector1 = c(vector1, i*i*i)} # displayvector1",
"e": 1323,
"s": 1134,
"text": null
},
{
"code": null,
"e": 1331,
"s": 1323,
"text": "Output:"
},
{
"code": null,
"e": 1360,
"s": 1331,
"text": "NULL\n[1] 1 8 27 64 125"
},
{
"code": null,
"e": 1420,
"s": 1360,
"text": "Here we are going to append a value for an existing vector."
},
{
"code": null,
"e": 1428,
"s": 1420,
"text": "Syntax:"
},
{
"code": null,
"e": 1451,
"s": 1428,
"text": "c(existing_vector,new)"
},
{
"code": null,
"e": 1458,
"s": 1451,
"text": "where,"
},
{
"code": null,
"e": 1488,
"s": 1458,
"text": "existing_vector is the vector"
},
{
"code": null,
"e": 1521,
"s": 1488,
"text": "new is the values to be appended"
},
{
"code": null,
"e": 1530,
"s": 1521,
"text": "Example:"
},
{
"code": null,
"e": 1532,
"s": 1530,
"text": "R"
},
{
"code": "# create vectorvector1 = c(1, 2, 3, 4, 5) # displayprint(vector1) # append 34vector1 = c(vector1, 34) # displayvector1",
"e": 1655,
"s": 1532,
"text": null
},
{
"code": null,
"e": 1663,
"s": 1655,
"text": "Output:"
},
{
"code": null,
"e": 1699,
"s": 1663,
"text": "[1] 1 2 3 4 5\n[1] 1 2 3 4 5 34"
},
{
"code": null,
"e": 1782,
"s": 1699,
"text": "Here we are going to append multiple values to the existing vector using for loop."
},
{
"code": null,
"e": 1790,
"s": 1782,
"text": "Syntax:"
},
{
"code": null,
"e": 1856,
"s": 1790,
"text": "for(iterator in range) {\n vector = c(existing_vector, iterator)\n}"
},
{
"code": null,
"e": 1863,
"s": 1856,
"text": "where,"
},
{
"code": null,
"e": 1892,
"s": 1863,
"text": "range is the range of values"
},
{
"code": null,
"e": 1935,
"s": 1892,
"text": "iterator is to iterate the range of values"
},
{
"code": null,
"e": 2034,
"s": 1935,
"text": "c(existing_vector,iterator) is an append function which will append values to the existing vector"
},
{
"code": null,
"e": 2043,
"s": 2034,
"text": "Example:"
},
{
"code": null,
"e": 2045,
"s": 2043,
"text": "R"
},
{
"code": "# create vectorvector1 = c(6, 7, 8, 9, 10) # displayprint(vector1) # use for loop to add elements from 1 to 5for(i in 1: 5) { vector1 = c(vector1, i)} # displayvector1",
"e": 2220,
"s": 2045,
"text": null
},
{
"code": null,
"e": 2228,
"s": 2220,
"text": "Output:"
},
{
"code": null,
"e": 2281,
"s": 2228,
"text": "[1] 6 7 8 9 10\n[1] 6 7 8 9 10 1 2 3 4 5"
},
{
"code": null,
"e": 2288,
"s": 2281,
"text": "Picked"
},
{
"code": null,
"e": 2306,
"s": 2288,
"text": "R Vector-Programs"
},
{
"code": null,
"e": 2316,
"s": 2306,
"text": "R-Vectors"
},
{
"code": null,
"e": 2327,
"s": 2316,
"text": "R Language"
},
{
"code": null,
"e": 2338,
"s": 2327,
"text": "R Programs"
},
{
"code": null,
"e": 2436,
"s": 2338,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2488,
"s": 2436,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2546,
"s": 2488,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2581,
"s": 2546,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2619,
"s": 2581,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2636,
"s": 2619,
"text": "R - if statement"
},
{
"code": null,
"e": 2694,
"s": 2636,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2743,
"s": 2694,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2786,
"s": 2743,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 2824,
"s": 2786,
"text": "Merge DataFrames by Column Names in R"
}
]
|
Python | numpy.assert_allclose() method | 17 Sep, 2019
With the help of numpy.assert_allclose() method, we can get the assertion errors when two array objects are not equal upto the mark by using numpy.assert_allclose().
Syntax : numpy.assert_allclose(actual_array, desired_array)
Return : Return the Assertion error if two array objects are not equal.
Example #1 :In this example we can see that using numpy.assert_allclose() method, we are able to get the assertion error if two arrays are not equal.
# import numpyimport numpy as np # using numpy.assert_allclose() methodgfg1 = [1, 2, 3]gfg2 = np.array(gfg1) if np.testing.assert_allclose(gfg1, gfg2): print("Matched")
Output :
Matched
Example #2 :
# import numpyimport numpy as np # using numpy.assert_allclose() methodgfg1 = [1, 2, 3]gfg2 = np.array([4, 5, 6]) print(np.testing.assert_allclose(gfg1, gfg2))
Output :
Mismatch: 100%Max absolute difference: 3Max relative difference: 0.75gfg1: array([1, 2, 3])gfg2: array([4, 5, 6])
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 194,
"s": 28,
"text": "With the help of numpy.assert_allclose() method, we can get the assertion errors when two array objects are not equal upto the mark by using numpy.assert_allclose()."
},
{
"code": null,
"e": 254,
"s": 194,
"text": "Syntax : numpy.assert_allclose(actual_array, desired_array)"
},
{
"code": null,
"e": 326,
"s": 254,
"text": "Return : Return the Assertion error if two array objects are not equal."
},
{
"code": null,
"e": 476,
"s": 326,
"text": "Example #1 :In this example we can see that using numpy.assert_allclose() method, we are able to get the assertion error if two arrays are not equal."
},
{
"code": "# import numpyimport numpy as np # using numpy.assert_allclose() methodgfg1 = [1, 2, 3]gfg2 = np.array(gfg1) if np.testing.assert_allclose(gfg1, gfg2): print(\"Matched\")",
"e": 651,
"s": 476,
"text": null
},
{
"code": null,
"e": 660,
"s": 651,
"text": "Output :"
},
{
"code": null,
"e": 668,
"s": 660,
"text": "Matched"
},
{
"code": null,
"e": 681,
"s": 668,
"text": "Example #2 :"
},
{
"code": "# import numpyimport numpy as np # using numpy.assert_allclose() methodgfg1 = [1, 2, 3]gfg2 = np.array([4, 5, 6]) print(np.testing.assert_allclose(gfg1, gfg2))",
"e": 843,
"s": 681,
"text": null
},
{
"code": null,
"e": 852,
"s": 843,
"text": "Output :"
},
{
"code": null,
"e": 966,
"s": 852,
"text": "Mismatch: 100%Max absolute difference: 3Max relative difference: 0.75gfg1: array([1, 2, 3])gfg2: array([4, 5, 6])"
},
{
"code": null,
"e": 979,
"s": 966,
"text": "Python-numpy"
},
{
"code": null,
"e": 986,
"s": 979,
"text": "Python"
},
{
"code": null,
"e": 1084,
"s": 986,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1116,
"s": 1084,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1143,
"s": 1116,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1164,
"s": 1143,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1187,
"s": 1164,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1243,
"s": 1187,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1274,
"s": 1243,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1316,
"s": 1274,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1358,
"s": 1316,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1397,
"s": 1358,
"text": "Python | datetime.timedelta() function"
}
]
|
Prime number in PL/SQL | 02 Jun, 2021
Prerequisite – PL/SQL introductionA prime number is a whole number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 .....In PL/SQL code groups of commands are arranged within a block. A block group-related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.Examples:
Input : 5
Output : true
Input : 10
Output : false
Below is the required implementation:
SQL
declare -- declare variable n, i-- and temp of datatype numbern number; i number; temp number; begin -- Here we Assigning 13 into nn := 13; -- Assigning 2 to ii := 2; -- Assigning 1 to temptemp := 1; -- loop from i = 2 to n/2 for i in 2..n/2 loop if mod(n, i) = 0 then temp := 0; exit; end if; end loop; if temp = 1 then dbms_output.put_line('true'); else dbms_output.put_line('false'); end if;end; -- Program End
Output:
true
snehabt18
Prime Number
SQL-PL/SQL
Misc
Misc
Misc
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hypervisor
Advantages and Disadvantages of OOP
Introduction to Electronic Mail
Cloud Computing
Analog to Digital Conversion
array::size() in C++ STL
Characteristics of Cloud Computing
Bubble Sort algorithm using JavaScript
Introduction to Deep Learning
Types of Cloud | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 457,
"s": 54,
"text": "Prerequisite – PL/SQL introductionA prime number is a whole number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 .....In PL/SQL code groups of commands are arranged within a block. A block group-related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.Examples: "
},
{
"code": null,
"e": 509,
"s": 457,
"text": "Input : 5\nOutput : true\n\nInput : 10\nOutput : false"
},
{
"code": null,
"e": 548,
"s": 509,
"text": "Below is the required implementation: "
},
{
"code": null,
"e": 552,
"s": 548,
"text": "SQL"
},
{
"code": "declare -- declare variable n, i-- and temp of datatype numbern number; i number; temp number; begin -- Here we Assigning 13 into nn := 13; -- Assigning 2 to ii := 2; -- Assigning 1 to temptemp := 1; -- loop from i = 2 to n/2 for i in 2..n/2 loop if mod(n, i) = 0 then temp := 0; exit; end if; end loop; if temp = 1 then dbms_output.put_line('true'); else dbms_output.put_line('false'); end if;end; -- Program End",
"e": 1108,
"s": 552,
"text": null
},
{
"code": null,
"e": 1118,
"s": 1108,
"text": "Output: "
},
{
"code": null,
"e": 1123,
"s": 1118,
"text": "true"
},
{
"code": null,
"e": 1133,
"s": 1123,
"text": "snehabt18"
},
{
"code": null,
"e": 1146,
"s": 1133,
"text": "Prime Number"
},
{
"code": null,
"e": 1157,
"s": 1146,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 1162,
"s": 1157,
"text": "Misc"
},
{
"code": null,
"e": 1167,
"s": 1162,
"text": "Misc"
},
{
"code": null,
"e": 1172,
"s": 1167,
"text": "Misc"
},
{
"code": null,
"e": 1185,
"s": 1172,
"text": "Prime Number"
},
{
"code": null,
"e": 1283,
"s": 1185,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1294,
"s": 1283,
"text": "Hypervisor"
},
{
"code": null,
"e": 1330,
"s": 1294,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 1362,
"s": 1330,
"text": "Introduction to Electronic Mail"
},
{
"code": null,
"e": 1378,
"s": 1362,
"text": "Cloud Computing"
},
{
"code": null,
"e": 1407,
"s": 1378,
"text": "Analog to Digital Conversion"
},
{
"code": null,
"e": 1432,
"s": 1407,
"text": "array::size() in C++ STL"
},
{
"code": null,
"e": 1467,
"s": 1432,
"text": "Characteristics of Cloud Computing"
},
{
"code": null,
"e": 1506,
"s": 1467,
"text": "Bubble Sort algorithm using JavaScript"
},
{
"code": null,
"e": 1536,
"s": 1506,
"text": "Introduction to Deep Learning"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.