title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Explain rename operation in relational algebra (DBMS)?
Query is a question or requesting information. Query language is a language which is used to retrieve information from a database. Query language is divided into two types − Procedural language Procedural language Non-procedural language Non-procedural language Information is retrieved from the database by specifying the sequence of operations to be performed. For Example − Relational algebra. Structure Query language (SQL) is based on relational algebra. Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output. The different types of relational algebra operations are as follows − Select operation Select operation Project operation Project operation Rename operation Rename operation Union operation Union operation Intersection operation Intersection operation Difference operation Difference operation Cartesian product operation Cartesian product operation Join operation Join operation Division operation Division operation Select, project, rename comes under unary operation (operate on one table). It is used to assign a new name to a relation and is denoted by ρ (rho). ρnewname (tablename or expression) Consider the student table given below − The student table is renamed with newstudent with the help of the following command − ρnewstudent (student) The name, branch column of student table are renamed and newbranch respectively ρnewname,newbranch(∏name,branch( student)) Binary operations are applied on two compatible relations. Two relations R1, R2 are to be compatible if they are of the same degree and the domains of corresponding attributes are the same. The Rho in DDL used for name of relation and in DML used for name of attributes. SQL Old name New name Renaming can be used by three methods, which are as follows − Changing name of the relation. Changing name of the relation. Changing name of the attribute. Changing name of the attribute. Changing both. Changing both.
[ { "code": null, "e": 1193, "s": 1062, "text": "Query is a question or requesting information. Query language is a language which is used to retrieve information from a database." }, { "code": null, "e": 1236, "s": 1193, "text": "Query language is divided into two types −" }, { "code": null, "e": 1256, "s": 1236, "text": "Procedural language" }, { "code": null, "e": 1276, "s": 1256, "text": "Procedural language" }, { "code": null, "e": 1300, "s": 1276, "text": "Non-procedural language" }, { "code": null, "e": 1324, "s": 1300, "text": "Non-procedural language" }, { "code": null, "e": 1425, "s": 1324, "text": "Information is retrieved from the database by specifying the sequence of operations to be performed." }, { "code": null, "e": 1459, "s": 1425, "text": "For Example − Relational algebra." }, { "code": null, "e": 1522, "s": 1459, "text": "Structure Query language (SQL) is based on relational algebra." }, { "code": null, "e": 1655, "s": 1522, "text": "Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output." }, { "code": null, "e": 1725, "s": 1655, "text": "The different types of relational algebra operations are as follows −" }, { "code": null, "e": 1742, "s": 1725, "text": "Select operation" }, { "code": null, "e": 1759, "s": 1742, "text": "Select operation" }, { "code": null, "e": 1777, "s": 1759, "text": "Project operation" }, { "code": null, "e": 1795, "s": 1777, "text": "Project operation" }, { "code": null, "e": 1812, "s": 1795, "text": "Rename operation" }, { "code": null, "e": 1829, "s": 1812, "text": "Rename operation" }, { "code": null, "e": 1845, "s": 1829, "text": "Union operation" }, { "code": null, "e": 1861, "s": 1845, "text": "Union operation" }, { "code": null, "e": 1884, "s": 1861, "text": "Intersection operation" }, { "code": null, "e": 1907, "s": 1884, "text": "Intersection operation" }, { "code": null, "e": 1928, "s": 1907, "text": "Difference operation" }, { "code": null, "e": 1949, "s": 1928, "text": "Difference operation" }, { "code": null, "e": 1977, "s": 1949, "text": "Cartesian product operation" }, { "code": null, "e": 2005, "s": 1977, "text": "Cartesian product operation" }, { "code": null, "e": 2020, "s": 2005, "text": "Join operation" }, { "code": null, "e": 2035, "s": 2020, "text": "Join operation" }, { "code": null, "e": 2054, "s": 2035, "text": "Division operation" }, { "code": null, "e": 2073, "s": 2054, "text": "Division operation" }, { "code": null, "e": 2149, "s": 2073, "text": "Select, project, rename comes under unary operation (operate on one table)." }, { "code": null, "e": 2222, "s": 2149, "text": "It is used to assign a new name to a relation and is denoted by ρ (rho)." }, { "code": null, "e": 2257, "s": 2222, "text": "ρnewname (tablename or expression)" }, { "code": null, "e": 2298, "s": 2257, "text": "Consider the student table given below −" }, { "code": null, "e": 2384, "s": 2298, "text": "The student table is renamed with newstudent with the help of the following command −" }, { "code": null, "e": 2406, "s": 2384, "text": "ρnewstudent (student)" }, { "code": null, "e": 2486, "s": 2406, "text": "The name, branch column of student table are renamed and newbranch respectively" }, { "code": null, "e": 2529, "s": 2486, "text": "ρnewname,newbranch(∏name,branch( student))" }, { "code": null, "e": 2588, "s": 2529, "text": "Binary operations are applied on two compatible relations." }, { "code": null, "e": 2719, "s": 2588, "text": "Two relations R1, R2 are to be compatible if they are of the same degree and the domains of corresponding attributes are the same." }, { "code": null, "e": 2800, "s": 2719, "text": "The Rho in DDL used for name of relation and in DML used for name of attributes." }, { "code": null, "e": 2870, "s": 2800, "text": " SQL Old name New name" }, { "code": null, "e": 2932, "s": 2870, "text": "Renaming can be used by three methods, which are as follows −" }, { "code": null, "e": 2963, "s": 2932, "text": "Changing name of the relation." }, { "code": null, "e": 2994, "s": 2963, "text": "Changing name of the relation." }, { "code": null, "e": 3026, "s": 2994, "text": "Changing name of the attribute." }, { "code": null, "e": 3058, "s": 3026, "text": "Changing name of the attribute." }, { "code": null, "e": 3073, "s": 3058, "text": "Changing both." }, { "code": null, "e": 3088, "s": 3073, "text": "Changing both." } ]
Using Manipulating Data
Oracle provide Data Manipulation Language commands to exercise data operations in the database.Data operations can be populating the database tables with the application or business data,modifying the data and removing the data from the database,whenever required. Besides the data operations,there are set of commands which are used to control these operations.These commands are grouped as Transaction Control Language. There are three types of DML statements involved in a logical SQL transaction namely, Insert, Update, Delete and Merge.A transaction is the logical collection of DML actions within a database session. The INSERT command is used to store data in tables. The INSERT command is often used in higher-level programming languages such as Visual Basic.NET or C++ as an embedded SQL command; however,this command can also be executed at the SQL*PLUS prompt in command mode.There are two different forms of the INSERT command. The first form is used if a new row will have a value inserted into each column of the row. The second form of the INSERT command is used to insert rows where some of the column data is unknown or defaulted from another business logic.This form of the INSERT command requires that you specify column names for which data are being stored. The below syntax can be followed if the values for all the columns in the table is definite and known. INSERT INTO table VALUES (column1 value, column2 value, ...); The below syntax can be used if only few columns from the table have to be populated with a value. Rest of the columns can deduce their values either as NULL or from a different business logic. INSERT INTO table (column1 name, column2 name, . . .) VALUES (column1 value, column2 value, . . .); The INSERT statement below creates a new employee record in the EMPLOYEES table. Note that it inserts the values for the primary columns EMPLOYEE_ID, FIRST_NAME, SALARY and DEPARTMENT_ID. INSERT INTO employees (EMPLOYEE_ID, FIRST_NAME, SALARY, DEPARTMENT_ID) VALUES (130, 'KEMP', 3800, 10); Otherwise, complete employee data can be inserted in the EMPLOYEES table without specifying the column list using the below INSERT statement - provided the values are known beforehand and must be in compliance with the data type and position of columns in the table. INSERT INTO employees VALUES (130, 'KEMP','GARNER', '[email protected]', '48309290',TO_DATE ('01-JAN-2012'), 'SALES', 3800, 0, 110, 10); Values to be inserted must be compatible with the data type of the column. Literals, fixed values and special values like functions, SYSDATE, CURRENT_DATE, SEQ.CURRVAL (NEXTVAL), or USER can be used as column values. Values specified must follow the generic rules. String literals and date values must be enclosed within quotes. Date value can be supplied in DD-MON-RR or D-MON-YYYY format, but YYYY is preferred since it clearly specifies the century and does not depend on internal RR century calculation logic. Data can be populated into the target table from the source table using INSERT..AS..SELECT (IAS) operation. Its a direct path read operation.Its a simple way of creating copy of the data from one table to another or creating a backup copy of the table which the source table operations are online. For example, data can be copied from EMPLOYEES table to EMP_HISTORY table. INSERT INTO EMP_HISTORY SELECT EMPLOYEE_ID, EMPLOYEE_NAME, SALARY, DEPARTMENT_ID FROM employees; The UPDATE command modifies the data stored in a column.It can update single or multiple rows at a time depending on the result set filtered by conditions specified in WHERE clause. Note that Updating columns is different from altering columns. Earlier in this chapter, you studied the ALTER command.The ALTER command changes the table structure, but leaves the table data unaffected.The UPDATE command changes data in the table, not the table structure. UPDATE table SET column = value [, column = value ...] [WHERE condition] From the syntax, The SET column = expression can be any combination of characters, formulas, or functions that will update data in the specified column name.The WHERE clause is optional, but if it is included, it specifies which rows will be updated.Only one table can be updated at a time with an UPDATE command. The UPDATE statement below updates the salary of employee JOHN to 5000. UPDATE employees SET salary = 5000 WHERE UPPER (first_name) = 'JOHN'; Though WHERE predicates are optional, but must be logically appended so as to modify only the required row in the table. The UPDATE statement below updates the salaries of all the employees in the table. UPDATE employees SET salary = 5000; Multiple columns can also be updated by specifying multiple columns in SET clause separated by a comma. For example, if both salary and job role has to be changed to 5000 and SALES respectively for JOHN, the UPDATE statement looks like, UPDATE employees SET SALARY = 5000, JOB_ID = 'SALES' WHERE UPPER (first_name) = 'JOHN'; 1 row updated. Another way of updating multiple columns of the same row shows the usage of subquery. UPDATE employees SET (SALARY, JOB_ID) = (SELECT 5000, 'SALES' FROM DUAL) WHERE UPPER (ENAME) = 'JOHN' The DELETE command is one of the simplest of the SQL statements. It removes one or more rows from a table. Multiple table delete operations are not allowed in SQL.The syntax of the DELETE command is as below. DELETE FROM table_name [WHERE condition]; The DELETE command deletes all rows in the table that satisfy the condition in the optional WHERE clause. Since the WHERE clause is optional, one can easily delete all rows from a table by omitting a WHERE clause since the WHERE clause limits the scope of the DELETE operation. The below DELETE statement would remove EDWIN's details from EMP table. DELETE employees WHERE UPPER (ENAME) = 'EDWIN' 1 row deleted. Note: DELETE [TABLE NAME] and DELETE FROM [TABLE NAME] hold the same meaning. The WHERE condition in the conditional delete statements can make use of subquery as shown below. DELETE FROM employees WHERE DEPARTMENT_ID IN (SELECT DEPARTMENT_ID FROM LOCATIONS WHERE LOCATION_CODE = 'SFO') Truncate is a DDL command which is used to flush out all records from a table but retaining the table structure. It does not supports WHERE condition to remove the selected records. TRUNCATE [table name] It is Auto Commit i.e. it commits the current active transaction in the session. Truncating the table does not drops dependent indexes, triggers or table constraints. If a table A is parent of a reference constraint of a table B in the database, the table A could not be truncated. A transaction is a logical unit of work done in database. It can either contain - Multiple DML commands ending with a TCL command i.e. COMMIT or ROLLBACK Multiple DML commands ending with a TCL command i.e. COMMIT or ROLLBACK One DDL command One DDL command One DCL command One DCL command Beginning of a transaction is marked with the first DML command. It ends with a TCL, DDL or DCL command. A TCL command i.e. COMMIT or ROLLBACK is issues explicitly to end an active transaction. By virtue of their basic behavior, if any of DDL or DCL commands get executed in a database session, commit the ongoing active transaction in the session. If the database instance crashes abnormally, the transaction is stopped. COMMIT, ROLLBACK and SAVEPOINT are the transaction control language. COMMIT applies the data changes permanently into the database while ROLLBACK does anti-commit operation. SAVEPOINT controls the series of a transaction by setting markers at different transaction stages. User can roll back the current transaction to the desired save point, which was set earlier. COMMIT - Commit ends the current active transaction by applying the data changes permanently into the database tables. COMMIT is a TCL command which explicitly ends the transaction. However, the DDL and DCL command implicitly commit the transaction. SAVEPOINT - Savepoint is used to mark a specific point in the current transaction in the session. Since it is logical marker in the transaction, savepoints cannot be queried in the data dictionaries. ROLLBACK - The ROLLBACK command is used to end the entire transaction by discarding the data changes. If the transaction contains marked savepoints, ROLLBACK TO SAVEPOINT [name] can be used to rollback the transaction upto the specified savepoint only. As a result, all the data changes upto the specified savepoint will be discarded. Consider the EMPLOYEES table which gets populated with newly hired employee details during first quarter of every year. The clerical staff appends each employee detail with a savepoint, so as to rollback any faulty data at any moment during the data feeding activity. Note that he keeps the savepoint names same as the employee names. INSERT INTO employees (employee_id, first_name, hire_date, job_id, salary, department_id) VALUES (105, 'Allen',TO_DATE ('15-JAN-2013','SALES',10000,10); SAVEPOINT Allen; INSERT INTO employees (employee_id, first_name, hire_date, job_id, salary, department_id) VALUES (106, 'Kate',TO_DATE ('15-JAN-2013','PROD',10000,20); SAVEPOINT Kate; INSERT INTO employees (employee_id, first_name, hire_date, job_id, salary, department_id) VALUES (107, 'McMan',TO_DATE ('15-JAN-2013','ADMIN',12000,30); SAVEPOINT McMan; Suppose, the data feeding operator realises that he has wrongly entered the salary of 'Kate' and 'McMan'. He rolls back the active transaction to the savepoint Kate and re-enters the employee details for Kate and McMan. ROLLBACK TO SAVEPOINT Kate; INSERT INTO employees (employee_id, first_name, hire_date, job_id, salary, department_id) VALUES (106, 'Kate',TO_DATE ('15-JAN-2013','PROD',12500,20); SAVEPOINT Kate; INSERT INTO employees (employee_id, first_name, hire_date, job_id, salary, department_id) VALUES (107, 'McMan',TO_DATE ('15-JAN-2013','ADMIN',13200,30); SAVEPOINT McMan; Once he is done with the data entry, he can commit the entire transaction by issuing COMMIT in the current session. Oracle maintains consistency among the users in each session in terms of data access and read/write actions. When a DML occurs on a table, the original data values changed by the action are recorded in the database undo records. As long as transaction is not committed into database, any user in other session that later queries the modified data views the original data values. Oracle uses current information in the system global area and information in the undo records to construct a read-consistent view of a table's data for a query. Only when a transaction is committed, the changes of the transaction made permanent. The transaction is the key to Oracle's strategy for providing read consistency. Start point for read-consistent views is generated on behalf of readers Controls when modified data can be seen by other transactions of the database for reading or updating 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2886, "s": 2463, "text": "Oracle provide Data Manipulation Language commands to exercise data operations in the database.Data operations can be populating the database tables with the application or business data,modifying the data and removing the data from the database,whenever required. Besides the data operations,there are set of commands which are used to control these operations.These commands are grouped as Transaction Control Language. " }, { "code": null, "e": 3087, "s": 2886, "text": "There are three types of DML statements involved in a logical SQL transaction namely, Insert, Update, Delete and Merge.A transaction is the logical collection of DML actions within a database session." }, { "code": null, "e": 3744, "s": 3087, "text": "The INSERT command is used to store data in tables. The INSERT command is often used in higher-level programming languages such as Visual Basic.NET or C++ as an embedded SQL command; however,this command can also be executed at the SQL*PLUS prompt in command mode.There are two different forms of the INSERT command. The first form is used if a new row will have a value inserted into each column of the row. The second form of the INSERT command is used to insert rows where some of the column data is unknown or defaulted from another business logic.This form of the INSERT command requires that you specify column names for which data are being stored." }, { "code": null, "e": 3847, "s": 3744, "text": "The below syntax can be followed if the values for all the columns in the table is definite and known." }, { "code": null, "e": 3910, "s": 3847, "text": "INSERT INTO table\nVALUES (column1 value, column2 value, \n...);" }, { "code": null, "e": 4104, "s": 3910, "text": "The below syntax can be used if only few columns from the table have to be populated with a value. Rest of the columns can deduce their values either as NULL or from a different business logic." }, { "code": null, "e": 4204, "s": 4104, "text": "INSERT INTO table (column1 name, column2 name, . . .)\nVALUES (column1 value, column2 value, . . .);" }, { "code": null, "e": 4392, "s": 4204, "text": "The INSERT statement below creates a new employee record in the EMPLOYEES table. Note that it inserts the values for the primary columns EMPLOYEE_ID, FIRST_NAME, SALARY and DEPARTMENT_ID." }, { "code": null, "e": 4495, "s": 4392, "text": "INSERT INTO employees (EMPLOYEE_ID, FIRST_NAME, SALARY, DEPARTMENT_ID)\nVALUES (130, 'KEMP', 3800, 10);" }, { "code": null, "e": 4762, "s": 4495, "text": "Otherwise, complete employee data can be inserted in the EMPLOYEES table without specifying the column list using the below INSERT statement - provided the values are known beforehand and must be in compliance with the data type and position of columns in the table." }, { "code": null, "e": 4901, "s": 4762, "text": "INSERT INTO employees\nVALUES (130, 'KEMP','GARNER', '[email protected]', '48309290',TO_DATE ('01-JAN-2012'), 'SALES', 3800, 0, 110, 10);" }, { "code": null, "e": 5415, "s": 4901, "text": "Values to be inserted must be compatible with the data type of the column. Literals, fixed values and special values like functions, SYSDATE, CURRENT_DATE, SEQ.CURRVAL (NEXTVAL), or USER can be used as column values. Values specified must follow the generic rules. String literals and date values must be enclosed within quotes. Date value can be supplied in DD-MON-RR or D-MON-YYYY format, but YYYY is preferred since it clearly specifies the century and does not depend on internal RR century calculation logic." }, { "code": null, "e": 5713, "s": 5415, "text": "Data can be populated into the target table from the source table using INSERT..AS..SELECT (IAS) operation. Its a direct path read operation.Its a simple way of creating copy of the data from one table to another or creating a backup copy of the table which the source table operations are online." }, { "code": null, "e": 5788, "s": 5713, "text": "For example, data can be copied from EMPLOYEES table to EMP_HISTORY table." }, { "code": null, "e": 5885, "s": 5788, "text": "INSERT INTO EMP_HISTORY\nSELECT EMPLOYEE_ID, EMPLOYEE_NAME, SALARY, DEPARTMENT_ID\nFROM employees;" }, { "code": null, "e": 6341, "s": 5885, "text": "The UPDATE command modifies the data stored in a column.It can update single or multiple rows at a time depending on the result set filtered by conditions specified in WHERE clause. Note that Updating columns is different from altering columns. Earlier in this chapter, you studied the ALTER command.The ALTER command changes the table structure, but leaves the table data unaffected.The UPDATE command changes data in the table, not the table structure." }, { "code": null, "e": 6414, "s": 6341, "text": "UPDATE table\nSET column = value [, column = value ...]\n[WHERE condition]" }, { "code": null, "e": 6431, "s": 6414, "text": "From the syntax," }, { "code": null, "e": 6729, "s": 6431, "text": "The SET column = expression can be any combination of characters, formulas, or functions that will update data in the specified column name.The WHERE clause is optional, but if it is included, it specifies which rows will be updated.Only one table can be updated at a time with an UPDATE command." }, { "code": null, "e": 6801, "s": 6729, "text": "The UPDATE statement below updates the salary of employee JOHN to 5000." }, { "code": null, "e": 6871, "s": 6801, "text": "UPDATE employees\nSET salary = 5000\nWHERE UPPER (first_name) = 'JOHN';" }, { "code": null, "e": 7075, "s": 6871, "text": "Though WHERE predicates are optional, but must be logically appended so as to modify only the required row in the table. The UPDATE statement below updates the salaries of all the employees in the table." }, { "code": null, "e": 7111, "s": 7075, "text": "UPDATE employees\nSET salary = 5000;" }, { "code": null, "e": 7348, "s": 7111, "text": "Multiple columns can also be updated by specifying multiple columns in SET clause separated by a comma. For example, if both salary and job role has to be changed to 5000 and SALES respectively for JOHN, the UPDATE statement looks like," }, { "code": null, "e": 7453, "s": 7348, "text": "UPDATE employees\nSET\tSALARY = 5000,\n\tJOB_ID = 'SALES'\nWHERE UPPER (first_name) = 'JOHN';\n\n1 row updated." }, { "code": null, "e": 7539, "s": 7453, "text": "Another way of updating multiple columns of the same row shows the usage of subquery." }, { "code": null, "e": 7641, "s": 7539, "text": "UPDATE employees\nSET (SALARY, JOB_ID) = (SELECT 5000, 'SALES' FROM DUAL)\nWHERE UPPER (ENAME) = 'JOHN'" }, { "code": null, "e": 7852, "s": 7641, "text": "The DELETE command is one of the simplest of the SQL statements. It removes one or more rows from a table. Multiple table delete operations are not allowed in SQL.The syntax of the DELETE command is as below." }, { "code": null, "e": 7898, "s": 7852, "text": "DELETE FROM table_name\n [WHERE condition];" }, { "code": null, "e": 8178, "s": 7898, "text": "The DELETE command deletes all rows in the table that satisfy the condition in the optional WHERE clause. Since the WHERE clause is optional, one can easily delete all rows from a table by omitting a WHERE clause since the WHERE clause limits the scope of the DELETE operation. " }, { "code": null, "e": 8250, "s": 8178, "text": "The below DELETE statement would remove EDWIN's details from EMP table." }, { "code": null, "e": 8313, "s": 8250, "text": "DELETE employees\nWHERE UPPER (ENAME) = 'EDWIN'\n\n1 row deleted." }, { "code": null, "e": 8391, "s": 8313, "text": "Note: DELETE [TABLE NAME] and DELETE FROM [TABLE NAME] hold the same meaning." }, { "code": null, "e": 8489, "s": 8391, "text": "The WHERE condition in the conditional delete statements can make use of subquery as shown below." }, { "code": null, "e": 8616, "s": 8489, "text": "DELETE FROM employees\nWHERE DEPARTMENT_ID IN (SELECT DEPARTMENT_ID\n\t\t\t\t FROM LOCATIONS\n\t\t\t\t WHERE LOCATION_CODE = 'SFO')" }, { "code": null, "e": 8798, "s": 8616, "text": "Truncate is a DDL command which is used to flush out all records from a table but retaining the table structure. It does not supports WHERE condition to remove the selected records." }, { "code": null, "e": 8820, "s": 8798, "text": "TRUNCATE [table name]" }, { "code": null, "e": 9102, "s": 8820, "text": "It is Auto Commit i.e. it commits the current active transaction in the session. Truncating the table does not drops dependent indexes, triggers or table constraints. If a table A is parent of a reference constraint of a table B in the database, the table A could not be truncated." }, { "code": null, "e": 9185, "s": 9102, "text": "A transaction is a logical unit of work done in database. It can either contain - " }, { "code": null, "e": 9257, "s": 9185, "text": "Multiple DML commands ending with a TCL command i.e. COMMIT or ROLLBACK" }, { "code": null, "e": 9329, "s": 9257, "text": "Multiple DML commands ending with a TCL command i.e. COMMIT or ROLLBACK" }, { "code": null, "e": 9346, "s": 9329, "text": "One DDL command " }, { "code": null, "e": 9363, "s": 9346, "text": "One DDL command " }, { "code": null, "e": 9380, "s": 9363, "text": "One DCL command " }, { "code": null, "e": 9397, "s": 9380, "text": "One DCL command " }, { "code": null, "e": 9820, "s": 9397, "text": "Beginning of a transaction is marked with the first DML command. It ends with a TCL, DDL or DCL command. A TCL command i.e. COMMIT or ROLLBACK is issues explicitly to end an active transaction. By virtue of their basic behavior, if any of DDL or DCL commands get executed in a database session, commit the ongoing active transaction in the session. If the database instance crashes abnormally, the transaction is stopped. " }, { "code": null, "e": 10186, "s": 9820, "text": "COMMIT, ROLLBACK and SAVEPOINT are the transaction control language. COMMIT applies the data changes permanently into the database while ROLLBACK does anti-commit operation. SAVEPOINT controls the series of a transaction by setting markers at different transaction stages. User can roll back the current transaction to the desired save point, which was set earlier." }, { "code": null, "e": 10436, "s": 10186, "text": "COMMIT - Commit ends the current active transaction by applying the data changes permanently into the database tables. COMMIT is a TCL command which explicitly ends the transaction. However, the DDL and DCL command implicitly commit the transaction." }, { "code": null, "e": 10636, "s": 10436, "text": "SAVEPOINT - Savepoint is used to mark a specific point in the current transaction in the session. Since it is logical marker in the transaction, savepoints cannot be queried in the data dictionaries." }, { "code": null, "e": 10971, "s": 10636, "text": "ROLLBACK - The ROLLBACK command is used to end the entire transaction by discarding the data changes. If the transaction contains marked savepoints, ROLLBACK TO SAVEPOINT [name] can be used to rollback the transaction upto the specified savepoint only. As a result, all the data changes upto the specified savepoint will be discarded." }, { "code": null, "e": 11306, "s": 10971, "text": "Consider the EMPLOYEES table which gets populated with newly hired employee details during first quarter of every year. The clerical staff appends each employee detail with a savepoint, so as to rollback any faulty data at any moment during the data feeding activity. Note that he keeps the savepoint names same as the employee names." }, { "code": null, "e": 11818, "s": 11306, "text": "INSERT INTO employees (employee_id, first_name, hire_date, job_id, salary, department_id)\nVALUES (105, 'Allen',TO_DATE ('15-JAN-2013','SALES',10000,10);\n\nSAVEPOINT Allen;\n\nINSERT INTO employees (employee_id, first_name, hire_date, job_id, salary, department_id)\nVALUES (106, 'Kate',TO_DATE ('15-JAN-2013','PROD',10000,20);\n\nSAVEPOINT Kate;\n\nINSERT INTO employees (employee_id, first_name, hire_date, job_id, salary, department_id)\nVALUES (107, 'McMan',TO_DATE ('15-JAN-2013','ADMIN',12000,30);\n\nSAVEPOINT McMan;" }, { "code": null, "e": 12039, "s": 11818, "text": "Suppose, the data feeding operator realises that he has wrongly entered the salary of 'Kate' and 'McMan'. He rolls back the active transaction to the savepoint Kate and re-enters the employee details for Kate and McMan. " }, { "code": null, "e": 12408, "s": 12039, "text": "ROLLBACK TO SAVEPOINT Kate;\n\nINSERT INTO employees (employee_id, first_name, hire_date, job_id, salary, department_id)\nVALUES (106, 'Kate',TO_DATE ('15-JAN-2013','PROD',12500,20);\n\nSAVEPOINT Kate;\n\nINSERT INTO employees (employee_id, first_name, hire_date, job_id, salary, department_id)\nVALUES (107, 'McMan',TO_DATE ('15-JAN-2013','ADMIN',13200,30);\n\nSAVEPOINT McMan;" }, { "code": null, "e": 12524, "s": 12408, "text": "Once he is done with the data entry, he can commit the entire transaction by issuing COMMIT in the current session." }, { "code": null, "e": 12634, "s": 12524, "text": "Oracle maintains consistency among the users in each session in terms of data access and read/write actions. " }, { "code": null, "e": 13231, "s": 12634, "text": "When a DML occurs on a table, the original data values changed by the action are recorded in the database undo records. As long as transaction is not committed into database, any user in other session that later queries the modified data views the original data values. Oracle uses current information in the system global area and information in the undo records to construct a read-consistent view of a table's data for a query. Only when a transaction is committed, the changes of the transaction made permanent. The transaction is the key to Oracle's strategy for providing read consistency. " }, { "code": null, "e": 13303, "s": 13231, "text": "Start point for read-consistent views is generated on behalf of readers" }, { "code": null, "e": 13405, "s": 13303, "text": "Controls when modified data can be seen by other transactions of the database for reading or updating" }, { "code": null, "e": 13438, "s": 13405, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 13452, "s": 13438, "text": " Anadi Sharma" }, { "code": null, "e": 13485, "s": 13452, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 13499, "s": 13485, "text": " Anadi Sharma" }, { "code": null, "e": 13534, "s": 13499, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13548, "s": 13534, "text": " Anadi Sharma" }, { "code": null, "e": 13581, "s": 13548, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 13603, "s": 13581, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 13638, "s": 13603, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 13692, "s": 13638, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 13725, "s": 13692, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 13753, "s": 13725, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 13760, "s": 13753, "text": " Print" }, { "code": null, "e": 13771, "s": 13760, "text": " Add Notes" } ]
Count number of rows in a MongoDB collection
To count number of documents, use count() in MongoDB. Let us create a collection with documents − > db.demo664.insertOne({_id:1,ClientName:"Chris"}); { "acknowledged" : true, "insertedId" : 1 } > db.demo664.insertOne({_id:2,ClientName:"Bob"}); { "acknowledged" : true, "insertedId" : 2 } > db.demo664.insertOne({_id:3,ClientName:"Sam"}); { "acknowledged" : true, "insertedId" : 3 } > db.demo664.insertOne({_id:4,ClientName:"David"}); { "acknowledged" : true, "insertedId" : 4 } Display all documents from a collection with the help of find() method − > db.demo664.find(); This will produce the following output − { "_id" : 1, "ClientName" : "Chris" } { "_id" : 2, "ClientName" : "Bob" } { "_id" : 3, "ClientName" : "Sam" } { "_id" : 4, "ClientName" : "David" } Following is the query to count number of rows − > var numberOfRows=db.demo664.count(); > print ("Number Of Rows="+numberOfRows); This will produce the following output − Number Of Rows=4
[ { "code": null, "e": 1160, "s": 1062, "text": "To count number of documents, use count() in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1540, "s": 1160, "text": "> db.demo664.insertOne({_id:1,ClientName:\"Chris\"});\n{ \"acknowledged\" : true, \"insertedId\" : 1 }\n> db.demo664.insertOne({_id:2,ClientName:\"Bob\"});\n{ \"acknowledged\" : true, \"insertedId\" : 2 }\n> db.demo664.insertOne({_id:3,ClientName:\"Sam\"});\n{ \"acknowledged\" : true, \"insertedId\" : 3 }\n> db.demo664.insertOne({_id:4,ClientName:\"David\"});\n{ \"acknowledged\" : true, \"insertedId\" : 4 }" }, { "code": null, "e": 1613, "s": 1540, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1634, "s": 1613, "text": "> db.demo664.find();" }, { "code": null, "e": 1675, "s": 1634, "text": "This will produce the following output −" }, { "code": null, "e": 1823, "s": 1675, "text": "{ \"_id\" : 1, \"ClientName\" : \"Chris\" }\n{ \"_id\" : 2, \"ClientName\" : \"Bob\" }\n{ \"_id\" : 3, \"ClientName\" : \"Sam\" }\n{ \"_id\" : 4, \"ClientName\" : \"David\" }" }, { "code": null, "e": 1872, "s": 1823, "text": "Following is the query to count number of rows −" }, { "code": null, "e": 1953, "s": 1872, "text": "> var numberOfRows=db.demo664.count();\n> print (\"Number Of Rows=\"+numberOfRows);" }, { "code": null, "e": 1994, "s": 1953, "text": "This will produce the following output −" }, { "code": null, "e": 2011, "s": 1994, "text": "Number Of Rows=4" } ]
D3.js - Transition
Transition is the process of changing from one state to another of an item. D3.js provides a transition() method to perform transition in the HTML page. Let us learn about transition in this chapter. The transition() method is available for all selectors and it starts the transition process. This method supports most of the selection methods such as – attr(), style(), etc. But, It does not support the append() and the data() methods, which need to be called before the transition() method. Also, it provides methods specific to transition like duration(), ease(), etc. A simple transition can be defined as follows − d3.select("body") .transition() .style("background-color", "lightblue"); A transition can be directly created using the d3.transition() method and then used along with selectors as follows. var t = d3.transition() .duration(2000); d3.select("body") .transition(t) .style("background-color", "lightblue"); Let us now create a basic example to understand how transition works. Create a new HTML file, transition_simple.html with the following code. <!DOCTYPE html> <html> <head> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> </head> <body> <h3>Simple transitions</h3> <script> d3.select("body").transition().style("background-color", "lightblue"); </script> </body> </html> Here, we have selected the body element and then started transition by calling the transition() method. Then, we have instructed to transit the background color from the current color, white to light blue. Now, refresh the browser and on the screen, the background color changes from white to light blue. If we want to change the background color from light blue to gray, we can use the following transition − d3.select("body").transition().style("background-color", "gray"); Print Add Notes Bookmark this page
[ { "code": null, "e": 2331, "s": 2130, "text": "Transition is the process of changing from one state to another of an item. D3.js provides a transition() method to perform transition in the HTML page. Let us learn about transition in this chapter." }, { "code": null, "e": 2752, "s": 2331, "text": "The transition() method is available for all selectors and it starts the transition process. This method supports most of the selection methods such as – attr(), style(), etc. But, It does not support the append() and the data() methods, which need to be called before the transition() method. Also, it provides methods specific to transition like duration(), ease(), etc. A simple transition can be defined as follows −" }, { "code": null, "e": 2831, "s": 2752, "text": "d3.select(\"body\")\n .transition()\n .style(\"background-color\", \"lightblue\");" }, { "code": null, "e": 2948, "s": 2831, "text": "A transition can be directly created using the d3.transition() method and then used along with selectors as follows." }, { "code": null, "e": 3072, "s": 2948, "text": "var t = d3.transition()\n .duration(2000);\nd3.select(\"body\")\n .transition(t)\n .style(\"background-color\", \"lightblue\");" }, { "code": null, "e": 3142, "s": 3072, "text": "Let us now create a basic example to understand how transition works." }, { "code": null, "e": 3214, "s": 3142, "text": "Create a new HTML file, transition_simple.html with the following code." }, { "code": null, "e": 3520, "s": 3214, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <h3>Simple transitions</h3>\n <script>\n d3.select(\"body\").transition().style(\"background-color\", \"lightblue\");\n </script>\n </body>\n</html>" }, { "code": null, "e": 3726, "s": 3520, "text": "Here, we have selected the body element and then started transition by calling the transition() method. Then, we have instructed to transit the background color from the current color, white to light blue." }, { "code": null, "e": 3930, "s": 3726, "text": "Now, refresh the browser and on the screen, the background color changes from white to light blue. If we want to change the background color from light blue to gray, we can use the following transition −" }, { "code": null, "e": 3996, "s": 3930, "text": "d3.select(\"body\").transition().style(\"background-color\", \"gray\");" }, { "code": null, "e": 4003, "s": 3996, "text": " Print" }, { "code": null, "e": 4014, "s": 4003, "text": " Add Notes" } ]
Cross field validation with Pandas. Final Blows to the Dirty Data. | Towards Data Science
Today, data never comes from a single source. More often than not, it is collected in different locations and merged together. A common challenge when merging data is data integrity. In simple words, making sure our data is correct by using multiple fields to check the validity of another. In fancier terms, this process is called Cross Field Validation. Sanity checking your dataset for data integrity is essential to have accurate analysis and running machine learning models. Cross field validation should come in after you dealt with most of the other cleaning issues like missing value imputation, ensuring field constraints are in place, etc. I wrote the code snippets for this post with regard to execution time. Since cross-field validation may involve performing operations across multiple columns for millions of observations, the execution speed should is very important. The solutions suggested here should be scalable enough for even massive datasets. I generated fake data to perform cross-field validation: In the setup section, we loaded a fake people dataset. For example purposes, we are going to assume that this data was collected from two sources: from census data that gives each individual's full name and birthday which was merged with their hospital records later. To have an accurate analysis, we should make sure our data is valid. In this case, we can check the validness of two fields: age and BMI (Body Mass Index). Let’s start with age. We have to ensure when we subtract their birth year from the current year, the result matches the age column. When you are performing cross-field validation, the speed should be the main concern. Unlike our little example, you may have to deal with millions of observations. One of the fastest methods for cross-field validation for datasets of any size is apply function of pandas. Here is a simple example of apply: The above was an example of a column-wise execution. apply takes a function name as an argument and calls that function on each element of the column it was called on. The function has an extra argument axis which is by default set to 0 or rows. If we set it to 1 or columns, the function shifts to row-wise execution. Note on axis argument: axis='rows' means performing an operation along the row axis which is vertical because rows are stacked vertically. axis='columns' means performing an operation along the column axis which is horizontal because columns are stacked horizontally. These two terms confuse a lot of people because they look like they are doing the opposite of what they are told to. In reality, it just takes a shift in perspective, or using the words if you will. Let’s create a function that validates a person’s age: Since we are going to use apply for a row-wise operation, its inputs will be each row of the dataset. That's why we can easily access each column's value just like we would in a normal situation. Using the datetime package we imported earlier, we will store today's date. Then, we calculate the age by subtracting the year components from each other. For this to work, you have to make sure the birthday column has a datetime data type. In the return statement we compare the calculated age and the given age, which returns True if they match, False if otherwise: The function works as expected. Now we can subset the data for invalid ages if any: people[people['age_valid'] == False] There were 75 rows with invalid age. If you do the math, the ages do not match. To correct these values, we could write a new function but that would involve a code repetition. We can update validate_age to replace any invalid values with valid ones: We can make sure the operation was successful with an assert statement: Next, we will validate the Body Mass Index column. Body mass index is a value derived from the mass and height of a person. A quick Google search gives us the formula to calculate BMI: Using the ideas from the first example, we will create the function for BMI which replaces invalid BMI with correct values: It is a good practice to start all of your validation functions with validate_. This gives a signal you are performing a validation to the readers of your code. In this section, we will perform a speed comparison of different methods for cross-field validation. We will start off with the apply function for validating the bmi: It took around 0.3 seconds for the 10k dataset. Next, we will use a for loop using pandas iterrows(): It took 10 times longer! Besides, this time difference will not be linear. For larger datasets, the difference becomes bigger and bigger. I don’t think any for loop can beat the apply function, but let's also try itertuples which is generally faster than iterrows(): Still much slower than apply. So, the general rule of thumb for cross-field validation is to always use apply function. Read more articles related to the topic:
[ { "code": null, "e": 528, "s": 172, "text": "Today, data never comes from a single source. More often than not, it is collected in different locations and merged together. A common challenge when merging data is data integrity. In simple words, making sure our data is correct by using multiple fields to check the validity of another. In fancier terms, this process is called Cross Field Validation." }, { "code": null, "e": 822, "s": 528, "text": "Sanity checking your dataset for data integrity is essential to have accurate analysis and running machine learning models. Cross field validation should come in after you dealt with most of the other cleaning issues like missing value imputation, ensuring field constraints are in place, etc." }, { "code": null, "e": 1138, "s": 822, "text": "I wrote the code snippets for this post with regard to execution time. Since cross-field validation may involve performing operations across multiple columns for millions of observations, the execution speed should is very important. The solutions suggested here should be scalable enough for even massive datasets." }, { "code": null, "e": 1195, "s": 1138, "text": "I generated fake data to perform cross-field validation:" }, { "code": null, "e": 1463, "s": 1195, "text": "In the setup section, we loaded a fake people dataset. For example purposes, we are going to assume that this data was collected from two sources: from census data that gives each individual's full name and birthday which was merged with their hospital records later." }, { "code": null, "e": 1619, "s": 1463, "text": "To have an accurate analysis, we should make sure our data is valid. In this case, we can check the validness of two fields: age and BMI (Body Mass Index)." }, { "code": null, "e": 1751, "s": 1619, "text": "Let’s start with age. We have to ensure when we subtract their birth year from the current year, the result matches the age column." }, { "code": null, "e": 2024, "s": 1751, "text": "When you are performing cross-field validation, the speed should be the main concern. Unlike our little example, you may have to deal with millions of observations. One of the fastest methods for cross-field validation for datasets of any size is apply function of pandas." }, { "code": null, "e": 2059, "s": 2024, "text": "Here is a simple example of apply:" }, { "code": null, "e": 2378, "s": 2059, "text": "The above was an example of a column-wise execution. apply takes a function name as an argument and calls that function on each element of the column it was called on. The function has an extra argument axis which is by default set to 0 or rows. If we set it to 1 or columns, the function shifts to row-wise execution." }, { "code": null, "e": 2845, "s": 2378, "text": "Note on axis argument: axis='rows' means performing an operation along the row axis which is vertical because rows are stacked vertically. axis='columns' means performing an operation along the column axis which is horizontal because columns are stacked horizontally. These two terms confuse a lot of people because they look like they are doing the opposite of what they are told to. In reality, it just takes a shift in perspective, or using the words if you will." }, { "code": null, "e": 2900, "s": 2845, "text": "Let’s create a function that validates a person’s age:" }, { "code": null, "e": 3096, "s": 2900, "text": "Since we are going to use apply for a row-wise operation, its inputs will be each row of the dataset. That's why we can easily access each column's value just like we would in a normal situation." }, { "code": null, "e": 3337, "s": 3096, "text": "Using the datetime package we imported earlier, we will store today's date. Then, we calculate the age by subtracting the year components from each other. For this to work, you have to make sure the birthday column has a datetime data type." }, { "code": null, "e": 3464, "s": 3337, "text": "In the return statement we compare the calculated age and the given age, which returns True if they match, False if otherwise:" }, { "code": null, "e": 3548, "s": 3464, "text": "The function works as expected. Now we can subset the data for invalid ages if any:" }, { "code": null, "e": 3585, "s": 3548, "text": "people[people['age_valid'] == False]" }, { "code": null, "e": 3836, "s": 3585, "text": "There were 75 rows with invalid age. If you do the math, the ages do not match. To correct these values, we could write a new function but that would involve a code repetition. We can update validate_age to replace any invalid values with valid ones:" }, { "code": null, "e": 3908, "s": 3836, "text": "We can make sure the operation was successful with an assert statement:" }, { "code": null, "e": 3959, "s": 3908, "text": "Next, we will validate the Body Mass Index column." }, { "code": null, "e": 4032, "s": 3959, "text": "Body mass index is a value derived from the mass and height of a person." }, { "code": null, "e": 4093, "s": 4032, "text": "A quick Google search gives us the formula to calculate BMI:" }, { "code": null, "e": 4217, "s": 4093, "text": "Using the ideas from the first example, we will create the function for BMI which replaces invalid BMI with correct values:" }, { "code": null, "e": 4378, "s": 4217, "text": "It is a good practice to start all of your validation functions with validate_. This gives a signal you are performing a validation to the readers of your code." }, { "code": null, "e": 4545, "s": 4378, "text": "In this section, we will perform a speed comparison of different methods for cross-field validation. We will start off with the apply function for validating the bmi:" }, { "code": null, "e": 4647, "s": 4545, "text": "It took around 0.3 seconds for the 10k dataset. Next, we will use a for loop using pandas iterrows():" }, { "code": null, "e": 4914, "s": 4647, "text": "It took 10 times longer! Besides, this time difference will not be linear. For larger datasets, the difference becomes bigger and bigger. I don’t think any for loop can beat the apply function, but let's also try itertuples which is generally faster than iterrows():" }, { "code": null, "e": 5034, "s": 4914, "text": "Still much slower than apply. So, the general rule of thumb for cross-field validation is to always use apply function." } ]
Split Array into Consecutive Subsequences in C++
Suppose we have an array nums that is sorted in ascending order. We have to return true if and only if we can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and whose length at least 3. So if the input is like [1,2,3,3,4,4,5,5], then the output will be True, as we have two consecutive sequences. These are [1,2,3,4,5] and [3,4,5]. To solve this, we will follow these steps − Make a map m and store the frequency of nums into m, store size of nums into m cnt := n for i in range 0 to n – 1x := nums[i]if m[x] and m[x + 1] and m[x + 2]decrease m[x], m[x + 1] and m[x + 2] by 1, increase x by 3 and decrease count by 3while m[x] > 0 and m[x] > m[x – 1]decrease cnt by 1, decrease m[x] by 1 and increase x by 1 x := nums[i] if m[x] and m[x + 1] and m[x + 2] decrease m[x], m[x + 1] and m[x + 2] by 1, increase x by 3 and decrease count by 3 while m[x] > 0 and m[x] > m[x – 1]decrease cnt by 1, decrease m[x] by 1 and increase x by 1 decrease cnt by 1, decrease m[x] by 1 and increase x by 1 return true if cnt is 0, otherwise false Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: bool isPossible(vector<int>& nums) { unordered_map <int, int> m; int n = nums.size(); for(int i = 0; i < n; i++){ m[nums[i]]++; } int cnt = n; for(int i = 0; i < n; i++){ int x = nums[i]; if(m[x] && m[x + 1] && m[x + 2]){ m[x]--; m[x + 1]--; m[x + 2]--; x += 3; cnt -= 3; while(m[x] > 0 && m[x] > m[x - 1]){ cnt--; m[x]--; x++; } } } return cnt == 0; } }; main(){ vector<int> v = {1,2,3,3,4,4,5,5}; Solution ob; cout << (ob.isPossible(v)); } [1,2,3,3,4,4,5,5] 1
[ { "code": null, "e": 1444, "s": 1062, "text": "Suppose we have an array nums that is sorted in ascending order. We have to return true if and only if we can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and whose length at least 3. So if the input is like [1,2,3,3,4,4,5,5], then the output will be True, as we have two consecutive sequences. These are [1,2,3,4,5] and [3,4,5]." }, { "code": null, "e": 1488, "s": 1444, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1567, "s": 1488, "text": "Make a map m and store the frequency of nums into m, store size of nums into m" }, { "code": null, "e": 1576, "s": 1567, "text": "cnt := n" }, { "code": null, "e": 1820, "s": 1576, "text": "for i in range 0 to n – 1x := nums[i]if m[x] and m[x + 1] and m[x + 2]decrease m[x], m[x + 1] and m[x + 2] by 1, increase x by 3 and decrease count by 3while m[x] > 0 and m[x] > m[x – 1]decrease cnt by 1, decrease m[x] by 1 and increase x by 1" }, { "code": null, "e": 1833, "s": 1820, "text": "x := nums[i]" }, { "code": null, "e": 1867, "s": 1833, "text": "if m[x] and m[x + 1] and m[x + 2]" }, { "code": null, "e": 1950, "s": 1867, "text": "decrease m[x], m[x + 1] and m[x + 2] by 1, increase x by 3 and decrease count by 3" }, { "code": null, "e": 2042, "s": 1950, "text": "while m[x] > 0 and m[x] > m[x – 1]decrease cnt by 1, decrease m[x] by 1 and increase x by 1" }, { "code": null, "e": 2100, "s": 2042, "text": "decrease cnt by 1, decrease m[x] by 1 and increase x by 1" }, { "code": null, "e": 2141, "s": 2100, "text": "return true if cnt is 0, otherwise false" }, { "code": null, "e": 2211, "s": 2141, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2222, "s": 2211, "text": " Live Demo" }, { "code": null, "e": 2966, "s": 2222, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n bool isPossible(vector<int>& nums) {\n unordered_map <int, int> m;\n int n = nums.size();\n for(int i = 0; i < n; i++){\n m[nums[i]]++;\n }\n int cnt = n;\n for(int i = 0; i < n; i++){\n int x = nums[i];\n if(m[x] && m[x + 1] && m[x + 2]){\n m[x]--;\n m[x + 1]--;\n m[x + 2]--;\n x += 3;\n cnt -= 3;\n while(m[x] > 0 && m[x] > m[x - 1]){\n cnt--;\n m[x]--;\n x++;\n }\n }\n }\n return cnt == 0;\n }\n};\nmain(){\n vector<int> v = {1,2,3,3,4,4,5,5};\n Solution ob;\n cout << (ob.isPossible(v));\n}" }, { "code": null, "e": 2984, "s": 2966, "text": "[1,2,3,3,4,4,5,5]" }, { "code": null, "e": 2986, "s": 2984, "text": "1" } ]
Python | Animation in Kivy using .kv file - GeeksforGeeks
19 Oct, 2021 Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, Linux, and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. Animation and AnimationTransition are used to animate Widget properties. You must specify at least a property name and target value. To use Animation, follow these steps: Setup an Animation object Use the Animation object on a Widget To use animation you must have to import: from kivy.animation import Animation Basic Approaches: 1) import runTouchApp 2) import Builder 3) import Widget 4) import Animation 5) import Clock 6) import Window 7) import random 8) import listproperty 9) Build the .kv file 10) Create root class 11) Create the clock and anim react class used to animate the boxes 12) Run the App In the below example we are creating the two boxes (red and green) in which we are giving animations to the red box i.e when the App starts the red box is in its animated view but to clear the concepts i am providing the green box which on click provide random animations i.e it goes anywhere at random. The program consists of two main classes first is clock class which is for the red box as we are declaring it animated and the green box animation is in anim class. To provide the motion you must have to play with velocity. Implementation of the Approach: Python3 # work same as kivy.App used to run the Appfrom kivy.base import runTouchApp # to use .kv file as a string we have to import itfrom kivy.lang import Builder # A Widget is the base building block of GUI interfaces in Kivyfrom kivy.uix.widget import Widget # The Clock object allows you to schedule a# function call in the futurefrom kivy.clock import Clock # Animation and AnimationTransition are# used to animate Widget propertiesfrom kivy.animation import Animation # The Properties classes are used when# you create an EventDispatcher.from kivy.properties import ListProperty # Core class for creating the default Kivy window.from kivy.core.window import Window # As name suggest used when random things requiredfrom random import random # load the kv file as stringBuilder.load_string('''<Root>: # Setting the position (initial) of boxes ClockRect: pos: 300, 300 AnimRect: pos: 500, 300 # creation and animation of red box<ClockRect>: canvas: Color: rgba: 1, 0, 0, 1 Rectangle: pos: self.pos size: self.size # creation and animation of red box<AnimRect>: canvas: Color: rgba: 0, 1, 0, 1 Rectangle: pos: self.pos size: self.size''') # Create the root classclass Root(Widget): pass # Create the clock class Then is when clicked# how much time to animate# the red colour block animation is created by itclass ClockRect(Widget): velocity = ListProperty([10, 15]) def __init__(self, **kwargs): super(ClockRect, self).__init__(**kwargs) Clock.schedule_interval(self.update, 1 / 60.) def update(self, *args): self.x += self.velocity[0] self.y += self.velocity[1] if self.x < 0 or (self.x + self.width) > Window.width: self.velocity[0] *= -1 if self.y < 0 or (self.y + self.height) > Window.height: self.velocity[1] *= -1 # Create the Animation class# And add animation# green colour box is animated through this classclass AnimRect(Widget): def anim_to_random_pos(self): Animation.cancel_all(self) random_x = random() * (Window.width - self.width) random_y = random() * (Window.height - self.height) anim = Animation(x = random_x, y = random_y, duration = 4, t ='out_elastic') anim.start(self) def on_touch_down(self, touch): if self.collide_point(*touch.pos): self.anim_to_random_pos() # run the ApprunTouchApp(Root()) Output: Animated Output video: sagar0719kumar kapoorsagar226 kk773572498 sooda367 Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python
[ { "code": null, "e": 23883, "s": 23855, "text": "\n19 Oct, 2021" }, { "code": null, "e": 24121, "s": 23883, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, Linux, and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications." }, { "code": null, "e": 24294, "s": 24121, "text": "Animation and AnimationTransition are used to animate Widget properties. You must specify at least a property name and target value. To use Animation, follow these steps: " }, { "code": null, "e": 24320, "s": 24294, "text": "Setup an Animation object" }, { "code": null, "e": 24357, "s": 24320, "text": "Use the Animation object on a Widget" }, { "code": null, "e": 24436, "s": 24357, "text": "To use animation you must have to import: from kivy.animation import Animation" }, { "code": null, "e": 24734, "s": 24436, "text": "Basic Approaches: \n\n1) import runTouchApp\n2) import Builder\n3) import Widget\n4) import Animation\n5) import Clock\n6) import Window\n7) import random\n8) import listproperty\n9) Build the .kv file\n10) Create root class\n11) Create the clock and anim react class used to animate the boxes\n12) Run the App" }, { "code": null, "e": 25203, "s": 24734, "text": "In the below example we are creating the two boxes (red and green) in which we are giving animations to the red box i.e when the App starts the red box is in its animated view but to clear the concepts i am providing the green box which on click provide random animations i.e it goes anywhere at random. The program consists of two main classes first is clock class which is for the red box as we are declaring it animated and the green box animation is in anim class." }, { "code": null, "e": 25262, "s": 25203, "text": "To provide the motion you must have to play with velocity." }, { "code": null, "e": 25294, "s": 25262, "text": "Implementation of the Approach:" }, { "code": null, "e": 25302, "s": 25294, "text": "Python3" }, { "code": "# work same as kivy.App used to run the Appfrom kivy.base import runTouchApp # to use .kv file as a string we have to import itfrom kivy.lang import Builder # A Widget is the base building block of GUI interfaces in Kivyfrom kivy.uix.widget import Widget # The Clock object allows you to schedule a# function call in the futurefrom kivy.clock import Clock # Animation and AnimationTransition are# used to animate Widget propertiesfrom kivy.animation import Animation # The Properties classes are used when# you create an EventDispatcher.from kivy.properties import ListProperty # Core class for creating the default Kivy window.from kivy.core.window import Window # As name suggest used when random things requiredfrom random import random # load the kv file as stringBuilder.load_string('''<Root>: # Setting the position (initial) of boxes ClockRect: pos: 300, 300 AnimRect: pos: 500, 300 # creation and animation of red box<ClockRect>: canvas: Color: rgba: 1, 0, 0, 1 Rectangle: pos: self.pos size: self.size # creation and animation of red box<AnimRect>: canvas: Color: rgba: 0, 1, 0, 1 Rectangle: pos: self.pos size: self.size''') # Create the root classclass Root(Widget): pass # Create the clock class Then is when clicked# how much time to animate# the red colour block animation is created by itclass ClockRect(Widget): velocity = ListProperty([10, 15]) def __init__(self, **kwargs): super(ClockRect, self).__init__(**kwargs) Clock.schedule_interval(self.update, 1 / 60.) def update(self, *args): self.x += self.velocity[0] self.y += self.velocity[1] if self.x < 0 or (self.x + self.width) > Window.width: self.velocity[0] *= -1 if self.y < 0 or (self.y + self.height) > Window.height: self.velocity[1] *= -1 # Create the Animation class# And add animation# green colour box is animated through this classclass AnimRect(Widget): def anim_to_random_pos(self): Animation.cancel_all(self) random_x = random() * (Window.width - self.width) random_y = random() * (Window.height - self.height) anim = Animation(x = random_x, y = random_y, duration = 4, t ='out_elastic') anim.start(self) def on_touch_down(self, touch): if self.collide_point(*touch.pos): self.anim_to_random_pos() # run the ApprunTouchApp(Root())", "e": 27836, "s": 25302, "text": null }, { "code": null, "e": 27845, "s": 27836, "text": "Output: " }, { "code": null, "e": 27870, "s": 27845, "text": "Animated Output video: " }, { "code": null, "e": 27887, "s": 27872, "text": "sagar0719kumar" }, { "code": null, "e": 27902, "s": 27887, "text": "kapoorsagar226" }, { "code": null, "e": 27914, "s": 27902, "text": "kk773572498" }, { "code": null, "e": 27923, "s": 27914, "text": "sooda367" }, { "code": null, "e": 27934, "s": 27923, "text": "Python-gui" }, { "code": null, "e": 27946, "s": 27934, "text": "Python-kivy" }, { "code": null, "e": 27953, "s": 27946, "text": "Python" }, { "code": null, "e": 28051, "s": 27953, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28060, "s": 28051, "text": "Comments" }, { "code": null, "e": 28073, "s": 28060, "text": "Old Comments" }, { "code": null, "e": 28091, "s": 28073, "text": "Python Dictionary" }, { "code": null, "e": 28113, "s": 28091, "text": "Enumerate() in Python" }, { "code": null, "e": 28145, "s": 28113, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28187, "s": 28145, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28213, "s": 28187, "text": "Python String | replace()" }, { "code": null, "e": 28257, "s": 28213, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28282, "s": 28257, "text": "sum() function in Python" }, { "code": null, "e": 28319, "s": 28282, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28375, "s": 28319, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
How to randomize the items of a list in Python?
The random module in the Python standard library provides a shuffle() function that returns a sequence with its elements randomly placed. >>> import random >>> l1=['aa',22,'ff',15,90,5.55] >>> random.shuffle(l1) >>> l1 [22, 15, 90, 5.55, 'ff', 'aa'] >>> random.shuffle(l1) >>> l1 ['aa', 'ff', 90, 22, 5.55, 15]
[ { "code": null, "e": 1200, "s": 1062, "text": "The random module in the Python standard library provides a shuffle() function that returns a sequence with its elements randomly placed." }, { "code": null, "e": 1373, "s": 1200, "text": ">>> import random\n>>> l1=['aa',22,'ff',15,90,5.55]\n>>> random.shuffle(l1)\n>>> l1\n[22, 15, 90, 5.55, 'ff', 'aa']\n>>> random.shuffle(l1)\n>>> l1\n['aa', 'ff', 90, 22, 5.55, 15]" } ]
Stock buy and sell | Practice | GeeksforGeeks
The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum. Note: There may be multiple possible solutions. Return any one of them. Any correct solution will result in an output of 1, whereas wrong solutions will result in an output of 0. Example 1: Input: N = 7 A[] = {100,180,260,310,40,535,695} Output: 1 Explanation: One possible solution is (0 3) (4 6) We can buy stock on day 0, and sell it on 3rd day, which will give us maximum profit. Now, we buy stock on day 4 and sell it on day 6. Example 2: Input: N = 5 A[] = {4,2,2,2,4} Output: 1 Explanation: There are multiple possible solutions. one of them is (3 4) We can buy stock on day 3, and sell it on 4th day, which will give us maximum profit. Your Task: The task is to complete the function stockBuySell() which takes an array A[] and N as input parameters and finds the days of buying and selling stock. The function must return a 2D list of integers containing all the buy-sell pairs. If there is No Profit, return an empty list. Note: Since there can be multiple solutions, the driver code will return 1 if your answer is correct, otherwise, it will return 0. In case there's no profit the driver code will return the string "No Profit" for a correct solution. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 2 ≤ N ≤ 106 0 ≤ A[i] ≤ 106 0 sangrambachu1 day ago let profit = []; for(let i=1; i<n; i++) { if(A[i] > A[i-1]) { profit.push([i-1, i]); } } return profit; 0 avfriendscc1 day ago just whenever the curr price is higher than the previous day price it means we can buy the share yesterday and sold it today. This is also a valid pair [prev_day, curr_day] if (curr_day>prev_day) //c++ vector<vector<int> > stockBuySell(vector<int> A, int n){ vector<vector<int>> a; for(int i=1; i<n; i++){ if(A[i]>A[i-1]){ vector<int>t; t.push_back(i-1); t.push_back(i); a.push_back(t); } } return a; } 0 aroopghosh5531 day ago vector<vector<int> > stockBuySell(vector<int> a, int n){ int curr = 0; vector<vector<int>> ans; for(int i = 1; i < n; i++){ if(a[i] <= a[i - 1]){ vector<int> temp; if(a[i - 1] - a[curr] > 0){ temp.push_back(curr); temp.push_back(i - 1); ans.push_back(temp);; } curr = i; } if(i == n - 1 && a[curr] < a[i]){ vector<int> temp; temp.push_back(curr); temp.push_back(i); ans.push_back(temp); } } return ans; } +1 lawbindpandey01w1 week ago The approach is to find the bottom points and peak points. i.e when the price are falling let them fall and once it reaches bottom i.e A[i] > A[i-1] then A[i - 1] is bottom point note it as start i.e start = A[i - 1] and when the price goes up let it rise and when the price reaches peak i.e A[j] < A[j - 1] then A[j - 1] is peak now mark it as end i.e end = A[j - 1] the max profit you'll get is when you'll buy stock at start and sell it on end and now find all such possible intervals from given array A vector<vector<int> > stockBuySell(vector<int> A, int n){ // code here vector<vector<int>> v; int st = 0, end = 0; for(int i = 1; i < n; i++){ if(A[i] > A[i - 1]) end++; else{ if(end > st){ vector<int> v1(2); v1[0] = st, v1[1] = end; v.push_back(v1); } bool flag = 0; while(i < n && A[i] <= A[i - 1]){ i++; flag = 1; } if(flag){ i--; st = i; end= i; } } } if(end > st){ vector<int> v1(2); v1[0] = st; v1[1] = end; v.push_back(v1); } /*(for(auto x : v){ for(auto x1 : x) cout << x1 << " "; cout << "\n"; }*/ return v; } +1 shivi13verma1 week ago easy approch profit=[] for i in range(1,n): if A[i]>A[i-1]: profit.append([i-1,i]) return profit -1 sreenivasulushreeharish1 week ago DUMMY CPP SOLUTIONS class Solution{public: //Function to find the days of buying and selling stock for max profit. vector<vector<int> > stockBuySell(vector<int> A, int n){ // code here vector<vector<int>> rV; vector<int> dummy; bool incr = false; for(int i = 0; i < n-1; i++){ if(A[i] < A[i+1] && !incr){ dummy.push_back(i); incr = !incr; } else if(A[i] > A[i+1] && incr){ incr = !incr; dummy.push_back(i); rV.push_back(dummy); dummy.clear(); } } if(dummy.size() == 1){ dummy.push_back(n-1); rV.push_back(dummy); } return rV; }}; +1 unknownsingh2 weeks ago EASY!!! C++ Solution. vector<vector<int> > stockBuySell(vector<int> arr, int n) { vector<vector<int>>v; int x=0; for(int i=0; i+1<n; i++) { if(arr[i]>arr[i+1]) { if(x!=i) v.push_back({x, i}); x=i+1; } } if(x!=n-1 && arr[x]<arr[n-1]) v.push_back({x, n-1}); return v; } +1 kaleem5302 weeks ago Question description is not clear update it with leetcode buy and sell stock stock 0 mahesh_phutane2 weeks ago #Simple java solution --> 0.86 sec class Solution{ //Function to find the days of buying and selling stock for max profit. ArrayList<ArrayList<Integer> > stockBuySell(int A[], int n) { ArrayList<Integer> k; ArrayList<ArrayList<Integer> > f = new ArrayList<ArrayList<Integer> >(); int i = 1; while(i<n){ int flag = 1; int idx = i; k = new ArrayList<>(); if(A[i]>A[i-1]){ idx = i-1; flag = 0; while(i<n && A[i]>A[i-1]){ i+=1; } } if(flag==0){ k.add(idx); k.add(i-1); f.add(k); } if(flag==1){ i++; } } return f; } } 0 joyrockok2 weeks ago class Solution{ ArrayList<ArrayList<Integer>> result;ArrayList<Integer> subResult;ArrayList<ArrayList<Integer>> finalResult; //Function to find the days of buying and selling stock for max profit. ArrayList<ArrayList<Integer> > stockBuySell(int A[], int n) { // code here finalResult = new ArrayList<ArrayList<Integer>>(); int p1=0, p2=1; long Max = Integer.MIN_VALUE; while (p1 < n && p2 < n) { if((A[p2] - A[p1] > Max && A[p2] - A[p1] > 0) && p1 < p2) { result = new ArrayList<ArrayList<Integer>>(); subResult = new ArrayList<Integer>(); subResult.add(p1); subResult.add(p2); result.add(subResult); Max = A[p2] - A[p1]; p2++; } else if ((A[p2] - A[p1] < Max || A[p2] - A[p1] <= 0) && p1 < p2) { if(result != null && result.size() > 0) { finalResult.add(result.get(0)); result.clear(); } p1=p2; Max = Integer.MIN_VALUE; } else if (A[p2] - A[p1] == Max && p1 < p2) { p2++; } if(p1 == p2) { p2++; } } if(result != null && result.size()>0) { finalResult.add(result.get(0)); result.clear(); } return finalResult; }} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 603, "s": 238, "text": "The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum.\nNote: There may be multiple possible solutions. Return any one of them. Any correct solution will result in an output of 1, whereas wrong solutions will result in an output of 0.\n\nExample 1:" }, { "code": null, "e": 849, "s": 603, "text": "Input:\nN = 7\nA[] = {100,180,260,310,40,535,695}\nOutput:\n1\nExplanation:\nOne possible solution is (0 3) (4 6)\nWe can buy stock on day 0,\nand sell it on 3rd day, which will \ngive us maximum profit. Now, we buy \nstock on day 4 and sell it on day 6.\n" }, { "code": null, "e": 860, "s": 849, "text": "Example 2:" }, { "code": null, "e": 1061, "s": 860, "text": "Input:\nN = 5\nA[] = {4,2,2,2,4}\nOutput:\n1\nExplanation:\nThere are multiple possible solutions.\none of them is (3 4)\nWe can buy stock on day 3,\nand sell it on 4th day, which will \ngive us maximum profit." }, { "code": null, "e": 1352, "s": 1061, "text": "\nYour Task:\nThe task is to complete the function stockBuySell() which takes an array A[] and N as input parameters and finds the days of buying and selling stock. The function must return a 2D list of integers containing all the buy-sell pairs. If there is No Profit, return an empty list. " }, { "code": null, "e": 1586, "s": 1354, "text": "Note: Since there can be multiple solutions, the driver code will return 1 if your answer is correct, otherwise, it will return 0. In case there's no profit the driver code will return the string \"No Profit\" for a correct solution." }, { "code": null, "e": 1649, "s": 1586, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1690, "s": 1649, "text": "\nConstraints:\n2 ≤ N ≤ 106\n0 ≤ A[i] ≤ 106" }, { "code": null, "e": 1692, "s": 1690, "text": "0" }, { "code": null, "e": 1714, "s": 1692, "text": "sangrambachu1 day ago" }, { "code": null, "e": 1902, "s": 1714, "text": "\t\tlet profit = [];\n \n for(let i=1; i<n; i++) {\n if(A[i] > A[i-1]) {\n profit.push([i-1, i]);\n }\n }\n \n return profit;" }, { "code": null, "e": 1904, "s": 1902, "text": "0" }, { "code": null, "e": 1925, "s": 1904, "text": "avfriendscc1 day ago" }, { "code": null, "e": 2121, "s": 1925, "text": "just whenever the curr price is higher than the previous day price it means we can buy the share yesterday and sold it today. This is also a valid pair [prev_day, curr_day] if (curr_day>prev_day)" }, { "code": null, "e": 2129, "s": 2123, "text": "//c++" }, { "code": null, "e": 2453, "s": 2129, "text": "vector<vector<int> > stockBuySell(vector<int> A, int n){ vector<vector<int>> a; for(int i=1; i<n; i++){ if(A[i]>A[i-1]){ vector<int>t; t.push_back(i-1); t.push_back(i); a.push_back(t); } } return a; }" }, { "code": null, "e": 2455, "s": 2453, "text": "0" }, { "code": null, "e": 2478, "s": 2455, "text": "aroopghosh5531 day ago" }, { "code": null, "e": 3163, "s": 2478, "text": "vector<vector<int> > stockBuySell(vector<int> a, int n){\n int curr = 0;\n vector<vector<int>> ans;\n for(int i = 1; i < n; i++){\n if(a[i] <= a[i - 1]){\n vector<int> temp;\n if(a[i - 1] - a[curr] > 0){\n temp.push_back(curr);\n temp.push_back(i - 1);\n ans.push_back(temp);;\n }\n curr = i;\n }\n if(i == n - 1 && a[curr] < a[i]){\n vector<int> temp;\n temp.push_back(curr);\n temp.push_back(i);\n ans.push_back(temp);\n }\n }\n return ans;\n }" }, { "code": null, "e": 3166, "s": 3163, "text": "+1" }, { "code": null, "e": 3193, "s": 3166, "text": "lawbindpandey01w1 week ago" }, { "code": null, "e": 3252, "s": 3193, "text": "The approach is to find the bottom points and peak points." }, { "code": null, "e": 3317, "s": 3252, "text": "i.e when the price are falling let them fall and once it reaches" }, { "code": null, "e": 3700, "s": 3317, "text": "bottom i.e A[i] > A[i-1] then A[i - 1] is bottom point note it as start i.e start = A[i - 1] and when the price goes up let it rise and when the price reaches peak i.e A[j] < A[j - 1] then A[j - 1] is peak now mark it as end i.e end = A[j - 1] the max profit you'll get is when you'll buy stock at start and sell it on end and now find all such possible intervals from given array A" }, { "code": null, "e": 4751, "s": 3704, "text": "vector<vector<int> > stockBuySell(vector<int> A, int n){ // code here vector<vector<int>> v; int st = 0, end = 0; for(int i = 1; i < n; i++){ if(A[i] > A[i - 1]) end++; else{ if(end > st){ vector<int> v1(2); v1[0] = st, v1[1] = end; v.push_back(v1); } bool flag = 0; while(i < n && A[i] <= A[i - 1]){ i++; flag = 1; } if(flag){ i--; st = i; end= i; } } } if(end > st){ vector<int> v1(2); v1[0] = st; v1[1] = end; v.push_back(v1); } /*(for(auto x : v){ for(auto x1 : x) cout << x1 << \" \"; cout << \"\\n\"; }*/ return v; }" }, { "code": null, "e": 4754, "s": 4751, "text": "+1" }, { "code": null, "e": 4777, "s": 4754, "text": "shivi13verma1 week ago" }, { "code": null, "e": 4791, "s": 4777, "text": "easy approch " }, { "code": null, "e": 4893, "s": 4791, "text": "profit=[] for i in range(1,n): if A[i]>A[i-1]: profit.append([i-1,i]) return profit" }, { "code": null, "e": 4896, "s": 4893, "text": "-1" }, { "code": null, "e": 4930, "s": 4896, "text": "sreenivasulushreeharish1 week ago" }, { "code": null, "e": 4950, "s": 4930, "text": "DUMMY CPP SOLUTIONS" }, { "code": null, "e": 5719, "s": 4952, "text": "class Solution{public: //Function to find the days of buying and selling stock for max profit. vector<vector<int> > stockBuySell(vector<int> A, int n){ // code here vector<vector<int>> rV; vector<int> dummy; bool incr = false; for(int i = 0; i < n-1; i++){ if(A[i] < A[i+1] && !incr){ dummy.push_back(i); incr = !incr; } else if(A[i] > A[i+1] && incr){ incr = !incr; dummy.push_back(i); rV.push_back(dummy); dummy.clear(); } } if(dummy.size() == 1){ dummy.push_back(n-1); rV.push_back(dummy); } return rV; }};" }, { "code": null, "e": 5722, "s": 5719, "text": "+1" }, { "code": null, "e": 5746, "s": 5722, "text": "unknownsingh2 weeks ago" }, { "code": null, "e": 5754, "s": 5746, "text": "EASY!!!" }, { "code": null, "e": 5768, "s": 5754, "text": "C++ Solution." }, { "code": null, "e": 6150, "s": 5772, "text": "vector<vector<int> > stockBuySell(vector<int> arr, int n) { vector<vector<int>>v; int x=0; for(int i=0; i+1<n; i++) { if(arr[i]>arr[i+1]) { if(x!=i) v.push_back({x, i}); x=i+1; } } if(x!=n-1 && arr[x]<arr[n-1]) v.push_back({x, n-1}); return v; }" }, { "code": null, "e": 6153, "s": 6150, "text": "+1" }, { "code": null, "e": 6174, "s": 6153, "text": "kaleem5302 weeks ago" }, { "code": null, "e": 6209, "s": 6174, "text": "Question description is not clear " }, { "code": null, "e": 6258, "s": 6209, "text": "update it with leetcode buy and sell stock stock" }, { "code": null, "e": 6260, "s": 6258, "text": "0" }, { "code": null, "e": 6286, "s": 6260, "text": "mahesh_phutane2 weeks ago" }, { "code": null, "e": 7110, "s": 6286, "text": "#Simple java solution --> 0.86 sec\n\nclass Solution{\n //Function to find the days of buying and selling stock for max profit.\n ArrayList<ArrayList<Integer> > stockBuySell(int A[], int n) {\n ArrayList<Integer> k;\n ArrayList<ArrayList<Integer> > f = new ArrayList<ArrayList<Integer> >();\n int i = 1;\n while(i<n){\n int flag = 1;\n int idx = i;\n k = new ArrayList<>();\n if(A[i]>A[i-1]){\n idx = i-1;\n flag = 0;\n while(i<n && A[i]>A[i-1]){\n i+=1;\n }\n }\n if(flag==0){\n k.add(idx);\n k.add(i-1);\n f.add(k);\n }\n if(flag==1){\n i++;\n }\n }\n return f;\n }\n}" }, { "code": null, "e": 7112, "s": 7110, "text": "0" }, { "code": null, "e": 7133, "s": 7112, "text": "joyrockok2 weeks ago" }, { "code": null, "e": 8344, "s": 7133, "text": "class Solution{ ArrayList<ArrayList<Integer>> result;ArrayList<Integer> subResult;ArrayList<ArrayList<Integer>> finalResult; //Function to find the days of buying and selling stock for max profit. ArrayList<ArrayList<Integer> > stockBuySell(int A[], int n) { // code here finalResult = new ArrayList<ArrayList<Integer>>(); int p1=0, p2=1; long Max = Integer.MIN_VALUE; while (p1 < n && p2 < n) { if((A[p2] - A[p1] > Max && A[p2] - A[p1] > 0) && p1 < p2) { result = new ArrayList<ArrayList<Integer>>(); subResult = new ArrayList<Integer>(); subResult.add(p1); subResult.add(p2); result.add(subResult); Max = A[p2] - A[p1]; p2++; } else if ((A[p2] - A[p1] < Max || A[p2] - A[p1] <= 0) && p1 < p2) { if(result != null && result.size() > 0) { finalResult.add(result.get(0)); result.clear(); } p1=p2; Max = Integer.MIN_VALUE; } else if (A[p2] - A[p1] == Max && p1 < p2) { p2++; } if(p1 == p2) { p2++; } } if(result != null && result.size()>0) { finalResult.add(result.get(0)); result.clear(); } return finalResult; }}" }, { "code": null, "e": 8490, "s": 8344, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 8526, "s": 8490, "text": " Login to access your submissions. " }, { "code": null, "e": 8536, "s": 8526, "text": "\nProblem\n" }, { "code": null, "e": 8546, "s": 8536, "text": "\nContest\n" }, { "code": null, "e": 8609, "s": 8546, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8757, "s": 8609, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8965, "s": 8757, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 9071, "s": 8965, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Find most frequent element in a list in Python
In this article we will see how to find the element which is most common in a given list. In other words, the element with highest frequency. We apply why the set function to get the unique elements of the list and then keep account of each of those elements in the list. Finally apply a max function to get the element with highest frequency. Live Demo # Given list listA = [45, 20, 11, 50, 17, 45, 50,13, 45] print("Given List:\n",listA) res = max(set(listA), key = listA.count) print("Element with highest frequency:\n",res) Running the above code gives us the following result − Given List: [45, 20, 11, 50, 17, 45, 50, 13, 45] Element with highest frequency: 45 We use the counter function from collections. Then apply the most common function to get the final result. Live Demo from collections import Counter # Given list listA = [45, 20, 11, 50, 17, 45, 50,13, 45] print("Given List:\n",listA) occurence_count = Counter(listA) res=occurence_count.most_common(1)[0][0] print("Element with highest frequency:\n",res) Running the above code gives us the following result − Given List: [45, 20, 11, 50, 17, 45, 50, 13, 45] Element with highest frequency: 45 This is a straight forward approach in which we use the mode function from statistics module. It directly gives us the result. from statistics import mode # Given list listA = [45, 20, 11, 50, 17, 45, 50,13, 45] print("Given List:\n",listA) res=mode(listA) print("Element with highest frequency:\n",res) Running the above code gives us the following result − Given List: [45, 20, 11, 50, 17, 45, 50, 13, 45] Element with highest frequency: 45
[ { "code": null, "e": 1204, "s": 1062, "text": "In this article we will see how to find the element which is most common in a given list. In other words, the element with highest frequency." }, { "code": null, "e": 1406, "s": 1204, "text": "We apply why the set function to get the unique elements of the list and then keep account of each of those elements in the list. Finally apply a max function to get the element with highest frequency." }, { "code": null, "e": 1417, "s": 1406, "text": " Live Demo" }, { "code": null, "e": 1591, "s": 1417, "text": "# Given list\nlistA = [45, 20, 11, 50, 17, 45, 50,13, 45]\nprint(\"Given List:\\n\",listA)\nres = max(set(listA), key = listA.count)\nprint(\"Element with highest frequency:\\n\",res)" }, { "code": null, "e": 1646, "s": 1591, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1730, "s": 1646, "text": "Given List:\n[45, 20, 11, 50, 17, 45, 50, 13, 45]\nElement with highest frequency:\n45" }, { "code": null, "e": 1837, "s": 1730, "text": "We use the counter function from collections. Then apply the most common function to get the final result." }, { "code": null, "e": 1848, "s": 1837, "text": " Live Demo" }, { "code": null, "e": 2087, "s": 1848, "text": "from collections import Counter\n# Given list\nlistA = [45, 20, 11, 50, 17, 45, 50,13, 45]\nprint(\"Given List:\\n\",listA)\noccurence_count = Counter(listA)\nres=occurence_count.most_common(1)[0][0]\nprint(\"Element with highest frequency:\\n\",res)" }, { "code": null, "e": 2142, "s": 2087, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2226, "s": 2142, "text": "Given List:\n[45, 20, 11, 50, 17, 45, 50, 13, 45]\nElement with highest frequency:\n45" }, { "code": null, "e": 2353, "s": 2226, "text": "This is a straight forward approach in which we use the mode function from statistics module. It directly gives us the result." }, { "code": null, "e": 2530, "s": 2353, "text": "from statistics import mode\n# Given list\nlistA = [45, 20, 11, 50, 17, 45, 50,13, 45]\nprint(\"Given List:\\n\",listA)\nres=mode(listA)\nprint(\"Element with highest frequency:\\n\",res)" }, { "code": null, "e": 2585, "s": 2530, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2669, "s": 2585, "text": "Given List:\n[45, 20, 11, 50, 17, 45, 50, 13, 45]\nElement with highest frequency:\n45" } ]
Clojure - Date and Time
Since the Clojure framework is derived from Java classes, one can use the date-time classes available in Java in Clojure. The class date represents a specific instant in time, with millisecond precision. Following are the methods available for the date-time class. This is used to create the date object in Clojure. Following is the syntax. java.util.Date. Parameters − None. Return Value − Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond. An example on how this is used is shown in the following program. (ns example) (defn Example [] (def date (.toString (java.util.Date.))) (println date)) (Example) The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run. Tue Mar 01 06:11:17 UTC 2016 This is used to format the date output. Following is the syntax. (java.text.SimpleDateFormat. format dt) Parameters − ‘format’ is the format to be used when formatting the date. ‘dt’ is the date which needs to be formatted. Return Value − A formatted date output. An example on how this is used is shown in the following program. (ns example) (defn Example [] (def date (.format (java.text.SimpleDateFormat. "MM/dd/yyyy") (new java.util.Date))) (println date)) (Example) The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run. 03/01/2016 Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. Following is the syntax. (.getTime) Parameters − None. Return Value − The number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date. An example on how this is used is shown in the following program. (ns example) (import java.util.Date) (defn Example [] (def date (.getTime (java.util.Date.))) (println date)) (Example) The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run. 1456812778160 Print Add Notes Bookmark this page
[ { "code": null, "e": 2578, "s": 2374, "text": "Since the Clojure framework is derived from Java classes, one can use the date-time classes available in Java in Clojure. The class date represents a specific instant in time, with millisecond precision." }, { "code": null, "e": 2639, "s": 2578, "text": "Following are the methods available for the date-time class." }, { "code": null, "e": 2690, "s": 2639, "text": "This is used to create the date object in Clojure." }, { "code": null, "e": 2715, "s": 2690, "text": "Following is the syntax." }, { "code": null, "e": 2732, "s": 2715, "text": "java.util.Date.\n" }, { "code": null, "e": 2751, "s": 2732, "text": "Parameters − None." }, { "code": null, "e": 2904, "s": 2751, "text": "Return Value − Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond." }, { "code": null, "e": 2970, "s": 2904, "text": "An example on how this is used is shown in the following program." }, { "code": null, "e": 3073, "s": 2970, "text": "(ns example)\n(defn Example []\n (def date (.toString (java.util.Date.)))\n (println date))\n(Example)" }, { "code": null, "e": 3218, "s": 3073, "text": "The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run." }, { "code": null, "e": 3248, "s": 3218, "text": "Tue Mar 01 06:11:17 UTC 2016\n" }, { "code": null, "e": 3288, "s": 3248, "text": "This is used to format the date output." }, { "code": null, "e": 3313, "s": 3288, "text": "Following is the syntax." }, { "code": null, "e": 3354, "s": 3313, "text": "(java.text.SimpleDateFormat. format dt)\n" }, { "code": null, "e": 3473, "s": 3354, "text": "Parameters − ‘format’ is the format to be used when formatting the date. ‘dt’ is the date which needs to be formatted." }, { "code": null, "e": 3513, "s": 3473, "text": "Return Value − A formatted date output." }, { "code": null, "e": 3579, "s": 3513, "text": "An example on how this is used is shown in the following program." }, { "code": null, "e": 3726, "s": 3579, "text": "(ns example)\n(defn Example []\n (def date (.format (java.text.SimpleDateFormat. \"MM/dd/yyyy\") (new java.util.Date)))\n (println date))\n(Example)" }, { "code": null, "e": 3871, "s": 3726, "text": "The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run." }, { "code": null, "e": 3883, "s": 3871, "text": "03/01/2016\n" }, { "code": null, "e": 3987, "s": 3883, "text": "Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object." }, { "code": null, "e": 4012, "s": 3987, "text": "Following is the syntax." }, { "code": null, "e": 4024, "s": 4012, "text": "(.getTime)\n" }, { "code": null, "e": 4043, "s": 4024, "text": "Parameters − None." }, { "code": null, "e": 4147, "s": 4043, "text": "Return Value − The number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date." }, { "code": null, "e": 4213, "s": 4147, "text": "An example on how this is used is shown in the following program." }, { "code": null, "e": 4339, "s": 4213, "text": "(ns example)\n(import java.util.Date)\n(defn Example []\n (def date (.getTime (java.util.Date.)))\n (println date))\n(Example)" }, { "code": null, "e": 4484, "s": 4339, "text": "The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run." }, { "code": null, "e": 4499, "s": 4484, "text": "1456812778160\n" }, { "code": null, "e": 4506, "s": 4499, "text": " Print" }, { "code": null, "e": 4517, "s": 4506, "text": " Add Notes" } ]
Discover the power of FILTER() in DAX | by Salvatore Cagliari | Towards Data Science
Most of you know something about the FILTER() function in DAX. But, there are chances that you misuse it or don’t use this function’s full power. For example, some time ago, I saw a query similar to this: EVALUATE SUMMARIZECOLUMNS( ‘Product’[BrandName] ,”Sales”, CALCULATE([Sum Online Sales] ,FILTER(‘Product’ ,’Product’[ProductCategoryName] = “Computers” ) ) ) While this query is syntactic correct, it is not optimal. In the following picture, you can see the Timing information from DAX Studio: A much better version is this one: EVALUATE SUMMARIZECOLUMNS( ‘Product’[BrandName] ,”Sales”, CALCULATE([Sum Online Sales] ,’Product’[ProductCategoryName] = “Computers” ) ) And here is the Server timing without FILTER from DAX Studio: When you look at the SE CPU time, you can see that the second query needs almost half the processing time without FILTER. And, while the first query needs three storage engine operations to complete, the second query can be processed with only one SE operation. Let’s look at why this happens and what we can do with the FILTER() function. The FILTER function is an Iterator like SUMX and the other X-functions. Consequently, you can use the Row-Context and Context transition to unleash the full power of FILTER(). If you are not familiar with context transition in DAX, look at my article about this topic: https://towardsdatascience.com/whats-fancy-about-context-transition-in-dax-efb5d5bc4c01 The fact that FILTER() is an iterator explains why it’s slower than adding a “normal” filter when using it with CALCULATE() or CALCULATETABLE() as shown above. But, when you need to work with row-based expressions or filter data based on Measures, you need to use FILTER(). Another fact is that FILTER() returns a table. For this reason, you can use FILTER() to generate filtered tables and use them in your data model or your measures. Because FILTER() returns a table, you can use it to create a calculated table in Power BI or to query your model. Or you can use the function to create a calculated table in your model. The following query shows an example with the use of FILTER to query a table and filter the result: EVALUATE FILTER(Store ,Store[StoreType] <> “Store” ) And, as an Iterator, you can use the row context to filter the result: EVALUATE FILTER(‘Online Sales’ ,’Online Sales’[UnitPrice] * ‘Online Sales’[SalesQuantity] > 1000 ) Of course, this is a very costly query, as the multiplication of the two columns has to be executed for every row in the Online Sales table. But it can be run entirely by the Storage engine and, consequently, use all available CPU cores, which makes this approach very efficient. While the Storage Engine (SE) can process data on multiple CPU cores, the Formula Engine (FE) can use only one CPU core per query. Thus, whatever can be processed by the SE, is more efficient than the processing with the FE. Next, we can use context transition to find the Stores, which had more than 1'000'000 of Sales: EVALUATE FILTER(Store ,[Sum Retail Sales] > 1000000 ) The possibility to use a Measure to filter a table is handy to calculate results, as we will see in the next section. But, these queries always return all columns from the filtered table. What if I want to retrieve only a subset of columns? In this case, I can use a table function to get only the columns I’m interested in. For example: EVALUATE FILTER(SUMMARIZECOLUMNS(Store[StoreType] ,Store[StoreName] ,Store[StoreManager]) ,[Sum Retail Sales] > 1000000 ) Here is the result of the query above: FILTER() accepts all table functions as the first parameter. CALCULATE() and CALCULATETABLE() accepts tables as filter parameter. Due to this fact, you can generate a table with FILTER() and modify the result of the measure with this mechanism. Look at the following query with the measure [Large Stores]: DEFINE MEASURE ‘All Measures’[Large Stores] = CALCULATE([Sum Retail Sales] ,FILTER(Store ,[Sum Retail Sales] > 100000000 ) ) EVALUATE CALCULATETABLE( SUMMARIZECOLUMNS(Store[StoreName] ,”Sales”, [Sum Retail Sales] ,”Is large Store”, IF([Large Stores]>0 ,TRUE(), FALSE()) ) ,’Date’[Year] = 2020 ) ORDER BY [Is large Store] DESC, [Sum Retail Sales] DESC This query aims to find all Stores with a Sales Amount over 100'000'000 ($, €, or whatever) in 2020. See the following picture for the result of the query: Let’s analyse what’s happening here: The query uses SUMMARIZECOLUMNS() to generate a list of all StoresCALCULATETABLE() is used to add a filter for the year 2020I call the [Sum Retail Sales] measure to get the sales for each Store for 2020I call the measure [Large Stores] and check the result if it’s larger than 0a. If yes, I return TRUE()b. If no, I return FALSE() The query uses SUMMARIZECOLUMNS() to generate a list of all Stores CALCULATETABLE() is used to add a filter for the year 2020 I call the [Sum Retail Sales] measure to get the sales for each Store for 2020 I call the measure [Large Stores] and check the result if it’s larger than 0a. If yes, I return TRUE()b. If no, I return FALSE() The measure uses the existing filter context to calculate the result. The filter context contains the filter for the year 2020. The FILTER() function considers this filter when evaluating the list of stores with more than 100'000'000 sales. FILTER() returns a list of Stores, which are above the threshold. CALCULATE() perform the calculation of [Sum Retail Sales] only for those Stores, as the result of FILTER() is used as a filter-modifier in the measure. Therefore we can use a check in the query, like IF([Large Stores]>0,TRUE(), FALSE()), to generate the desired output. Context transition is an important topic when you’re working with FILTER(). Let’s assume that we want to filter our Sales transactions to get only the rows, which have a value of 1000 or more. You might be tempted to use FILTER() to construct a table and use this table as a source for SUMX(): Large Sales Amount =SUMX( FILTER( ‘Retail Sales’ ,’Retail Sales’[SalesQuantity] * ‘Retail Sales’[UnitPrice] >= 1000 ) ,[Sum Retail Sales] ) Here, I use FILTER() to generate a list of transactions above the threshold mentioned above. While the result might be correct, I’m triggering a context transition by calling the [Sum Retail Sales] measure inside SUMX. A better and faster approach is the following measure: Large Sales Amount =CALCULATE ( [Sum Retail Sales], FILTER ( ALL ( ‘Retail Sales’[SalesQuantity] ,‘Retail Sales’[UnitPrice] ), ‘Retail Sales’[SalesQuantity] * ‘Retail Sales’[UnitPrice] >= 1000 ) ) Here I use the measure in CALCULATE(), and I use FILTER() to apply a filter on the ‘OnlineSales’ table to calculate the desired result. The difference in performance is dramatic, as you can see in the following picture: The first measurement shows the timing and query plan of the first measure with SUMX() and FILTER(). Below, you can see the timing of the second measure with CALCULATE() and FILTER(). The reason is visible in the Query plan, where you can see that the query processes 1'451'337 rows twice. In addition, two CallbackDataID steps are executed, which pushes data between the formula and the storage engine. These operations are very costly. The FILTER() function is essential for your DAX toolbelt. You need to understand his capabilities and the potential issues when using this function. But, it gives you a lot of opportunities for enhancing your DAX expressions. As a summary: FILTER() is an iterator FILTER() returns a table FILTER() can be used in CALCULATE() to set the filter context You can use context transition in FILTER() If not used properly, you can slow down your DAX expressions As soon as you understand this function correctly, you can start using it at the right places and unleash the full power of FILTER(). The FILTER() function is described on this page: FILTER — DAX Guide This page has an embedded video with further information and examples. Information about what to avoid when using FILTER() in CALCULATE(), can be found here: Avoid using FILTER as a filter argument in DAX — DAX | Microsoft Docs I use the Contoso sample dataset, like in my previous articles. You can download the ContosoRetailDW Dataset for free from Microsoft here. The Contoso Data can be freely used under the MIT License, as described here. I enlarged the dataset to make the DAX engine work harder. The Online Sales table contains 63 million rows (instead of 12.6 million rows), and the Retail Sales table contains 15.5 million rows (instead of 3.4 million rows).
[ { "code": null, "e": 235, "s": 172, "text": "Most of you know something about the FILTER() function in DAX." }, { "code": null, "e": 318, "s": 235, "text": "But, there are chances that you misuse it or don’t use this function’s full power." }, { "code": null, "e": 377, "s": 318, "text": "For example, some time ago, I saw a query similar to this:" }, { "code": null, "e": 594, "s": 377, "text": "EVALUATE SUMMARIZECOLUMNS( ‘Product’[BrandName] ,”Sales”, CALCULATE([Sum Online Sales] ,FILTER(‘Product’ ,’Product’[ProductCategoryName] = “Computers” ) ) )" }, { "code": null, "e": 652, "s": 594, "text": "While this query is syntactic correct, it is not optimal." }, { "code": null, "e": 730, "s": 652, "text": "In the following picture, you can see the Timing information from DAX Studio:" }, { "code": null, "e": 765, "s": 730, "text": "A much better version is this one:" }, { "code": null, "e": 948, "s": 765, "text": "EVALUATE SUMMARIZECOLUMNS( ‘Product’[BrandName] ,”Sales”, CALCULATE([Sum Online Sales] ,’Product’[ProductCategoryName] = “Computers” ) )" }, { "code": null, "e": 1010, "s": 948, "text": "And here is the Server timing without FILTER from DAX Studio:" }, { "code": null, "e": 1132, "s": 1010, "text": "When you look at the SE CPU time, you can see that the second query needs almost half the processing time without FILTER." }, { "code": null, "e": 1272, "s": 1132, "text": "And, while the first query needs three storage engine operations to complete, the second query can be processed with only one SE operation." }, { "code": null, "e": 1350, "s": 1272, "text": "Let’s look at why this happens and what we can do with the FILTER() function." }, { "code": null, "e": 1422, "s": 1350, "text": "The FILTER function is an Iterator like SUMX and the other X-functions." }, { "code": null, "e": 1526, "s": 1422, "text": "Consequently, you can use the Row-Context and Context transition to unleash the full power of FILTER()." }, { "code": null, "e": 1619, "s": 1526, "text": "If you are not familiar with context transition in DAX, look at my article about this topic:" }, { "code": null, "e": 1707, "s": 1619, "text": "https://towardsdatascience.com/whats-fancy-about-context-transition-in-dax-efb5d5bc4c01" }, { "code": null, "e": 1867, "s": 1707, "text": "The fact that FILTER() is an iterator explains why it’s slower than adding a “normal” filter when using it with CALCULATE() or CALCULATETABLE() as shown above." }, { "code": null, "e": 1981, "s": 1867, "text": "But, when you need to work with row-based expressions or filter data based on Measures, you need to use FILTER()." }, { "code": null, "e": 2144, "s": 1981, "text": "Another fact is that FILTER() returns a table. For this reason, you can use FILTER() to generate filtered tables and use them in your data model or your measures." }, { "code": null, "e": 2330, "s": 2144, "text": "Because FILTER() returns a table, you can use it to create a calculated table in Power BI or to query your model. Or you can use the function to create a calculated table in your model." }, { "code": null, "e": 2430, "s": 2330, "text": "The following query shows an example with the use of FILTER to query a table and filter the result:" }, { "code": null, "e": 2497, "s": 2430, "text": "EVALUATE FILTER(Store ,Store[StoreType] <> “Store” )" }, { "code": null, "e": 2568, "s": 2497, "text": "And, as an Iterator, you can use the row context to filter the result:" }, { "code": null, "e": 2671, "s": 2568, "text": "EVALUATE FILTER(‘Online Sales’ ,’Online Sales’[UnitPrice] * ‘Online Sales’[SalesQuantity] > 1000 )" }, { "code": null, "e": 2951, "s": 2671, "text": "Of course, this is a very costly query, as the multiplication of the two columns has to be executed for every row in the Online Sales table. But it can be run entirely by the Storage engine and, consequently, use all available CPU cores, which makes this approach very efficient." }, { "code": null, "e": 3176, "s": 2951, "text": "While the Storage Engine (SE) can process data on multiple CPU cores, the Formula Engine (FE) can use only one CPU core per query. Thus, whatever can be processed by the SE, is more efficient than the processing with the FE." }, { "code": null, "e": 3272, "s": 3176, "text": "Next, we can use context transition to find the Stores, which had more than 1'000'000 of Sales:" }, { "code": null, "e": 3340, "s": 3272, "text": "EVALUATE FILTER(Store ,[Sum Retail Sales] > 1000000 )" }, { "code": null, "e": 3458, "s": 3340, "text": "The possibility to use a Measure to filter a table is handy to calculate results, as we will see in the next section." }, { "code": null, "e": 3581, "s": 3458, "text": "But, these queries always return all columns from the filtered table. What if I want to retrieve only a subset of columns?" }, { "code": null, "e": 3665, "s": 3581, "text": "In this case, I can use a table function to get only the columns I’m interested in." }, { "code": null, "e": 3678, "s": 3665, "text": "For example:" }, { "code": null, "e": 3881, "s": 3678, "text": "EVALUATE FILTER(SUMMARIZECOLUMNS(Store[StoreType] ,Store[StoreName] ,Store[StoreManager]) ,[Sum Retail Sales] > 1000000 )" }, { "code": null, "e": 3920, "s": 3881, "text": "Here is the result of the query above:" }, { "code": null, "e": 3981, "s": 3920, "text": "FILTER() accepts all table functions as the first parameter." }, { "code": null, "e": 4050, "s": 3981, "text": "CALCULATE() and CALCULATETABLE() accepts tables as filter parameter." }, { "code": null, "e": 4165, "s": 4050, "text": "Due to this fact, you can generate a table with FILTER() and modify the result of the measure with this mechanism." }, { "code": null, "e": 4226, "s": 4165, "text": "Look at the following query with the measure [Large Stores]:" }, { "code": null, "e": 4842, "s": 4226, "text": "DEFINE MEASURE ‘All Measures’[Large Stores] = CALCULATE([Sum Retail Sales] ,FILTER(Store ,[Sum Retail Sales] > 100000000 ) ) EVALUATE CALCULATETABLE( SUMMARIZECOLUMNS(Store[StoreName] ,”Sales”, [Sum Retail Sales] ,”Is large Store”, IF([Large Stores]>0 ,TRUE(), FALSE()) ) ,’Date’[Year] = 2020 ) ORDER BY [Is large Store] DESC, [Sum Retail Sales] DESC" }, { "code": null, "e": 4943, "s": 4842, "text": "This query aims to find all Stores with a Sales Amount over 100'000'000 ($, €, or whatever) in 2020." }, { "code": null, "e": 4998, "s": 4943, "text": "See the following picture for the result of the query:" }, { "code": null, "e": 5035, "s": 4998, "text": "Let’s analyse what’s happening here:" }, { "code": null, "e": 5366, "s": 5035, "text": "The query uses SUMMARIZECOLUMNS() to generate a list of all StoresCALCULATETABLE() is used to add a filter for the year 2020I call the [Sum Retail Sales] measure to get the sales for each Store for 2020I call the measure [Large Stores] and check the result if it’s larger than 0a. If yes, I return TRUE()b. If no, I return FALSE()" }, { "code": null, "e": 5433, "s": 5366, "text": "The query uses SUMMARIZECOLUMNS() to generate a list of all Stores" }, { "code": null, "e": 5492, "s": 5433, "text": "CALCULATETABLE() is used to add a filter for the year 2020" }, { "code": null, "e": 5571, "s": 5492, "text": "I call the [Sum Retail Sales] measure to get the sales for each Store for 2020" }, { "code": null, "e": 5700, "s": 5571, "text": "I call the measure [Large Stores] and check the result if it’s larger than 0a. If yes, I return TRUE()b. If no, I return FALSE()" }, { "code": null, "e": 5828, "s": 5700, "text": "The measure uses the existing filter context to calculate the result. The filter context contains the filter for the year 2020." }, { "code": null, "e": 6007, "s": 5828, "text": "The FILTER() function considers this filter when evaluating the list of stores with more than 100'000'000 sales. FILTER() returns a list of Stores, which are above the threshold." }, { "code": null, "e": 6277, "s": 6007, "text": "CALCULATE() perform the calculation of [Sum Retail Sales] only for those Stores, as the result of FILTER() is used as a filter-modifier in the measure. Therefore we can use a check in the query, like IF([Large Stores]>0,TRUE(), FALSE()), to generate the desired output." }, { "code": null, "e": 6353, "s": 6277, "text": "Context transition is an important topic when you’re working with FILTER()." }, { "code": null, "e": 6470, "s": 6353, "text": "Let’s assume that we want to filter our Sales transactions to get only the rows, which have a value of 1000 or more." }, { "code": null, "e": 6571, "s": 6470, "text": "You might be tempted to use FILTER() to construct a table and use this table as a source for SUMX():" }, { "code": null, "e": 6727, "s": 6571, "text": "Large Sales Amount =SUMX( FILTER( ‘Retail Sales’ ,’Retail Sales’[SalesQuantity] * ‘Retail Sales’[UnitPrice] >= 1000 ) ,[Sum Retail Sales] )" }, { "code": null, "e": 6820, "s": 6727, "text": "Here, I use FILTER() to generate a list of transactions above the threshold mentioned above." }, { "code": null, "e": 6946, "s": 6820, "text": "While the result might be correct, I’m triggering a context transition by calling the [Sum Retail Sales] measure inside SUMX." }, { "code": null, "e": 7001, "s": 6946, "text": "A better and faster approach is the following measure:" }, { "code": null, "e": 7230, "s": 7001, "text": "Large Sales Amount =CALCULATE ( [Sum Retail Sales], FILTER ( ALL ( ‘Retail Sales’[SalesQuantity] ,‘Retail Sales’[UnitPrice] ), ‘Retail Sales’[SalesQuantity] * ‘Retail Sales’[UnitPrice] >= 1000 ) )" }, { "code": null, "e": 7366, "s": 7230, "text": "Here I use the measure in CALCULATE(), and I use FILTER() to apply a filter on the ‘OnlineSales’ table to calculate the desired result." }, { "code": null, "e": 7450, "s": 7366, "text": "The difference in performance is dramatic, as you can see in the following picture:" }, { "code": null, "e": 7634, "s": 7450, "text": "The first measurement shows the timing and query plan of the first measure with SUMX() and FILTER(). Below, you can see the timing of the second measure with CALCULATE() and FILTER()." }, { "code": null, "e": 7888, "s": 7634, "text": "The reason is visible in the Query plan, where you can see that the query processes 1'451'337 rows twice. In addition, two CallbackDataID steps are executed, which pushes data between the formula and the storage engine. These operations are very costly." }, { "code": null, "e": 7946, "s": 7888, "text": "The FILTER() function is essential for your DAX toolbelt." }, { "code": null, "e": 8037, "s": 7946, "text": "You need to understand his capabilities and the potential issues when using this function." }, { "code": null, "e": 8114, "s": 8037, "text": "But, it gives you a lot of opportunities for enhancing your DAX expressions." }, { "code": null, "e": 8128, "s": 8114, "text": "As a summary:" }, { "code": null, "e": 8152, "s": 8128, "text": "FILTER() is an iterator" }, { "code": null, "e": 8177, "s": 8152, "text": "FILTER() returns a table" }, { "code": null, "e": 8239, "s": 8177, "text": "FILTER() can be used in CALCULATE() to set the filter context" }, { "code": null, "e": 8282, "s": 8239, "text": "You can use context transition in FILTER()" }, { "code": null, "e": 8343, "s": 8282, "text": "If not used properly, you can slow down your DAX expressions" }, { "code": null, "e": 8477, "s": 8343, "text": "As soon as you understand this function correctly, you can start using it at the right places and unleash the full power of FILTER()." }, { "code": null, "e": 8545, "s": 8477, "text": "The FILTER() function is described on this page: FILTER — DAX Guide" }, { "code": null, "e": 8616, "s": 8545, "text": "This page has an embedded video with further information and examples." }, { "code": null, "e": 8773, "s": 8616, "text": "Information about what to avoid when using FILTER() in CALCULATE(), can be found here: Avoid using FILTER as a filter argument in DAX — DAX | Microsoft Docs" }, { "code": null, "e": 8912, "s": 8773, "text": "I use the Contoso sample dataset, like in my previous articles. You can download the ContosoRetailDW Dataset for free from Microsoft here." }, { "code": null, "e": 8990, "s": 8912, "text": "The Contoso Data can be freely used under the MIT License, as described here." } ]
Tryit Editor v3.7
Tryit: HTML href attribute
[]
Python | TextBlob.Word.spellcheck() method - GeeksforGeeks
09 Sep, 2019 With the help of TextBlob.Word.spellcheck() method, we can check the word if that word have spelling mistake by using TextBlob.Word.spellcheck() method. Syntax : TextBlob.Word.spellcheck()Return : Return the word with correctness accuracy. Example #1 :In this example we can say that by using TextBlob.Word.spellcheck() method, we are able to get the accuracy of word weather it is correct or not. # import Wordfrom textblob import Word gfg = Word("Facility") # using Word.spellcheck() methodprint(gfg.spellcheck()) Output : [(‘Facility’, 1.0)] Example #2 : # import Wordfrom textblob import Word gfg = Word("Prediction") # using Word.spellcheck() methodprint(gfg.spellcheck()) Output : [(‘Prediction’, 1.0)] Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n09 Sep, 2019" }, { "code": null, "e": 25800, "s": 25647, "text": "With the help of TextBlob.Word.spellcheck() method, we can check the word if that word have spelling mistake by using TextBlob.Word.spellcheck() method." }, { "code": null, "e": 25887, "s": 25800, "text": "Syntax : TextBlob.Word.spellcheck()Return : Return the word with correctness accuracy." }, { "code": null, "e": 26045, "s": 25887, "text": "Example #1 :In this example we can say that by using TextBlob.Word.spellcheck() method, we are able to get the accuracy of word weather it is correct or not." }, { "code": "# import Wordfrom textblob import Word gfg = Word(\"Facility\") # using Word.spellcheck() methodprint(gfg.spellcheck())", "e": 26165, "s": 26045, "text": null }, { "code": null, "e": 26174, "s": 26165, "text": "Output :" }, { "code": null, "e": 26194, "s": 26174, "text": "[(‘Facility’, 1.0)]" }, { "code": null, "e": 26207, "s": 26194, "text": "Example #2 :" }, { "code": "# import Wordfrom textblob import Word gfg = Word(\"Prediction\") # using Word.spellcheck() methodprint(gfg.spellcheck())", "e": 26329, "s": 26207, "text": null }, { "code": null, "e": 26338, "s": 26329, "text": "Output :" }, { "code": null, "e": 26360, "s": 26338, "text": "[(‘Prediction’, 1.0)]" }, { "code": null, "e": 26377, "s": 26360, "text": "Python-Functions" }, { "code": null, "e": 26384, "s": 26377, "text": "Python" }, { "code": null, "e": 26482, "s": 26384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26514, "s": 26482, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26556, "s": 26514, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26598, "s": 26556, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26654, "s": 26598, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26681, "s": 26654, "text": "Python Classes and Objects" }, { "code": null, "e": 26712, "s": 26681, "text": "Python | os.path.join() method" }, { "code": null, "e": 26741, "s": 26712, "text": "Create a directory in Python" }, { "code": null, "e": 26763, "s": 26741, "text": "Defaultdict in Python" }, { "code": null, "e": 26799, "s": 26763, "text": "Python | Pandas dataframe.groupby()" } ]
Remove comma from a string in PHP?
To remove comma, you can replace. To replace, use str_replace() in PHP. Let’s say the following is our input string with comma $name="John,Smith"; We want the output after removing comma from the above string is JohnSmith The PHP code is as follows Live Demo <!DOCTYPE html> <html> <body> <?php $name="John,Smith"; $result = str_replace(',', '', $name); echo "The actual value is=",$name,"<br>"; echo "After removing the comma(,)=",$result,"<br>"; ?> </body> </html> This will produce the following output The actual value is=John,Smith After removing the comma(,)=JohnSmith
[ { "code": null, "e": 1134, "s": 1062, "text": "To remove comma, you can replace. To replace, use str_replace() in PHP." }, { "code": null, "e": 1190, "s": 1134, "text": "Let’s say the following is our input string with comma " }, { "code": null, "e": 1210, "s": 1190, "text": "$name=\"John,Smith\";" }, { "code": null, "e": 1276, "s": 1210, "text": "We want the output after removing comma from the above string is " }, { "code": null, "e": 1286, "s": 1276, "text": "JohnSmith" }, { "code": null, "e": 1313, "s": 1286, "text": "The PHP code is as follows" }, { "code": null, "e": 1324, "s": 1313, "text": " Live Demo" }, { "code": null, "e": 1532, "s": 1324, "text": "<!DOCTYPE html>\n<html>\n<body>\n<?php\n$name=\"John,Smith\";\n$result = str_replace(',', '', $name);\necho \"The actual value is=\",$name,\"<br>\";\necho \"After removing the comma(,)=\",$result,\"<br>\";\n?>\n</body>\n</html>" }, { "code": null, "e": 1571, "s": 1532, "text": "This will produce the following output" }, { "code": null, "e": 1640, "s": 1571, "text": "The actual value is=John,Smith\nAfter removing the comma(,)=JohnSmith" } ]
How to highlight text in a tkinter Text widget?
Tkinter Text widget is used to create text fields that accept multiline user inputs. Let us suppose that in a text widget, we want to highlight some text. In order to highlight a specific text written in the text widget, tkinter provides the tag_add(tag, i,j) method. It adds tags to the specific text by defining the indexes, i and j. In this example, we will create a window application that contains some text and a button which can be triggered to highlight the text. #Import tkinter library from tkinter import * #Create an instance of tkinter frame win= Tk() win.geometry("750x450") #Define a function to highlight the text def add_highlighter(): text.tag_add("start", "1.11","1.17") text.tag_config("start", background= "black", foreground= "white") #Create a Tex Field text= Text(win); text.insert(INSERT, "Hey there! Howdy?") text.pack() #Create a Button to highlight text Button(win, text= "Highlight", command= add_highlighter).pack() win.mainloop() Running the above code will display a window that contain a button and a text in it. Now, click the "Highlight" button to highlight the text "Howdy?"
[ { "code": null, "e": 1398, "s": 1062, "text": "Tkinter Text widget is used to create text fields that accept multiline user inputs. Let us suppose that in a text widget, we want to highlight some text. In order to highlight a specific text written in the text widget, tkinter provides the tag_add(tag, i,j) method. It adds tags to the specific text by defining the indexes, i and j." }, { "code": null, "e": 1534, "s": 1398, "text": "In this example, we will create a window application that contains some text and a button which can be triggered to highlight the text." }, { "code": null, "e": 2029, "s": 1534, "text": "#Import tkinter library\nfrom tkinter import *\n#Create an instance of tkinter frame\nwin= Tk()\nwin.geometry(\"750x450\")\n#Define a function to highlight the text\ndef add_highlighter():\n text.tag_add(\"start\", \"1.11\",\"1.17\")\n text.tag_config(\"start\", background= \"black\", foreground= \"white\")\n#Create a Tex Field\ntext= Text(win);\ntext.insert(INSERT, \"Hey there! Howdy?\")\ntext.pack()\n#Create a Button to highlight text\nButton(win, text= \"Highlight\", command= add_highlighter).pack()\nwin.mainloop()" }, { "code": null, "e": 2114, "s": 2029, "text": "Running the above code will display a window that contain a button and a text in it." }, { "code": null, "e": 2179, "s": 2114, "text": "Now, click the \"Highlight\" button to highlight the text \"Howdy?\"" } ]
How to style a checkbox using CSS? - GeeksforGeeks
30 Jul, 2021 Checkbox is an HTML element which is used to take input from the user. Although it is bit complicated to style it but using Pseudo Elements like :before, :after, :hover and :checked, it is possible to style a checkbox. In order to style the checkbox the user first need to hide the default checkbox which can be done by setting the value of the visibility property to hidden. Example 1: Consider the example where HTML checkbox is styled using CSS. First three check-boxes are created and then the default check-boxes are hide and new checkbox is created using height and width attribute. Set the height and width attribute to 25px and initial background color to black. The check-mark is also styled manually by using webkit. “:checked” is used to style checkbox after it is checked. When the user clicks the checkbox, the background color is set to green.Basically you should approach by thinking about the scenarios in which you want your checkbox to be styled differently like when it is normal, active, hovered over or checked etc. Then for each scenario specify different styles as used in normal CSS. Moreover it can also be possible to change the check-mark. <!DOCTYPE html><html> <head> <style> .main { display: block; position: relative; padding-left: 45px; margin-bottom: 15px; cursor: pointer; font-size: 20px; } /* Hide the default checkbox */ input[type=checkbox] { visibility: hidden; } /* Creating a custom checkbox based on demand */ .geekmark { position: absolute; top: 0; left: 0; height: 25px; width: 25px; background-color: black; } /* Specify the background color to be shown when hovering over checkbox */ .main:hover input ~ .geekmark { background-color: yellow; } /* Specify the background color to be shown when checkbox is active */ .main input:active ~ .geekmark { background-color: red; } /* Specify the background color to be shown when checkbox is checked */ .main input:checked ~ .geekmark { background-color: green; } /* Checkmark to be shown in checkbox */ /* It is not be shown when not checked */ .geekmark:after { content: ""; position: absolute; display: none; } /* Display checkmark when checked */ .main input:checked ~ .geekmark:after { display: block; } /* Styling the checkmark using webkit */ /* Rotated the rectangle by 45 degree and showing only two border to make it look like a tickmark */ .main .geekmark:after { left: 8px; bottom: 5px; width: 6px; height: 12px; border: solid white; border-width: 0 4px 4px 0; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); } </style></head> <body> <h1 style="color:green;"> Best Computer Science Platform </h1> <label class="main">CodeX <input type="checkbox"> <span class="geekmark"></span> </label> <label class="main">GeeksforGeeks <input type="checkbox" checked="checked"> <span class="geekmark"></span> </label> <label class="main">CodeY <input type="checkbox"> <span class="geekmark"></span> </label></body></html> Output: Note: “~” is the sibling combinator which selects all the elements which are preceded by the former selector. “:hover” is used to style the checkbox when user hovers over it. Notice that when the mouse pointer move over the checkbox the color of it changes to yellow. “:active” is used to style the checkbox when it is active. Notice that when click the checkbox it will first notice a red color and then the green color. Example 2: Consider another example with a bit modified design of check-mark. <!DOCTYPE html><html> <head> <title> Style a checkbox using CSS </title> <style> .script { display: block; position: relative; padding-left: 45px; margin-bottom: 15px; cursor: pointer; font-size: 20px; } /* Hide the default checkbox */ input[type=checkbox] { visibility: hidden; } /* creating a custom checkbox based on demand */ .geekmark { position: absolute; top: 0; left: 0; height: 25px; width: 25px; background-color: green; } /* specify the background color to be shown when hovering over checkbox */ .script:hover input ~ .geekmark { background-color: yellow; } /* specify the background color to be shown when checkbox is active */ .script input:active ~ .geekmark { background-color: red; } /* specify the background color to be shown when checkbox is checked */ .script input:checked ~ .geekmark { background-color: green; } /* checkmark to be shown in checkbox */ /* It is not be shown when not checked */ .geekmark:after { content: ""; position: absolute; display: none; } /* display checkmark when checked */ .script input:checked ~ .geekmark:after { display: block; } /* styling the checkmark using webkit */ /* creating a square to be the sign of checkmark */ .script .geekmark:after { left: 6px; bottom: 5px; width: 6px; height: 6px; border: solid white; border-width: 4px 4px 4px 4px; } </style></head> <body> <h1>Is GeeksforGeeks Useful?</h1> <label class="script" style = "color:green;"> Yes <input type="checkbox"> <span class="geekmark"></span> </label> <label class="script" style = "color:green;"> Absolutely Yes <input type="checkbox" checked="checked"> <span class="geekmark"></span> </label></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. CSS-Misc Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24479, "s": 24451, "text": "\n30 Jul, 2021" }, { "code": null, "e": 24855, "s": 24479, "text": "Checkbox is an HTML element which is used to take input from the user. Although it is bit complicated to style it but using Pseudo Elements like :before, :after, :hover and :checked, it is possible to style a checkbox. In order to style the checkbox the user first need to hide the default checkbox which can be done by setting the value of the visibility property to hidden." }, { "code": null, "e": 25646, "s": 24855, "text": "Example 1: Consider the example where HTML checkbox is styled using CSS. First three check-boxes are created and then the default check-boxes are hide and new checkbox is created using height and width attribute. Set the height and width attribute to 25px and initial background color to black. The check-mark is also styled manually by using webkit. “:checked” is used to style checkbox after it is checked. When the user clicks the checkbox, the background color is set to green.Basically you should approach by thinking about the scenarios in which you want your checkbox to be styled differently like when it is normal, active, hovered over or checked etc. Then for each scenario specify different styles as used in normal CSS. Moreover it can also be possible to change the check-mark." }, { "code": "<!DOCTYPE html><html> <head> <style> .main { display: block; position: relative; padding-left: 45px; margin-bottom: 15px; cursor: pointer; font-size: 20px; } /* Hide the default checkbox */ input[type=checkbox] { visibility: hidden; } /* Creating a custom checkbox based on demand */ .geekmark { position: absolute; top: 0; left: 0; height: 25px; width: 25px; background-color: black; } /* Specify the background color to be shown when hovering over checkbox */ .main:hover input ~ .geekmark { background-color: yellow; } /* Specify the background color to be shown when checkbox is active */ .main input:active ~ .geekmark { background-color: red; } /* Specify the background color to be shown when checkbox is checked */ .main input:checked ~ .geekmark { background-color: green; } /* Checkmark to be shown in checkbox */ /* It is not be shown when not checked */ .geekmark:after { content: \"\"; position: absolute; display: none; } /* Display checkmark when checked */ .main input:checked ~ .geekmark:after { display: block; } /* Styling the checkmark using webkit */ /* Rotated the rectangle by 45 degree and showing only two border to make it look like a tickmark */ .main .geekmark:after { left: 8px; bottom: 5px; width: 6px; height: 12px; border: solid white; border-width: 0 4px 4px 0; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); } </style></head> <body> <h1 style=\"color:green;\"> Best Computer Science Platform </h1> <label class=\"main\">CodeX <input type=\"checkbox\"> <span class=\"geekmark\"></span> </label> <label class=\"main\">GeeksforGeeks <input type=\"checkbox\" checked=\"checked\"> <span class=\"geekmark\"></span> </label> <label class=\"main\">CodeY <input type=\"checkbox\"> <span class=\"geekmark\"></span> </label></body></html> ", "e": 28190, "s": 25646, "text": null }, { "code": null, "e": 28198, "s": 28190, "text": "Output:" }, { "code": null, "e": 28204, "s": 28198, "text": "Note:" }, { "code": null, "e": 28308, "s": 28204, "text": "“~” is the sibling combinator which selects all the elements which are preceded by the former selector." }, { "code": null, "e": 28466, "s": 28308, "text": "“:hover” is used to style the checkbox when user hovers over it. Notice that when the mouse pointer move over the checkbox the color of it changes to yellow." }, { "code": null, "e": 28620, "s": 28466, "text": "“:active” is used to style the checkbox when it is active. Notice that when click the checkbox it will first notice a red color and then the green color." }, { "code": null, "e": 28698, "s": 28620, "text": "Example 2: Consider another example with a bit modified design of check-mark." }, { "code": "<!DOCTYPE html><html> <head> <title> Style a checkbox using CSS </title> <style> .script { display: block; position: relative; padding-left: 45px; margin-bottom: 15px; cursor: pointer; font-size: 20px; } /* Hide the default checkbox */ input[type=checkbox] { visibility: hidden; } /* creating a custom checkbox based on demand */ .geekmark { position: absolute; top: 0; left: 0; height: 25px; width: 25px; background-color: green; } /* specify the background color to be shown when hovering over checkbox */ .script:hover input ~ .geekmark { background-color: yellow; } /* specify the background color to be shown when checkbox is active */ .script input:active ~ .geekmark { background-color: red; } /* specify the background color to be shown when checkbox is checked */ .script input:checked ~ .geekmark { background-color: green; } /* checkmark to be shown in checkbox */ /* It is not be shown when not checked */ .geekmark:after { content: \"\"; position: absolute; display: none; } /* display checkmark when checked */ .script input:checked ~ .geekmark:after { display: block; } /* styling the checkmark using webkit */ /* creating a square to be the sign of checkmark */ .script .geekmark:after { left: 6px; bottom: 5px; width: 6px; height: 6px; border: solid white; border-width: 4px 4px 4px 4px; } </style></head> <body> <h1>Is GeeksforGeeks Useful?</h1> <label class=\"script\" style = \"color:green;\"> Yes <input type=\"checkbox\"> <span class=\"geekmark\"></span> </label> <label class=\"script\" style = \"color:green;\"> Absolutely Yes <input type=\"checkbox\" checked=\"checked\"> <span class=\"geekmark\"></span> </label></body> </html> ", "e": 31058, "s": 28698, "text": null }, { "code": null, "e": 31066, "s": 31058, "text": "Output:" }, { "code": null, "e": 31252, "s": 31066, "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": 31261, "s": 31252, "text": "CSS-Misc" }, { "code": null, "e": 31268, "s": 31261, "text": "Picked" }, { "code": null, "e": 31272, "s": 31268, "text": "CSS" }, { "code": null, "e": 31289, "s": 31272, "text": "Web Technologies" }, { "code": null, "e": 31387, "s": 31289, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31396, "s": 31387, "text": "Comments" }, { "code": null, "e": 31409, "s": 31396, "text": "Old Comments" }, { "code": null, "e": 31471, "s": 31409, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31521, "s": 31471, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 31579, "s": 31521, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 31627, "s": 31579, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 31664, "s": 31627, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 31720, "s": 31664, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31753, "s": 31720, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31815, "s": 31753, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31858, "s": 31815, "text": "How to fetch data from an API in ReactJS ?" } ]
How to plot 4D scatter-plot with custom colours and cutom area size in Python Matplotlib?
Scatter-plot are very useful when representing the data with two dimensions to verify whether there's any relationship between two variables. A scatter plot is chart where the data is represented as dots with X and Y values. 1. Install matplotlib by following command. pip install matplotlib 2. Import matplotlib import matplotlib.pyplot as plt tennis_stats = (('Federer', 20),('Nadal', 20),('Djokovic', 17),('Sampras', 14),('Emerson', 12),('laver', 11),('Murray', 3),('Wawrinka', 3),('Zverev', 0),('Theim', 1),('Medvedev',0),('Tsitsipas', 0),('Dimitrov', 0),('Rublev', 0)) 3. Next step is to prepare the data in any array format. We can also read the data from database or from a spreadsheets and format the data in below format. titles = [title for player, title in tennis_stats] players = [player for player, title in tennis_stats] 4. The parameters for .scatter, as with other methods of matplotlib, require an array of X and Y values. *Note -* X and Y values both need to be the same size and also the data is by default converted into a float. plt.scatter(titles, players) <matplotlib.collections.PathCollection at 0x28df3684ac0> 5. Ohh, my GrandSlam titles plotted on x-axis is a float. I will convert them to integer and also add a title for x-axis and y-axis in below function. The axis formatter will be overwritten with .set_major_formatter. from matplotlib.ticker import FuncFormatter def format_titles(title, pos): return '{}'.format(int(title)) plt.gca().xaxis.set_major_formatter(FuncFormatter(format_titles)) plt.xlabel('Grandslam Titles') plt.ylabel('Tennis Player') plt.scatter(titles, players) 6. Do not think of scatter plots as just a 2D chart, a scatter plot can also add a third(area) and even a fourth dimension (color). Let me explain a bit what i will be doing below. First we will define the colors of your choice and then loop them through randomly picking up the colors and assiging it tour values. The alpha value makes each of the points semitransparent, allowing us to see where they overlap. The higher this value is, the less transparent the points will be. import random # define your own color scale. random_colors = ['#FF0000', '#FFFF00', '#FFFFF0', '#FFFFFF', '#00000F'] # set the number of colors similar to our data values color = [random.choice(random_colors) for _ in range(len(titles))] plt.scatter(titles, players, c=color, alpha=0.5) <matplotlib.collections.PathCollection at 0x28df2242d00> 7. Now I, let us make the size/area of representation a bit larger. import random # define your own color scale. random_colors = ['#FF0000', '#FFFF00', '#FFFFF0', '#FFFFFF', '#00000F'] # set the number of colors similar to our data values color = [random.choice(random_colors) for _ in range(len(titles))] # set the size size = [(50 * random.random()) ** 2 for _ in range(len(titles))] plt.gca().xaxis.set_major_formatter(FuncFormatter(format_titles)) plt.xlabel('Grandslam Titles') plt.ylabel('Tennis Player') plt.scatter(titles, players, c=color, s=size, alpha=0.1) <matplotlib.collections.PathCollection at 0x28df22e2430> Remember, the ultimate goal of a graph is to make data easy to understand. I have shown the basics of what you can do with scatter plots. You can do more even more for instance, making the color dependent on the size to make all the points of the same size the same color, which may help us distinguish between the data. Explore more - https://matplotlib.org/. Finally, putting everything together. # imports import matplotlib.pyplot as plt import random # preparing data.. tennis_stats = (('Federer', 20),('Nadal', 20),('Djokovic', 17),('Sampras', 14),('Emerson', 12),('laver', 11),('Murray', 3),('Wawrinka', 3),('Zverev', 0),('Theim', 1),('Medvedev',0),('Tsitsipas', 0),('Dimitrov', 0),('Rublev', 0)) titles = [title for player, title in tennis_stats] players = [player for player, title in tennis_stats] # custom function from matplotlib.ticker import FuncFormatter def format_titles(title, pos): return '{}'.format(int(title)) # define your own color scale. random_colors = ['#FF0000', '#FFFF00', '#FFFFF0', '#FFFFFF', '#00000F'] # set the number of colors similar to our data values color = [random.choice(random_colors) for _ in range(len(titles))] # set the size size = [(50 * random.random()) ** 2 for _ in range(len(titles))] plt.gca().xaxis.set_major_formatter(FuncFormatter(format_titles)) plt.xlabel('Grandslam Titles') plt.ylabel('Tennis Player') plt.scatter(titles, players, c=color, s=size, alpha=0.1) <matplotlib.collections.PathCollection at 0x2aa7676b670>
[ { "code": null, "e": 1287, "s": 1062, "text": "Scatter-plot are very useful when representing the data with two dimensions to verify whether there's any relationship between two variables. A scatter plot is chart where the data is represented as dots with X and Y values." }, { "code": null, "e": 1331, "s": 1287, "text": "1. Install matplotlib by following command." }, { "code": null, "e": 1354, "s": 1331, "text": "pip install matplotlib" }, { "code": null, "e": 1375, "s": 1354, "text": "2. Import matplotlib" }, { "code": null, "e": 1636, "s": 1375, "text": "import matplotlib.pyplot as plt\ntennis_stats = (('Federer', 20),('Nadal', 20),('Djokovic', 17),('Sampras', 14),('Emerson', 12),('laver', 11),('Murray', 3),('Wawrinka', 3),('Zverev', 0),('Theim', 1),('Medvedev',0),('Tsitsipas', 0),('Dimitrov', 0),('Rublev', 0))" }, { "code": null, "e": 1793, "s": 1636, "text": "3. Next step is to prepare the data in any array format. We can also read the data from database or from a spreadsheets and format the data in below format." }, { "code": null, "e": 1897, "s": 1793, "text": "titles = [title for player, title in tennis_stats]\nplayers = [player for player, title in tennis_stats]" }, { "code": null, "e": 2002, "s": 1897, "text": "4. The parameters for .scatter, as with other methods of matplotlib, require an array of X and Y values." }, { "code": null, "e": 2112, "s": 2002, "text": "*Note -* X and Y values both need to be the same size and also the data is by default converted into a float." }, { "code": null, "e": 2141, "s": 2112, "text": "plt.scatter(titles, players)" }, { "code": null, "e": 2198, "s": 2141, "text": "<matplotlib.collections.PathCollection at 0x28df3684ac0>" }, { "code": null, "e": 2415, "s": 2198, "text": "5. Ohh, my GrandSlam titles plotted on x-axis is a float. I will convert them to integer and also add a title for x-axis and y-axis in below function. The axis formatter will be overwritten with .set_major_formatter." }, { "code": null, "e": 2676, "s": 2415, "text": "from matplotlib.ticker import FuncFormatter\ndef format_titles(title, pos):\nreturn '{}'.format(int(title))\n\nplt.gca().xaxis.set_major_formatter(FuncFormatter(format_titles))\nplt.xlabel('Grandslam Titles')\nplt.ylabel('Tennis Player')\nplt.scatter(titles, players)" }, { "code": null, "e": 2857, "s": 2676, "text": "6. Do not think of scatter plots as just a 2D chart, a scatter plot can also add a third(area) and even a fourth dimension (color). Let me explain a bit what i will be doing below." }, { "code": null, "e": 2991, "s": 2857, "text": "First we will define the colors of your choice and then loop them through randomly picking up the colors and assiging it tour values." }, { "code": null, "e": 3155, "s": 2991, "text": "The alpha value makes each of the points semitransparent, allowing us to see where they overlap. The higher this value is, the less transparent the points will be." }, { "code": null, "e": 3445, "s": 3155, "text": "import random\n\n# define your own color scale.\nrandom_colors = ['#FF0000', '#FFFF00', '#FFFFF0', '#FFFFFF', '#00000F']\n\n# set the number of colors similar to our data values\ncolor = [random.choice(random_colors) for _ in range(len(titles))]\n\nplt.scatter(titles, players, c=color, alpha=0.5)" }, { "code": null, "e": 3502, "s": 3445, "text": "<matplotlib.collections.PathCollection at 0x28df2242d00>" }, { "code": null, "e": 3570, "s": 3502, "text": "7. Now I, let us make the size/area of representation a bit larger." }, { "code": null, "e": 4075, "s": 3570, "text": "import random\n\n# define your own color scale.\nrandom_colors = ['#FF0000', '#FFFF00', '#FFFFF0', '#FFFFFF', '#00000F']\n\n# set the number of colors similar to our data values\ncolor = [random.choice(random_colors) for _ in range(len(titles))]\n\n# set the size\nsize = [(50 * random.random()) ** 2 for _ in range(len(titles))]\n\nplt.gca().xaxis.set_major_formatter(FuncFormatter(format_titles))\nplt.xlabel('Grandslam Titles')\nplt.ylabel('Tennis Player')\n\nplt.scatter(titles, players, c=color, s=size, alpha=0.1)" }, { "code": null, "e": 4132, "s": 4075, "text": "<matplotlib.collections.PathCollection at 0x28df22e2430>" }, { "code": null, "e": 4207, "s": 4132, "text": "Remember, the ultimate goal of a graph is to make data easy to understand." }, { "code": null, "e": 4453, "s": 4207, "text": "I have shown the basics of what you can do with scatter plots. You can do more even more for instance, making the color dependent on the size to make all the points of the same size the same color, which may help us distinguish between the data." }, { "code": null, "e": 4493, "s": 4453, "text": "Explore more - https://matplotlib.org/." }, { "code": null, "e": 4531, "s": 4493, "text": "Finally, putting everything together." }, { "code": null, "e": 5557, "s": 4531, "text": "# imports\nimport matplotlib.pyplot as plt\nimport random\n\n# preparing data..\ntennis_stats = (('Federer', 20),('Nadal', 20),('Djokovic', 17),('Sampras', 14),('Emerson', 12),('laver', 11),('Murray', 3),('Wawrinka', 3),('Zverev', 0),('Theim', 1),('Medvedev',0),('Tsitsipas', 0),('Dimitrov', 0),('Rublev', 0))\n\ntitles = [title for player, title in tennis_stats]\nplayers = [player for player, title in tennis_stats]\n\n# custom function\nfrom matplotlib.ticker import FuncFormatter\ndef format_titles(title, pos):\nreturn '{}'.format(int(title))\n\n# define your own color scale.\nrandom_colors = ['#FF0000', '#FFFF00', '#FFFFF0', '#FFFFFF', '#00000F']\n\n# set the number of colors similar to our data values\ncolor = [random.choice(random_colors) for _ in range(len(titles))]\n\n# set the size\nsize = [(50 * random.random()) ** 2 for _ in range(len(titles))]\n\nplt.gca().xaxis.set_major_formatter(FuncFormatter(format_titles))\nplt.xlabel('Grandslam Titles')\nplt.ylabel('Tennis Player')\n\nplt.scatter(titles, players, c=color, s=size, alpha=0.1)" }, { "code": null, "e": 5614, "s": 5557, "text": "<matplotlib.collections.PathCollection at 0x2aa7676b670>" } ]
Android - WebView
WebView is a view that display web pages inside your application. You can also specify HTML string and can show it inside your application using WebView. WebView makes turns your application to a web application. In order to add WebView to your application, you have to add <WebView> element to your xml layout file. Its syntax is as follows − <WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> In order to use it, you have to get a reference of this view in Java file. To get a reference, create an object of the class WebView. Its syntax is − WebView browser = (WebView) findViewById(R.id.webview); In order to load a web url into the WebView, you need to call a method loadUrl(String url) of the WebView class, specifying the required url. Its syntax is: browser.loadUrl("http://www.tutorialspoint.com"); Apart from just loading url, you can have more control over your WebView by using the methods defined in WebView class. They are listed as follows − canGoBack() This method specifies the WebView has a back history item. canGoForward() This method specifies the WebView has a forward history item. clearHistory() This method will clear the WebView forward and backward history. destroy() This method destroy the internal state of WebView. findAllAsync(String find) This method find all instances of string and highlight them. getProgress() This method gets the progress of the current page. getTitle() This method return the title of the current page. getUrl() This method return the url of the current page. If you click on any link inside the webpage of the WebView, that page will not be loaded inside your WebView. In order to do that you need to extend your class from WebViewClient and override its method. Its syntax is − private class MyBrowser extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } Here is an example demonstrating the use of WebView Layout. It creates a basic web application that will ask you to specify a url and will load this url website in the WebView. To experiment with this example, you need to run this on an actual device on which internet is running. Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { Button b1; EditText ed1; private WebView wv1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.button); ed1=(EditText)findViewById(R.id.editText); wv1=(WebView)findViewById(R.id.webView); wv1.setWebViewClient(new MyBrowser()); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = ed1.getText().toString(); wv1.getSettings().setLoadsImagesAutomatically(true); wv1.getSettings().setJavaScriptEnabled(true); wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); wv1.loadUrl(url); } }); } private class MyBrowser extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } } Following is the modified content of the xml res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:text="WebView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview" android:textSize="35dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tutorials point" android:id="@+id/textView" android:layout_below="@+id/textview" android:layout_centerHorizontal="true" android:textColor="#ff7aff24" android:textSize="35dp" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText" android:hint="Enter Text" android:focusable="true" android:textColorHighlight="#ff7eff15" android:textColorHint="#ffff25e6" android:layout_marginTop="46dp" android:layout_below="@+id/imageView" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignRight="@+id/imageView" android:layout_alignEnd="@+id/imageView" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:src="@drawable/abc" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter" android:id="@+id/button" android:layout_alignTop="@+id/editText" android:layout_toRightOf="@+id/imageView" android:layout_toEndOf="@+id/imageView" /> <WebView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/webView" android:layout_below="@+id/button" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_alignParentBottom="true" /> </RelativeLayout> Following is the content of the res/values/string.xml. <resources> <string name="app_name">My Application</string> </resources> Following is the content of AndroidManifest.xml file. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sairamkrishna.myapplication" > <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your WebView application. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio will display as shown below Now just specify a url on the url field and press the browse button that appears,to launch the website. But before that please make sure that you are connected to the internet. After pressing the button, the following screen would appear − Note. By just changing the url in the url field, your WebView will open your desired website. Above image shows webview of tutorialspoint.com 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3820, "s": 3607, "text": "WebView is a view that display web pages inside your application. You can also specify HTML string and can show it inside your application using WebView. WebView makes turns your application to a web application." }, { "code": null, "e": 3951, "s": 3820, "text": "In order to add WebView to your application, you have to add <WebView> element to your xml layout file. Its syntax is as follows −" }, { "code": null, "e": 4129, "s": 3951, "text": "<WebView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/webview\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n/>" }, { "code": null, "e": 4279, "s": 4129, "text": "In order to use it, you have to get a reference of this view in Java file. To get a reference, create an object of the class WebView. Its syntax is −" }, { "code": null, "e": 4336, "s": 4279, "text": "WebView browser = (WebView) findViewById(R.id.webview);\n" }, { "code": null, "e": 4493, "s": 4336, "text": "In order to load a web url into the WebView, you need to call a method loadUrl(String url) of the WebView class, specifying the required url. Its syntax is:" }, { "code": null, "e": 4544, "s": 4493, "text": "browser.loadUrl(\"http://www.tutorialspoint.com\");\n" }, { "code": null, "e": 4693, "s": 4544, "text": "Apart from just loading url, you can have more control over your WebView by using the methods defined in WebView class. They are listed as follows −" }, { "code": null, "e": 4705, "s": 4693, "text": "canGoBack()" }, { "code": null, "e": 4764, "s": 4705, "text": "This method specifies the WebView has a back history item." }, { "code": null, "e": 4779, "s": 4764, "text": "canGoForward()" }, { "code": null, "e": 4841, "s": 4779, "text": "This method specifies the WebView has a forward history item." }, { "code": null, "e": 4856, "s": 4841, "text": "clearHistory()" }, { "code": null, "e": 4921, "s": 4856, "text": "This method will clear the WebView forward and backward history." }, { "code": null, "e": 4931, "s": 4921, "text": "destroy()" }, { "code": null, "e": 4982, "s": 4931, "text": "This method destroy the internal state of WebView." }, { "code": null, "e": 5008, "s": 4982, "text": "findAllAsync(String find)" }, { "code": null, "e": 5069, "s": 5008, "text": "This method find all instances of string and highlight them." }, { "code": null, "e": 5083, "s": 5069, "text": "getProgress()" }, { "code": null, "e": 5134, "s": 5083, "text": "This method gets the progress of the current page." }, { "code": null, "e": 5145, "s": 5134, "text": "getTitle()" }, { "code": null, "e": 5195, "s": 5145, "text": "This method return the title of the current page." }, { "code": null, "e": 5204, "s": 5195, "text": "getUrl()" }, { "code": null, "e": 5252, "s": 5204, "text": "This method return the url of the current page." }, { "code": null, "e": 5472, "s": 5252, "text": "If you click on any link inside the webpage of the WebView, that page will not be loaded inside your WebView. In order to do that you need to extend your class from WebViewClient and override its method. Its syntax is −" }, { "code": null, "e": 5655, "s": 5472, "text": "private class MyBrowser extends WebViewClient {\n @Override\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\n view.loadUrl(url);\n return true;\n }\n}" }, { "code": null, "e": 5832, "s": 5655, "text": "Here is an example demonstrating the use of WebView Layout. It creates a basic web application that will ask you to specify a url and will load this url website in the WebView." }, { "code": null, "e": 5936, "s": 5832, "text": "To experiment with this example, you need to run this on an actual device on which internet is running." }, { "code": null, "e": 6019, "s": 5936, "text": "Following is the content of the modified main activity file src/MainActivity.java." }, { "code": null, "e": 7349, "s": 6019, "text": "package com.example.sairamkrishna.myapplication;\nimport android.app.Activity;\nimport android.os.Bundle;\n\nimport android.view.View;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.Button;\nimport android.widget.EditText;\n\n\npublic class MainActivity extends Activity {\n Button b1;\n EditText ed1;\n\n private WebView wv1;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n b1=(Button)findViewById(R.id.button);\n ed1=(EditText)findViewById(R.id.editText);\n\n wv1=(WebView)findViewById(R.id.webView);\n wv1.setWebViewClient(new MyBrowser());\n\n b1.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String url = ed1.getText().toString();\n\n wv1.getSettings().setLoadsImagesAutomatically(true);\n wv1.getSettings().setJavaScriptEnabled(true);\n wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);\n wv1.loadUrl(url);\n }\n });\n }\n\n private class MyBrowser extends WebViewClient {\n @Override\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\n view.loadUrl(url);\n return true;\n }\n }\n}" }, { "code": null, "e": 7424, "s": 7349, "text": "Following is the modified content of the xml res/layout/activity_main.xml." }, { "code": null, "e": 10084, "s": 7424, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" tools:context=\".MainActivity\">\n \n <TextView android:text=\"WebView\" android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textview\"\n android:textSize=\"35dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point\"\n android:id=\"@+id/textView\"\n android:layout_below=\"@+id/textview\"\n android:layout_centerHorizontal=\"true\"\n android:textColor=\"#ff7aff24\"\n android:textSize=\"35dp\" />\n \n <EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText\"\n android:hint=\"Enter Text\"\n android:focusable=\"true\"\n android:textColorHighlight=\"#ff7eff15\"\n android:textColorHint=\"#ffff25e6\"\n android:layout_marginTop=\"46dp\"\n android:layout_below=\"@+id/imageView\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentStart=\"true\"\n android:layout_alignRight=\"@+id/imageView\"\n android:layout_alignEnd=\"@+id/imageView\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Enter\"\n android:id=\"@+id/button\"\n android:layout_alignTop=\"@+id/editText\"\n android:layout_toRightOf=\"@+id/imageView\"\n android:layout_toEndOf=\"@+id/imageView\" />\n \n <WebView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/webView\"\n android:layout_below=\"@+id/button\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentStart=\"true\"\n android:layout_alignParentRight=\"true\"\n android:layout_alignParentEnd=\"true\"\n android:layout_alignParentBottom=\"true\" />\n \n</RelativeLayout>" }, { "code": null, "e": 10139, "s": 10084, "text": "Following is the content of the res/values/string.xml." }, { "code": null, "e": 10215, "s": 10139, "text": "<resources>\n <string name=\"app_name\">My Application</string>\n</resources>" }, { "code": null, "e": 10269, "s": 10215, "text": "Following is the content of AndroidManifest.xml file." }, { "code": null, "e": 11033, "s": 10269, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n <uses-permission android:name=\"android.permission.INTERNET\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>" }, { "code": null, "e": 11235, "s": 11033, "text": "Let's try to run your WebView application. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio will display as shown below" }, { "code": null, "e": 11475, "s": 11235, "text": "Now just specify a url on the url field and press the browse button that appears,to launch the website. But before that please make sure that you are connected to the internet. After pressing the button, the following screen would appear −" }, { "code": null, "e": 11569, "s": 11475, "text": "Note. By just changing the url in the url field, your WebView will open your desired website." }, { "code": null, "e": 11617, "s": 11569, "text": "Above image shows webview of tutorialspoint.com" }, { "code": null, "e": 11652, "s": 11617, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 11664, "s": 11652, "text": " Aditya Dua" }, { "code": null, "e": 11699, "s": 11664, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 11713, "s": 11699, "text": " Sharad Kumar" }, { "code": null, "e": 11745, "s": 11713, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 11762, "s": 11745, "text": " Abhilash Nelson" }, { "code": null, "e": 11797, "s": 11762, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11814, "s": 11797, "text": " Abhilash Nelson" }, { "code": null, "e": 11849, "s": 11814, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11866, "s": 11849, "text": " Abhilash Nelson" }, { "code": null, "e": 11899, "s": 11866, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 11916, "s": 11899, "text": " Abhilash Nelson" }, { "code": null, "e": 11923, "s": 11916, "text": " Print" }, { "code": null, "e": 11934, "s": 11923, "text": " Add Notes" } ]
How to extract only first sub-element from a list in R?
To extract only first element from a list, we can use sapply function and access the first element with double square brackets. For example, if we have a list called LIST that contains 5 elements each containing 20 elements then the first sub-element can be extracted by using the command sapply(LIST,"[[",1). Consider the below data frame − Live Demo List1<-list(x1=rnorm(50),x2=rnorm(50),x3=rnorm(50),x4=rnorm(50)) List1 $x1 [1] 0.161249858 0.036092622 -1.044116113 1.711548086 0.643501331 [6] 0.382859773 -0.792628167 -0.711300381 -0.422021222 0.745896168 [11] 0.196128414 -0.298657403 0.634259386 -0.437460026 -0.806850028 [16] 0.137813278 -0.006745093 -1.919094377 0.419949298 1.050802517 [21] -0.162697580 -0.182900434 0.911989574 0.456641498 0.501877946 [26] 1.019027122 -0.069249412 1.001133923 1.816262055 -1.047496717 [31] 0.287840421 0.742884790 -0.427961572 0.119784063 0.383153950 [36] -1.665170199 -0.524123898 0.286375036 -0.708250387 -0.715677729 [41] -1.894281105 -0.202630787 -1.925498062 -1.487425694 2.111946755 [46] 1.629015061 0.650948453 0.682603315 1.106431496 1.450096730 $x2 [1] 0.75378773 0.05249257 0.39375180 -0.19774168 0.39574154 0.21836481 [7] 0.46384754 -0.71917075 -1.43891164 -0.69293833 -0.45450458 -0.65776233 [13] 2.46455531 1.12250992 0.87239212 0.44463664 -0.78254250 -0.62857243 [19] 0.12313098 -0.70724790 0.59767273 -0.13321977 0.04811096 -0.54943951 [25] -0.28317900 0.27360876 0.32741112 -0.76000268 0.71394849 -0.52250184 [31] -0.36304544 0.46658600 0.12323175 -0.79092922 -1.18324766 -0.11712640 [37] 0.04891661 -0.24084771 0.61827617 -0.97107224 0.12126594 1.05355407 [43] -0.63041363 -0.78451193 0.53188055 -0.25393411 0.81460637 1.16082247 [49] -0.79304579 -0.97305990 $x3 [1] -0.13624214 1.90010480 0.69451332 2.13687511 -0.23066909 1.64692306 [7] -0.14711053 0.44208938 0.35531069 1.06209464 -1.81956846 -1.12509450 [13] 1.43256682 -0.02674276 -2.03427910 0.55615959 -1.40908574 -0.23011933 [19] -0.08360304 -0.50644360 -0.90820700 -0.24305283 -1.54668354 2.13954075 [25] 0.81472415 0.33037344 0.44158303 0.94220437 0.15045454 0.01357773 [31] 0.01231589 0.26622480 0.38282127 0.67098995 0.40259268 -1.44272053 [37] -0.70237660 0.39312657 -0.99737047 1.64467399 -0.91297020 -0.86162356 [43] -1.58048278 -0.24313534 -0.60451908 -0.64249832 -0.84198760 0.55292228 [49] 0.51750276 0.63131623 $x4 [1] -0.69509383 -0.22673120 0.48862526 0.51866187 -0.18995667 0.38839070 [7] 0.40172376 0.24034591 1.43575563 -0.96673760 1.90413695 2.37696269 [13] -0.67572738 2.03771152 -0.76142607 -0.66753431 -0.08930211 -2.32531986 [19] 0.42993078 -0.12933197 -1.58200214 1.60530348 0.59869548 0.68581561 [25] -0.22293216 -0.09693568 -0.14181344 -0.26035230 0.27148301 -0.12910718 [31] 0.20186925 0.62118418 -0.04921471 -0.61318088 -0.61041790 -0.91881398 [37] -0.31245844 0.71726962 1.12492512 0.89030799 -0.90499379 0.12365878 [43] -0.37452970 -0.54310263 0.46503125 -0.42180015 1.47912529 0.53569710 [49] 1.19356765 -0.04135349 Extracting first sub-element in List1 − sapply(List1,"[[",1) x1 x2 x3 x4 0.1612499 0.7537877 -0.1362421 -0.6950938 Live Demo List2<-list(y1=sample(LETTERS[1:4],50,replace=TRUE),y2=sample(LETTERS[1:4],50,replace=TRUE),y3=sample(LETTERS[1:4],50,replace=TRUE),y4=sample(LETTERS[1:4],50,replace=TRUE)) List2 $y1 [1] "B" "C" "A" "C" "B" "D" "A" "C" "D" "B" "D" "C" "B" "D" "B" "A" "C" "A" "C" [20] "C" "A" "D" "B" "C" "B" "B" "C" "D" "D" "D" "C" "B" "B" "B" "B" "B" "C" "D" [39] "D" "C" "A" "D" "B" "C" "D" "D" "D" "C" "D" "C" $y2 [1] "B" "A" "B" "C" "A" "B" "A" "A" "A" "C" "C" "A" "D" "A" "C" "B" "A" "A" "C" [20] "A" "B" "B" "A" "A" "D" "D" "A" "D" "C" "C" "A" "D" "C" "A" "B" "C" "D" "A" [39] "C" "D" "B" "A" "D" "C" "A" "C" "D" "A" "B" "A" $y3 [1] "C" "B" "A" "D" "B" "B" "D" "A" "B" "A" "C" "B" "D" "B" "A" "B" "C" "D" "D" [20] "B" "C" "D" "C" "D" "D" "D" "C" "B" "C" "D" "C" "D" "D" "C" "B" "C" "A" "D" [39] "A" "A" "B" "B" "A" "C" "A" "D" "A" "D" "D" "A" $y4 [1] "D" "D" "D" "C" "D" "B" "C" "B" "D" "D" "A" "D" "D" "D" "D" "B" "D" "C" "A" [20] "D" "D" "D" "B" "D" "A" "C" "C" "D" "D" "D" "B" "B" "A" "D" "C" "C" "C" "D" [39] "B" "D" "A" "C" "D" "D" "A" "B" "A" "D" "C" "B" Extracting first sub-element in List2 − sapply(List2,"[[",1) y1 y2 y3 y4 "B" "B" "C" "D"
[ { "code": null, "e": 1372, "s": 1062, "text": "To extract only first element from a list, we can use sapply function and access the first element with double square brackets. For example, if we have a list called LIST that contains 5 elements each containing 20 elements then the first sub-element can be extracted by using the command sapply(LIST,\"[[\",1)." }, { "code": null, "e": 1404, "s": 1372, "text": "Consider the below data frame −" }, { "code": null, "e": 1415, "s": 1404, "text": " Live Demo" }, { "code": null, "e": 1486, "s": 1415, "text": "List1<-list(x1=rnorm(50),x2=rnorm(50),x3=rnorm(50),x4=rnorm(50))\nList1" }, { "code": null, "e": 4026, "s": 1486, "text": "$x1\n[1] 0.161249858 0.036092622 -1.044116113 1.711548086 0.643501331\n[6] 0.382859773 -0.792628167 -0.711300381 -0.422021222 0.745896168\n[11] 0.196128414 -0.298657403 0.634259386 -0.437460026 -0.806850028\n[16] 0.137813278 -0.006745093 -1.919094377 0.419949298 1.050802517\n[21] -0.162697580 -0.182900434 0.911989574 0.456641498 0.501877946\n[26] 1.019027122 -0.069249412 1.001133923 1.816262055 -1.047496717\n[31] 0.287840421 0.742884790 -0.427961572 0.119784063 0.383153950\n[36] -1.665170199 -0.524123898 0.286375036 -0.708250387 -0.715677729\n[41] -1.894281105 -0.202630787 -1.925498062 -1.487425694 2.111946755\n[46] 1.629015061 0.650948453 0.682603315 1.106431496 1.450096730\n$x2\n[1] 0.75378773 0.05249257 0.39375180 -0.19774168 0.39574154 0.21836481\n[7] 0.46384754 -0.71917075 -1.43891164 -0.69293833 -0.45450458 -0.65776233\n[13] 2.46455531 1.12250992 0.87239212 0.44463664 -0.78254250 -0.62857243\n[19] 0.12313098 -0.70724790 0.59767273 -0.13321977 0.04811096 -0.54943951\n[25] -0.28317900 0.27360876 0.32741112 -0.76000268 0.71394849 -0.52250184\n[31] -0.36304544 0.46658600 0.12323175 -0.79092922 -1.18324766 -0.11712640\n[37] 0.04891661 -0.24084771 0.61827617 -0.97107224 0.12126594 1.05355407\n[43] -0.63041363 -0.78451193 0.53188055 -0.25393411 0.81460637 1.16082247\n[49] -0.79304579 -0.97305990\n$x3\n[1] -0.13624214 1.90010480 0.69451332 2.13687511 -0.23066909 1.64692306\n[7] -0.14711053 0.44208938 0.35531069 1.06209464 -1.81956846 -1.12509450\n[13] 1.43256682 -0.02674276 -2.03427910 0.55615959 -1.40908574 -0.23011933\n[19] -0.08360304 -0.50644360 -0.90820700 -0.24305283 -1.54668354 2.13954075\n[25] 0.81472415 0.33037344 0.44158303 0.94220437 0.15045454 0.01357773\n[31] 0.01231589 0.26622480 0.38282127 0.67098995 0.40259268 -1.44272053\n[37] -0.70237660 0.39312657 -0.99737047 1.64467399 -0.91297020 -0.86162356\n[43] -1.58048278 -0.24313534 -0.60451908 -0.64249832 -0.84198760 0.55292228\n[49] 0.51750276 0.63131623\n$x4\n[1] -0.69509383 -0.22673120 0.48862526 0.51866187 -0.18995667 0.38839070\n[7] 0.40172376 0.24034591 1.43575563 -0.96673760 1.90413695 2.37696269\n[13] -0.67572738 2.03771152 -0.76142607 -0.66753431 -0.08930211 -2.32531986\n[19] 0.42993078 -0.12933197 -1.58200214 1.60530348 0.59869548 0.68581561\n[25] -0.22293216 -0.09693568 -0.14181344 -0.26035230 0.27148301 -0.12910718\n[31] 0.20186925 0.62118418 -0.04921471 -0.61318088 -0.61041790 -0.91881398\n[37] -0.31245844 0.71726962 1.12492512 0.89030799 -0.90499379 0.12365878\n[43] -0.37452970 -0.54310263 0.46503125 -0.42180015 1.47912529 0.53569710\n[49] 1.19356765 -0.04135349" }, { "code": null, "e": 4066, "s": 4026, "text": "Extracting first sub-element in List1 −" }, { "code": null, "e": 4087, "s": 4066, "text": "sapply(List1,\"[[\",1)" }, { "code": null, "e": 4141, "s": 4087, "text": "x1 x2 x3 x4\n0.1612499 0.7537877 -0.1362421 -0.6950938" }, { "code": null, "e": 4152, "s": 4141, "text": " Live Demo" }, { "code": null, "e": 4331, "s": 4152, "text": "List2<-list(y1=sample(LETTERS[1:4],50,replace=TRUE),y2=sample(LETTERS[1:4],50,replace=TRUE),y3=sample(LETTERS[1:4],50,replace=TRUE),y4=sample(LETTERS[1:4],50,replace=TRUE))\nList2" }, { "code": null, "e": 5203, "s": 4331, "text": "$y1\n[1] \"B\" \"C\" \"A\" \"C\" \"B\" \"D\" \"A\" \"C\" \"D\" \"B\" \"D\" \"C\" \"B\" \"D\" \"B\" \"A\" \"C\" \"A\" \"C\"\n[20] \"C\" \"A\" \"D\" \"B\" \"C\" \"B\" \"B\" \"C\" \"D\" \"D\" \"D\" \"C\" \"B\" \"B\" \"B\" \"B\" \"B\" \"C\" \"D\"\n[39] \"D\" \"C\" \"A\" \"D\" \"B\" \"C\" \"D\" \"D\" \"D\" \"C\" \"D\" \"C\"\n$y2\n[1] \"B\" \"A\" \"B\" \"C\" \"A\" \"B\" \"A\" \"A\" \"A\" \"C\" \"C\" \"A\" \"D\" \"A\" \"C\" \"B\" \"A\" \"A\" \"C\"\n[20] \"A\" \"B\" \"B\" \"A\" \"A\" \"D\" \"D\" \"A\" \"D\" \"C\" \"C\" \"A\" \"D\" \"C\" \"A\" \"B\" \"C\" \"D\" \"A\"\n[39] \"C\" \"D\" \"B\" \"A\" \"D\" \"C\" \"A\" \"C\" \"D\" \"A\" \"B\" \"A\"\n$y3\n[1] \"C\" \"B\" \"A\" \"D\" \"B\" \"B\" \"D\" \"A\" \"B\" \"A\" \"C\" \"B\" \"D\" \"B\" \"A\" \"B\" \"C\" \"D\" \"D\"\n[20] \"B\" \"C\" \"D\" \"C\" \"D\" \"D\" \"D\" \"C\" \"B\" \"C\" \"D\" \"C\" \"D\" \"D\" \"C\" \"B\" \"C\" \"A\" \"D\"\n[39] \"A\" \"A\" \"B\" \"B\" \"A\" \"C\" \"A\" \"D\" \"A\" \"D\" \"D\" \"A\"\n$y4\n[1] \"D\" \"D\" \"D\" \"C\" \"D\" \"B\" \"C\" \"B\" \"D\" \"D\" \"A\" \"D\" \"D\" \"D\" \"D\" \"B\" \"D\" \"C\" \"A\"\n[20] \"D\" \"D\" \"D\" \"B\" \"D\" \"A\" \"C\" \"C\" \"D\" \"D\" \"D\" \"B\" \"B\" \"A\" \"D\" \"C\" \"C\" \"C\" \"D\"\n[39] \"B\" \"D\" \"A\" \"C\" \"D\" \"D\" \"A\" \"B\" \"A\" \"D\" \"C\" \"B\"" }, { "code": null, "e": 5243, "s": 5203, "text": "Extracting first sub-element in List2 −" }, { "code": null, "e": 5264, "s": 5243, "text": "sapply(List2,\"[[\",1)" }, { "code": null, "e": 5292, "s": 5264, "text": "y1 y2 y3 y4\n\"B\" \"B\" \"C\" \"D\"" } ]
JavaScript code for recursive Fibonacci series
We have to write a recursive function fibonacci() that takes in a number n and returns an array with first n elements of fibonacci series. Therefore, let’s write the code for this function − const fibonacci = (n, res = [], count = 1, last = 0) => { if(n){ return fibonacci(n-1, res.concat(count), count+last, count); }; return res; }; console.log(fibonacci(8)); console.log(fibonacci(0)); console.log(fibonacci(1)); console.log(fibonacci(19)); The output in the console will be − [ 1, 1, 2, 3, 5, 8, 13, 21 ] [] [ 1 ] [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181 ]
[ { "code": null, "e": 1253, "s": 1062, "text": "We have to write a recursive function fibonacci() that takes in a number n and returns an array\nwith first n elements of fibonacci series. Therefore, let’s write the code for this function −" }, { "code": null, "e": 1521, "s": 1253, "text": "const fibonacci = (n, res = [], count = 1, last = 0) => {\n if(n){\n return fibonacci(n-1, res.concat(count), count+last, count);\n };\n return res;\n};\nconsole.log(fibonacci(8));\nconsole.log(fibonacci(0));\nconsole.log(fibonacci(1));\nconsole.log(fibonacci(19));" }, { "code": null, "e": 1557, "s": 1521, "text": "The output in the console will be −" }, { "code": null, "e": 1697, "s": 1557, "text": "[\n 1, 1, 2, 3,\n 5, 8, 13, 21\n]\n[]\n[ 1 ]\n[\n 1, 1, 2, 3, 5,\n 8, 13, 21, 34, 55,\n 89, 144, 233, 377, 610,\n 987, 1597, 2584, 4181\n]" } ]
Java Program to check for Integer overflow
To check for Integer overflow, we need to check the Integer.MAX_VALUE, which is the maximum value of an integer in Java. Let us see an example wherein integers are added and if the sum is more than the Integer.MAX_VALUE, then an exception is thrown. Live Demo public class Demo { public static void main(String[] args) { int val1 = 9898989; int val2 = 6789054; System.out.println("Value1: "+val1); System.out.println("Value2: "+val2); long sum = (long)val1 + (long)val2; if (sum > Integer.MAX_VALUE) { throw new ArithmeticException("Overflow!"); } // displaying sum System.out.println("Sum: "+(int)sum); } } Value1: 9898989 Value2: 6789054 Sum: 16688043 In the above example, we have taken the following two integers − int val1 = 9898989; int val2 = 6789054; Now we will cast and add them to a long. long sum = (long)val1 + (long)val2; If the result is more than the maximum value, then a exception is thrown. if (sum > Integer.MAX_VALUE) { throw new ArithmeticException("Overflow!"); }
[ { "code": null, "e": 1183, "s": 1062, "text": "To check for Integer overflow, we need to check the Integer.MAX_VALUE, which is the maximum value of an integer in Java." }, { "code": null, "e": 1312, "s": 1183, "text": "Let us see an example wherein integers are added and if the sum is more than the Integer.MAX_VALUE, then an exception is thrown." }, { "code": null, "e": 1323, "s": 1312, "text": " Live Demo" }, { "code": null, "e": 1740, "s": 1323, "text": "public class Demo {\n public static void main(String[] args) {\n int val1 = 9898989;\n int val2 = 6789054;\n System.out.println(\"Value1: \"+val1);\n System.out.println(\"Value2: \"+val2);\n long sum = (long)val1 + (long)val2;\n if (sum > Integer.MAX_VALUE) {\n throw new ArithmeticException(\"Overflow!\");\n }\n // displaying sum\n System.out.println(\"Sum: \"+(int)sum);\n }\n}" }, { "code": null, "e": 1786, "s": 1740, "text": "Value1: 9898989\nValue2: 6789054\nSum: 16688043" }, { "code": null, "e": 1851, "s": 1786, "text": "In the above example, we have taken the following two integers −" }, { "code": null, "e": 1891, "s": 1851, "text": "int val1 = 9898989;\nint val2 = 6789054;" }, { "code": null, "e": 1932, "s": 1891, "text": "Now we will cast and add them to a long." }, { "code": null, "e": 1968, "s": 1932, "text": "long sum = (long)val1 + (long)val2;" }, { "code": null, "e": 2042, "s": 1968, "text": "If the result is more than the maximum value, then a exception is thrown." }, { "code": null, "e": 2122, "s": 2042, "text": "if (sum > Integer.MAX_VALUE) {\n throw new ArithmeticException(\"Overflow!\");\n}" } ]
SciPy Sparse Data
Sparse data is data that has mostly unused elements (elements that don't carry any information ). It can be an array like this one: [1, 0, 2, 0, 0, 3, 0, 0, 0, 0, 0, 0] Sparse Data: is a data set where most of the item values are zero. Dense Array: is the opposite of a sparse array: most of the values are not zero. In scientific computing, when we are dealing with partial derivatives in linear algebra we will come across sparse data. SciPy has a module, scipy.sparse that provides functions to deal with sparse data. There are primarily two types of sparse matrices that we use: CSC - Compressed Sparse Column. For efficient arithmetic, fast column slicing. CSR - Compressed Sparse Row. For fast row slicing, faster matrix vector products We will use the CSR matrix in this tutorial. We can create CSR matrix by passing an arrray into function scipy.sparse.csr_matrix(). Create a CSR matrix from an array: The example above returns: (0, 5) 1 (0, 6) 1 (0, 8) 2 From the result we can see that there are 3 items with value. The 1. item is in row 0 position 5 and has the value 1. The 2. item is in row 0 position 6 and has the value 1. The 3. item is in row 0 position 8 and has the value 2. Viewing stored data (not the zero items) with the data property: Counting nonzeros with the count_nonzero() method: Removing zero-entries from the matrix with the eliminate_zeros() method: Eliminating duplicate entries with the sum_duplicates() method: Eliminating duplicates by adding them: Converting from csr to csc with the tocsc() method: Note: Apart from the mentioned sparse specific operations, sparse matrices support all of the operations that normal matrices support e.g. reshaping, summing, arithemetic, broadcasting etc. Insert the missing method to print the number of values in the array that are NOT zeros: import numpy as np from scipy.sparse import csr_matrix arr = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 2]]) print(csr_matrix(arr).()) Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 98, "s": 0, "text": "Sparse data is data that has mostly unused elements (elements that don't carry any information )." }, { "code": null, "e": 132, "s": 98, "text": "It can be an array like this one:" }, { "code": null, "e": 169, "s": 132, "text": "[1, 0, 2, 0, 0, 3, 0, 0, 0, 0, 0, 0]" }, { "code": null, "e": 236, "s": 169, "text": "Sparse Data: is a data set where most of the item values are zero." }, { "code": null, "e": 317, "s": 236, "text": "Dense Array: is the opposite of a sparse array: most of the values are not zero." }, { "code": null, "e": 438, "s": 317, "text": "In scientific computing, when we are dealing with partial derivatives in linear algebra we will come across sparse data." }, { "code": null, "e": 521, "s": 438, "text": "SciPy has a module, scipy.sparse\nthat provides functions to deal with sparse data." }, { "code": null, "e": 583, "s": 521, "text": "There are primarily two types of sparse matrices that we use:" }, { "code": null, "e": 663, "s": 583, "text": "CSC - Compressed Sparse Column. For efficient arithmetic, \nfast column slicing." }, { "code": null, "e": 745, "s": 663, "text": "CSR - Compressed Sparse Row. For fast row slicing, faster \nmatrix vector products" }, { "code": null, "e": 790, "s": 745, "text": "We will use the CSR matrix in this tutorial." }, { "code": null, "e": 877, "s": 790, "text": "We can create CSR matrix by passing an arrray into function scipy.sparse.csr_matrix()." }, { "code": null, "e": 912, "s": 877, "text": "Create a CSR matrix from an array:" }, { "code": null, "e": 939, "s": 912, "text": "The example above returns:" }, { "code": null, "e": 975, "s": 939, "text": "\n (0, 5)\t1\n (0, 6)\t1\n (0, 8)\t2\n\n" }, { "code": null, "e": 1037, "s": 975, "text": "From the result we can see that there are 3 items with value." }, { "code": null, "e": 1095, "s": 1037, "text": "The 1. item is in row 0 position \n5 and has the value \n1." }, { "code": null, "e": 1153, "s": 1095, "text": "The 2. item is in row 0 position \n6 and has the value \n1." }, { "code": null, "e": 1211, "s": 1153, "text": "The 3. item is in row 0 position \n8 and has the value \n2." }, { "code": null, "e": 1276, "s": 1211, "text": "Viewing stored data (not the zero items) with the data property:" }, { "code": null, "e": 1327, "s": 1276, "text": "Counting nonzeros with the count_nonzero() method:" }, { "code": null, "e": 1400, "s": 1327, "text": "Removing zero-entries from the matrix with the eliminate_zeros() method:" }, { "code": null, "e": 1464, "s": 1400, "text": "Eliminating duplicate entries with the sum_duplicates() method:" }, { "code": null, "e": 1503, "s": 1464, "text": "Eliminating duplicates by adding them:" }, { "code": null, "e": 1555, "s": 1503, "text": "Converting from csr to csc with the tocsc() method:" }, { "code": null, "e": 1745, "s": 1555, "text": "Note: Apart from the mentioned sparse specific operations, sparse matrices support all of the operations that normal matrices support e.g. reshaping, summing, arithemetic, broadcasting etc." }, { "code": null, "e": 1834, "s": 1745, "text": "Insert the missing method to print the number of values in the array that are NOT zeros:" }, { "code": null, "e": 1968, "s": 1834, "text": "import numpy as np\nfrom scipy.sparse import csr_matrix\n\narr = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 2]])\n\nprint(csr_matrix(arr).())\n" }, { "code": null, "e": 1987, "s": 1968, "text": "Start the Exercise" }, { "code": null, "e": 2020, "s": 1987, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2062, "s": 2020, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2169, "s": 2062, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2188, "s": 2169, "text": "[email protected]" } ]
Assign Function to a Variable in Python - GeeksforGeeks
17 May, 2021 In this article, we are going to see how to assign a function to a variable in Python. In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Implementation Simply assign a function to the desired variable but without () i.e. just with the name of the function. If the variable is assigned with function along with the brackets (), None will be returned. Syntax: def func(): { .. } var=func var() var() Example: Python3 def a(): print("GFG") # assigning function to a variablevar=a # calling the variablevar() Output: GFG The following programs will help you understand better: Example 1: Python3 # defined functionx = 123 def sum(): x = 98 print(x) print(globals()['x']) # drivercodeprint(x) # assigning functionz = sum # invoke functionz()z() Output: 123 98 123 98 123 Example 2: parameterized function Python3 # function defineddef even_num(a): if a % 2 == 0: print("even number") else: print("odd number") # drivercode# assigning functionz = even_num # invoke function with argumentz(67)z(10)z(7) Output: odd number even number odd number Example 3: Python3 # function defineddef multiply_num(a): b = 40 r = a*b return r # drivercode# assigning functionz = multiply_num # invoke functionprint(z(6))print(z(10))print(z(100)) Output: 240 400 4000 anikaseth98 Python function-programs Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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 Create a Pandas DataFrame from Lists
[ { "code": null, "e": 23773, "s": 23745, "text": "\n17 May, 2021" }, { "code": null, "e": 24025, "s": 23773, "text": "In this article, we are going to see how to assign a function to a variable in Python. In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. " }, { "code": null, "e": 24040, "s": 24025, "text": "Implementation" }, { "code": null, "e": 24238, "s": 24040, "text": "Simply assign a function to the desired variable but without () i.e. just with the name of the function. If the variable is assigned with function along with the brackets (), None will be returned." }, { "code": null, "e": 24246, "s": 24238, "text": "Syntax:" }, { "code": null, "e": 24288, "s": 24246, "text": "def func():\n{\n..\n}\n\nvar=func\n\nvar()\nvar()" }, { "code": null, "e": 24297, "s": 24288, "text": "Example:" }, { "code": null, "e": 24305, "s": 24297, "text": "Python3" }, { "code": "def a(): print(\"GFG\") # assigning function to a variablevar=a # calling the variablevar()", "e": 24398, "s": 24305, "text": null }, { "code": null, "e": 24407, "s": 24398, "text": "Output: " }, { "code": null, "e": 24411, "s": 24407, "text": "GFG" }, { "code": null, "e": 24467, "s": 24411, "text": "The following programs will help you understand better:" }, { "code": null, "e": 24479, "s": 24467, "text": "Example 1: " }, { "code": null, "e": 24487, "s": 24479, "text": "Python3" }, { "code": "# defined functionx = 123 def sum(): x = 98 print(x) print(globals()['x']) # drivercodeprint(x) # assigning functionz = sum # invoke functionz()z()", "e": 24645, "s": 24487, "text": null }, { "code": null, "e": 24653, "s": 24645, "text": "Output:" }, { "code": null, "e": 24671, "s": 24653, "text": "123\n98\n123\n98\n123" }, { "code": null, "e": 24705, "s": 24671, "text": "Example 2: parameterized function" }, { "code": null, "e": 24713, "s": 24705, "text": "Python3" }, { "code": "# function defineddef even_num(a): if a % 2 == 0: print(\"even number\") else: print(\"odd number\") # drivercode# assigning functionz = even_num # invoke function with argumentz(67)z(10)z(7)", "e": 24922, "s": 24713, "text": null }, { "code": null, "e": 24930, "s": 24922, "text": "Output:" }, { "code": null, "e": 24964, "s": 24930, "text": "odd number\neven number\nodd number" }, { "code": null, "e": 24975, "s": 24964, "text": "Example 3:" }, { "code": null, "e": 24983, "s": 24975, "text": "Python3" }, { "code": "# function defineddef multiply_num(a): b = 40 r = a*b return r # drivercode# assigning functionz = multiply_num # invoke functionprint(z(6))print(z(10))print(z(100))", "e": 25159, "s": 24983, "text": null }, { "code": null, "e": 25167, "s": 25159, "text": "Output:" }, { "code": null, "e": 25180, "s": 25167, "text": "240\n400\n4000" }, { "code": null, "e": 25192, "s": 25180, "text": "anikaseth98" }, { "code": null, "e": 25217, "s": 25192, "text": "Python function-programs" }, { "code": null, "e": 25234, "s": 25217, "text": "Python-Functions" }, { "code": null, "e": 25241, "s": 25234, "text": "Python" }, { "code": null, "e": 25339, "s": 25241, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25348, "s": 25339, "text": "Comments" }, { "code": null, "e": 25361, "s": 25348, "text": "Old Comments" }, { "code": null, "e": 25396, "s": 25361, "text": "Read a file line by line in Python" }, { "code": null, "e": 25418, "s": 25396, "text": "Enumerate() in Python" }, { "code": null, "e": 25450, "s": 25418, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25480, "s": 25450, "text": "Iterate over a list in Python" }, { "code": null, "e": 25522, "s": 25480, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25548, "s": 25522, "text": "Python String | replace()" }, { "code": null, "e": 25591, "s": 25548, "text": "Python program to convert a list to string" }, { "code": null, "e": 25635, "s": 25591, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 25660, "s": 25635, "text": "sum() function in Python" } ]
How to get a bitmap from Url in Android app?
This example demonstrates how do I get a bitmap from Url in android app. 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" android:padding="8dp" android:orientation="vertical" tools:context=".MainActivity"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_gravity="center"> <ImageView android:layout_width="150dp" android:layout_height="150dp" android:layout_gravity="center" android:layout_margin="15dp" android:src="@drawable/image"/> </LinearLayout> <ImageView android:id="@+id/iMageView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:layout_margin="20sp"/> </LinearLayout> Step 3 – Copy and paste an image (.png/.jpg/.jpeg) into res/drawable Step 4 − Add the following code to src/MainActivity.java import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import java.io.IOException; import java.io.InputStream; public class MainActivity extends AppCompatActivity { Bitmap bitmap; ImageView image; String urlImage = "https://thumbs.dreamstime.com/z/hands-holding-blue-earth-cloud-sky" + "-elements-imag-background-image-furnished-nasa-61052787.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); image = findViewById(R.id.iMageView); new GetImageFromUrl(image).execute(urlImage); } public class GetImageFromUrl extends AsyncTask<String, Void, Bitmap>{ ImageView imageView; public GetImageFromUrl(ImageView img){ this.imageView = img; } @Override protected Bitmap doInBackground(String... url) { String stringUrl = url[0]; bitmap = null; InputStream inputStream; try { inputStream = new java.net.URL(stringUrl).openStream(); bitmap = BitmapFactory.decodeStream(inputStream); } catch (IOException e) { e.printStackTrace(); } return bitmap; } @Override protected void onPostExecute(Bitmap bitmap){ super.onPostExecute(bitmap); imageView.setImageBitmap(bitmap); } } } Step 5 - Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1135, "s": 1062, "text": "This example demonstrates how do I get a bitmap from Url in android app." }, { "code": null, "e": 1264, "s": 1135, "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": 1329, "s": 1264, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2298, "s": 1329, "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 android:padding=\"8dp\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n <LinearLayout\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"vertical\"\n android:layout_gravity=\"center\">\n <ImageView\n android:layout_width=\"150dp\"\n android:layout_height=\"150dp\"\n android:layout_gravity=\"center\"\n android:layout_margin=\"15dp\"\n android:src=\"@drawable/image\"/>\n </LinearLayout>\n <ImageView\n android:id=\"@+id/iMageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_gravity=\"center\"\n android:layout_margin=\"20sp\"/>\n</LinearLayout>" }, { "code": null, "e": 2367, "s": 2298, "text": "Step 3 – Copy and paste an image (.png/.jpg/.jpeg) into res/drawable" }, { "code": null, "e": 2424, "s": 2367, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3967, "s": 2424, "text": "import android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.os.AsyncTask;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.ImageView;\nimport java.io.IOException;\nimport java.io.InputStream;\npublic class MainActivity extends AppCompatActivity {\n Bitmap bitmap;\n ImageView image;\n String urlImage = \"https://thumbs.dreamstime.com/z/hands-holding-blue-earth-cloud-sky\" + \"-elements-imag-background-image-furnished-nasa-61052787.jpg\";\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n image = findViewById(R.id.iMageView);\n new GetImageFromUrl(image).execute(urlImage);\n }\n public class GetImageFromUrl extends AsyncTask<String, Void, Bitmap>{\n ImageView imageView;\n public GetImageFromUrl(ImageView img){\n this.imageView = img;\n }\n @Override\n protected Bitmap doInBackground(String... url) {\n String stringUrl = url[0];\n bitmap = null;\n InputStream inputStream;\n try {\n inputStream = new java.net.URL(stringUrl).openStream();\n bitmap = BitmapFactory.decodeStream(inputStream);\n } catch (IOException e) {\n e.printStackTrace();\n }\n return bitmap;\n }\n @Override\n protected void onPostExecute(Bitmap bitmap){\n super.onPostExecute(bitmap);\n imageView.setImageBitmap(bitmap);\n } \n }\n}" }, { "code": null, "e": 4022, "s": 3967, "text": "Step 5 - Add the following code to androidManifest.xml" }, { "code": null, "e": 4757, "s": 4022, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.INTERNET\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5105, "s": 4757, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click 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": 5146, "s": 5105, "text": "Click here to download the project code." } ]
ML | Feature Scaling - Part 1 - GeeksforGeeks
25 Aug, 2021 Feature Scaling is a technique to standardize the independent features present in the data in a fixed range. It is performed during the data pre-processing. Working: Given a data-set with features- Age, Salary, BHK Apartment with the data size of 5000 people, each having these independent data features. Each data point is labeled as: Class1- YES (means with the given Age, Salary, BHK Apartment feature value one can buy the property) Class2- NO (means with the given Age, Salary, BHK Apartment feature value one can’t buy the property). Using a dataset to train the model, one aims to build a model that can predict whether one can buy a property or not with given feature values. Once the model is trained, an N-dimensional (where N is the no. of features present in the dataset) graph with data points from the given dataset, can be created. The figure given below is an ideal representation of the model. As shown in the figure, star data points belong to Class1 – Yes and circles represent Class2 – No labels, and the model gets trained using these data points. Now a new data point (diamond as shown in the figure) is given and it has different independent values for the 3 features (Age, Salary, BHK Apartment) mentioned above. The model has to predict whether this data point belongs to Yes or No. Prediction of the class of new data points: The model calculates the distance of this data point from the centroid of each class group. Finally, this data point will belong to that class, which will have a minimum centroid distance from it. The distance can be calculated between centroid and data point using these methods- Euclidean Distance: It is the square root of the sum of squares of differences between the coordinates (feature values – Age, Salary, BHK Apartment) of data point and centroid of each class. This formula is given by the Pythagorean theorem. where x is Data Point value, y is Centroid value and k is no. of feature values, Example: given data set has k = 3 Manhattan Distance: It is calculated as the sum of absolute differences between the coordinates (feature values) of data point and centroid of each class. Minkowski Distance: It is a generalization of the above two methods. As shown in the figure, different values can be used for finding r. Need of Feature Scaling: The given data set contains 3 features – Age, Salary, BHK Apartment. Consider a range of 10- 60 for Age, 1 Lac- 40 Lacs for Salary, 1- 5 for BHK of Flat. All these features are independent of each other. Suppose the centroid of class 1 is [40, 22 Lacs, 3] and the data point to be predicted is [57, 33 Lacs, 2]. Using Manhattan Method, Distance = (|(40 - 57)| + |(2200000 - 3300000)| + |(3 - 2)|) It can be seen that the Salary feature will dominate all other features while predicting the class of the given data point and since all the features are independent of each other i.e. a person’s salary has no relation with his/her age or what requirement of the flat he/she has. This means that the model will always predict wrong. So, the simple solution to this problem is Feature Scaling. Feature Scaling Algorithms will scale Age, Salary, BHK in a fixed range say [-1, 1] or [0, 1]. And then no feature can dominate others. Pushpender007 Advanced Computer Subject Machine Learning Mathematical Mathematical Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments System Design Tutorial Copying Files to and from Docker Containers ML | Underfitting and Overfitting KDD Process in Data Mining Clustering in Machine Learning Agents in Artificial Intelligence Search Algorithms in AI Support Vector Machine Algorithm Elbow Method for optimal value of k in KMeans ML | Underfitting and Overfitting
[ { "code": null, "e": 24334, "s": 24306, "text": "\n25 Aug, 2021" }, { "code": null, "e": 24492, "s": 24334, "text": "Feature Scaling is a technique to standardize the independent features present in the data in a fixed range. It is performed during the data pre-processing. " }, { "code": null, "e": 24641, "s": 24492, "text": "Working: Given a data-set with features- Age, Salary, BHK Apartment with the data size of 5000 people, each having these independent data features. " }, { "code": null, "e": 24673, "s": 24641, "text": "Each data point is labeled as: " }, { "code": null, "e": 24774, "s": 24673, "text": "Class1- YES (means with the given Age, Salary, BHK Apartment feature value one can buy the property)" }, { "code": null, "e": 24877, "s": 24774, "text": "Class2- NO (means with the given Age, Salary, BHK Apartment feature value one can’t buy the property)." }, { "code": null, "e": 25022, "s": 24877, "text": "Using a dataset to train the model, one aims to build a model that can predict whether one can buy a property or not with given feature values. " }, { "code": null, "e": 25251, "s": 25022, "text": "Once the model is trained, an N-dimensional (where N is the no. of features present in the dataset) graph with data points from the given dataset, can be created. The figure given below is an ideal representation of the model. " }, { "code": null, "e": 25649, "s": 25251, "text": "As shown in the figure, star data points belong to Class1 – Yes and circles represent Class2 – No labels, and the model gets trained using these data points. Now a new data point (diamond as shown in the figure) is given and it has different independent values for the 3 features (Age, Salary, BHK Apartment) mentioned above. The model has to predict whether this data point belongs to Yes or No. " }, { "code": null, "e": 25975, "s": 25649, "text": "Prediction of the class of new data points: The model calculates the distance of this data point from the centroid of each class group. Finally, this data point will belong to that class, which will have a minimum centroid distance from it. The distance can be calculated between centroid and data point using these methods- " }, { "code": null, "e": 26331, "s": 25975, "text": "Euclidean Distance: It is the square root of the sum of squares of differences between the coordinates (feature values – Age, Salary, BHK Apartment) of data point and centroid of each class. This formula is given by the Pythagorean theorem. where x is Data Point value, y is Centroid value and k is no. of feature values, Example: given data set has k = 3" }, { "code": null, "e": 26488, "s": 26331, "text": "Manhattan Distance: It is calculated as the sum of absolute differences between the coordinates (feature values) of data point and centroid of each class. " }, { "code": null, "e": 26625, "s": 26488, "text": "Minkowski Distance: It is a generalization of the above two methods. As shown in the figure, different values can be used for finding r." }, { "code": null, "e": 26963, "s": 26625, "text": "Need of Feature Scaling: The given data set contains 3 features – Age, Salary, BHK Apartment. Consider a range of 10- 60 for Age, 1 Lac- 40 Lacs for Salary, 1- 5 for BHK of Flat. All these features are independent of each other. Suppose the centroid of class 1 is [40, 22 Lacs, 3] and the data point to be predicted is [57, 33 Lacs, 2]. " }, { "code": null, "e": 26988, "s": 26963, "text": "Using Manhattan Method, " }, { "code": null, "e": 27049, "s": 26988, "text": "Distance = (|(40 - 57)| + |(2200000 - 3300000)| + |(3 - 2)|)" }, { "code": null, "e": 27383, "s": 27049, "text": "It can be seen that the Salary feature will dominate all other features while predicting the class of the given data point and since all the features are independent of each other i.e. a person’s salary has no relation with his/her age or what requirement of the flat he/she has. This means that the model will always predict wrong. " }, { "code": null, "e": 27580, "s": 27383, "text": "So, the simple solution to this problem is Feature Scaling. Feature Scaling Algorithms will scale Age, Salary, BHK in a fixed range say [-1, 1] or [0, 1]. And then no feature can dominate others. " }, { "code": null, "e": 27596, "s": 27582, "text": "Pushpender007" }, { "code": null, "e": 27622, "s": 27596, "text": "Advanced Computer Subject" }, { "code": null, "e": 27639, "s": 27622, "text": "Machine Learning" }, { "code": null, "e": 27652, "s": 27639, "text": "Mathematical" }, { "code": null, "e": 27665, "s": 27652, "text": "Mathematical" }, { "code": null, "e": 27682, "s": 27665, "text": "Machine Learning" }, { "code": null, "e": 27780, "s": 27682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27789, "s": 27780, "text": "Comments" }, { "code": null, "e": 27802, "s": 27789, "text": "Old Comments" }, { "code": null, "e": 27825, "s": 27802, "text": "System Design Tutorial" }, { "code": null, "e": 27869, "s": 27825, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 27903, "s": 27869, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 27930, "s": 27903, "text": "KDD Process in Data Mining" }, { "code": null, "e": 27961, "s": 27930, "text": "Clustering in Machine Learning" }, { "code": null, "e": 27995, "s": 27961, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 28019, "s": 27995, "text": "Search Algorithms in AI" }, { "code": null, "e": 28052, "s": 28019, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28098, "s": 28052, "text": "Elbow Method for optimal value of k in KMeans" } ]
PHP | Serializing Data - GeeksforGeeks
23 Aug, 2019 Most often we need to store a complex array in the database or in a file from PHP. Some of us might have surely searched for some built-in function to accomplish this task. Complex arrays are arrays with elements of more than one data-types or array.But, we already have a handy solution to handle this situation. We don’t have to write our own function to convert the complex array to a formatted string. There are two popular methods of serializing variables. serialize() unserialize() We can serialize any data in PHP using the serialize() function. The serialize() function accepts a single parameter which is the data we want to serialize and returns a serialized string. Below program illustrate this: <?php // a complex array$myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // convert to a string$string = serialize($myvar); // printing the serialized dataecho $string; ?> Output: a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i: 0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";} From the above code, we have a variable with serialized data, $string . We can unserialize the value of the variable using unserialize() function to get back to the original value of the complex array, $myvar. Below program illustrate both serialize() and unserialize() functions: <?php // a complex array$myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // serialize the above data$string = serialize($myvar); // unserializing the data in $string$newvar = unserialize($string); // printing the unserialized data print_r($newvar); ?> Output: Array ( [0] => hello [1] => 42 [2] => Array ( [0] => 1 [1] => two ) [3] => apple ) This was the native PHP serialization method. However, since JSON has become so popular in recent years, they decided to add support for it in PHP 5.2. Now you can use the json_encode() and json_decode() functions as well for serializing and unserializing data in PHP respectively. Since the JSON format is text only, it can be easily sent to and from a server and can be used as a data format by any programming language. Lets have a look how to use json_encode() in PHP: <?php // a complex array$myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // serializing data$string = json_encode($myvar); // printing the serialized dataecho $string; ?> Output: ["hello",42,[1,"two"],"apple"] We can decode the data encoded in above program using the json_decode() function to get the original complex array. Below program illustrate this: <?php // a complex array$myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // serializing data$string = json_encode($myvar); // decoding the above encoded string$newvar = json_decode($string); // printing the decoded data print_r($newvar); ?> Output: Array ( [0] => hello [1] => 42 [2] => Array ( [0] => 1 [1] => two ) [3] => apple ) Note: JSON encoding and decoding is more compact, and best of all, compatible with javascript and many other languages. However, for complex objects, some information may be lost. Akanksha_Rai PHP-basics PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to fetch data from localserver database and display on HTML table using PHP ? How to run JavaScript from PHP? How to pass JavaScript variables to PHP ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23964, "s": 23936, "text": "\n23 Aug, 2019" }, { "code": null, "e": 24426, "s": 23964, "text": "Most often we need to store a complex array in the database or in a file from PHP. Some of us might have surely searched for some built-in function to accomplish this task. Complex arrays are arrays with elements of more than one data-types or array.But, we already have a handy solution to handle this situation. We don’t have to write our own function to convert the complex array to a formatted string. There are two popular methods of serializing variables." }, { "code": null, "e": 24438, "s": 24426, "text": "serialize()" }, { "code": null, "e": 24452, "s": 24438, "text": "unserialize()" }, { "code": null, "e": 24672, "s": 24452, "text": "We can serialize any data in PHP using the serialize() function. The serialize() function accepts a single parameter which is the data we want to serialize and returns a serialized string. Below program illustrate this:" }, { "code": "<?php // a complex array$myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // convert to a string$string = serialize($myvar); // printing the serialized dataecho $string; ?>", "e": 24867, "s": 24672, "text": null }, { "code": null, "e": 24875, "s": 24867, "text": "Output:" }, { "code": null, "e": 24957, "s": 24875, "text": "a:4:{i:0;s:5:\"hello\";i:1;i:42;i:2;a:2:{i:\n0;i:1;i:1;s:3:\"two\";}i:3;s:5:\"apple\";}\n" }, { "code": null, "e": 25167, "s": 24957, "text": "From the above code, we have a variable with serialized data, $string . We can unserialize the value of the variable using unserialize() function to get back to the original value of the complex array, $myvar." }, { "code": null, "e": 25238, "s": 25167, "text": "Below program illustrate both serialize() and unserialize() functions:" }, { "code": "<?php // a complex array$myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // serialize the above data$string = serialize($myvar); // unserializing the data in $string$newvar = unserialize($string); // printing the unserialized data print_r($newvar); ?>", "e": 25517, "s": 25238, "text": null }, { "code": null, "e": 25525, "s": 25517, "text": "Output:" }, { "code": null, "e": 25666, "s": 25525, "text": "Array\n(\n [0] => hello\n [1] => 42\n [2] => Array\n (\n [0] => 1\n [1] => two\n )\n\n [3] => apple\n)\n" }, { "code": null, "e": 25948, "s": 25666, "text": "This was the native PHP serialization method. However, since JSON has become so popular in recent years, they decided to add support for it in PHP 5.2. Now you can use the json_encode() and json_decode() functions as well for serializing and unserializing data in PHP respectively." }, { "code": null, "e": 26089, "s": 25948, "text": "Since the JSON format is text only, it can be easily sent to and from a server and can be used as a data format by any programming language." }, { "code": null, "e": 26139, "s": 26089, "text": "Lets have a look how to use json_encode() in PHP:" }, { "code": "<?php // a complex array$myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // serializing data$string = json_encode($myvar); // printing the serialized dataecho $string; ?>", "e": 26333, "s": 26139, "text": null }, { "code": null, "e": 26341, "s": 26333, "text": "Output:" }, { "code": null, "e": 26373, "s": 26341, "text": "[\"hello\",42,[1,\"two\"],\"apple\"]\n" }, { "code": null, "e": 26520, "s": 26373, "text": "We can decode the data encoded in above program using the json_decode() function to get the original complex array. Below program illustrate this:" }, { "code": "<?php // a complex array$myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // serializing data$string = json_encode($myvar); // decoding the above encoded string$newvar = json_decode($string); // printing the decoded data print_r($newvar); ?>", "e": 26787, "s": 26520, "text": null }, { "code": null, "e": 26795, "s": 26787, "text": "Output:" }, { "code": null, "e": 26936, "s": 26795, "text": "Array\n(\n [0] => hello\n [1] => 42\n [2] => Array\n (\n [0] => 1\n [1] => two\n )\n\n [3] => apple\n)\n" }, { "code": null, "e": 27116, "s": 26936, "text": "Note: JSON encoding and decoding is more compact, and best of all, compatible with javascript and many other languages. However, for complex objects, some information may be lost." }, { "code": null, "e": 27129, "s": 27116, "text": "Akanksha_Rai" }, { "code": null, "e": 27140, "s": 27129, "text": "PHP-basics" }, { "code": null, "e": 27144, "s": 27140, "text": "PHP" }, { "code": null, "e": 27161, "s": 27144, "text": "Web Technologies" }, { "code": null, "e": 27165, "s": 27161, "text": "PHP" }, { "code": null, "e": 27263, "s": 27165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27272, "s": 27263, "text": "Comments" }, { "code": null, "e": 27285, "s": 27272, "text": "Old Comments" }, { "code": null, "e": 27325, "s": 27285, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27370, "s": 27325, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27452, "s": 27370, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 27484, "s": 27452, "text": "How to run JavaScript from PHP?" }, { "code": null, "e": 27526, "s": 27484, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 27568, "s": 27526, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27601, "s": 27568, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27663, "s": 27601, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27706, "s": 27663, "text": "How to fetch data from an API in ReactJS ?" } ]
Another Twitter sentiment analysis with Python — Part 10 (Neural Network with Doc2Vec/Word2Vec/GloVe) | by Ricky Kim | Towards Data Science
This is the 10th part of my ongoing Twitter sentiment analysis project. You can find the previous posts from the below links. Part 1: Data cleaning Part 2: EDA, Data visualisation Part 3: Zipf’s Law, Data visualisation Part 4: Feature extraction (count vectorizer), N-gram, confusion matrix Part 5: Feature extraction (Tfidf vectorizer), machine learning model comparison, lexical approach Part 6: Doc2Vec Part 7: Phrase modeling + Doc2Vec Part 8: Dimensionality reduction (Chi2, PCA) Part 9: Neural Networks with Tfidf vectors In the previous post, I implemented neural network modelling with Tf-idf vectors, but found that with high-dimensional sparse data, neural network did not perform well. In this post, I will see if feeding document vectors from Doc2Vec models or word vectors is any different from Tf-idf vectors. *In addition to short code blocks I will attach, you can find the link for the whole Jupyter Notebook at the end of this post. Before I jump into neural network modelling with the vectors I got from Doc2Vec, I would like to give you some background on how I got these document vectors. I have implemented Doc2Vec using Gensim library in the 6th part of this series. There are three different methods used to train Doc2Vec. Distributed Bag of Words, Distributed Memory (Mean), Distributed Memory (Concatenation). These models were trained with 1.5 million tweets through 30 epochs and the output of the models are 100 dimension vectors for each tweet. After I got document vectors from each model, I have tried concatenating these (so the concatenated document vectors have 200 dimensions) in combination: DBOW + DMM, DBOW + DMC, and saw an improvement to the performance when compared with models with any single pure method. Using different methods of training and concatenating them to improve the performance has already been demonstrated by Le and Mikolov (2014) in their research paper. Finally, I have applied phrase modelling to detect bigram phrase and trigram phrase as a pre-step of Doc2Vec training and tried different combination across n-grams. When tested with a logistic regression model, I got the best performance result from ‘unigram DBOW + trigram DMM’ document vectors. I will first start by loading Gensim’s Doc2Vec, and define a function to extract document vectors, then load the doc2vec model I trained. When fed to a simple logistic regression, the concatenated document vectors (unigram DBOW + trigram DMM) yields 75.90% training set accuracy, and 75.76% validation set accuracy. I will try different numbers of hidden layers, hidden nodes to compare the performance. In the below code block, you see I first define the seed as “7” but not setting the random seed, “np.random.seed()” will be defined at the start of each model. This is for a reproducibility of various results from different model structures. *Side Note (reproducibility): To be honest, this took me a while to figure out. I first tried by setting the random seed before I import Keras, and ran one model after another. However, if I define the same model structure after it has run, I couldn’t get the same result. But I also realised if I restart the kernel, and re-run code blocks from start it gives me the same result as the last kernel. So I figured, after running a model the random seed changes, and that is the reason why I cannot get the same result with the same structure if I run them in the same kernel consecutively. Anyway, that is why I set the random seed every time I try a different model. For your information, I am running Keras with Theano backend, and only using CPU not GPU. If you are on the same setting, this should work. I explicitly specified backend as Theano by launching Jupyter Notebook in the command line as follows: “KERAS_BACKEND=theano jupyter notebook” Please note that not all of the dependencies loaded in the below cell has been used for this post, but imported for later use. Defining different model structures will be quite repetitive codes, so I will just give you two examples so that you can understand how to define model structures with Keras. After trying 12 different models with a range of hidden layers (from 1 to 3) and a range of hidden nodes for each hidden layer (64, 128, 256, 512), below is the result I got. Best validation accuracy (79.93%) is from “model_d2v_09” at epoch 7, which has 3 hidden layers of 256 hidden nodes for each hidden layer. Now I know which model gives me the best result, I will run the final model of “model_d2v_09”, but this time with callback functions in Keras. I was not quite familiar with callback functions in Keras before I received a comment in my previous post. After I got the comment, I did some digging and found all the useful functions in Keras callbacks. Thanks to @rcshubha for the comment. With my final model of Doc2Vec below, I used “checkpoint” and “earlystop”. You can set the “checkpoint” function with options, and with the below parameter setting, “checkpoint” will save the best performing model up until the point of running, and only if a new epoch outperforms the saved model it will save it as a new model. And “early_stop” I defined it as to monitor validation accuracy, and if it doesn’t outperform the best validation accuracy so far for 5 epochs, it will stop. If I evaluate the model I just run, it will give me the result as same as I got from the last epoch. model_d2v_09_es.evaluate(x=validation_vecs_ugdbow_tgdmm, y=y_validation) But if I load the saved model at the best epoch, then this model will give me the result at that epoch. from keras.models import load_modelloaded_model = load_model('d2v_09_best_weights.07-0.7993.hdf5')loaded_model.evaluate(x=validation_vecs_ugdbow_tgdmm, y=y_validation) If you remember the validation accuracy with the same vector representation of the tweets with a logistic regression model (75.76%), you can see that feeding the same information to neural networks yields a significantly better result. It’s amazing to see how neural network can boost the performance of dense vectors, but the best validation accuracy is still lower than the Tfidf vectors + logistic regression model, which gave me 82.92% validation accuracy. If you have read my posts on Doc2Vec, or familiar with Doc2Vec, you might know that you can also extract word vectors for each word from the trained Doc2Vec model. I will move on to Word2Vec, and try different methods to see if any of those can outperform the Doc2Vec result (79.93%), ultimately outperform the Tfidf + logistic regression model (82.92%). To make use of word vectors extracted from Doc2Vec model, I can no longer use the concatenated vectors of different n-grams, since they will not consist of the same vocabularies. Thus below, I load the model for unigram DMM and create concatenated vectors with unigram DBOW of 200 dimensions for each word in the vocabularies. What I will do first before I try neural networks with document representations computed from word vectors is that I will fit logistic regressions with various methods of document representation and with the one that gives me the best validation accuracy, I will finally define a neural network model. I will also give you the summary of result from all the different word vectors fit with logistic regression as a table. There could be a number of different ways to come up with document representational vectors with individual word vectors. One obvious choice is to average them. For every word in a tweet, see if trained Doc2Vec has word vector representation of the word, if so, sum them up throughout the document while counting how many words were detected as having word vectors, and finally by dividing the summed vector by the count you get the averaged word vector for the whole document which will have the same dimension (200 in this case) as the individual word vectors. Another method is just the sum of the word vectors without averaging them. This might distort the vector representation of the document if some tweets only have a few words in the Doc2Vec vocabulary and some tweets have most of the words in the Doc2Vec vocabulary. But I will try both summing and averaging and compare the results. The validation accuracy with averaged word vectors of unigram DBOW + unigram DMM is 71.74%, which is significantly lower than document vectors extracted from unigram DBOW + trigram DMM (75.76%), and also from the results I got from the 6th part of this series, I know that document vectors extracted from unigram DBOW + unigram DMM will give me 75.51% validation accuracy. I also tried scaling the vectors using ScikitLearn’s scale function and saw significant improvement in computation time and a slight improvement of the accuracy. Let’s see how summed word vectors perform compared to the averaged counterpart. The summation method gave me higher accuracy without scaling compared to the average method. But the simple logistic regression with the summed vectors took more than 3 hours to run. So again I tried scaling these vectors. Surprising! With scaling, logistic regression fitting only took 3 minutes! That’s quite a difference. Validation accuracies with scaled word vectors are 72.42% with averaging, 72.51% with summing. In the 5th part of this series, I have already explained what TF-IDF is. TF-IDF is a way of weighting each word by calculating the product of relative term frequency and inverse document frequency. Since it gives one scalar value for each word in the vocabulary, this can also be used as a weighting factor of each word vectors. Correa Jr. et al (2017) has implemented this Tf-idf weighting in their paper “NILC-USP at SemEval-2017 Task 4: A Multi-view Ensemble for Twitter Sentiment Analysis” In order to get the Tfidf value for each word, I first fit and transform the training set with TfidfVectorizer and create a dictionary containing “word”, “tfidf value” pairs. Also, I defined a function “get_w2v_general” to get either averaged word vectors or summed word vectors with given Word2Vec model. Finally, I calculate the multiplication of word vectors with corresponding Tfidf values. From below code, the Tfidf multiplication part took quite a bit of time. To be honest, I am still not sure why it took so long to compute the Tfidf weighting of the word vectors, but after 5 hours it finally finished computing. You can also see later that I tried another method of weighting but that took less than 10 seconds. If you have an answer to this, any insight would be appreciated. Then I can call “get_w2v_general” function in the same way I did with the above word vectors without weighting factors, then fit a logistic regression model. The validation accuracy for mean is 70.57%, for sum is 70.32%. The results are not what I expected, especially after 5 hours of waiting. By weighting word vectors with Tfidf values, the validation accuracy dropped around 2% both for averaging and summing. In the 3rd part of this series, I have defined a custom metric called “pos_normcdf_hmean”, which is a metric borrowed from the presentation by Jason Kessler in PyData 2017 Seattle. If you want to know more in detail about the calculation, you can either check my previous post or you can also watch Jason Kessler’s presentation. To give you a high-level intuition, by calculating harmonic mean of CDF(Cumulative Distribution Function) transformed values of term frequency rate within the whole document and the term frequency within a class, you can get a meaningful metric which shows how each word is related to a certain class. I have used this metric to visualise tokens in the 3rd part of the series, and also used this again to create custom lexicon to be used for classification purpose in the 5th part. I will use this again as a weighting factor for the word vectors and see how it affects the performance. The validation accuracy for mean is 73.27%, and for sum is 70.94%. Unlike Tfidf weighting, this time with custom weighting it actually gave me some performance boost when used with averaging method. But with summing, this weighting has performed no better than the word vectors without weighting. GloVe is another kind of word representation in vectors proposed by Pennington et al. (2014) from the Stanford NLP Group. The difference between Word2Vec and Glove is how the two models compute the word vectors. In Word2Vec, the word vectors you are getting is a kind of a by-product of a shallow neural network, when it tries to predict either centre word given surrounding words or vice versa. But with GloVe, the word vectors you are getting is the object matrix of GloVe model, and it calculates this using term co-occurrence matrix and dimensionality reduction. The good news is you can now easily load and use the pre-trained GloVe vectors from Gensim thanks to its latest update (Gensim 3.2.0). In addition to some pre-trained word vectors, new datasets are also added and this also can be easily downloaded using their downloader API. If you want to know more about this, please check this blog post by RaRe Technologies. The Stanford NLP Group has made their pre-trained GloVe vectors publicly available, and among them, there are GloVe vectors trained specifically with Tweets. This sounds like something definitely worth trying. They have four different versions of Tweet vectors each with different dimensions (25, 50, 100, 200) trained on 2 billion Tweets. You can find more detail on their website. For this post, I will use 200 dimensions pre-trained GloVe vectors. (You might need to update Gensim if your version of Gensim is lower than 3.2.0) By using pre-trained GloVe vectors, I can see that the validation accuracy significantly improved. So far the best validation accuracy was from the averaged word vectors with custom weighting, which gave me 73.27% accuracy, and compared to this, GloVe vectors yield 76.27%, 76.60% for average and sum respectively. With new updated Gensim, I can also load the famous pre-trained Google News word vectors. These word vectors are trained using Word2Vec model on Google News dataset (about 100 billion words) and published by Google. The model contains 300-dimensional vectors for 3 million words and phrases. You can find more detail in the Google project archive. The validation accuracy for mean is 74.96%, and for sum is 74.92%. Even though it gives me a better result than the word vectors extracted from custom trained Doc2Vec models, but it fails to outperform GloVe vectors. And the vector dimension is even larger in Google News word vectors. But, this is trained with Google News, and GloVe vector I used was trained specifically with Tweets, thus it is hard to compare each other directly. What if Word2Vec is specifically trained with Tweets? I know I have already tried word vectors I extracted from Doc2Vec models, but what if I train separate Word2Vec models? Even though Doc2Vec models gave good representational vectors of document level, would it be more efficiently learning word vectors if I train pure Word2Vec? In order to answer my own questions, I trained two Word2Vec models using CBOW (Continuous Bag Of Words) and Skip Gram models. In terms of parameter setting, I set the same parameters I used for Doc2Vec. size of vectors: 100 dimensions negative sampling: 5 window: 2 minimum word count: 2 alpha: 0.065 (decrease alpha by 0.002 per epoch) number of epochs: 30 With above settings, I defined CBOW model by passing “sg=0”, and Skip Gram model by passing “sg=1”. And once I get the results from two models, I concatenate vectors of two models for each word so that the concatenated vectors will have 200-dimensional representation of each word. Please note that in the 6th part, where I trained Doc2Vec, I used “LabeledSentence” function imported from Gensim. This has now been deprecated, thus for this post I used “TaggedDocument” function instead. The usage is the same. The concatenated vectors of unigram CBOW and unigram Skip Gram models has yielded 76.50%, 76.75% validation accuracy respectively with mean and sum method. These results are even higher than the results I got from GloVe vectors. But please do not confuse this as a general statement. This is an empirical finding in this particular setting. As a final step, I will apply the custom weighting I have implemented above and see if this affects the performance. Finally I get the best performing word vectors. Averaged word vectors (separately trained Word2Vec models) weighted with custom metric has yielded the best validation accuracy of 77.97%! Below is the table of all the results I tried above. The best performing word vectors with logistic regression was chosen to feed to a neural network model. This time I did not try various different architecture. Based on what I have observed during trials of different architectures with Doc2Vec document vectors, the best performing architecture was one with 3 hidden layers with 256 hidden nodes at each hidden layer.I will finally fit a neural network with early stopping and checkpoint so that I can save the best performing weights on validation accuracy. from keras.models import load_modelloaded_w2v_model = load_model('w2v_01_best_weights.10-0.8048.hdf5')loaded_w2v_model.evaluate(x=validation_w2v_final, y=y_validation) The best validation accuracy is 80.48%. Surprisingly this is even higher than the best accuracy I got by feeding document vectors to neural network models in the above. It took quite some time for me to try different settings, different calculations, but I learned some valuable lessons through all the trial and errors. Specifically trained Word2Vec with carefully engineered weighting can even outperform Doc2Vec in the classification task. In the next post, I will try more sophisticated neural network model, Convolutional Neural Network. Again I hope this will give me some boost of the performance. Thank you for reading, and you can find the Jupyter Notebook from the below link.
[ { "code": null, "e": 172, "s": 46, "text": "This is the 10th part of my ongoing Twitter sentiment analysis project. You can find the previous posts from the below links." }, { "code": null, "e": 194, "s": 172, "text": "Part 1: Data cleaning" }, { "code": null, "e": 226, "s": 194, "text": "Part 2: EDA, Data visualisation" }, { "code": null, "e": 265, "s": 226, "text": "Part 3: Zipf’s Law, Data visualisation" }, { "code": null, "e": 337, "s": 265, "text": "Part 4: Feature extraction (count vectorizer), N-gram, confusion matrix" }, { "code": null, "e": 436, "s": 337, "text": "Part 5: Feature extraction (Tfidf vectorizer), machine learning model comparison, lexical approach" }, { "code": null, "e": 452, "s": 436, "text": "Part 6: Doc2Vec" }, { "code": null, "e": 486, "s": 452, "text": "Part 7: Phrase modeling + Doc2Vec" }, { "code": null, "e": 531, "s": 486, "text": "Part 8: Dimensionality reduction (Chi2, PCA)" }, { "code": null, "e": 574, "s": 531, "text": "Part 9: Neural Networks with Tfidf vectors" }, { "code": null, "e": 870, "s": 574, "text": "In the previous post, I implemented neural network modelling with Tf-idf vectors, but found that with high-dimensional sparse data, neural network did not perform well. In this post, I will see if feeding document vectors from Doc2Vec models or word vectors is any different from Tf-idf vectors." }, { "code": null, "e": 997, "s": 870, "text": "*In addition to short code blocks I will attach, you can find the link for the whole Jupyter Notebook at the end of this post." }, { "code": null, "e": 1236, "s": 997, "text": "Before I jump into neural network modelling with the vectors I got from Doc2Vec, I would like to give you some background on how I got these document vectors. I have implemented Doc2Vec using Gensim library in the 6th part of this series." }, { "code": null, "e": 1962, "s": 1236, "text": "There are three different methods used to train Doc2Vec. Distributed Bag of Words, Distributed Memory (Mean), Distributed Memory (Concatenation). These models were trained with 1.5 million tweets through 30 epochs and the output of the models are 100 dimension vectors for each tweet. After I got document vectors from each model, I have tried concatenating these (so the concatenated document vectors have 200 dimensions) in combination: DBOW + DMM, DBOW + DMC, and saw an improvement to the performance when compared with models with any single pure method. Using different methods of training and concatenating them to improve the performance has already been demonstrated by Le and Mikolov (2014) in their research paper." }, { "code": null, "e": 2260, "s": 1962, "text": "Finally, I have applied phrase modelling to detect bigram phrase and trigram phrase as a pre-step of Doc2Vec training and tried different combination across n-grams. When tested with a logistic regression model, I got the best performance result from ‘unigram DBOW + trigram DMM’ document vectors." }, { "code": null, "e": 2398, "s": 2260, "text": "I will first start by loading Gensim’s Doc2Vec, and define a function to extract document vectors, then load the doc2vec model I trained." }, { "code": null, "e": 2576, "s": 2398, "text": "When fed to a simple logistic regression, the concatenated document vectors (unigram DBOW + trigram DMM) yields 75.90% training set accuracy, and 75.76% validation set accuracy." }, { "code": null, "e": 2906, "s": 2576, "text": "I will try different numbers of hidden layers, hidden nodes to compare the performance. In the below code block, you see I first define the seed as “7” but not setting the random seed, “np.random.seed()” will be defined at the start of each model. This is for a reproducibility of various results from different model structures." }, { "code": null, "e": 3856, "s": 2906, "text": "*Side Note (reproducibility): To be honest, this took me a while to figure out. I first tried by setting the random seed before I import Keras, and ran one model after another. However, if I define the same model structure after it has run, I couldn’t get the same result. But I also realised if I restart the kernel, and re-run code blocks from start it gives me the same result as the last kernel. So I figured, after running a model the random seed changes, and that is the reason why I cannot get the same result with the same structure if I run them in the same kernel consecutively. Anyway, that is why I set the random seed every time I try a different model. For your information, I am running Keras with Theano backend, and only using CPU not GPU. If you are on the same setting, this should work. I explicitly specified backend as Theano by launching Jupyter Notebook in the command line as follows: “KERAS_BACKEND=theano jupyter notebook”" }, { "code": null, "e": 3983, "s": 3856, "text": "Please note that not all of the dependencies loaded in the below cell has been used for this post, but imported for later use." }, { "code": null, "e": 4158, "s": 3983, "text": "Defining different model structures will be quite repetitive codes, so I will just give you two examples so that you can understand how to define model structures with Keras." }, { "code": null, "e": 4471, "s": 4158, "text": "After trying 12 different models with a range of hidden layers (from 1 to 3) and a range of hidden nodes for each hidden layer (64, 128, 256, 512), below is the result I got. Best validation accuracy (79.93%) is from “model_d2v_09” at epoch 7, which has 3 hidden layers of 256 hidden nodes for each hidden layer." }, { "code": null, "e": 5344, "s": 4471, "text": "Now I know which model gives me the best result, I will run the final model of “model_d2v_09”, but this time with callback functions in Keras. I was not quite familiar with callback functions in Keras before I received a comment in my previous post. After I got the comment, I did some digging and found all the useful functions in Keras callbacks. Thanks to @rcshubha for the comment. With my final model of Doc2Vec below, I used “checkpoint” and “earlystop”. You can set the “checkpoint” function with options, and with the below parameter setting, “checkpoint” will save the best performing model up until the point of running, and only if a new epoch outperforms the saved model it will save it as a new model. And “early_stop” I defined it as to monitor validation accuracy, and if it doesn’t outperform the best validation accuracy so far for 5 epochs, it will stop." }, { "code": null, "e": 5445, "s": 5344, "text": "If I evaluate the model I just run, it will give me the result as same as I got from the last epoch." }, { "code": null, "e": 5518, "s": 5445, "text": "model_d2v_09_es.evaluate(x=validation_vecs_ugdbow_tgdmm, y=y_validation)" }, { "code": null, "e": 5622, "s": 5518, "text": "But if I load the saved model at the best epoch, then this model will give me the result at that epoch." }, { "code": null, "e": 5790, "s": 5622, "text": "from keras.models import load_modelloaded_model = load_model('d2v_09_best_weights.07-0.7993.hdf5')loaded_model.evaluate(x=validation_vecs_ugdbow_tgdmm, y=y_validation)" }, { "code": null, "e": 6251, "s": 5790, "text": "If you remember the validation accuracy with the same vector representation of the tweets with a logistic regression model (75.76%), you can see that feeding the same information to neural networks yields a significantly better result. It’s amazing to see how neural network can boost the performance of dense vectors, but the best validation accuracy is still lower than the Tfidf vectors + logistic regression model, which gave me 82.92% validation accuracy." }, { "code": null, "e": 6606, "s": 6251, "text": "If you have read my posts on Doc2Vec, or familiar with Doc2Vec, you might know that you can also extract word vectors for each word from the trained Doc2Vec model. I will move on to Word2Vec, and try different methods to see if any of those can outperform the Doc2Vec result (79.93%), ultimately outperform the Tfidf + logistic regression model (82.92%)." }, { "code": null, "e": 6933, "s": 6606, "text": "To make use of word vectors extracted from Doc2Vec model, I can no longer use the concatenated vectors of different n-grams, since they will not consist of the same vocabularies. Thus below, I load the model for unigram DMM and create concatenated vectors with unigram DBOW of 200 dimensions for each word in the vocabularies." }, { "code": null, "e": 7235, "s": 6933, "text": "What I will do first before I try neural networks with document representations computed from word vectors is that I will fit logistic regressions with various methods of document representation and with the one that gives me the best validation accuracy, I will finally define a neural network model." }, { "code": null, "e": 7355, "s": 7235, "text": "I will also give you the summary of result from all the different word vectors fit with logistic regression as a table." }, { "code": null, "e": 7918, "s": 7355, "text": "There could be a number of different ways to come up with document representational vectors with individual word vectors. One obvious choice is to average them. For every word in a tweet, see if trained Doc2Vec has word vector representation of the word, if so, sum them up throughout the document while counting how many words were detected as having word vectors, and finally by dividing the summed vector by the count you get the averaged word vector for the whole document which will have the same dimension (200 in this case) as the individual word vectors." }, { "code": null, "e": 8250, "s": 7918, "text": "Another method is just the sum of the word vectors without averaging them. This might distort the vector representation of the document if some tweets only have a few words in the Doc2Vec vocabulary and some tweets have most of the words in the Doc2Vec vocabulary. But I will try both summing and averaging and compare the results." }, { "code": null, "e": 8623, "s": 8250, "text": "The validation accuracy with averaged word vectors of unigram DBOW + unigram DMM is 71.74%, which is significantly lower than document vectors extracted from unigram DBOW + trigram DMM (75.76%), and also from the results I got from the 6th part of this series, I know that document vectors extracted from unigram DBOW + unigram DMM will give me 75.51% validation accuracy." }, { "code": null, "e": 8785, "s": 8623, "text": "I also tried scaling the vectors using ScikitLearn’s scale function and saw significant improvement in computation time and a slight improvement of the accuracy." }, { "code": null, "e": 8865, "s": 8785, "text": "Let’s see how summed word vectors perform compared to the averaged counterpart." }, { "code": null, "e": 9088, "s": 8865, "text": "The summation method gave me higher accuracy without scaling compared to the average method. But the simple logistic regression with the summed vectors took more than 3 hours to run. So again I tried scaling these vectors." }, { "code": null, "e": 9285, "s": 9088, "text": "Surprising! With scaling, logistic regression fitting only took 3 minutes! That’s quite a difference. Validation accuracies with scaled word vectors are 72.42% with averaging, 72.51% with summing." }, { "code": null, "e": 9779, "s": 9285, "text": "In the 5th part of this series, I have already explained what TF-IDF is. TF-IDF is a way of weighting each word by calculating the product of relative term frequency and inverse document frequency. Since it gives one scalar value for each word in the vocabulary, this can also be used as a weighting factor of each word vectors. Correa Jr. et al (2017) has implemented this Tf-idf weighting in their paper “NILC-USP at SemEval-2017 Task 4: A Multi-view Ensemble for Twitter Sentiment Analysis”" }, { "code": null, "e": 10567, "s": 9779, "text": "In order to get the Tfidf value for each word, I first fit and transform the training set with TfidfVectorizer and create a dictionary containing “word”, “tfidf value” pairs. Also, I defined a function “get_w2v_general” to get either averaged word vectors or summed word vectors with given Word2Vec model. Finally, I calculate the multiplication of word vectors with corresponding Tfidf values. From below code, the Tfidf multiplication part took quite a bit of time. To be honest, I am still not sure why it took so long to compute the Tfidf weighting of the word vectors, but after 5 hours it finally finished computing. You can also see later that I tried another method of weighting but that took less than 10 seconds. If you have an answer to this, any insight would be appreciated." }, { "code": null, "e": 10981, "s": 10567, "text": "Then I can call “get_w2v_general” function in the same way I did with the above word vectors without weighting factors, then fit a logistic regression model. The validation accuracy for mean is 70.57%, for sum is 70.32%. The results are not what I expected, especially after 5 hours of waiting. By weighting word vectors with Tfidf values, the validation accuracy dropped around 2% both for averaging and summing." }, { "code": null, "e": 11612, "s": 10981, "text": "In the 3rd part of this series, I have defined a custom metric called “pos_normcdf_hmean”, which is a metric borrowed from the presentation by Jason Kessler in PyData 2017 Seattle. If you want to know more in detail about the calculation, you can either check my previous post or you can also watch Jason Kessler’s presentation. To give you a high-level intuition, by calculating harmonic mean of CDF(Cumulative Distribution Function) transformed values of term frequency rate within the whole document and the term frequency within a class, you can get a meaningful metric which shows how each word is related to a certain class." }, { "code": null, "e": 11897, "s": 11612, "text": "I have used this metric to visualise tokens in the 3rd part of the series, and also used this again to create custom lexicon to be used for classification purpose in the 5th part. I will use this again as a weighting factor for the word vectors and see how it affects the performance." }, { "code": null, "e": 12194, "s": 11897, "text": "The validation accuracy for mean is 73.27%, and for sum is 70.94%. Unlike Tfidf weighting, this time with custom weighting it actually gave me some performance boost when used with averaging method. But with summing, this weighting has performed no better than the word vectors without weighting." }, { "code": null, "e": 12316, "s": 12194, "text": "GloVe is another kind of word representation in vectors proposed by Pennington et al. (2014) from the Stanford NLP Group." }, { "code": null, "e": 12761, "s": 12316, "text": "The difference between Word2Vec and Glove is how the two models compute the word vectors. In Word2Vec, the word vectors you are getting is a kind of a by-product of a shallow neural network, when it tries to predict either centre word given surrounding words or vice versa. But with GloVe, the word vectors you are getting is the object matrix of GloVe model, and it calculates this using term co-occurrence matrix and dimensionality reduction." }, { "code": null, "e": 13124, "s": 12761, "text": "The good news is you can now easily load and use the pre-trained GloVe vectors from Gensim thanks to its latest update (Gensim 3.2.0). In addition to some pre-trained word vectors, new datasets are also added and this also can be easily downloaded using their downloader API. If you want to know more about this, please check this blog post by RaRe Technologies." }, { "code": null, "e": 13507, "s": 13124, "text": "The Stanford NLP Group has made their pre-trained GloVe vectors publicly available, and among them, there are GloVe vectors trained specifically with Tweets. This sounds like something definitely worth trying. They have four different versions of Tweet vectors each with different dimensions (25, 50, 100, 200) trained on 2 billion Tweets. You can find more detail on their website." }, { "code": null, "e": 13655, "s": 13507, "text": "For this post, I will use 200 dimensions pre-trained GloVe vectors. (You might need to update Gensim if your version of Gensim is lower than 3.2.0)" }, { "code": null, "e": 13970, "s": 13655, "text": "By using pre-trained GloVe vectors, I can see that the validation accuracy significantly improved. So far the best validation accuracy was from the averaged word vectors with custom weighting, which gave me 73.27% accuracy, and compared to this, GloVe vectors yield 76.27%, 76.60% for average and sum respectively." }, { "code": null, "e": 14318, "s": 13970, "text": "With new updated Gensim, I can also load the famous pre-trained Google News word vectors. These word vectors are trained using Word2Vec model on Google News dataset (about 100 billion words) and published by Google. The model contains 300-dimensional vectors for 3 million words and phrases. You can find more detail in the Google project archive." }, { "code": null, "e": 14604, "s": 14318, "text": "The validation accuracy for mean is 74.96%, and for sum is 74.92%. Even though it gives me a better result than the word vectors extracted from custom trained Doc2Vec models, but it fails to outperform GloVe vectors. And the vector dimension is even larger in Google News word vectors." }, { "code": null, "e": 14807, "s": 14604, "text": "But, this is trained with Google News, and GloVe vector I used was trained specifically with Tweets, thus it is hard to compare each other directly. What if Word2Vec is specifically trained with Tweets?" }, { "code": null, "e": 15085, "s": 14807, "text": "I know I have already tried word vectors I extracted from Doc2Vec models, but what if I train separate Word2Vec models? Even though Doc2Vec models gave good representational vectors of document level, would it be more efficiently learning word vectors if I train pure Word2Vec?" }, { "code": null, "e": 15288, "s": 15085, "text": "In order to answer my own questions, I trained two Word2Vec models using CBOW (Continuous Bag Of Words) and Skip Gram models. In terms of parameter setting, I set the same parameters I used for Doc2Vec." }, { "code": null, "e": 15320, "s": 15288, "text": "size of vectors: 100 dimensions" }, { "code": null, "e": 15341, "s": 15320, "text": "negative sampling: 5" }, { "code": null, "e": 15351, "s": 15341, "text": "window: 2" }, { "code": null, "e": 15373, "s": 15351, "text": "minimum word count: 2" }, { "code": null, "e": 15422, "s": 15373, "text": "alpha: 0.065 (decrease alpha by 0.002 per epoch)" }, { "code": null, "e": 15443, "s": 15422, "text": "number of epochs: 30" }, { "code": null, "e": 15543, "s": 15443, "text": "With above settings, I defined CBOW model by passing “sg=0”, and Skip Gram model by passing “sg=1”." }, { "code": null, "e": 15725, "s": 15543, "text": "And once I get the results from two models, I concatenate vectors of two models for each word so that the concatenated vectors will have 200-dimensional representation of each word." }, { "code": null, "e": 15954, "s": 15725, "text": "Please note that in the 6th part, where I trained Doc2Vec, I used “LabeledSentence” function imported from Gensim. This has now been deprecated, thus for this post I used “TaggedDocument” function instead. The usage is the same." }, { "code": null, "e": 16183, "s": 15954, "text": "The concatenated vectors of unigram CBOW and unigram Skip Gram models has yielded 76.50%, 76.75% validation accuracy respectively with mean and sum method. These results are even higher than the results I got from GloVe vectors." }, { "code": null, "e": 16295, "s": 16183, "text": "But please do not confuse this as a general statement. This is an empirical finding in this particular setting." }, { "code": null, "e": 16412, "s": 16295, "text": "As a final step, I will apply the custom weighting I have implemented above and see if this affects the performance." }, { "code": null, "e": 16652, "s": 16412, "text": "Finally I get the best performing word vectors. Averaged word vectors (separately trained Word2Vec models) weighted with custom metric has yielded the best validation accuracy of 77.97%! Below is the table of all the results I tried above." }, { "code": null, "e": 17161, "s": 16652, "text": "The best performing word vectors with logistic regression was chosen to feed to a neural network model. This time I did not try various different architecture. Based on what I have observed during trials of different architectures with Doc2Vec document vectors, the best performing architecture was one with 3 hidden layers with 256 hidden nodes at each hidden layer.I will finally fit a neural network with early stopping and checkpoint so that I can save the best performing weights on validation accuracy." }, { "code": null, "e": 17329, "s": 17161, "text": "from keras.models import load_modelloaded_w2v_model = load_model('w2v_01_best_weights.10-0.8048.hdf5')loaded_w2v_model.evaluate(x=validation_w2v_final, y=y_validation)" }, { "code": null, "e": 17498, "s": 17329, "text": "The best validation accuracy is 80.48%. Surprisingly this is even higher than the best accuracy I got by feeding document vectors to neural network models in the above." }, { "code": null, "e": 17772, "s": 17498, "text": "It took quite some time for me to try different settings, different calculations, but I learned some valuable lessons through all the trial and errors. Specifically trained Word2Vec with carefully engineered weighting can even outperform Doc2Vec in the classification task." }, { "code": null, "e": 17934, "s": 17772, "text": "In the next post, I will try more sophisticated neural network model, Convolutional Neural Network. Again I hope this will give me some boost of the performance." } ]
Adding base n numbers
In this problem, two numbers are given. The base of those numbers is n. We have to find the result of those number after addition in base n also. At first, the numbers are converted into decimal numbers. From the decimal values, we can simply add them. Finally, the numbers are converted to base n number again. The n base numbers are given as a string, because for those numbers, which have base greater than 9, it may contain some alphabets to represent numbers, like hexadecimal numbers, there are 6 letters (A-F). Input: The base of a number system: 16 First number 2C Second number 5F Output: The result of addition is: 8B baseNtoDec(number, base) Input − The number string of base N, the value of base N. Output − The Decimal equivalent of the number in base N. Begin len := length of number power := 1 num := 0 for i := len -1 down to 0, do if number[i] >= base, then return invalid number num := num + number[i] * power power := power * base done return num End decToBaseN(dec, base) Input: The decimal number, the base N to convert a decimal number to that base. Output: The number string of base N. Begin while dec > 0, do res := concatenate (dec mod base) with res dec := dec / base done reverse the result return res End addBaseN(num1, num2, base) Input: Two numbers in base N, the value of base N. Output: The number after addition in base N. Begin dec1 := baseNtoDec(num1, base) dec2 := baseNtoDec(num2, base) sum := decToBaseN(dec1 + dec2, base) return sum End #include<iostream> #include<algorithm> using namespace std; int getVal(char c) { if(c >= '0' && c<='9') return int(c-'0'); //decimal value of given number else return int(c-'A'+10); //for Alphanumeric numbers } char revVal(int n) { if(n >= 0 && n <=9) return char(n+'0'); //character value of given number else return char(n+'A'-10); //for Alphanumeric numbers, get alphabet from decimal } int baseNtoDec(string number, int base) { int len = number.size(); int power = 1; int num = 0; for(int i = len-1; i>= 0; i--) { //from last digit to first digit if(getVal(number[i]) >= base) return INT_MIN; //when a digit is >= base, return -ve infinity as error num += getVal(number[i])*power; power = power*base; } return num; } string decToBaseN(int dec, int base) { string res = ""; //empty string while(dec > 0) { res += revVal(dec%base); dec /= base; } reverse(res.begin(), res.end()); //reverse the string to get final answer return res; } int main() { int base; string num1, num2, sum; cout << "Enter Base: "; cin >> base; cout << "Enter first number in base "<<base<<": ";cin >> num1; cout << "Enter second number in base "<<base<<": ";cin >> num2; sum = decToBaseN((baseNtoDec(num1, base) + baseNtoDec(num2, base)), base); cout << "The result of addition is: " << sum; } Enter Base: 16 Enter first number in base 16: 2C Enter second number in base 16: 5F The result of addition is: 8B
[ { "code": null, "e": 1208, "s": 1062, "text": "In this problem, two numbers are given. The base of those numbers is n. We have to find the result of those number after addition in base n also." }, { "code": null, "e": 1374, "s": 1208, "text": "At first, the numbers are converted into decimal numbers. From the decimal values, we can simply add them. Finally, the numbers are converted to base n number again." }, { "code": null, "e": 1580, "s": 1374, "text": "The n base numbers are given as a string, because for those numbers, which have base greater than 9, it may contain some alphabets to represent numbers, like hexadecimal numbers, there are 6 letters (A-F)." }, { "code": null, "e": 1691, "s": 1580, "text": "Input: \nThe base of a number system: 16\nFirst number 2C\nSecond number 5F\nOutput:\nThe result of addition is: 8B" }, { "code": null, "e": 1716, "s": 1691, "text": "baseNtoDec(number, base)" }, { "code": null, "e": 1774, "s": 1716, "text": "Input − The number string of base N, the value of base N." }, { "code": null, "e": 1831, "s": 1774, "text": "Output − The Decimal equivalent of the number in base N." }, { "code": null, "e": 2080, "s": 1831, "text": "Begin\n len := length of number\n power := 1\n num := 0\n\n for i := len -1 down to 0, do\n if number[i] >= base, then\n return invalid number\n num := num + number[i] * power\n power := power * base\n done\n\n return num\nEnd" }, { "code": null, "e": 2102, "s": 2080, "text": "decToBaseN(dec, base)" }, { "code": null, "e": 2182, "s": 2102, "text": "Input: The decimal number, the base N to convert a decimal number to that base." }, { "code": null, "e": 2219, "s": 2182, "text": "Output: The number string of base N." }, { "code": null, "e": 2368, "s": 2219, "text": "Begin\n while dec > 0, do\n res := concatenate (dec mod base) with res\n dec := dec / base\n done\n\n reverse the result\n return res\nEnd" }, { "code": null, "e": 2395, "s": 2368, "text": "addBaseN(num1, num2, base)" }, { "code": null, "e": 2446, "s": 2395, "text": "Input: Two numbers in base N, the value of base N." }, { "code": null, "e": 2491, "s": 2446, "text": "Output: The number after addition in base N." }, { "code": null, "e": 2623, "s": 2491, "text": "Begin\n dec1 := baseNtoDec(num1, base)\n dec2 := baseNtoDec(num2, base)\n sum := decToBaseN(dec1 + dec2, base)\n return sum\nEnd" }, { "code": null, "e": 4054, "s": 2623, "text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\n\nint getVal(char c) {\n if(c >= '0' && c<='9')\n return int(c-'0'); //decimal value of given number\n else\n return int(c-'A'+10); //for Alphanumeric numbers\n}\n\nchar revVal(int n) {\n if(n >= 0 && n <=9)\n return char(n+'0'); //character value of given number\n else\n return char(n+'A'-10); //for Alphanumeric numbers, get alphabet from decimal\n}\n\nint baseNtoDec(string number, int base) {\n int len = number.size();\n int power = 1;\n int num = 0;\n\n for(int i = len-1; i>= 0; i--) { //from last digit to first digit\n if(getVal(number[i]) >= base)\n return INT_MIN; //when a digit is >= base, return -ve infinity as error\n num += getVal(number[i])*power;\n power = power*base;\n }\n return num;\n}\n\nstring decToBaseN(int dec, int base) {\n string res = \"\"; //empty string\n while(dec > 0) {\n res += revVal(dec%base);\n dec /= base;\n }\n\n reverse(res.begin(), res.end()); //reverse the string to get final answer\n return res;\n}\n\nint main() {\n int base;\n string num1, num2, sum;\n cout << \"Enter Base: \"; cin >> base;\n cout << \"Enter first number in base \"<<base<<\": \";cin >> num1;\n cout << \"Enter second number in base \"<<base<<\": \";cin >> num2;\n sum = decToBaseN((baseNtoDec(num1, base) + baseNtoDec(num2, base)), base);\n cout << \"The result of addition is: \" << sum;\n}" }, { "code": null, "e": 4168, "s": 4054, "text": "Enter Base: 16\nEnter first number in base 16: 2C\nEnter second number in base 16: 5F\nThe result of addition is: 8B" } ]
Sound Event Classification: A to Z | by Chathuranga Siriwardhana | Towards Data Science
Audio(Sound) is one of the main sensory information we receive to perceive our environment. Almost every action or an event in our surroundings has its unique sound. Audio has 3 main attributes which help us in distinguish between two sounds. Amplitude — Loudness of the sound Frequency — The pitch of the sound Timbre — Quality of the sound or the identity of the sound (e.g. the Sound difference between a piano and a violin) Let’s say a sound event is an audio clip which is generated from an action. The action can be speaking, humming, finger-snapping, walking, water pouring, etc. As humans, we have been training since we are very little to recognize events with audio. Someone can say that humans are very efficient in learning new sound events and recognize sound events. Listening to a podcast only uses the sound recognition ability to make sense of the podcast. Sometimes, we use sound recognition with other sensory information to perceive the surroundings. However, the audio event recognition systematically (preferably using a computer program or an algorithm) is very challenging. This is mainly because of, The noisiness of recorded sound clips — transducer noise and background noise. An event can be occurring at various loudness levels and various time durations. Having a limited number of examples to feed into an algorithm. Let’s come to the sound classification part. Let’s say the problem is to classify a given audio clip as one of the following events using only sound. Calling — Talk on a phone Clapping Falling — A man falls on the ground Sweeping — Sweeping the floor using a broom Washing Hands — Washing hands with a sink and a water tap Watching TV — TV sound Entering / Exiting — Door opening or closing sound other — None of the above events The audio data used in this post are from the Assisted Living Dataset collected at University of Moratuwa, Sri Lanka. The audio clips are recorded with two MOVO USB omnidirectional microphones as .wav files. The sound event classification is done by performing Audio preprocessing, Feature extraction and classification. First, we need to come up with a method to represent audio clips (.wav files). Then, the audio data should be preprocessed to use as inputs to the machine learning algorithms. The Librosa library provides some useful functionalities for processing audio with python. The audio files are loaded into a numpy array using Librosa. The array will consist of the amplitudes of the respective audio clip at a rate called ‘Sampling rate’. (The sampling rate usually would 22050 or 44100) Having loaded an audio clip into an array, the first challenge, noisiness should be addressed. The Audacity uses ‘spectral gating’ algorithm to suppress the noise in the audio. A good implementation of the algorithm can be found in noisereduce python library. The algorithm can be found on the documentation of the noisereduce library. import noisereduce as nr# Load audio fileaudio_data, sampling_rate = librosa.load(<audio_file_path.wav>)# Noise reductionnoisy_part = audio_data[0:25000] reduced_noise = nr.reduce_noise(audio_clip=audio_data, noise_clip=noisy_part, verbose=False)# Visualizeprint("Original audio file:")plotAudio(audio_data)print("Noise removed audio file:")plotAudio(reduced_noise) The resulting audio clip is containing an empty length (unnecessary silence) in it. Let’s trim the leading and trailing parts which are silence than a threshold loudness level. trimmed, index = librosa.effects.trim(reduced_noise, top_db=20, frame_length=512, hop_length=64)print(“Trimmed audio file:”)plotAudio(trimmed) The preprocessed audio files themselves cannot be used to classify as sound events. We have to extract feature from the audio clips to make the classification process more efficient and accurate. Let’s extract the absolute values of Short-Time Fourier Transform (STFT) from each audio clip. To calculate STFT, Fast Fourier transform window size(n_fft) is used as 512. According to the equation n_stft = n_fft/2 + 1, 257 frequency bins(n_stft) are calculated over a window size of 512. The window is moved by a hop length of 256 to have a better overlapping of the windows in calculating the STFT. stft = np.abs(librosa.stft(trimmed, n_fft=512, hop_length=256, win_length=512)) The number of frequency bins, window length and hop length are determined empirically for the dataset. There is no universal set of values for the parameters in the feature generation. This will be discussed again in the Tuning and enhancing Results section. Let’s review the meaning of the absolute STFT features of an audio clip. Consider an audio clip which has a t number of samples in it. Say we are obtaining anf number of frequency bins in the STFT. Consider the window length is w and window’s hop length h. When calculating STFT, a series of windows are obtained sliding a fixed w length window by a step of h. This will produce 1+(t-w)/h number of windows. For each such window, the amplitudes of frequency bins (in Hz) in the range 0 to sampling_rate/2 are recorded. The frequency range is equally divided when determining the values of the frequency bins. For example, consider STFT bins with n_fft=16 and sampling rate of 22050. Then there will be 9 frequency bins having the following values(in Hz). [ 0 , 1378.125, 2756.25 , 4134.375, 5512.5 , 6890.625, 8268.75 , 9646.875, 11025 ] The absolute STFT features of an audio clip is a 2-dimensional array which contains mentioned frequency amplitude bins for each window. Since sound events have different durations(number of samples), the 2-d feature arrays are flattened using mean on the frequency axis. Thus, the audio clips will be represented using an array of fixed size 257 (number of STFT frequency bins). This seems like a bad representation of the audio clip since it does not contain temporal information. But every given audio event has its unique frequency range. For example, the scratching sound of the sweeping-event makes its feature vector having more high-frequency amplitudes than Falling-event. Finally, the feature vector is normalized by min-max normalization. Normalization is applied to make every sound event lie on a common loudness level. (As introduced, the amplitude is an audio property and we should not use amplitude in this use case to differentiate sound events). The following figure shows the Normalized STFT Frequency signatures of sound events captured by the absolute STFT features. Now, the sound events are preprocessed and represented efficiently using STFT features. The STFT features are used to train a fully connected Neural Network(NN) which will be used to classify new sound events. The NN consists of 5 fully connected layers. The layers are having 256, 256, 128, 128 and 8 neurons in them. All layers are having ReLU activation function and the 4th layer is having a dropout layer to reduce the overfitting to the training data. The neural network (model) can be easily built using Keras Dense layers. The model is compiled using the ‘Adam’ optimizer. # build modelmodel = Sequential()model.add(Dense(256, input_shape=(257,)))model.add(Activation(‘relu’))model.add(Dense(256))model.add(Activation(‘relu’))model.add(Dense(128))model.add(Activation(‘relu’))model.add(Dense(128))model.add(Activation(‘relu’))model.add(Dropout(0.5))model.add(Dense(num_labels))model.add(Activation(‘relu’))model.compile(loss=’categorical_crossentropy’, metrics=[‘accuracy’], optimizer=’adam’) The above NN model was trained on 880 samples and validated on 146 samples. It classifies unseen audio events with an average accuracy of 93%. The following figure shows the normalized confusing matrix corresponding to a prediction. We have obtained a very good model by now. Can we do even better? Always there will be a better model. The limit is how good we want our classification is. Looking at the confusion matrix we can observe that some activities like Watching TV have been misclassified with an error of 50%. Therefore, we should consider tuning the model, preprocessing and feature extraction steps. We can programmatically check what is the best values for the number of frequency bins, window length and hop length in feature extraction. A visualization method can be used to determine what are the best values for the parameters. The feature type (Absolutes of STFTs here)also can be decided empirically. The machine learning model is the necessary part to be tuned. The number of layers, dropout layer properties, activation functions, optimizers and learning rates can be determined in such a manner. Note: Tuning is done for some extend to make the accuracy of above Neural Network high. You can still improve. As the next step, we can implement a continuous sound event classifier which is accepting a stream of audio and classify the sound events real-time. Hope you find the article useful. A complement article will be published on continuous audio classification near future. Find full python code in this Git repository.
[ { "code": null, "e": 415, "s": 172, "text": "Audio(Sound) is one of the main sensory information we receive to perceive our environment. Almost every action or an event in our surroundings has its unique sound. Audio has 3 main attributes which help us in distinguish between two sounds." }, { "code": null, "e": 449, "s": 415, "text": "Amplitude — Loudness of the sound" }, { "code": null, "e": 484, "s": 449, "text": "Frequency — The pitch of the sound" }, { "code": null, "e": 600, "s": 484, "text": "Timbre — Quality of the sound or the identity of the sound (e.g. the Sound difference between a piano and a violin)" }, { "code": null, "e": 1143, "s": 600, "text": "Let’s say a sound event is an audio clip which is generated from an action. The action can be speaking, humming, finger-snapping, walking, water pouring, etc. As humans, we have been training since we are very little to recognize events with audio. Someone can say that humans are very efficient in learning new sound events and recognize sound events. Listening to a podcast only uses the sound recognition ability to make sense of the podcast. Sometimes, we use sound recognition with other sensory information to perceive the surroundings." }, { "code": null, "e": 1297, "s": 1143, "text": "However, the audio event recognition systematically (preferably using a computer program or an algorithm) is very challenging. This is mainly because of," }, { "code": null, "e": 1376, "s": 1297, "text": "The noisiness of recorded sound clips — transducer noise and background noise." }, { "code": null, "e": 1457, "s": 1376, "text": "An event can be occurring at various loudness levels and various time durations." }, { "code": null, "e": 1520, "s": 1457, "text": "Having a limited number of examples to feed into an algorithm." }, { "code": null, "e": 1670, "s": 1520, "text": "Let’s come to the sound classification part. Let’s say the problem is to classify a given audio clip as one of the following events using only sound." }, { "code": null, "e": 1696, "s": 1670, "text": "Calling — Talk on a phone" }, { "code": null, "e": 1705, "s": 1696, "text": "Clapping" }, { "code": null, "e": 1741, "s": 1705, "text": "Falling — A man falls on the ground" }, { "code": null, "e": 1785, "s": 1741, "text": "Sweeping — Sweeping the floor using a broom" }, { "code": null, "e": 1843, "s": 1785, "text": "Washing Hands — Washing hands with a sink and a water tap" }, { "code": null, "e": 1866, "s": 1843, "text": "Watching TV — TV sound" }, { "code": null, "e": 1917, "s": 1866, "text": "Entering / Exiting — Door opening or closing sound" }, { "code": null, "e": 1950, "s": 1917, "text": "other — None of the above events" }, { "code": null, "e": 2271, "s": 1950, "text": "The audio data used in this post are from the Assisted Living Dataset collected at University of Moratuwa, Sri Lanka. The audio clips are recorded with two MOVO USB omnidirectional microphones as .wav files. The sound event classification is done by performing Audio preprocessing, Feature extraction and classification." }, { "code": null, "e": 2752, "s": 2271, "text": "First, we need to come up with a method to represent audio clips (.wav files). Then, the audio data should be preprocessed to use as inputs to the machine learning algorithms. The Librosa library provides some useful functionalities for processing audio with python. The audio files are loaded into a numpy array using Librosa. The array will consist of the amplitudes of the respective audio clip at a rate called ‘Sampling rate’. (The sampling rate usually would 22050 or 44100)" }, { "code": null, "e": 3088, "s": 2752, "text": "Having loaded an audio clip into an array, the first challenge, noisiness should be addressed. The Audacity uses ‘spectral gating’ algorithm to suppress the noise in the audio. A good implementation of the algorithm can be found in noisereduce python library. The algorithm can be found on the documentation of the noisereduce library." }, { "code": null, "e": 3455, "s": 3088, "text": "import noisereduce as nr# Load audio fileaudio_data, sampling_rate = librosa.load(<audio_file_path.wav>)# Noise reductionnoisy_part = audio_data[0:25000] reduced_noise = nr.reduce_noise(audio_clip=audio_data, noise_clip=noisy_part, verbose=False)# Visualizeprint(\"Original audio file:\")plotAudio(audio_data)print(\"Noise removed audio file:\")plotAudio(reduced_noise)" }, { "code": null, "e": 3632, "s": 3455, "text": "The resulting audio clip is containing an empty length (unnecessary silence) in it. Let’s trim the leading and trailing parts which are silence than a threshold loudness level." }, { "code": null, "e": 3775, "s": 3632, "text": "trimmed, index = librosa.effects.trim(reduced_noise, top_db=20, frame_length=512, hop_length=64)print(“Trimmed audio file:”)plotAudio(trimmed)" }, { "code": null, "e": 4372, "s": 3775, "text": "The preprocessed audio files themselves cannot be used to classify as sound events. We have to extract feature from the audio clips to make the classification process more efficient and accurate. Let’s extract the absolute values of Short-Time Fourier Transform (STFT) from each audio clip. To calculate STFT, Fast Fourier transform window size(n_fft) is used as 512. According to the equation n_stft = n_fft/2 + 1, 257 frequency bins(n_stft) are calculated over a window size of 512. The window is moved by a hop length of 256 to have a better overlapping of the windows in calculating the STFT." }, { "code": null, "e": 4452, "s": 4372, "text": "stft = np.abs(librosa.stft(trimmed, n_fft=512, hop_length=256, win_length=512))" }, { "code": null, "e": 4711, "s": 4452, "text": "The number of frequency bins, window length and hop length are determined empirically for the dataset. There is no universal set of values for the parameters in the feature generation. This will be discussed again in the Tuning and enhancing Results section." }, { "code": null, "e": 5466, "s": 4711, "text": "Let’s review the meaning of the absolute STFT features of an audio clip. Consider an audio clip which has a t number of samples in it. Say we are obtaining anf number of frequency bins in the STFT. Consider the window length is w and window’s hop length h. When calculating STFT, a series of windows are obtained sliding a fixed w length window by a step of h. This will produce 1+(t-w)/h number of windows. For each such window, the amplitudes of frequency bins (in Hz) in the range 0 to sampling_rate/2 are recorded. The frequency range is equally divided when determining the values of the frequency bins. For example, consider STFT bins with n_fft=16 and sampling rate of 22050. Then there will be 9 frequency bins having the following values(in Hz)." }, { "code": null, "e": 5571, "s": 5466, "text": "[ 0 , 1378.125, 2756.25 , 4134.375, 5512.5 , 6890.625, 8268.75 , 9646.875, 11025 ]" }, { "code": null, "e": 5707, "s": 5571, "text": "The absolute STFT features of an audio clip is a 2-dimensional array which contains mentioned frequency amplitude bins for each window." }, { "code": null, "e": 6659, "s": 5707, "text": "Since sound events have different durations(number of samples), the 2-d feature arrays are flattened using mean on the frequency axis. Thus, the audio clips will be represented using an array of fixed size 257 (number of STFT frequency bins). This seems like a bad representation of the audio clip since it does not contain temporal information. But every given audio event has its unique frequency range. For example, the scratching sound of the sweeping-event makes its feature vector having more high-frequency amplitudes than Falling-event. Finally, the feature vector is normalized by min-max normalization. Normalization is applied to make every sound event lie on a common loudness level. (As introduced, the amplitude is an audio property and we should not use amplitude in this use case to differentiate sound events). The following figure shows the Normalized STFT Frequency signatures of sound events captured by the absolute STFT features." }, { "code": null, "e": 7240, "s": 6659, "text": "Now, the sound events are preprocessed and represented efficiently using STFT features. The STFT features are used to train a fully connected Neural Network(NN) which will be used to classify new sound events. The NN consists of 5 fully connected layers. The layers are having 256, 256, 128, 128 and 8 neurons in them. All layers are having ReLU activation function and the 4th layer is having a dropout layer to reduce the overfitting to the training data. The neural network (model) can be easily built using Keras Dense layers. The model is compiled using the ‘Adam’ optimizer." }, { "code": null, "e": 7660, "s": 7240, "text": "# build modelmodel = Sequential()model.add(Dense(256, input_shape=(257,)))model.add(Activation(‘relu’))model.add(Dense(256))model.add(Activation(‘relu’))model.add(Dense(128))model.add(Activation(‘relu’))model.add(Dense(128))model.add(Activation(‘relu’))model.add(Dropout(0.5))model.add(Dense(num_labels))model.add(Activation(‘relu’))model.compile(loss=’categorical_crossentropy’, metrics=[‘accuracy’], optimizer=’adam’)" }, { "code": null, "e": 7893, "s": 7660, "text": "The above NN model was trained on 880 samples and validated on 146 samples. It classifies unseen audio events with an average accuracy of 93%. The following figure shows the normalized confusing matrix corresponding to a prediction." }, { "code": null, "e": 8272, "s": 7893, "text": "We have obtained a very good model by now. Can we do even better? Always there will be a better model. The limit is how good we want our classification is. Looking at the confusion matrix we can observe that some activities like Watching TV have been misclassified with an error of 50%. Therefore, we should consider tuning the model, preprocessing and feature extraction steps." }, { "code": null, "e": 8778, "s": 8272, "text": "We can programmatically check what is the best values for the number of frequency bins, window length and hop length in feature extraction. A visualization method can be used to determine what are the best values for the parameters. The feature type (Absolutes of STFTs here)also can be decided empirically. The machine learning model is the necessary part to be tuned. The number of layers, dropout layer properties, activation functions, optimizers and learning rates can be determined in such a manner." }, { "code": null, "e": 8889, "s": 8778, "text": "Note: Tuning is done for some extend to make the accuracy of above Neural Network high. You can still improve." }, { "code": null, "e": 9159, "s": 8889, "text": "As the next step, we can implement a continuous sound event classifier which is accepting a stream of audio and classify the sound events real-time. Hope you find the article useful. A complement article will be published on continuous audio classification near future." } ]
GATE | GATE-CS-2007 | Question 56 - GeeksforGeeks
28 Jun, 2021 A virtual memory system uses First In First Out (FIFO) page replacement policy and allocates a fixed number of frames to a process. Consider the following statements: P: Increasing the number of page frames allocated to a process sometimes increases the page fault rate. Q: Some programs do not exhibit locality of reference. Which one of the following is TRUE?(A) Both P and Q are true, and Q is the reason for P(B) Both P and Q are true, but Q is not the reason for P.(C) P is false, but Q is true(D) Both P and Q are falseAnswer: (B)Explanation: First In First Out Page Replacement Algorithms: This is the simplest page replacement algorithm. In this algorithm, operating system keeps track of all pages in the memory in a queue, oldest page is in the front of the queue. When a page needs to be replaced page in the front of the queue is selected for removal. FIFO Page replacement algorithms suffers from Belady’s anomaly : Belady’s anomaly states that it is possible to have more page faults when increasing the number of page frames. Solution: Statement P: Increasing the number of page frames allocated to a process sometimes increases the page fault rate. Correct, as FIFO page replacement algorithm suffers from belady’s anomaly which states above statement. Statement Q: Some programs do not exhibit locality of reference. Correct, Locality often occurs because code contains loops that tend to reference arrays or other data structures by indices. So we can write a program does not contain loop and do not exhibit locality of reference. So, both statement P and Q are correct but Q is not the reason for P as Belady’s Anomaly occurs for some specific patterns of page references. See Question 1 of https://www.geeksforgeeks.org/operating-systems-set-13/ Reference :https://www.geeksforgeeks.org/page-replacement-algorithms-in-operating-systems/ This solution is contributed by Nitika BansalQuiz of this Question GATE-CS-2007 GATE-GATE-CS-2007 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-IT-2004 | Question 12 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2007 | Question 17 GATE | GATE CS 2010 | Question 33
[ { "code": null, "e": 24366, "s": 24338, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24533, "s": 24366, "text": "A virtual memory system uses First In First Out (FIFO) page replacement policy and allocates a fixed number of frames to a process. Consider the following statements:" }, { "code": null, "e": 24698, "s": 24533, "text": "\nP: Increasing the number of page frames allocated to a \n process sometimes increases the page fault rate.\nQ: Some programs do not exhibit locality of reference. " }, { "code": null, "e": 24921, "s": 24698, "text": "Which one of the following is TRUE?(A) Both P and Q are true, and Q is the reason for P(B) Both P and Q are true, but Q is not the reason for P.(C) P is false, but Q is true(D) Both P and Q are falseAnswer: (B)Explanation:" }, { "code": null, "e": 25236, "s": 24921, "text": "First In First Out Page Replacement Algorithms: This is the simplest page replacement algorithm. In this algorithm, operating system keeps track of all pages in the memory in a queue, oldest page is in the front of the queue. When a page needs to be replaced page in the front of the queue is selected for removal." }, { "code": null, "e": 25301, "s": 25236, "text": "FIFO Page replacement algorithms suffers from Belady’s anomaly :" }, { "code": null, "e": 25413, "s": 25301, "text": "Belady’s anomaly states that it is possible to have more page faults when increasing the number of page frames." }, { "code": null, "e": 25423, "s": 25413, "text": "Solution:" }, { "code": null, "e": 25537, "s": 25423, "text": "Statement P: Increasing the number of page frames allocated to a process sometimes increases the page fault rate." }, { "code": null, "e": 25641, "s": 25537, "text": "Correct, as FIFO page replacement algorithm suffers from belady’s anomaly which states above statement." }, { "code": null, "e": 25922, "s": 25641, "text": "Statement Q: Some programs do not exhibit locality of reference. Correct, Locality often occurs because code contains loops that tend to reference arrays or other data structures by indices. So we can write a program does not contain loop and do not exhibit locality of reference." }, { "code": null, "e": 26065, "s": 25922, "text": "So, both statement P and Q are correct but Q is not the reason for P as Belady’s Anomaly occurs for some specific patterns of page references." }, { "code": null, "e": 26139, "s": 26065, "text": "See Question 1 of https://www.geeksforgeeks.org/operating-systems-set-13/" }, { "code": null, "e": 26230, "s": 26139, "text": "Reference :https://www.geeksforgeeks.org/page-replacement-algorithms-in-operating-systems/" }, { "code": null, "e": 26297, "s": 26230, "text": "This solution is contributed by Nitika BansalQuiz of this Question" }, { "code": null, "e": 26310, "s": 26297, "text": "GATE-CS-2007" }, { "code": null, "e": 26328, "s": 26310, "text": "GATE-GATE-CS-2007" }, { "code": null, "e": 26333, "s": 26328, "text": "GATE" }, { "code": null, "e": 26431, "s": 26333, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26440, "s": 26431, "text": "Comments" }, { "code": null, "e": 26453, "s": 26440, "text": "Old Comments" }, { "code": null, "e": 26495, "s": 26453, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 26529, "s": 26495, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 26563, "s": 26529, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 26605, "s": 26563, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 26647, "s": 26605, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 26689, "s": 26647, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 26723, "s": 26689, "text": "GATE | GATE-IT-2004 | Question 12" }, { "code": null, "e": 26765, "s": 26723, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 26799, "s": 26765, "text": "GATE | GATE-CS-2007 | Question 17" } ]
Multithreading in Python | Set 2 (Synchronization) - GeeksforGeeks
28 Aug, 2019 This article discusses the concept of thread synchronization in case of multithreading in Python programming language. Synchronization between threads Thread synchronization is defined as a mechanism which ensures that two or more concurrent threads do not simultaneously execute some particular program segment known as critical section. Critical section refers to the parts of the program where the shared resource is accessed. For example, in the diagram below, 3 threads try to access shared resource or critical section at the same time. Concurrent accesses to shared resource can lead to race condition. A race condition occurs when two or more threads can access shared data and they try to change it at the same time. As a result, the values of variables may be unpredictable and vary depending on the timings of context switches of the processes. Consider the program below to understand the concept of race condition: import threading # global variable xx = 0 def increment(): """ function to increment global variable x """ global x x += 1 def thread_task(): """ task for thread calls increment function 100000 times. """ for _ in range(100000): increment() def main_task(): global x # setting global variable x as 0 x = 0 # creating threads t1 = threading.Thread(target=thread_task) t2 = threading.Thread(target=thread_task) # start threads t1.start() t2.start() # wait until threads finish their job t1.join() t2.join() if __name__ == "__main__": for i in range(10): main_task() print("Iteration {0}: x = {1}".format(i,x)) Output: Iteration 0: x = 175005 Iteration 1: x = 200000 Iteration 2: x = 200000 Iteration 3: x = 169432 Iteration 4: x = 153316 Iteration 5: x = 200000 Iteration 6: x = 167322 Iteration 7: x = 200000 Iteration 8: x = 169917 Iteration 9: x = 153589 In above program: Two threads t1 and t2 are created in main_task function and global variable x is set to 0. Each thread has a target function thread_task in which increment function is called 100000 times. increment function will increment the global variable x by 1 in each call. The expected final value of x is 200000 but what we get in 10 iterations of main_task function is some different values. This happens due to concurrent access of threads to the shared variable x. This unpredictability in value of x is nothing but race condition. Given below is a diagram which shows how can race condition occur in above program: Notice that expected value of x in above diagram is 12 but due to race condition, it turns out to be 11!Hence, we need a tool for proper synchronization between multiple threads. Using Locks threading module provides a Lock class to deal with the race conditions. Lock is implemented using a Semaphore object provided by the Operating System. A semaphore is a synchronization object that controls access by multiple processes/threads to a common resource in a parallel programming environment. It is simply a value in a designated place in operating system (or kernel) storage that each process/thread can check and then change. Depending on the value that is found, the process/thread can use the resource or will find that it is already in use and must wait for some period before trying again. Semaphores can be binary (0 or 1) or can have additional values. Typically, a process/thread using semaphores checks the value and then, if it using the resource, changes the value to reflect this so that subsequent semaphore users will know to wait. Lock class provides following methods: acquire([blocking]) : To acquire a lock. A lock can be blocking or non-blocking.When invoked with the blocking argument set to True (the default), thread execution is blocked until the lock is unlocked, then lock is set to locked and return True.When invoked with the blocking argument set to False, thread execution is not blocked. If lock is unlocked, then set it to locked and return True else return False immediately. When invoked with the blocking argument set to True (the default), thread execution is blocked until the lock is unlocked, then lock is set to locked and return True. When invoked with the blocking argument set to False, thread execution is not blocked. If lock is unlocked, then set it to locked and return True else return False immediately. release() : To release a lock.When the lock is locked, reset it to unlocked, and return. If any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed.If lock is already unlocked, a ThreadError is raised. When the lock is locked, reset it to unlocked, and return. If any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If lock is already unlocked, a ThreadError is raised. Consider the example given below: import threading # global variable xx = 0 def increment(): """ function to increment global variable x """ global x x += 1 def thread_task(lock): """ task for thread calls increment function 100000 times. """ for _ in range(100000): lock.acquire() increment() lock.release() def main_task(): global x # setting global variable x as 0 x = 0 # creating a lock lock = threading.Lock() # creating threads t1 = threading.Thread(target=thread_task, args=(lock,)) t2 = threading.Thread(target=thread_task, args=(lock,)) # start threads t1.start() t2.start() # wait until threads finish their job t1.join() t2.join() if __name__ == "__main__": for i in range(10): main_task() print("Iteration {0}: x = {1}".format(i,x)) Output: Iteration 0: x = 200000 Iteration 1: x = 200000 Iteration 2: x = 200000 Iteration 3: x = 200000 Iteration 4: x = 200000 Iteration 5: x = 200000 Iteration 6: x = 200000 Iteration 7: x = 200000 Iteration 8: x = 200000 Iteration 9: x = 200000 Let us try to understand the above code step by step: Firstly, a Lock object is created using: lock = threading.Lock() lock = threading.Lock() Then, lock is passed as target function argument: t1 = threading.Thread(target=thread_task, args=(lock,)) t2 = threading.Thread(target=thread_task, args=(lock,)) t1 = threading.Thread(target=thread_task, args=(lock,)) t2 = threading.Thread(target=thread_task, args=(lock,)) In the critical section of target function, we apply lock using lock.acquire() method. As soon as a lock is acquired, no other thread can access the critical section (here, increment function) until the lock is released using lock.release() method. lock.acquire() increment() lock.release() As you can see in the results, the final value of x comes out to be 200000 every time (which is the expected final result). lock.acquire() increment() lock.release() As you can see in the results, the final value of x comes out to be 200000 every time (which is the expected final result). Here is a diagram given below which depicts the implementation of locks in above program: This brings us to the end of this tutorial series on Multithreading in Python.Finally, here are a few advantages and disadvantages of multithreading: Advantages: It doesn’t block the user. This is because threads are independent of each other. Better use of system resources is possible since threads execute tasks parallely. Enhanced performance on multi-processor machines. Multi-threaded servers and interactive GUIs use multithreading exclusively. Disadvantages: As number of threads increase, complexity increases. Synchronization of shared resources (objects, data) is necessary. It is difficult to debug, result is sometimes unpredictable. Potential deadlocks which leads to starvation, i.e. some threads may not be served with a bad design Constructing and synchronizing threads is CPU/memory intensive. This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nikhil.knit nidhi_biet Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe 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()
[ { "code": null, "e": 41163, "s": 41135, "text": "\n28 Aug, 2019" }, { "code": null, "e": 41282, "s": 41163, "text": "This article discusses the concept of thread synchronization in case of multithreading in Python programming language." }, { "code": null, "e": 41314, "s": 41282, "text": "Synchronization between threads" }, { "code": null, "e": 41502, "s": 41314, "text": "Thread synchronization is defined as a mechanism which ensures that two or more concurrent threads do not simultaneously execute some particular program segment known as critical section." }, { "code": null, "e": 41593, "s": 41502, "text": "Critical section refers to the parts of the program where the shared resource is accessed." }, { "code": null, "e": 41706, "s": 41593, "text": "For example, in the diagram below, 3 threads try to access shared resource or critical section at the same time." }, { "code": null, "e": 41773, "s": 41706, "text": "Concurrent accesses to shared resource can lead to race condition." }, { "code": null, "e": 42019, "s": 41773, "text": "A race condition occurs when two or more threads can access shared data and they try to change it at the same time. As a result, the values of variables may be unpredictable and vary depending on the timings of context switches of the processes." }, { "code": null, "e": 42091, "s": 42019, "text": "Consider the program below to understand the concept of race condition:" }, { "code": "import threading # global variable xx = 0 def increment(): \"\"\" function to increment global variable x \"\"\" global x x += 1 def thread_task(): \"\"\" task for thread calls increment function 100000 times. \"\"\" for _ in range(100000): increment() def main_task(): global x # setting global variable x as 0 x = 0 # creating threads t1 = threading.Thread(target=thread_task) t2 = threading.Thread(target=thread_task) # start threads t1.start() t2.start() # wait until threads finish their job t1.join() t2.join() if __name__ == \"__main__\": for i in range(10): main_task() print(\"Iteration {0}: x = {1}\".format(i,x))", "e": 42800, "s": 42091, "text": null }, { "code": null, "e": 42808, "s": 42800, "text": "Output:" }, { "code": null, "e": 43048, "s": 42808, "text": "Iteration 0: x = 175005\nIteration 1: x = 200000\nIteration 2: x = 200000\nIteration 3: x = 169432\nIteration 4: x = 153316\nIteration 5: x = 200000\nIteration 6: x = 167322\nIteration 7: x = 200000\nIteration 8: x = 169917\nIteration 9: x = 153589" }, { "code": null, "e": 43066, "s": 43048, "text": "In above program:" }, { "code": null, "e": 43157, "s": 43066, "text": "Two threads t1 and t2 are created in main_task function and global variable x is set to 0." }, { "code": null, "e": 43255, "s": 43157, "text": "Each thread has a target function thread_task in which increment function is called 100000 times." }, { "code": null, "e": 43330, "s": 43255, "text": "increment function will increment the global variable x by 1 in each call." }, { "code": null, "e": 43451, "s": 43330, "text": "The expected final value of x is 200000 but what we get in 10 iterations of main_task function is some different values." }, { "code": null, "e": 43593, "s": 43451, "text": "This happens due to concurrent access of threads to the shared variable x. This unpredictability in value of x is nothing but race condition." }, { "code": null, "e": 43677, "s": 43593, "text": "Given below is a diagram which shows how can race condition occur in above program:" }, { "code": null, "e": 43856, "s": 43677, "text": "Notice that expected value of x in above diagram is 12 but due to race condition, it turns out to be 11!Hence, we need a tool for proper synchronization between multiple threads." }, { "code": null, "e": 43868, "s": 43856, "text": "Using Locks" }, { "code": null, "e": 44020, "s": 43868, "text": "threading module provides a Lock class to deal with the race conditions. Lock is implemented using a Semaphore object provided by the Operating System." }, { "code": null, "e": 44725, "s": 44020, "text": "A semaphore is a synchronization object that controls access by multiple processes/threads to a common resource in a parallel programming environment. It is simply a value in a designated place in operating system (or kernel) storage that each process/thread can check and then change. Depending on the value that is found, the process/thread can use the resource or will find that it is already in use and must wait for some period before trying again. Semaphores can be binary (0 or 1) or can have additional values. Typically, a process/thread using semaphores checks the value and then, if it using the resource, changes the value to reflect this so that subsequent semaphore users will know to wait." }, { "code": null, "e": 44764, "s": 44725, "text": "Lock class provides following methods:" }, { "code": null, "e": 45187, "s": 44764, "text": "acquire([blocking]) : To acquire a lock. A lock can be blocking or non-blocking.When invoked with the blocking argument set to True (the default), thread execution is blocked until the lock is unlocked, then lock is set to locked and return True.When invoked with the blocking argument set to False, thread execution is not blocked. If lock is unlocked, then set it to locked and return True else return False immediately." }, { "code": null, "e": 45354, "s": 45187, "text": "When invoked with the blocking argument set to True (the default), thread execution is blocked until the lock is unlocked, then lock is set to locked and return True." }, { "code": null, "e": 45531, "s": 45354, "text": "When invoked with the blocking argument set to False, thread execution is not blocked. If lock is unlocked, then set it to locked and return True else return False immediately." }, { "code": null, "e": 45785, "s": 45531, "text": "release() : To release a lock.When the lock is locked, reset it to unlocked, and return. If any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed.If lock is already unlocked, a ThreadError is raised." }, { "code": null, "e": 45956, "s": 45785, "text": "When the lock is locked, reset it to unlocked, and return. If any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed." }, { "code": null, "e": 46010, "s": 45956, "text": "If lock is already unlocked, a ThreadError is raised." }, { "code": null, "e": 46044, "s": 46010, "text": "Consider the example given below:" }, { "code": "import threading # global variable xx = 0 def increment(): \"\"\" function to increment global variable x \"\"\" global x x += 1 def thread_task(lock): \"\"\" task for thread calls increment function 100000 times. \"\"\" for _ in range(100000): lock.acquire() increment() lock.release() def main_task(): global x # setting global variable x as 0 x = 0 # creating a lock lock = threading.Lock() # creating threads t1 = threading.Thread(target=thread_task, args=(lock,)) t2 = threading.Thread(target=thread_task, args=(lock,)) # start threads t1.start() t2.start() # wait until threads finish their job t1.join() t2.join() if __name__ == \"__main__\": for i in range(10): main_task() print(\"Iteration {0}: x = {1}\".format(i,x))", "e": 46879, "s": 46044, "text": null }, { "code": null, "e": 46887, "s": 46879, "text": "Output:" }, { "code": null, "e": 47128, "s": 46887, "text": "Iteration 0: x = 200000\nIteration 1: x = 200000\nIteration 2: x = 200000\nIteration 3: x = 200000\nIteration 4: x = 200000\nIteration 5: x = 200000\nIteration 6: x = 200000\nIteration 7: x = 200000\nIteration 8: x = 200000\nIteration 9: x = 200000\n" }, { "code": null, "e": 47182, "s": 47128, "text": "Let us try to understand the above code step by step:" }, { "code": null, "e": 47249, "s": 47182, "text": "Firstly, a Lock object is created using: lock = threading.Lock()\n" }, { "code": null, "e": 47276, "s": 47249, "text": " lock = threading.Lock()\n" }, { "code": null, "e": 47442, "s": 47276, "text": "Then, lock is passed as target function argument: t1 = threading.Thread(target=thread_task, args=(lock,))\n t2 = threading.Thread(target=thread_task, args=(lock,))\n" }, { "code": null, "e": 47559, "s": 47442, "text": " t1 = threading.Thread(target=thread_task, args=(lock,))\n t2 = threading.Thread(target=thread_task, args=(lock,))\n" }, { "code": null, "e": 47979, "s": 47559, "text": "In the critical section of target function, we apply lock using lock.acquire() method. As soon as a lock is acquired, no other thread can access the critical section (here, increment function) until the lock is released using lock.release() method. lock.acquire()\n increment()\n lock.release()\nAs you can see in the results, the final value of x comes out to be 200000 every time (which is the expected final result)." }, { "code": null, "e": 48028, "s": 47979, "text": " lock.acquire()\n increment()\n lock.release()\n" }, { "code": null, "e": 48152, "s": 48028, "text": "As you can see in the results, the final value of x comes out to be 200000 every time (which is the expected final result)." }, { "code": null, "e": 48242, "s": 48152, "text": "Here is a diagram given below which depicts the implementation of locks in above program:" }, { "code": null, "e": 48392, "s": 48242, "text": "This brings us to the end of this tutorial series on Multithreading in Python.Finally, here are a few advantages and disadvantages of multithreading:" }, { "code": null, "e": 48404, "s": 48392, "text": "Advantages:" }, { "code": null, "e": 48486, "s": 48404, "text": "It doesn’t block the user. This is because threads are independent of each other." }, { "code": null, "e": 48568, "s": 48486, "text": "Better use of system resources is possible since threads execute tasks parallely." }, { "code": null, "e": 48618, "s": 48568, "text": "Enhanced performance on multi-processor machines." }, { "code": null, "e": 48694, "s": 48618, "text": "Multi-threaded servers and interactive GUIs use multithreading exclusively." }, { "code": null, "e": 48709, "s": 48694, "text": "Disadvantages:" }, { "code": null, "e": 48762, "s": 48709, "text": "As number of threads increase, complexity increases." }, { "code": null, "e": 48828, "s": 48762, "text": "Synchronization of shared resources (objects, data) is necessary." }, { "code": null, "e": 48889, "s": 48828, "text": "It is difficult to debug, result is sometimes unpredictable." }, { "code": null, "e": 48990, "s": 48889, "text": "Potential deadlocks which leads to starvation, i.e. some threads may not be served with a bad design" }, { "code": null, "e": 49054, "s": 48990, "text": "Constructing and synchronizing threads is CPU/memory intensive." }, { "code": null, "e": 49354, "s": 49054, "text": "This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 49479, "s": 49354, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 49491, "s": 49479, "text": "nikhil.knit" }, { "code": null, "e": 49502, "s": 49491, "text": "nidhi_biet" }, { "code": null, "e": 49509, "s": 49502, "text": "Python" }, { "code": null, "e": 49607, "s": 49509, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49616, "s": 49607, "text": "Comments" }, { "code": null, "e": 49629, "s": 49616, "text": "Old Comments" }, { "code": null, "e": 49657, "s": 49629, "text": "Read JSON file using Python" }, { "code": null, "e": 49707, "s": 49657, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 49729, "s": 49707, "text": "Python map() function" }, { "code": null, "e": 49773, "s": 49729, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 49808, "s": 49773, "text": "Read a file line by line in Python" }, { "code": null, "e": 49830, "s": 49808, "text": "Enumerate() in Python" }, { "code": null, "e": 49862, "s": 49830, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 49892, "s": 49862, "text": "Iterate over a list in Python" }, { "code": null, "e": 49934, "s": 49892, "text": "Different ways to create Pandas Dataframe" } ]
How to upgrade Python PIP version on Windows | upgrade pip version
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws There is a need of keeping upgrade python PIP every time because while installing new python packages, we have to make sure that the Python PIP has to be the latest version on your machine. Otherwise, you may get the below error: Here I am going to show to you how to upgrade Python PIP on the windows machine. Open the windows command prompt and go to PIP installations directory. For me it is : C:\Users\{user_name}\AppData\Local\Programs\Python\Python37\Scripts pip --version pip 20.0.2 from c:\users\user\appdata\local\programs\python\python37\lib\site-packages\pip (python 3.7) Currently, I am on PIP 20.0.0, let’s upgrade PIP with the latest version. pip install –upgrade pip command is used to upgrade the pip. Go to the same pip installation directory and hit the below command. C:\Users\user\AppData\Local\Programs\Python\Python37\Scripts>pip install --upgrade pip Collecting pip Downloading pip-20.1-py2.py3-none-any.whl (1.5 MB) |████████████████████████████████| 1.5 MB 13 kB/s Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 20.0.2 Uninstalling pip-20.0.2: Successfully uninstalled pip-20.0.2 Successfully installed pip-20.1 If everything went well you could see the above success message. C:\Users\user\AppData\Local\Programs\Python\Python37\Scripts>pip --version pip 20.1 Now I have the latest PIP. Done. Where can I find PIP installation on Windows How to install Python on Windows Happy Learning 🙂 Where can I find Python PIP in windows ? Python Selenium HelloWorld Example How install Python on Windows 10 How to connect MySQL DB with Python How to find Linux RHEL version ? OS and Kernel Version ? How to install AWS CLI on Windows 10 Python Django Helloworld Example Modes of Python Program Python Selenium Automate the Login Form Ubuntu – How to set default Java version on Ubuntu How to access for loop index in Python How to Copy Local Files to AWS EC2 instance Manually ? How to check whether a file exists python ? How to pass Command line Arguments in Python Python raw_input read input from keyboard Where can I find Python PIP in windows ? Python Selenium HelloWorld Example How install Python on Windows 10 How to connect MySQL DB with Python How to find Linux RHEL version ? OS and Kernel Version ? How to install AWS CLI on Windows 10 Python Django Helloworld Example Modes of Python Program Python Selenium Automate the Login Form Ubuntu – How to set default Java version on Ubuntu How to access for loop index in Python How to Copy Local Files to AWS EC2 instance Manually ? How to check whether a file exists python ? How to pass Command line Arguments in Python Python raw_input read input from keyboard Aashrith March 26, 2022 at 3:44 pm - Reply Its very helpful, Thank you. Aashrith March 26, 2022 at 3:44 pm - Reply Its very helpful, Thank you. Its very helpful, Thank you. Δ Python – Introduction Python – Features Python – Install on Windows Python – Modes of Program Python – Number System Python – Identifiers Python – Operators Python – Ternary Operator Python – Command Line Arguments Python – Keywords Python – Data Types Python – Upgrade Python PIP Python – Virtual Environment Pyhton – Type Casting Python – String to Int Python – Conditional Statements Python – if statement Python – *args and **kwargs Python – Date Formatting Python – Read input from keyboard Python – raw_input Python – List In Depth Python – List Comprehension Python – Set in Depth Python – Dictionary in Depth Python – Tuple in Depth Python – Stack Datastructure Python – Classes and Objects Python – Constructors Python – Object Introspection Python – Inheritance Python – Decorators Python – Serialization with Pickle Python – Exceptions Handling Python – User defined Exceptions Python – Multiprocessing Python – Default function parameters Python – Lambdas Functions Python – NumPy Library Python – MySQL Connector Python – MySQL Create Database Python – MySQL Read Data Python – MySQL Insert Data Python – MySQL Update Records Python – MySQL Delete Records Python – String Case Conversion Howto – Find biggest of 2 numbers Howto – Remove duplicates from List Howto – Convert any Number to Binary Howto – Merge two Lists Howto – Merge two dicts Howto – Get Characters Count in a File Howto – Get Words Count in a File Howto – Remove Spaces from String Howto – Read Env variables Howto – Read a text File Howto – Read a JSON File Howto – Read Config.ini files Howto – Iterate Dictionary Howto – Convert List Of Objects to CSV Howto – Merge two dict in Python Howto – create Zip File Howto – Get OS info Howto – Get size of Directory Howto – Check whether a file exists Howto – Remove key from dictionary Howto – Sort Objects Howto – Create or Delete Directories Howto – Read CSV File Howto – Create Python Iterable class Howto – Access for loop index Howto – Clear all elements from List Howto – Remove empty lists from a List Howto – Remove special characters from String Howto – Sort dictionary by key Howto – Filter a list
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 628, "s": 398, "text": "There is a need of keeping upgrade python PIP every time because while installing new python packages, we have to make sure that the Python PIP has to be the latest version on your machine. Otherwise, you may get the below error:" }, { "code": null, "e": 709, "s": 628, "text": "Here I am going to show to you how to upgrade Python PIP on the windows machine." }, { "code": null, "e": 780, "s": 709, "text": "Open the windows command prompt and go to PIP installations directory." }, { "code": null, "e": 863, "s": 780, "text": "For me it is : C:\\Users\\{user_name}\\AppData\\Local\\Programs\\Python\\Python37\\Scripts" }, { "code": null, "e": 981, "s": 863, "text": "pip --version\npip 20.0.2 from c:\\users\\user\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\pip (python 3.7)" }, { "code": null, "e": 1055, "s": 981, "text": "Currently, I am on PIP 20.0.0, let’s upgrade PIP with the latest version." }, { "code": null, "e": 1185, "s": 1055, "text": "pip install –upgrade pip command is used to upgrade the pip. Go to the same pip installation directory and hit the below command." }, { "code": null, "e": 1605, "s": 1185, "text": "C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37\\Scripts>pip install --upgrade pip\nCollecting pip\n Downloading pip-20.1-py2.py3-none-any.whl (1.5 MB)\n |████████████████████████████████| 1.5 MB 13 kB/s\nInstalling collected packages: pip\n Attempting uninstall: pip\n Found existing installation: pip 20.0.2\n Uninstalling pip-20.0.2:\n Successfully uninstalled pip-20.0.2\nSuccessfully installed pip-20.1" }, { "code": null, "e": 1670, "s": 1605, "text": "If everything went well you could see the above success message." }, { "code": null, "e": 1754, "s": 1670, "text": "C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37\\Scripts>pip --version\npip 20.1" }, { "code": null, "e": 1781, "s": 1754, "text": "Now I have the latest PIP." }, { "code": null, "e": 1787, "s": 1781, "text": "Done." }, { "code": null, "e": 1832, "s": 1787, "text": "Where can I find PIP installation on Windows" }, { "code": null, "e": 1865, "s": 1832, "text": "How to install Python on Windows" }, { "code": null, "e": 1882, "s": 1865, "text": "Happy Learning 🙂" }, { "code": null, "e": 2496, "s": 1882, "text": "\nWhere can I find Python PIP in windows ?\nPython Selenium HelloWorld Example\nHow install Python on Windows 10\nHow to connect MySQL DB with Python\nHow to find Linux RHEL version ? OS and Kernel Version ?\nHow to install AWS CLI on Windows 10\nPython Django Helloworld Example\nModes of Python Program\nPython Selenium Automate the Login Form\nUbuntu – How to set default Java version on Ubuntu\nHow to access for loop index in Python\nHow to Copy Local Files to AWS EC2 instance Manually ?\nHow to check whether a file exists python ?\nHow to pass Command line Arguments in Python\nPython raw_input read input from keyboard\n" }, { "code": null, "e": 2537, "s": 2496, "text": "Where can I find Python PIP in windows ?" }, { "code": null, "e": 2572, "s": 2537, "text": "Python Selenium HelloWorld Example" }, { "code": null, "e": 2605, "s": 2572, "text": "How install Python on Windows 10" }, { "code": null, "e": 2641, "s": 2605, "text": "How to connect MySQL DB with Python" }, { "code": null, "e": 2698, "s": 2641, "text": "How to find Linux RHEL version ? OS and Kernel Version ?" }, { "code": null, "e": 2735, "s": 2698, "text": "How to install AWS CLI on Windows 10" }, { "code": null, "e": 2768, "s": 2735, "text": "Python Django Helloworld Example" }, { "code": null, "e": 2792, "s": 2768, "text": "Modes of Python Program" }, { "code": null, "e": 2832, "s": 2792, "text": "Python Selenium Automate the Login Form" }, { "code": null, "e": 2883, "s": 2832, "text": "Ubuntu – How to set default Java version on Ubuntu" }, { "code": null, "e": 2922, "s": 2883, "text": "How to access for loop index in Python" }, { "code": null, "e": 2977, "s": 2922, "text": "How to Copy Local Files to AWS EC2 instance Manually ?" }, { "code": null, "e": 3021, "s": 2977, "text": "How to check whether a file exists python ?" }, { "code": null, "e": 3066, "s": 3021, "text": "How to pass Command line Arguments in Python" }, { "code": null, "e": 3108, "s": 3066, "text": "Python raw_input read input from keyboard" }, { "code": null, "e": 3193, "s": 3108, "text": "\n\n\n\n\n\nAashrith\nMarch 26, 2022 at 3:44 pm - Reply \n\nIts very helpful, Thank you.\n\n\n\n\n" }, { "code": null, "e": 3276, "s": 3193, "text": "\n\n\n\n\nAashrith\nMarch 26, 2022 at 3:44 pm - Reply \n\nIts very helpful, Thank you.\n\n\n\n" }, { "code": null, "e": 3305, "s": 3276, "text": "Its very helpful, Thank you." }, { "code": null, "e": 3311, "s": 3309, "text": "Δ" }, { "code": null, "e": 3334, "s": 3311, "text": " Python – Introduction" }, { "code": null, "e": 3353, "s": 3334, "text": " Python – Features" }, { "code": null, "e": 3382, "s": 3353, "text": " Python – Install on Windows" }, { "code": null, "e": 3409, "s": 3382, "text": " Python – Modes of Program" }, { "code": null, "e": 3433, "s": 3409, "text": " Python – Number System" }, { "code": null, "e": 3455, "s": 3433, "text": " Python – Identifiers" }, { "code": null, "e": 3475, "s": 3455, "text": " Python – Operators" }, { "code": null, "e": 3502, "s": 3475, "text": " Python – Ternary Operator" }, { "code": null, "e": 3535, "s": 3502, "text": " Python – Command Line Arguments" }, { "code": null, "e": 3554, "s": 3535, "text": " Python – Keywords" }, { "code": null, "e": 3575, "s": 3554, "text": " Python – Data Types" }, { "code": null, "e": 3604, "s": 3575, "text": " Python – Upgrade Python PIP" }, { "code": null, "e": 3634, "s": 3604, "text": " Python – Virtual Environment" }, { "code": null, "e": 3657, "s": 3634, "text": " Pyhton – Type Casting" }, { "code": null, "e": 3681, "s": 3657, "text": " Python – String to Int" }, { "code": null, "e": 3714, "s": 3681, "text": " Python – Conditional Statements" }, { "code": null, "e": 3737, "s": 3714, "text": " Python – if statement" }, { "code": null, "e": 3766, "s": 3737, "text": " Python – *args and **kwargs" }, { "code": null, "e": 3792, "s": 3766, "text": " Python – Date Formatting" }, { "code": null, "e": 3827, "s": 3792, "text": " Python – Read input from keyboard" }, { "code": null, "e": 3847, "s": 3827, "text": " Python – raw_input" }, { "code": null, "e": 3871, "s": 3847, "text": " Python – List In Depth" }, { "code": null, "e": 3900, "s": 3871, "text": " Python – List Comprehension" }, { "code": null, "e": 3923, "s": 3900, "text": " Python – Set in Depth" }, { "code": null, "e": 3953, "s": 3923, "text": " Python – Dictionary in Depth" }, { "code": null, "e": 3978, "s": 3953, "text": " Python – Tuple in Depth" }, { "code": null, "e": 4008, "s": 3978, "text": " Python – Stack Datastructure" }, { "code": null, "e": 4038, "s": 4008, "text": " Python – Classes and Objects" }, { "code": null, "e": 4061, "s": 4038, "text": " Python – Constructors" }, { "code": null, "e": 4092, "s": 4061, "text": " Python – Object Introspection" }, { "code": null, "e": 4114, "s": 4092, "text": " Python – Inheritance" }, { "code": null, "e": 4135, "s": 4114, "text": " Python – Decorators" }, { "code": null, "e": 4171, "s": 4135, "text": " Python – Serialization with Pickle" }, { "code": null, "e": 4201, "s": 4171, "text": " Python – Exceptions Handling" }, { "code": null, "e": 4235, "s": 4201, "text": " Python – User defined Exceptions" }, { "code": null, "e": 4261, "s": 4235, "text": " Python – Multiprocessing" }, { "code": null, "e": 4299, "s": 4261, "text": " Python – Default function parameters" }, { "code": null, "e": 4327, "s": 4299, "text": " Python – Lambdas Functions" }, { "code": null, "e": 4351, "s": 4327, "text": " Python – NumPy Library" }, { "code": null, "e": 4377, "s": 4351, "text": " Python – MySQL Connector" }, { "code": null, "e": 4409, "s": 4377, "text": " Python – MySQL Create Database" }, { "code": null, "e": 4435, "s": 4409, "text": " Python – MySQL Read Data" }, { "code": null, "e": 4463, "s": 4435, "text": " Python – MySQL Insert Data" }, { "code": null, "e": 4494, "s": 4463, "text": " Python – MySQL Update Records" }, { "code": null, "e": 4525, "s": 4494, "text": " Python – MySQL Delete Records" }, { "code": null, "e": 4558, "s": 4525, "text": " Python – String Case Conversion" }, { "code": null, "e": 4593, "s": 4558, "text": " Howto – Find biggest of 2 numbers" }, { "code": null, "e": 4630, "s": 4593, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 4668, "s": 4630, "text": " Howto – Convert any Number to Binary" }, { "code": null, "e": 4694, "s": 4668, "text": " Howto – Merge two Lists" }, { "code": null, "e": 4719, "s": 4694, "text": " Howto – Merge two dicts" }, { "code": null, "e": 4759, "s": 4719, "text": " Howto – Get Characters Count in a File" }, { "code": null, "e": 4794, "s": 4759, "text": " Howto – Get Words Count in a File" }, { "code": null, "e": 4829, "s": 4794, "text": " Howto – Remove Spaces from String" }, { "code": null, "e": 4858, "s": 4829, "text": " Howto – Read Env variables" }, { "code": null, "e": 4884, "s": 4858, "text": " Howto – Read a text File" }, { "code": null, "e": 4910, "s": 4884, "text": " Howto – Read a JSON File" }, { "code": null, "e": 4942, "s": 4910, "text": " Howto – Read Config.ini files" }, { "code": null, "e": 4970, "s": 4942, "text": " Howto – Iterate Dictionary" }, { "code": null, "e": 5010, "s": 4970, "text": " Howto – Convert List Of Objects to CSV" }, { "code": null, "e": 5044, "s": 5010, "text": " Howto – Merge two dict in Python" }, { "code": null, "e": 5069, "s": 5044, "text": " Howto – create Zip File" }, { "code": null, "e": 5090, "s": 5069, "text": " Howto – Get OS info" }, { "code": null, "e": 5121, "s": 5090, "text": " Howto – Get size of Directory" }, { "code": null, "e": 5158, "s": 5121, "text": " Howto – Check whether a file exists" }, { "code": null, "e": 5195, "s": 5158, "text": " Howto – Remove key from dictionary" }, { "code": null, "e": 5217, "s": 5195, "text": " Howto – Sort Objects" }, { "code": null, "e": 5255, "s": 5217, "text": " Howto – Create or Delete Directories" }, { "code": null, "e": 5278, "s": 5255, "text": " Howto – Read CSV File" }, { "code": null, "e": 5316, "s": 5278, "text": " Howto – Create Python Iterable class" }, { "code": null, "e": 5347, "s": 5316, "text": " Howto – Access for loop index" }, { "code": null, "e": 5385, "s": 5347, "text": " Howto – Clear all elements from List" }, { "code": null, "e": 5425, "s": 5385, "text": " Howto – Remove empty lists from a List" }, { "code": null, "e": 5472, "s": 5425, "text": " Howto – Remove special characters from String" }, { "code": null, "e": 5504, "s": 5472, "text": " Howto – Sort dictionary by key" } ]
Maximum value at each level in an N-ary Tree - GeeksforGeeks
22 Jun, 2021 Given a N-ary Tree consisting of nodes valued in the range [0, N – 1] and an array arr[] where each node i is associated to value arr[i], the task is to print the maximum value associated with any node at each level of the given N-ary Tree. Examples: Input: N = 8, Edges[][] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}}, arr[] = {4, 2, 3, -5, -1, 3, -2, 6} Output: 4 3 6 Explanation: Below is the given N-ary Tree: The Max of all nodes of the 0th level is 4. The Max of all nodes of the 1st level is 3. The Max of all nodes of the 2nd level is 6. Input: N = 10, Edges[][] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}, {6, 8}, {6, 9}}, arr[] = {1, 2, -1, 3, 4, 5, 8, 6, 12, 7} Output: 1 3 8 12 Explanation: Below is the given N-ary Tree: The Max of all nodes of the 0th level is 1. The Max of all nodes of the 1st level is 3. The Max of all nodes of the 2nd level is 8. The Max of all nodes of the 3rd level is 12. Approach: This problem can be solved by performing the Level Order Traversal of the given tree. While traversing the tree, process nodes of each level separately. For every level being processed, compute the maximum value of all nodes in the level. Follow the steps below: Store all the child nodes of the current level in a Queue and pop the nodes of the current level one by one.Find the maximum value of all the popped nodes of the current level.Print the maximum value obtained in the above step.Follow the above steps for each level of the given Tree and print the maximum value for each level respectively. Store all the child nodes of the current level in a Queue and pop the nodes of the current level one by one. Find the maximum value of all the popped nodes of the current level. Print the maximum value obtained in the above step. Follow the above steps for each level of the given Tree and print the maximum value for each level respectively. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum value// at each level of N-ary treeint maxAtLevel(int N, int M, vector<int> Value, int Edges[][2]){ // Stores the adjacency list vector<int> adj[N]; // Create the adjacency list for (int i = 0; i < M; i++) { int u = Edges[i][0]; int v = Edges[i][1]; adj[u].push_back(v); } // Perform level order traversal // of nodes at each level queue<int> q; // Push the root node q.push(0); // Iterate until queue is empty while (!q.empty()) { // Get the size of queue int count = q.size(); int maxVal = 0; // Iterate for all the nodes // in the queue currently while (count--) { // Dequeue an node from queue int temp = q.front(); q.pop(); maxVal = max(maxVal, Value[temp]); // Enqueue the children of // dequeued node for (int i = 0; i < adj[temp].size(); i++) { q.push(adj[temp][i]); } } // Print the result cout << maxVal << " "; }} // Driver Codeint main(){ // Number of nodes int N = 10; // Edges of the N-ary tree int Edges[][2] = { { 0, 1 }, { 0, 2 }, { 0, 3 }, { 1, 4 }, { 1, 5 }, { 3, 6 }, { 6, 7 }, { 6, 8 }, { 6, 9 } }; // Given cost vector<int> Value = { 1, 2, -1, 3, 4, 5, 8, 6, 12, 7 }; // Function Call maxAtLevel(N, N - 1, Value, Edges); return 0;} // Java program for// the above approachimport java.util.*;class GFG{ // Function to find the maximum value// at each level of N-ary treestatic void maxAtLevel(int N, int M, int []Value, int Edges[][]){ // Stores the adjacency list Vector<Integer> []adj = new Vector[N]; for (int i = 0; i < adj.length; i++) adj[i] = new Vector<Integer>(); // Create the adjacency list for (int i = 0; i < M; i++) { int u = Edges[i][0]; int v = Edges[i][1]; adj[u].add(v); } // Perform level order traversal // of nodes at each level Queue<Integer> q = new LinkedList<>(); // Push the root node q.add(0); // Iterate until queue is empty while (!q.isEmpty()) { // Get the size of queue int count = q.size(); int maxVal = 0; // Iterate for all the nodes // in the queue currently while (count-- > 0) { // Dequeue an node from queue int temp = q.peek(); q.remove(); maxVal = Math.max(maxVal, Value[temp]); // Enqueue the children of // dequeued node for (int i = 0; i < adj[temp].size(); i++) { q.add(adj[temp].get(i)); } } // Print the result System.out.print(maxVal + " "); }} // Driver Codepublic static void main(String[] args){ // Number of nodes int N = 10; // Edges of the N-ary tree int Edges[][] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}, {6, 8}, {6, 9}}; // Given cost int []Value = {1, 2, -1, 3, 4, 5, 8, 6, 12, 7}; // Function Call maxAtLevel(N, N - 1, Value, Edges);}} // This code is contributed by 29AjayKumar # Python3 program for the above approach # Function to find the maximum value# at each level of N-ary treedef maxAtLevel(N, M, Value, Edges): # Stores the adjacency list adj = [[] for i in range(N)] # Create the adjacency list for i in range(M): u = Edges[i][0] v = Edges[i][1] adj[u].append(v) # Perform level order traversal # of nodes at each level q = [] # Push the root node q.append(0) # Iterate until queue is empty while (len(q)): # Get the size of queue count = len(q) maxVal = 0 # Iterate for: all the nodes # in the queue currently while (count): # Dequeue an node from queue temp = q[0] q.remove(q[0]) maxVal = max(maxVal, Value[temp]) # Enqueue the children of # dequeued node for i in range(len(adj[temp])): q.append(adj[temp][i]) count -= 1 # Print the result print(maxVal, end = " ") # Driver Codeif __name__ == '__main__': # Number of nodes N = 10 # Edges of the N-ary tree Edges = [ [ 0, 1 ], [ 0, 2 ], [ 0, 3 ], [ 1, 4 ], [ 1, 5 ], [ 3, 6 ], [ 6, 7 ], [ 6, 8 ], [ 6, 9 ] ] # Given cost Value = [ 1, 2, -1, 3, 4, 5, 8, 6, 12, 7 ] # Function Call maxAtLevel(N, N - 1, Value, Edges) # This code is contributed by ipg2016107 // C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the// maximum value at each// level of N-ary treestatic void maxAtLevel(int N, int M, int []Value, int [,]Edges){ // Stores the adjacency list List<int> []adj = new List<int>[N]; for (int i = 0; i < adj.Length; i++) adj[i] = new List<int>(); // Create the adjacency list for (int i = 0; i < M; i++) { int u = Edges[i, 0]; int v = Edges[i, 1]; adj[u].Add(v); } // Perform level order traversal // of nodes at each level Queue<int> q = new Queue<int>(); // Push the root node q.Enqueue(0); // Iterate until queue is empty while (q.Count != 0) { // Get the size of queue int count = q.Count; int maxVal = 0; // Iterate for all the nodes // in the queue currently while (count-- > 0) { // Dequeue an node from queue int temp = q.Peek(); q.Dequeue(); maxVal = Math.Max(maxVal, Value[temp]); // Enqueue the children of // dequeued node for (int i = 0; i < adj[temp].Count; i++) { q.Enqueue(adj[temp][i]); } } // Print the result Console.Write(maxVal + " "); }} // Driver Codepublic static void Main(String[] args){ // Number of nodes int N = 10; // Edges of the N-ary tree int [,]Edges = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}, {6, 8}, {6, 9}}; // Given cost int []Value = {1, 2, -1, 3, 4, 5, 8, 6, 12, 7}; // Function Call maxAtLevel(N, N - 1, Value, Edges);}} // This code is contributed by 29AjayKumar <script> // Javascript program for the above approach // Function to find the maximum value// at each level of N-ary treefunction maxAtLevel(N, M, Value, Edges){ // Stores the adjacency list let adj = new Array(N); for(let i = 0; i < adj.length; i++) adj[i] = []; // Create the adjacency list for(let i = 0; i < M; i++) { let u = Edges[i][0]; let v = Edges[i][1]; adj[u].push(v); } // Perform level order traversal // of nodes at each level let q = []; // Push the root node q.push(0); // Iterate until queue is empty while (q.length > 0) { // Get the size of queue let count = q.length; let maxVal = 0; // Iterate for all the nodes // in the queue currently while (count-- > 0) { // Dequeue an node from queue let temp = q[0]; q.shift(); maxVal = Math.max(maxVal, Value[temp]); // Enqueue the children of // dequeued node for(let i = 0; i < adj[temp].length; i++) { q.push(adj[temp][i]); } } // Print the result document.write(maxVal + " "); }} // Driver code // Number of nodeslet N = 10; // Edges of the N-ary treelet Edges = [ [ 0, 1 ], [ 0, 2 ], [ 0, 3 ], [ 1, 4 ], [ 1, 5 ], [ 3, 6 ], [ 6, 7 ], [ 6, 8 ], [ 6, 9 ] ]; // Given costlet Value = [ 1, 2, -1, 3, 4, 5, 8, 6, 12, 7 ]; // Function CallmaxAtLevel(N, N - 1, Value, Edges); // This code is contributed by suresh07 </script> 1 3 8 12 Time Complexity: O(N)Auxiliary Space: O(N) 29AjayKumar ipg2016107 suresh07 BFS n-ary-tree Tree Traversals tree-level-order Searching Tree Searching Tree BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Given an array of size n and a number k, find all elements that appear more than n/k times Program to find largest element in an array k largest(or smallest) elements in an array Search an element in a sorted and rotated array Median of two sorted arrays of different sizes Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) AVL Tree | Set 1 (Insertion) Level Order Binary Tree Traversal Inorder Tree Traversal without Recursion
[ { "code": null, "e": 25055, "s": 25027, "text": "\n22 Jun, 2021" }, { "code": null, "e": 25296, "s": 25055, "text": "Given a N-ary Tree consisting of nodes valued in the range [0, N – 1] and an array arr[] where each node i is associated to value arr[i], the task is to print the maximum value associated with any node at each level of the given N-ary Tree." }, { "code": null, "e": 25306, "s": 25296, "text": "Examples:" }, { "code": null, "e": 25485, "s": 25306, "text": "Input: N = 8, Edges[][] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}}, arr[] = {4, 2, 3, -5, -1, 3, -2, 6} Output: 4 3 6 Explanation: Below is the given N-ary Tree: " }, { "code": null, "e": 25617, "s": 25485, "text": "The Max of all nodes of the 0th level is 4. The Max of all nodes of the 1st level is 3. The Max of all nodes of the 2nd level is 6." }, { "code": null, "e": 25821, "s": 25617, "text": "Input: N = 10, Edges[][] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}, {6, 8}, {6, 9}}, arr[] = {1, 2, -1, 3, 4, 5, 8, 6, 12, 7} Output: 1 3 8 12 Explanation: Below is the given N-ary Tree: " }, { "code": null, "e": 26000, "s": 25821, "text": "The Max of all nodes of the 0th level is 1. The Max of all nodes of the 1st level is 3. The Max of all nodes of the 2nd level is 8. The Max of all nodes of the 3rd level is 12. " }, { "code": null, "e": 26274, "s": 26000, "text": "Approach: This problem can be solved by performing the Level Order Traversal of the given tree. While traversing the tree, process nodes of each level separately. For every level being processed, compute the maximum value of all nodes in the level. Follow the steps below: " }, { "code": null, "e": 26614, "s": 26274, "text": "Store all the child nodes of the current level in a Queue and pop the nodes of the current level one by one.Find the maximum value of all the popped nodes of the current level.Print the maximum value obtained in the above step.Follow the above steps for each level of the given Tree and print the maximum value for each level respectively." }, { "code": null, "e": 26723, "s": 26614, "text": "Store all the child nodes of the current level in a Queue and pop the nodes of the current level one by one." }, { "code": null, "e": 26792, "s": 26723, "text": "Find the maximum value of all the popped nodes of the current level." }, { "code": null, "e": 26844, "s": 26792, "text": "Print the maximum value obtained in the above step." }, { "code": null, "e": 26957, "s": 26844, "text": "Follow the above steps for each level of the given Tree and print the maximum value for each level respectively." }, { "code": null, "e": 27008, "s": 26957, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27012, "s": 27008, "text": "C++" }, { "code": null, "e": 27017, "s": 27012, "text": "Java" }, { "code": null, "e": 27025, "s": 27017, "text": "Python3" }, { "code": null, "e": 27028, "s": 27025, "text": "C#" }, { "code": null, "e": 27039, "s": 27028, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum value// at each level of N-ary treeint maxAtLevel(int N, int M, vector<int> Value, int Edges[][2]){ // Stores the adjacency list vector<int> adj[N]; // Create the adjacency list for (int i = 0; i < M; i++) { int u = Edges[i][0]; int v = Edges[i][1]; adj[u].push_back(v); } // Perform level order traversal // of nodes at each level queue<int> q; // Push the root node q.push(0); // Iterate until queue is empty while (!q.empty()) { // Get the size of queue int count = q.size(); int maxVal = 0; // Iterate for all the nodes // in the queue currently while (count--) { // Dequeue an node from queue int temp = q.front(); q.pop(); maxVal = max(maxVal, Value[temp]); // Enqueue the children of // dequeued node for (int i = 0; i < adj[temp].size(); i++) { q.push(adj[temp][i]); } } // Print the result cout << maxVal << \" \"; }} // Driver Codeint main(){ // Number of nodes int N = 10; // Edges of the N-ary tree int Edges[][2] = { { 0, 1 }, { 0, 2 }, { 0, 3 }, { 1, 4 }, { 1, 5 }, { 3, 6 }, { 6, 7 }, { 6, 8 }, { 6, 9 } }; // Given cost vector<int> Value = { 1, 2, -1, 3, 4, 5, 8, 6, 12, 7 }; // Function Call maxAtLevel(N, N - 1, Value, Edges); return 0;}", "e": 28773, "s": 27039, "text": null }, { "code": "// Java program for// the above approachimport java.util.*;class GFG{ // Function to find the maximum value// at each level of N-ary treestatic void maxAtLevel(int N, int M, int []Value, int Edges[][]){ // Stores the adjacency list Vector<Integer> []adj = new Vector[N]; for (int i = 0; i < adj.length; i++) adj[i] = new Vector<Integer>(); // Create the adjacency list for (int i = 0; i < M; i++) { int u = Edges[i][0]; int v = Edges[i][1]; adj[u].add(v); } // Perform level order traversal // of nodes at each level Queue<Integer> q = new LinkedList<>(); // Push the root node q.add(0); // Iterate until queue is empty while (!q.isEmpty()) { // Get the size of queue int count = q.size(); int maxVal = 0; // Iterate for all the nodes // in the queue currently while (count-- > 0) { // Dequeue an node from queue int temp = q.peek(); q.remove(); maxVal = Math.max(maxVal, Value[temp]); // Enqueue the children of // dequeued node for (int i = 0; i < adj[temp].size(); i++) { q.add(adj[temp].get(i)); } } // Print the result System.out.print(maxVal + \" \"); }} // Driver Codepublic static void main(String[] args){ // Number of nodes int N = 10; // Edges of the N-ary tree int Edges[][] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}, {6, 8}, {6, 9}}; // Given cost int []Value = {1, 2, -1, 3, 4, 5, 8, 6, 12, 7}; // Function Call maxAtLevel(N, N - 1, Value, Edges);}} // This code is contributed by 29AjayKumar", "e": 30473, "s": 28773, "text": null }, { "code": "# Python3 program for the above approach # Function to find the maximum value# at each level of N-ary treedef maxAtLevel(N, M, Value, Edges): # Stores the adjacency list adj = [[] for i in range(N)] # Create the adjacency list for i in range(M): u = Edges[i][0] v = Edges[i][1] adj[u].append(v) # Perform level order traversal # of nodes at each level q = [] # Push the root node q.append(0) # Iterate until queue is empty while (len(q)): # Get the size of queue count = len(q) maxVal = 0 # Iterate for: all the nodes # in the queue currently while (count): # Dequeue an node from queue temp = q[0] q.remove(q[0]) maxVal = max(maxVal, Value[temp]) # Enqueue the children of # dequeued node for i in range(len(adj[temp])): q.append(adj[temp][i]) count -= 1 # Print the result print(maxVal, end = \" \") # Driver Codeif __name__ == '__main__': # Number of nodes N = 10 # Edges of the N-ary tree Edges = [ [ 0, 1 ], [ 0, 2 ], [ 0, 3 ], [ 1, 4 ], [ 1, 5 ], [ 3, 6 ], [ 6, 7 ], [ 6, 8 ], [ 6, 9 ] ] # Given cost Value = [ 1, 2, -1, 3, 4, 5, 8, 6, 12, 7 ] # Function Call maxAtLevel(N, N - 1, Value, Edges) # This code is contributed by ipg2016107", "e": 31976, "s": 30473, "text": null }, { "code": "// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the// maximum value at each// level of N-ary treestatic void maxAtLevel(int N, int M, int []Value, int [,]Edges){ // Stores the adjacency list List<int> []adj = new List<int>[N]; for (int i = 0; i < adj.Length; i++) adj[i] = new List<int>(); // Create the adjacency list for (int i = 0; i < M; i++) { int u = Edges[i, 0]; int v = Edges[i, 1]; adj[u].Add(v); } // Perform level order traversal // of nodes at each level Queue<int> q = new Queue<int>(); // Push the root node q.Enqueue(0); // Iterate until queue is empty while (q.Count != 0) { // Get the size of queue int count = q.Count; int maxVal = 0; // Iterate for all the nodes // in the queue currently while (count-- > 0) { // Dequeue an node from queue int temp = q.Peek(); q.Dequeue(); maxVal = Math.Max(maxVal, Value[temp]); // Enqueue the children of // dequeued node for (int i = 0; i < adj[temp].Count; i++) { q.Enqueue(adj[temp][i]); } } // Print the result Console.Write(maxVal + \" \"); }} // Driver Codepublic static void Main(String[] args){ // Number of nodes int N = 10; // Edges of the N-ary tree int [,]Edges = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}, {6, 8}, {6, 9}}; // Given cost int []Value = {1, 2, -1, 3, 4, 5, 8, 6, 12, 7}; // Function Call maxAtLevel(N, N - 1, Value, Edges);}} // This code is contributed by 29AjayKumar", "e": 33703, "s": 31976, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find the maximum value// at each level of N-ary treefunction maxAtLevel(N, M, Value, Edges){ // Stores the adjacency list let adj = new Array(N); for(let i = 0; i < adj.length; i++) adj[i] = []; // Create the adjacency list for(let i = 0; i < M; i++) { let u = Edges[i][0]; let v = Edges[i][1]; adj[u].push(v); } // Perform level order traversal // of nodes at each level let q = []; // Push the root node q.push(0); // Iterate until queue is empty while (q.length > 0) { // Get the size of queue let count = q.length; let maxVal = 0; // Iterate for all the nodes // in the queue currently while (count-- > 0) { // Dequeue an node from queue let temp = q[0]; q.shift(); maxVal = Math.max(maxVal, Value[temp]); // Enqueue the children of // dequeued node for(let i = 0; i < adj[temp].length; i++) { q.push(adj[temp][i]); } } // Print the result document.write(maxVal + \" \"); }} // Driver code // Number of nodeslet N = 10; // Edges of the N-ary treelet Edges = [ [ 0, 1 ], [ 0, 2 ], [ 0, 3 ], [ 1, 4 ], [ 1, 5 ], [ 3, 6 ], [ 6, 7 ], [ 6, 8 ], [ 6, 9 ] ]; // Given costlet Value = [ 1, 2, -1, 3, 4, 5, 8, 6, 12, 7 ]; // Function CallmaxAtLevel(N, N - 1, Value, Edges); // This code is contributed by suresh07 </script>", "e": 35419, "s": 33703, "text": null }, { "code": null, "e": 35428, "s": 35419, "text": "1 3 8 12" }, { "code": null, "e": 35473, "s": 35430, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 35485, "s": 35473, "text": "29AjayKumar" }, { "code": null, "e": 35496, "s": 35485, "text": "ipg2016107" }, { "code": null, "e": 35505, "s": 35496, "text": "suresh07" }, { "code": null, "e": 35509, "s": 35505, "text": "BFS" }, { "code": null, "e": 35520, "s": 35509, "text": "n-ary-tree" }, { "code": null, "e": 35536, "s": 35520, "text": "Tree Traversals" }, { "code": null, "e": 35553, "s": 35536, "text": "tree-level-order" }, { "code": null, "e": 35563, "s": 35553, "text": "Searching" }, { "code": null, "e": 35568, "s": 35563, "text": "Tree" }, { "code": null, "e": 35578, "s": 35568, "text": "Searching" }, { "code": null, "e": 35583, "s": 35578, "text": "Tree" }, { "code": null, "e": 35587, "s": 35583, "text": "BFS" }, { "code": null, "e": 35685, "s": 35587, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35694, "s": 35685, "text": "Comments" }, { "code": null, "e": 35707, "s": 35694, "text": "Old Comments" }, { "code": null, "e": 35798, "s": 35707, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" }, { "code": null, "e": 35842, "s": 35798, "text": "Program to find largest element in an array" }, { "code": null, "e": 35886, "s": 35842, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 35934, "s": 35886, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 35981, "s": 35934, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 36031, "s": 35981, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 36066, "s": 36031, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 36095, "s": 36066, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 36129, "s": 36095, "text": "Level Order Binary Tree Traversal" } ]
Place a specific value for NULL values in a MySQL column
Use IFNULL() to find and place a specific value for NULL values. Let us first create a table − mysql> create table DemoTable1878 ( FirstName varchar(20) ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1878 values('Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1878 values(NULL); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1878 values('David'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1878 values(NULL); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1878; This will produce the following output − +-----------+ | FirstName | +-----------+ | Chris | | NULL | | David | | NULL | +-----------+ 4 rows in set (0.00 sec) Here is the query to work with IFNULL() − mysql> select ifnull(FirstName,'Robert') from DemoTable1878; This will produce the following output − +----------------------------+ | ifnull(FirstName,'Robert') | +----------------------------+ | Chris | | Robert | | David | | Robert | +----------------------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1157, "s": 1062, "text": "Use IFNULL() to find and place a specific value for NULL values. Let us first create a table −" }, { "code": null, "e": 1264, "s": 1157, "text": "mysql> create table DemoTable1878\n (\n FirstName varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1320, "s": 1264, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1658, "s": 1320, "text": "mysql> insert into DemoTable1878 values('Chris');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1878 values(NULL);\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1878 values('David');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1878 values(NULL);\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 1718, "s": 1658, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1754, "s": 1718, "text": "mysql> select * from DemoTable1878;" }, { "code": null, "e": 1795, "s": 1754, "text": "This will produce the following output −" }, { "code": null, "e": 1932, "s": 1795, "text": "+-----------+\n| FirstName |\n+-----------+\n| Chris |\n| NULL |\n| David |\n| NULL |\n+-----------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 1974, "s": 1932, "text": "Here is the query to work with IFNULL() −" }, { "code": null, "e": 2035, "s": 1974, "text": "mysql> select ifnull(FirstName,'Robert') from DemoTable1878;" }, { "code": null, "e": 2076, "s": 2035, "text": "This will produce the following output −" }, { "code": null, "e": 2349, "s": 2076, "text": "+----------------------------+\n| ifnull(FirstName,'Robert') |\n+----------------------------+\n| Chris |\n| Robert |\n| David |\n| Robert |\n+----------------------------+\n4 rows in set (0.00 sec)" } ]
Knight Probability in Chessboard in C++
Suppose we have one NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. Here the rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1). A knight can move in 8 different cells from a cell, that can be shown in this diagram − Each time the knight is to move, it chooses one of eight possible moves randomly. The knight continues moving until it has made exactly K moves or has moved off the chessboard. We have to find the probability that the knight remains on the board after it has stopped moving. So if the input is like 3, 2, 0, 0, then the output will be 0.0625. This is because there are two moves (to (1,2), (2,1)) that will keep the knight on the board. Now from each of those positions, there are also two moves that will keep the knight on the board. So here the total probability the knight stays on the board is 0.0625. To solve this, we will follow these steps − Define one direction array dir, this is like [[-2,-1], [-2, 1],[2,-1], [2, 1], [1,2], [1,-2], [-1,2], [-1,-2]] Define recursive method solve(), this will take x, y, n, k, and 3d array dp if x >= n or y >= n or x < 0 or y < 0, then return 0 if k is 0, then return 1 if dp[k,x,y] is not -1, then return dp[k,x,y] dp[k, x, y] := 0 for i in range 0 to 7dp[k,x,y] := solve(x+dir[i,0], y + dir[i, 1], n, k – 1, dp) dp[k,x,y] := solve(x+dir[i,0], y + dir[i, 1], n, k – 1, dp) return dp[k,x,y] From the main method, do the following make a 3d array of size (k + 1) x N x N. Fill this with – 1 return solve(r, c, N, k, dp) / (8^K) Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; int dir[8][2] = {{-2, -1}, {-2, 1}, {2, -1}, {2, 1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}}; class Solution { public: double solve(int x, int y, int n, int k, vector < vector < vector < double > > >& dp){ if(x >= n || y >= n || x < 0 || y < 0 ) return 0.0; if(k == 0) return 1.0; if(dp[k][x][y] != -1) return dp[k][x][y]; dp[k][x][y] = 0; for(int i = 0; i < 8; i++){ dp[k][x][y] += solve(x + dir[i][0], y + dir[i][1], n, k - 1, dp); } return dp[k][x][y]; } double knightProbability(int N, int K, int r, int c) { vector < vector < vector < double > > > dp (K + 1, vector < vector < double > >(N, vector < double >(N, -1))) ; return solve(r, c, N, K, dp) / pow(8, K); } }; main(){ Solution ob; cout << (ob.knightProbability(3, 2, 0, 0)); } 3 2 0 0 0.0625
[ { "code": null, "e": 1302, "s": 1062, "text": "Suppose we have one NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. Here the rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1)." }, { "code": null, "e": 1390, "s": 1302, "text": "A knight can move in 8 different cells from a cell, that can be shown in this diagram −" }, { "code": null, "e": 1665, "s": 1390, "text": "Each time the knight is to move, it chooses one of eight possible moves randomly. The knight continues moving until it has made exactly K moves or has moved off the chessboard. We have to find the probability that the knight remains on the board after it has stopped moving." }, { "code": null, "e": 1997, "s": 1665, "text": "So if the input is like 3, 2, 0, 0, then the output will be 0.0625. This is because there are two moves (to (1,2), (2,1)) that will keep the knight on the board. Now from each of those positions, there are also two moves that will keep the knight on the board. So here the total probability the knight stays on the board is 0.0625." }, { "code": null, "e": 2041, "s": 1997, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 2152, "s": 2041, "text": "Define one direction array dir, this is like [[-2,-1], [-2, 1],[2,-1], [2, 1], [1,2], [1,-2], [-1,2], [-1,-2]]" }, { "code": null, "e": 2228, "s": 2152, "text": "Define recursive method solve(), this will take x, y, n, k, and 3d array dp" }, { "code": null, "e": 2281, "s": 2228, "text": "if x >= n or y >= n or x < 0 or y < 0, then return 0" }, { "code": null, "e": 2306, "s": 2281, "text": "if k is 0, then return 1" }, { "code": null, "e": 2352, "s": 2306, "text": "if dp[k,x,y] is not -1, then return dp[k,x,y]" }, { "code": null, "e": 2369, "s": 2352, "text": "dp[k, x, y] := 0" }, { "code": null, "e": 2450, "s": 2369, "text": "for i in range 0 to 7dp[k,x,y] := solve(x+dir[i,0], y + dir[i, 1], n, k – 1, dp)" }, { "code": null, "e": 2510, "s": 2450, "text": "dp[k,x,y] := solve(x+dir[i,0], y + dir[i, 1], n, k – 1, dp)" }, { "code": null, "e": 2527, "s": 2510, "text": "return dp[k,x,y]" }, { "code": null, "e": 2566, "s": 2527, "text": "From the main method, do the following" }, { "code": null, "e": 2626, "s": 2566, "text": "make a 3d array of size (k + 1) x N x N. Fill this with – 1" }, { "code": null, "e": 2663, "s": 2626, "text": "return solve(r, c, N, k, dp) / (8^K)" }, { "code": null, "e": 2733, "s": 2663, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2744, "s": 2733, "text": " Live Demo" }, { "code": null, "e": 3609, "s": 2744, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint dir[8][2] = {{-2, -1}, {-2, 1}, {2, -1}, {2, 1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};\nclass Solution {\n public:\n double solve(int x, int y, int n, int k, vector < vector < vector < double > > >& dp){\n if(x >= n || y >= n || x < 0 || y < 0 ) return 0.0;\n if(k == 0) return 1.0;\n if(dp[k][x][y] != -1) return dp[k][x][y];\n dp[k][x][y] = 0;\n for(int i = 0; i < 8; i++){\n dp[k][x][y] += solve(x + dir[i][0], y + dir[i][1], n, k - 1, dp);\n }\n return dp[k][x][y];\n }\n double knightProbability(int N, int K, int r, int c) {\n vector < vector < vector < double > > > dp (K + 1, vector < vector < double > >(N, vector < double >(N, -1))) ;\n return solve(r, c, N, K, dp) / pow(8, K);\n }\n};\nmain(){\n Solution ob;\n cout << (ob.knightProbability(3, 2, 0, 0));\n}" }, { "code": null, "e": 3617, "s": 3609, "text": "3\n2\n0\n0" }, { "code": null, "e": 3624, "s": 3617, "text": "0.0625" } ]
How do I create a Python namespace?
Each package, module, class, function and method function owns a "namespace" in which variable names are resolved. When a function, module or package is evaluated (that is, starts execution), a namespace is created. So if you want to create a namespace, you just need to call a function, instantiate an object, import a module or import a package. For example, we can create a class called Namespace and when you create an object of that class, you're basically creating a namespace. In this class, you can also pass variable names to attach to the namespace, for example, class Namespace: def __init__(self, **kwargs): self.__dict__.update(kwargs) args = Namespace(a=1, b='c') print args.a, args.b This will give the output: 1 c
[ { "code": null, "e": 1546, "s": 1062, "text": "Each package, module, class, function and method function owns a \"namespace\" in which variable names are resolved. When a function, module or package is evaluated (that is, starts execution), a namespace is created. So if you want to create a namespace, you just need to call a function, instantiate an object, import a module or import a package. For example, we can create a class called Namespace and when you create an object of that class, you're basically creating a namespace." }, { "code": null, "e": 1635, "s": 1546, "text": "In this class, you can also pass variable names to attach to the namespace, for example," }, { "code": null, "e": 1773, "s": 1635, "text": "class Namespace:\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\nargs = Namespace(a=1, b='c')\nprint args.a, args.b" }, { "code": null, "e": 1800, "s": 1773, "text": "This will give the output:" }, { "code": null, "e": 1804, "s": 1800, "text": "1 c" } ]
ISRO | ISRO CS 2015 | Question 78 - GeeksforGeeks
05 Apr, 2018 Consider the following C declaration struct ( short s[5]; union { float y; long z; }u; }t; Assume that the objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively. The memory requirement for variable t, ignoring alignment consideration, is(A) 22 bytes(B) 18 bytes(C) 14 bytes(D) 10 bytesAnswer: (B)Explanation: Refer: GATE-CS-2000 | Question 17Quiz of this Question ISRO Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ISRO | ISRO CS 2013 | Question 54 ISRO | ISRO CS 2015 | Question 51 ISRO | ISRO CS 2008 | Question 50 ISRO | ISRO CS 2009 | Question 30 ISRO | ISRO CS 2011 | Question 22 ISRO | ISRO CS 2014 | Question 48 ISRO | ISRO CS 2007 | Question 78 ISRO | ISRO CS 2014 | Question 34 ISRO | ISRO CS 2013 | Question 2 ISRO | ISRO CS 2013 | Question 7
[ { "code": null, "e": 24067, "s": 24039, "text": "\n05 Apr, 2018" }, { "code": null, "e": 24104, "s": 24067, "text": "Consider the following C declaration" }, { "code": null, "e": 24159, "s": 24104, "text": "struct (\nshort s[5];\nunion {\nfloat y;\nlong z;\n}u;\n}t;\n" }, { "code": null, "e": 24470, "s": 24159, "text": "Assume that the objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively. The memory requirement for variable t, ignoring alignment consideration, is(A) 22 bytes(B) 18 bytes(C) 14 bytes(D) 10 bytesAnswer: (B)Explanation: Refer: GATE-CS-2000 | Question 17Quiz of this Question" }, { "code": null, "e": 24475, "s": 24470, "text": "ISRO" }, { "code": null, "e": 24573, "s": 24475, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24582, "s": 24573, "text": "Comments" }, { "code": null, "e": 24595, "s": 24582, "text": "Old Comments" }, { "code": null, "e": 24629, "s": 24595, "text": "ISRO | ISRO CS 2013 | Question 54" }, { "code": null, "e": 24663, "s": 24629, "text": "ISRO | ISRO CS 2015 | Question 51" }, { "code": null, "e": 24697, "s": 24663, "text": "ISRO | ISRO CS 2008 | Question 50" }, { "code": null, "e": 24731, "s": 24697, "text": "ISRO | ISRO CS 2009 | Question 30" }, { "code": null, "e": 24765, "s": 24731, "text": "ISRO | ISRO CS 2011 | Question 22" }, { "code": null, "e": 24799, "s": 24765, "text": "ISRO | ISRO CS 2014 | Question 48" }, { "code": null, "e": 24833, "s": 24799, "text": "ISRO | ISRO CS 2007 | Question 78" }, { "code": null, "e": 24867, "s": 24833, "text": "ISRO | ISRO CS 2014 | Question 34" }, { "code": null, "e": 24900, "s": 24867, "text": "ISRO | ISRO CS 2013 | Question 2" } ]
Image Processing with Python — Template Matching with Scikit-Image | by Tonichi Edeza | Towards Data Science
Template matching is a useful technique for identifying objects of interest in a picture. Unlike similar methods of object identification such as image masking and blob detection. Template matching is helpful as it allows us to identify more complex figures. This article will discuss exactly how to do this in Python. Let’s get started! As always, begin by importing the required Python libraries. import numpy as npfrom skimage.io import imread, imshowimport matplotlib.pyplot as pltfrom matplotlib.patches import Circle, Rectanglefrom skimage import transformfrom skimage.color import rgb2grayfrom skimage.feature import match_templatefrom skimage.feature import peak_local_max Great, now let us load the image we will be working with. leuven = imread('leuven_picture.PNG')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(leuven); The image above is of the Leuven Town Hall I took some years ago. Its highly decorative window arches are definitely a sight to behold. For our task let us try to use template matching to identify as many of them as possible. Our first step of course is to convert the image to grayscale. leuven_gray = rgb2gray(leuven)plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(leuven_gray); Excellent, now let us pick out one of the windows and use it as a template. To do this we simply have to cut out that slice of the image. template = leuven_gray[310:390,240:270]imshow(template); At this point we can feed the template into the match_template function of Skimage. resulting_image = match_template(leuven_gray, template)plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(resulting_image, cmap='magma'); The above is the result of using the match_template function. Put very simply, the brighter the section of the image, the closer of a match it is to the template. Let us see which section of the image the function thinks is the closest match to the template. x, y = np.unravel_index(np.argmax(resulting_image), resulting_image.shape)template_width, template_height = template.shaperect = plt.Rectangle((y, x), template_height, template_width, color='r', fc='none')plt.figure(num=None, figsize=(8, 6), dpi=80)plt.gca().add_patch(rect)imshow(leuven_gray); We can see that the image was able to correctly identify the perfect match for the template (to validate you can check with the slicing coordinates we used). This will definitely be useful in any task that would require you to search for an exact match of an object within an image. Let us now see if we can get the function to identify the other windows as being more or less similar to our template. template_width, template_height = template.shape plt.figure(num=None, figsize=(8, 6), dpi=80)for x, y in peak_local_max(result, threshold_abs=0.5, exclude_border = 20): rect = plt.Rectangle((y, x), template_height, template_width, color='r', fc='none') plt.gca().add_patch(rect)imshow(leuven_gray); We see that though the function does accurately identify several other windows. It also erroneously identifies several other objects that are clearly not windows. Let us see if we can cut down on the amount of false positives. One way we can can remedy this is by making use of use of the homography matrix. I’ve written an article previously on how to make use of the transform.warp function in Skimage, but generally it warps the image and make it seem as if the image had been taken from another angle. points_of_interest =[[240, 130], [525, 255], [550, 545], [250, 545]]projection = [[180, 150], [520, 150], [520, 550], [180, 550]]color = 'red'patches = []fig, ax = plt.subplots(1,2, figsize=(15, 10), dpi = 80)for coordinates in (points_of_interest + projection): patch = Circle((coordinates[0],coordinates[1]), 10, facecolor = color) patches.append(patch)for p in patches[:4]: ax[0].add_patch(p)ax[0].imshow(leuven_gray);for p in patches[4:]: ax[1].add_patch(p)ax[1].imshow(np.ones((leuven_gray.shape[0], leuven_gray.shape[1]))); points_of_interest = np.array(points_of_interest)projection = np.array(projection)tform = transform.estimate_transform('projective', points_of_interest, projection)tf_img_warp = transform.warp(leuven, tform.inverse)plt.figure(num=None, figsize=(8, 6), dpi=80)fig, ax = plt.subplots(1,2, figsize=(15, 10), dpi = 80)ax[0].set_title(f'Original', fontsize = 15)ax[0].imshow(leuven)ax[0].set_axis_off();ax[1].set_title(f'Transformed', fontsize = 15)ax[1].imshow(tf_img_warp)ax[1].set_axis_off(); We can see that the image now faces forward. As we have mitigated the effect the angle has on template matching, let us see if we get better results. As before, let us first convert the image into grayscale and then apply the transform function. points_of_interest = np.array(points_of_interest)projection = np.array(projection)tform = transform.estimate_transform('projective', points_of_interest, projection)tf_img_warp = transform.warp(leuven_gray, tform.inverse)plt.figure(num=None, figsize=(8, 6), dpi=80)fig, ax = plt.subplots(1,2, figsize=(15, 10), dpi = 80)ax[0].set_title(f'Original', fontsize = 15)ax[0].imshow(leuven_gray, cmap = 'gray')ax[0].set_axis_off();ax[1].set_title(f'Transformed', fontsize = 15)ax[1].imshow(tf_img_warp, cmap = 'gray')ax[1].set_axis_off(); result = match_template(tf_img_warp, template)plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(result, cmap=’magma’); Now let us apply the exact same codes as before and see if we get better results. template_width, template_height = template.shape plt.figure(num=None, figsize=(8, 6), dpi=80)for x, y in peak_local_max(result, threshold_abs=0.5, exclude_border = 10): rect = plt.Rectangle((y, x), template_height, template_width, color='r', fc='none') plt.gca().add_patch(rect)imshow(tf_img_warp); We can see that the algorithm can still identify every window on the image, however it still has those pesky false positives. To alleviate this, let us apply a filter the template matches. Below are some codes to do our data wrangling, apologies if they are slightly abtruse. template_width, template_height = template.shapematched_list = []for x, y in peak_local_max(result, threshold_abs=0.50, exclude_border = 10): rect = plt.Rectangle((y, x), template_height, template_width) coord = Rectangle.get_bbox(rect).get_points() matched_list.append(coord) matched_patches = [tf_img_warp[int(match[0][1]):int(match[1][1]), int(match[0][0]):int(match[1][0])] for match in matched_list]difference = [abs(i.flatten() - template.flatten()) for i in matched_patches]summed_diff = [array.sum() for array in difference]final_patches =list(zip(matched_list,summed_diff))statistics.mean(summed_diff) After running the above codes, we can now create the filtered list of template matches. Again apologies if the code may not be that easy to follow. summed_diff = np.array(summed_diff)filtered_list_mean =list(filter(lambda x: x[1] <= summed_diff.mean(), final_patches))filtered_list_median =list(filter(lambda x: x[1] <= np.percentile(summed_diff, 50), final_patches))filtered_list_75 =list(filter(lambda x: x[1] <= np.percentile(summed_diff, 75), final_patches)) The above code should filter the matches by the mean difference, the median difference, and the 75% percentile difference. Essentially it will only hold matches that have absolute differences below those thresholds. The final step is to plot these out and see if the results have improved. fig, ax = plt.subplots(1,3, figsize=(17, 10), dpi = 80)template_width, template_height = template.shapefor box in filtered_list_mean: patch = Rectangle((box[0][0][0],box[0][0][1]), template_height, template_width, edgecolor='b', facecolor='none', linewidth = 3.0) ax[0].add_patch(patch)ax[0].imshow(tf_img_warp, cmap = 'gray');ax[0].set_axis_off()for box in filtered_list_median: patch = Rectangle((box[0][0][0],box[0][0][1]), template_height, template_width, edgecolor='b', facecolor='none', linewidth = 3.0) ax[1].add_patch(patch)ax[1].imshow(tf_img_warp, cmap = 'gray');ax[1].set_axis_off()for box in filtered_list_75: patch = Rectangle((box[0][0][0],box[0][0][1]), template_height, template_width, edgecolor='b', facecolor='none', linewidth = 3.0) ax[2].add_patch(patch)ax[2].imshow(tf_img_warp, cmap = 'gray');ax[2].set_axis_off()fig.tight_layout() We can see that all of them do look much better than the original image. However, we notice that though Mean and Median have far less false positives they also have far less true positives. The 75 Perc filter however is able to retain almost all the true positives. In Conclusion Template matching can be a tricky thing if the template is a particularly complex image. We must remember that though we as humans may interpret the image as a simple window, the machine only sees a matrix. There then two ways we can tackle this issue. One is by ensuring that the template is unique enough that false positives will be rare, the other is developing a sophisticated filtering system that is able to accurately remove any false positives from the data. A topic like this deserves several articles and in the future we shall go over some best practices when it comes to template matching. For now I hope you were able to learn how to make use of template matching in your own projects and can now think ahead of how to deal with the inevitable issues.
[ { "code": null, "e": 491, "s": 172, "text": "Template matching is a useful technique for identifying objects of interest in a picture. Unlike similar methods of object identification such as image masking and blob detection. Template matching is helpful as it allows us to identify more complex figures. This article will discuss exactly how to do this in Python." }, { "code": null, "e": 510, "s": 491, "text": "Let’s get started!" }, { "code": null, "e": 571, "s": 510, "text": "As always, begin by importing the required Python libraries." }, { "code": null, "e": 853, "s": 571, "text": "import numpy as npfrom skimage.io import imread, imshowimport matplotlib.pyplot as pltfrom matplotlib.patches import Circle, Rectanglefrom skimage import transformfrom skimage.color import rgb2grayfrom skimage.feature import match_templatefrom skimage.feature import peak_local_max" }, { "code": null, "e": 911, "s": 853, "text": "Great, now let us load the image we will be working with." }, { "code": null, "e": 1008, "s": 911, "text": "leuven = imread('leuven_picture.PNG')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(leuven);" }, { "code": null, "e": 1297, "s": 1008, "text": "The image above is of the Leuven Town Hall I took some years ago. Its highly decorative window arches are definitely a sight to behold. For our task let us try to use template matching to identify as many of them as possible. Our first step of course is to convert the image to grayscale." }, { "code": null, "e": 1392, "s": 1297, "text": "leuven_gray = rgb2gray(leuven)plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(leuven_gray);" }, { "code": null, "e": 1530, "s": 1392, "text": "Excellent, now let us pick out one of the windows and use it as a template. To do this we simply have to cut out that slice of the image." }, { "code": null, "e": 1587, "s": 1530, "text": "template = leuven_gray[310:390,240:270]imshow(template);" }, { "code": null, "e": 1671, "s": 1587, "text": "At this point we can feed the template into the match_template function of Skimage." }, { "code": null, "e": 1809, "s": 1671, "text": "resulting_image = match_template(leuven_gray, template)plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(resulting_image, cmap='magma');" }, { "code": null, "e": 2068, "s": 1809, "text": "The above is the result of using the match_template function. Put very simply, the brighter the section of the image, the closer of a match it is to the template. Let us see which section of the image the function thinks is the closest match to the template." }, { "code": null, "e": 2384, "s": 2068, "text": "x, y = np.unravel_index(np.argmax(resulting_image), resulting_image.shape)template_width, template_height = template.shaperect = plt.Rectangle((y, x), template_height, template_width, color='r', fc='none')plt.figure(num=None, figsize=(8, 6), dpi=80)plt.gca().add_patch(rect)imshow(leuven_gray);" }, { "code": null, "e": 2667, "s": 2384, "text": "We can see that the image was able to correctly identify the perfect match for the template (to validate you can check with the slicing coordinates we used). This will definitely be useful in any task that would require you to search for an exact match of an object within an image." }, { "code": null, "e": 2786, "s": 2667, "text": "Let us now see if we can get the function to identify the other windows as being more or less similar to our template." }, { "code": null, "e": 3146, "s": 2786, "text": "template_width, template_height = template.shape plt.figure(num=None, figsize=(8, 6), dpi=80)for x, y in peak_local_max(result, threshold_abs=0.5, exclude_border = 20): rect = plt.Rectangle((y, x), template_height, template_width, color='r', fc='none') plt.gca().add_patch(rect)imshow(leuven_gray);" }, { "code": null, "e": 3373, "s": 3146, "text": "We see that though the function does accurately identify several other windows. It also erroneously identifies several other objects that are clearly not windows. Let us see if we can cut down on the amount of false positives." }, { "code": null, "e": 3652, "s": 3373, "text": "One way we can can remedy this is by making use of use of the homography matrix. I’ve written an article previously on how to make use of the transform.warp function in Skimage, but generally it warps the image and make it seem as if the image had been taken from another angle." }, { "code": null, "e": 4316, "s": 3652, "text": "points_of_interest =[[240, 130], [525, 255], [550, 545], [250, 545]]projection = [[180, 150], [520, 150], [520, 550], [180, 550]]color = 'red'patches = []fig, ax = plt.subplots(1,2, figsize=(15, 10), dpi = 80)for coordinates in (points_of_interest + projection): patch = Circle((coordinates[0],coordinates[1]), 10, facecolor = color) patches.append(patch)for p in patches[:4]: ax[0].add_patch(p)ax[0].imshow(leuven_gray);for p in patches[4:]: ax[1].add_patch(p)ax[1].imshow(np.ones((leuven_gray.shape[0], leuven_gray.shape[1])));" }, { "code": null, "e": 4807, "s": 4316, "text": "points_of_interest = np.array(points_of_interest)projection = np.array(projection)tform = transform.estimate_transform('projective', points_of_interest, projection)tf_img_warp = transform.warp(leuven, tform.inverse)plt.figure(num=None, figsize=(8, 6), dpi=80)fig, ax = plt.subplots(1,2, figsize=(15, 10), dpi = 80)ax[0].set_title(f'Original', fontsize = 15)ax[0].imshow(leuven)ax[0].set_axis_off();ax[1].set_title(f'Transformed', fontsize = 15)ax[1].imshow(tf_img_warp)ax[1].set_axis_off();" }, { "code": null, "e": 5053, "s": 4807, "text": "We can see that the image now faces forward. As we have mitigated the effect the angle has on template matching, let us see if we get better results. As before, let us first convert the image into grayscale and then apply the transform function." }, { "code": null, "e": 5584, "s": 5053, "text": "points_of_interest = np.array(points_of_interest)projection = np.array(projection)tform = transform.estimate_transform('projective', points_of_interest, projection)tf_img_warp = transform.warp(leuven_gray, tform.inverse)plt.figure(num=None, figsize=(8, 6), dpi=80)fig, ax = plt.subplots(1,2, figsize=(15, 10), dpi = 80)ax[0].set_title(f'Original', fontsize = 15)ax[0].imshow(leuven_gray, cmap = 'gray')ax[0].set_axis_off();ax[1].set_title(f'Transformed', fontsize = 15)ax[1].imshow(tf_img_warp, cmap = 'gray')ax[1].set_axis_off();" }, { "code": null, "e": 5704, "s": 5584, "text": "result = match_template(tf_img_warp, template)plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(result, cmap=’magma’);" }, { "code": null, "e": 5786, "s": 5704, "text": "Now let us apply the exact same codes as before and see if we get better results." }, { "code": null, "e": 6147, "s": 5786, "text": "template_width, template_height = template.shape plt.figure(num=None, figsize=(8, 6), dpi=80)for x, y in peak_local_max(result, threshold_abs=0.5, exclude_border = 10): rect = plt.Rectangle((y, x), template_height, template_width, color='r', fc='none') plt.gca().add_patch(rect)imshow(tf_img_warp);" }, { "code": null, "e": 6423, "s": 6147, "text": "We can see that the algorithm can still identify every window on the image, however it still has those pesky false positives. To alleviate this, let us apply a filter the template matches. Below are some codes to do our data wrangling, apologies if they are slightly abtruse." }, { "code": null, "e": 7076, "s": 6423, "text": "template_width, template_height = template.shapematched_list = []for x, y in peak_local_max(result, threshold_abs=0.50, exclude_border = 10): rect = plt.Rectangle((y, x), template_height, template_width) coord = Rectangle.get_bbox(rect).get_points() matched_list.append(coord) matched_patches = [tf_img_warp[int(match[0][1]):int(match[1][1]), int(match[0][0]):int(match[1][0])] for match in matched_list]difference = [abs(i.flatten() - template.flatten()) for i in matched_patches]summed_diff = [array.sum() for array in difference]final_patches =list(zip(matched_list,summed_diff))statistics.mean(summed_diff)" }, { "code": null, "e": 7224, "s": 7076, "text": "After running the above codes, we can now create the filtered list of template matches. Again apologies if the code may not be that easy to follow." }, { "code": null, "e": 7662, "s": 7224, "text": "summed_diff = np.array(summed_diff)filtered_list_mean =list(filter(lambda x: x[1] <= summed_diff.mean(), final_patches))filtered_list_median =list(filter(lambda x: x[1] <= np.percentile(summed_diff, 50), final_patches))filtered_list_75 =list(filter(lambda x: x[1] <= np.percentile(summed_diff, 75), final_patches))" }, { "code": null, "e": 7952, "s": 7662, "text": "The above code should filter the matches by the mean difference, the median difference, and the 75% percentile difference. Essentially it will only hold matches that have absolute differences below those thresholds. The final step is to plot these out and see if the results have improved." }, { "code": null, "e": 8986, "s": 7952, "text": "fig, ax = plt.subplots(1,3, figsize=(17, 10), dpi = 80)template_width, template_height = template.shapefor box in filtered_list_mean: patch = Rectangle((box[0][0][0],box[0][0][1]), template_height, template_width, edgecolor='b', facecolor='none', linewidth = 3.0) ax[0].add_patch(patch)ax[0].imshow(tf_img_warp, cmap = 'gray');ax[0].set_axis_off()for box in filtered_list_median: patch = Rectangle((box[0][0][0],box[0][0][1]), template_height, template_width, edgecolor='b', facecolor='none', linewidth = 3.0) ax[1].add_patch(patch)ax[1].imshow(tf_img_warp, cmap = 'gray');ax[1].set_axis_off()for box in filtered_list_75: patch = Rectangle((box[0][0][0],box[0][0][1]), template_height, template_width, edgecolor='b', facecolor='none', linewidth = 3.0) ax[2].add_patch(patch)ax[2].imshow(tf_img_warp, cmap = 'gray');ax[2].set_axis_off()fig.tight_layout()" }, { "code": null, "e": 9252, "s": 8986, "text": "We can see that all of them do look much better than the original image. However, we notice that though Mean and Median have far less false positives they also have far less true positives. The 75 Perc filter however is able to retain almost all the true positives." }, { "code": null, "e": 9266, "s": 9252, "text": "In Conclusion" } ]
GATE | GATE-CS-2000 | Question 49 - GeeksforGeeks
28 Jun, 2021 Given relations r(w, x) and s(y, z), the result of SELECT DISTINCT w, x FROM r, s is guaranteed to be same as r, provided (A) r has no duplicates and s is non-empty(B) r and s have no duplicates(C) s has no duplicates and r is non-empty(D) r and s have the same number of tuplesAnswer: (A)Explanation: See question 3 of https://www.geeksforgeeks.org/database-management-system-set-1/Quiz of this Question GATE-CS-2000 GATE-GATE-CS-2000 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE-IT-2004 | Question 83 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2007 | Question 17 GATE | GATE-IT-2004 | Question 12 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2007 | Question 64
[ { "code": null, "e": 24302, "s": 24274, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24353, "s": 24302, "text": "Given relations r(w, x) and s(y, z), the result of" }, { "code": null, "e": 24392, "s": 24353, "text": "SELECT DISTINCT w, x\n FROM r, s " }, { "code": null, "e": 24432, "s": 24392, "text": "is guaranteed to be same as r, provided" }, { "code": null, "e": 24715, "s": 24432, "text": "(A) r has no duplicates and s is non-empty(B) r and s have no duplicates(C) s has no duplicates and r is non-empty(D) r and s have the same number of tuplesAnswer: (A)Explanation: See question 3 of https://www.geeksforgeeks.org/database-management-system-set-1/Quiz of this Question" }, { "code": null, "e": 24728, "s": 24715, "text": "GATE-CS-2000" }, { "code": null, "e": 24746, "s": 24728, "text": "GATE-GATE-CS-2000" }, { "code": null, "e": 24751, "s": 24746, "text": "GATE" }, { "code": null, "e": 24849, "s": 24751, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24858, "s": 24849, "text": "Comments" }, { "code": null, "e": 24871, "s": 24858, "text": "Old Comments" }, { "code": null, "e": 24913, "s": 24871, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 24947, "s": 24913, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 24981, "s": 24947, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 25023, "s": 24981, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25065, "s": 25023, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 25107, "s": 25065, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 25141, "s": 25107, "text": "GATE | GATE-CS-2007 | Question 17" }, { "code": null, "e": 25175, "s": 25141, "text": "GATE | GATE-IT-2004 | Question 12" }, { "code": null, "e": 25217, "s": 25175, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" } ]
Insert sequential number in MySQL?
You can insert sequential number in MySQL using session variable. The syntax is as follows − SELECT @anyVariableName − = anyIntegerValue; UPDATE yourTableName SET yourColumnName = @anyVariableName − = @anyVariableName+IncrementStep; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table SequentialNumberDemo -> ( -> SequentialNumber int not null -> ); Query OK, 0 rows affected (0.84 sec) Insert records in the table using insert command. The query is as follows − mysql> insert into SequentialNumberDemo values(100); Query OK, 1 row affected (0.11 sec) mysql> insert into SequentialNumberDemo values(10); Query OK, 1 row affected (0.22 sec) mysql> insert into SequentialNumberDemo values(9); Query OK, 1 row affected (0.15 sec) mysql> insert into SequentialNumberDemo values(60); Query OK, 1 row affected (0.11 sec) mysql> insert into SequentialNumberDemo values(50); Query OK, 1 row affected (0.14 sec) mysql> insert into SequentialNumberDemo values(40); Query OK, 1 row affected (0.13 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from SequentialNumberDemo; The following is the output − +------------------+ | SequentialNumber | +------------------+ | 100 | | 10 | | 9 | | 60 | | 50 | | 40 | +------------------+ 6 rows in set (0.00 sec) Look at the above output, the number is not in a sequential order. Here is the query to get the sequential number beginning from 1. At first, set the sequence − mysql> select @sequence: = 0; The output − +---------------+ | @sequence:= 0 | +---------------+ | 0 | +---------------+ 1 row in set (0.03 sec) Now, the query to update and begin the sequence from 1 − mysql> update SequentialNumberDemo set SequentialNumber = @sequence − = @sequence+1; Query OK, 6 rows affected (0.15 sec) Rows matched − 6 Changed − 6 Warnings − 0 Check the table records once again. The query is as follows − mysql> select *from SequentialNumberDemo; The following is the output − +------------------+ | SequentialNumber | +------------------+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | +------------------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1155, "s": 1062, "text": "You can insert sequential number in MySQL using session variable. The syntax is as follows −" }, { "code": null, "e": 1295, "s": 1155, "text": "SELECT @anyVariableName − = anyIntegerValue;\nUPDATE yourTableName SET yourColumnName = @anyVariableName − = @anyVariableName+IncrementStep;" }, { "code": null, "e": 1394, "s": 1295, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1525, "s": 1394, "text": "mysql> create table SequentialNumberDemo\n -> (\n -> SequentialNumber int not null\n -> );\nQuery OK, 0 rows affected (0.84 sec)" }, { "code": null, "e": 1601, "s": 1525, "text": "Insert records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2134, "s": 1601, "text": "mysql> insert into SequentialNumberDemo values(100);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into SequentialNumberDemo values(10);\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into SequentialNumberDemo values(9);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into SequentialNumberDemo values(60);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into SequentialNumberDemo values(50);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into SequentialNumberDemo values(40);\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 2219, "s": 2134, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2261, "s": 2219, "text": "mysql> select *from SequentialNumberDemo;" }, { "code": null, "e": 2291, "s": 2261, "text": "The following is the output −" }, { "code": null, "e": 2526, "s": 2291, "text": "+------------------+\n| SequentialNumber |\n+------------------+\n| 100 |\n| 10 |\n| 9 |\n| 60 |\n| 50 |\n| 40 |\n+------------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2687, "s": 2526, "text": "Look at the above output, the number is not in a sequential order. Here is the query to get the sequential number beginning from 1. At first, set the sequence −" }, { "code": null, "e": 2717, "s": 2687, "text": "mysql> select @sequence: = 0;" }, { "code": null, "e": 2730, "s": 2717, "text": "The output −" }, { "code": null, "e": 2844, "s": 2730, "text": "+---------------+\n| @sequence:= 0 |\n+---------------+\n| 0 |\n+---------------+\n1 row in set (0.03 sec)" }, { "code": null, "e": 2901, "s": 2844, "text": "Now, the query to update and begin the sequence from 1 −" }, { "code": null, "e": 3065, "s": 2901, "text": "mysql> update SequentialNumberDemo set SequentialNumber = @sequence − = @sequence+1;\nQuery OK, 6 rows affected (0.15 sec)\nRows matched − 6 Changed − 6 Warnings − 0" }, { "code": null, "e": 3127, "s": 3065, "text": "Check the table records once again. The query is as follows −" }, { "code": null, "e": 3169, "s": 3127, "text": "mysql> select *from SequentialNumberDemo;" }, { "code": null, "e": 3199, "s": 3169, "text": "The following is the output −" }, { "code": null, "e": 3434, "s": 3199, "text": "+------------------+\n| SequentialNumber |\n+------------------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n+------------------+\n6 rows in set (0.00 sec)" } ]
How to control fps with requestAnimationFrame?
02 Jun, 2020 Introduction:It is important to control the frames per second limit, especially, when developing games where the animated objects should not exceed particular frames per second limit. The requestAnimationFrame() is used for simply repainting the screen — it is not a timer or a loop function. requestAnimationFrame(callback):Used to update or repaint the screen using the callback function specified. Whenever a function call is made to requestAnimationFrame() the screen/frame is repainted according to the update code written by the developer, which makes it a suitable option for controlling the frame rate. There are two ways of controlling the fps with requestAnimationFrame(). These are discussed as follows. Using `setTimeout` Function:This is a quick and easy approach to controlling the fps. The setTimeout() function has the following declaration:setTimeout(function, milliseconds) :Can be used to execute a function after waiting for the specified number of seconds.The code to control fps using setTimeout() is given below, the requestAnimationFrame() is passed as a function to setTimeout() for regularly updating the screen at the specified fps.<h1>Controlling requestAnimationFrame to a FPS</h1><h2>Testing approach 1: Results should be approximately 5 fps</h2><h3 id="results">Results:</h3><canvas id="canvas" width="300" height="300"></canvas> <script> var frameCount = 0; var $results = $("#results"); var fps, fpsInterval, startTime, now, then, elapsed; startAnimating(5); function startAnimating(fps) { fpsInterval = 1000 / fps; then = Date.now(); startTime = then; console.log(startTime); animate(); } function animate() { setTimeout(function () { // requestAnimationFrame() is called // with animate() callback // to update content at specified fps requestAnimationFrame(animate); // ... Code for Animating the Objects ... now = Date.now(); var sinceStart = now - startTime; var currentFps = Math.round((1000 / (sinceStart / ++frameCount)) * 100) / 100; $results.text("Elapsed time= " + Math.round((sinceStart / 1000) * 100) / 100 + " secs @ " + currentFps + " fps."); }, fpsInterval); }</script>Output:The two images show the fps fluctuating around 5 fps, as assumed by the above code. setTimeout(function, milliseconds) :Can be used to execute a function after waiting for the specified number of seconds. The code to control fps using setTimeout() is given below, the requestAnimationFrame() is passed as a function to setTimeout() for regularly updating the screen at the specified fps. <h1>Controlling requestAnimationFrame to a FPS</h1><h2>Testing approach 1: Results should be approximately 5 fps</h2><h3 id="results">Results:</h3><canvas id="canvas" width="300" height="300"></canvas> <script> var frameCount = 0; var $results = $("#results"); var fps, fpsInterval, startTime, now, then, elapsed; startAnimating(5); function startAnimating(fps) { fpsInterval = 1000 / fps; then = Date.now(); startTime = then; console.log(startTime); animate(); } function animate() { setTimeout(function () { // requestAnimationFrame() is called // with animate() callback // to update content at specified fps requestAnimationFrame(animate); // ... Code for Animating the Objects ... now = Date.now(); var sinceStart = now - startTime; var currentFps = Math.round((1000 / (sinceStart / ++frameCount)) * 100) / 100; $results.text("Elapsed time= " + Math.round((sinceStart / 1000) * 100) / 100 + " secs @ " + currentFps + " fps."); }, fpsInterval); }</script> Output:The two images show the fps fluctuating around 5 fps, as assumed by the above code. FPS is 4.9, after 5.31 seconds have elapsed: FPS is 4.91, after 18.34 seconds have elapsed: The above code is simply, calling the setTimeout() function at the interval rate specified by the fps. Each time setTimeout() is called, the requestAnimationFrame() is executed and the screen is repainted or updated. All this occurs at the fps specified, as determined by the developer. A More Optimized Approach:Most browsers cannot optimize the setTimeout() function, so to optimize the process of controlling fps simple calculation can be used. This can be easily done by keeping track of time when the frame was updated last. If the change in time (current time — previous time) exceeds the update interval, then update the frame/screen.To do so, keep track of the current_time and the previous_time. Each time we get:current_time - previous_time > update_interval the frame is updated and repainted onto the screen. The code for this is as follows:<h1>Controlling requestAnimationFrame to a FPS</h1><h2>This test: Results should be approximately 5 fps</h2><h2 id="results">Results:</h2><canvas id="canvas" width="300" height="300"></canvas> <script> var frameCount = 0; var $results = $("#results"); var fps, fpsInterval, startTime, now, then, elapsed; startAnimating(5); function startAnimating(fps) { fpsInterval = 1000 / fps; then = Date.now(); startTime = then; console.log(startTime); animate(); } function animate() { // request another frame requestAnimationFrame(animate); // calc elapsed time since the last loop now = Date.now(); elapsed = now - then; // if enough time has elapsed, draw the next frame if (elapsed > fpsInterval) { then = now - (elapsed % fpsInterval); // draw animating objects here... // below code is used for testing, whether // the frame is animating at the specified fps var sinceStart = now - startTime; var currentFps = Math.round((1000 / (sinceStart / ++frameCount)) * 100) / 100; $results.text("Elapsed time= " + Math.round((sinceStart / 1000) * 100) / 100 + " secs @ " + currentFps + " fps."); } }</script>Output:The two images show the fps fluctuating around 5 fps, as assumed by the above code. To do so, keep track of the current_time and the previous_time. Each time we get: current_time - previous_time > update_interval the frame is updated and repainted onto the screen. The code for this is as follows: <h1>Controlling requestAnimationFrame to a FPS</h1><h2>This test: Results should be approximately 5 fps</h2><h2 id="results">Results:</h2><canvas id="canvas" width="300" height="300"></canvas> <script> var frameCount = 0; var $results = $("#results"); var fps, fpsInterval, startTime, now, then, elapsed; startAnimating(5); function startAnimating(fps) { fpsInterval = 1000 / fps; then = Date.now(); startTime = then; console.log(startTime); animate(); } function animate() { // request another frame requestAnimationFrame(animate); // calc elapsed time since the last loop now = Date.now(); elapsed = now - then; // if enough time has elapsed, draw the next frame if (elapsed > fpsInterval) { then = now - (elapsed % fpsInterval); // draw animating objects here... // below code is used for testing, whether // the frame is animating at the specified fps var sinceStart = now - startTime; var currentFps = Math.round((1000 / (sinceStart / ++frameCount)) * 100) / 100; $results.text("Elapsed time= " + Math.round((sinceStart / 1000) * 100) / 100 + " secs @ " + currentFps + " fps."); } }</script> Output:The two images show the fps fluctuating around 5 fps, as assumed by the above code. FPS is 4.99, after 8.61seconds have elapsed: FPS is 5.00, after 9.21 seconds have elapsed: In the above code, two variable current_time and previous_time are used to keep track of the time elapsed since the last update. Whenever the condition is satisfied (change in time is greater than interval time), the frame is updated to animate the objects. JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jun, 2020" }, { "code": null, "e": 321, "s": 28, "text": "Introduction:It is important to control the frames per second limit, especially, when developing games where the animated objects should not exceed particular frames per second limit. The requestAnimationFrame() is used for simply repainting the screen — it is not a timer or a loop function." }, { "code": null, "e": 429, "s": 321, "text": "requestAnimationFrame(callback):Used to update or repaint the screen using the callback function specified." }, { "code": null, "e": 743, "s": 429, "text": "Whenever a function call is made to requestAnimationFrame() the screen/frame is repainted according to the update code written by the developer, which makes it a suitable option for controlling the frame rate. There are two ways of controlling the fps with requestAnimationFrame(). These are discussed as follows." }, { "code": null, "e": 2419, "s": 743, "text": "Using `setTimeout` Function:This is a quick and easy approach to controlling the fps. The setTimeout() function has the following declaration:setTimeout(function, milliseconds) :Can be used to execute a function after waiting for the specified number of seconds.The code to control fps using setTimeout() is given below, the requestAnimationFrame() is passed as a function to setTimeout() for regularly updating the screen at the specified fps.<h1>Controlling requestAnimationFrame to a FPS</h1><h2>Testing approach 1: Results should be approximately 5 fps</h2><h3 id=\"results\">Results:</h3><canvas id=\"canvas\" width=\"300\" height=\"300\"></canvas> <script> var frameCount = 0; var $results = $(\"#results\"); var fps, fpsInterval, startTime, now, then, elapsed; startAnimating(5); function startAnimating(fps) { fpsInterval = 1000 / fps; then = Date.now(); startTime = then; console.log(startTime); animate(); } function animate() { setTimeout(function () { // requestAnimationFrame() is called // with animate() callback // to update content at specified fps requestAnimationFrame(animate); // ... Code for Animating the Objects ... now = Date.now(); var sinceStart = now - startTime; var currentFps = Math.round((1000 / (sinceStart / ++frameCount)) * 100) / 100; $results.text(\"Elapsed time= \" + Math.round((sinceStart / 1000) * 100) / 100 + \" secs @ \" + currentFps + \" fps.\"); }, fpsInterval); }</script>Output:The two images show the fps fluctuating around 5 fps, as assumed by the above code." }, { "code": null, "e": 2540, "s": 2419, "text": "setTimeout(function, milliseconds) :Can be used to execute a function after waiting for the specified number of seconds." }, { "code": null, "e": 2723, "s": 2540, "text": "The code to control fps using setTimeout() is given below, the requestAnimationFrame() is passed as a function to setTimeout() for regularly updating the screen at the specified fps." }, { "code": "<h1>Controlling requestAnimationFrame to a FPS</h1><h2>Testing approach 1: Results should be approximately 5 fps</h2><h3 id=\"results\">Results:</h3><canvas id=\"canvas\" width=\"300\" height=\"300\"></canvas> <script> var frameCount = 0; var $results = $(\"#results\"); var fps, fpsInterval, startTime, now, then, elapsed; startAnimating(5); function startAnimating(fps) { fpsInterval = 1000 / fps; then = Date.now(); startTime = then; console.log(startTime); animate(); } function animate() { setTimeout(function () { // requestAnimationFrame() is called // with animate() callback // to update content at specified fps requestAnimationFrame(animate); // ... Code for Animating the Objects ... now = Date.now(); var sinceStart = now - startTime; var currentFps = Math.round((1000 / (sinceStart / ++frameCount)) * 100) / 100; $results.text(\"Elapsed time= \" + Math.round((sinceStart / 1000) * 100) / 100 + \" secs @ \" + currentFps + \" fps.\"); }, fpsInterval); }</script>", "e": 3865, "s": 2723, "text": null }, { "code": null, "e": 3956, "s": 3865, "text": "Output:The two images show the fps fluctuating around 5 fps, as assumed by the above code." }, { "code": null, "e": 4001, "s": 3956, "text": "FPS is 4.9, after 5.31 seconds have elapsed:" }, { "code": null, "e": 4048, "s": 4001, "text": "FPS is 4.91, after 18.34 seconds have elapsed:" }, { "code": null, "e": 4335, "s": 4048, "text": "The above code is simply, calling the setTimeout() function at the interval rate specified by the fps. Each time setTimeout() is called, the requestAnimationFrame() is executed and the screen is repainted or updated. All this occurs at the fps specified, as determined by the developer." }, { "code": null, "e": 6317, "s": 4335, "text": "A More Optimized Approach:Most browsers cannot optimize the setTimeout() function, so to optimize the process of controlling fps simple calculation can be used. This can be easily done by keeping track of time when the frame was updated last. If the change in time (current time — previous time) exceeds the update interval, then update the frame/screen.To do so, keep track of the current_time and the previous_time. Each time we get:current_time - previous_time > update_interval \nthe frame is updated and repainted onto the screen. The code for this is as follows:<h1>Controlling requestAnimationFrame to a FPS</h1><h2>This test: Results should be approximately 5 fps</h2><h2 id=\"results\">Results:</h2><canvas id=\"canvas\" width=\"300\" height=\"300\"></canvas> <script> var frameCount = 0; var $results = $(\"#results\"); var fps, fpsInterval, startTime, now, then, elapsed; startAnimating(5); function startAnimating(fps) { fpsInterval = 1000 / fps; then = Date.now(); startTime = then; console.log(startTime); animate(); } function animate() { // request another frame requestAnimationFrame(animate); // calc elapsed time since the last loop now = Date.now(); elapsed = now - then; // if enough time has elapsed, draw the next frame if (elapsed > fpsInterval) { then = now - (elapsed % fpsInterval); // draw animating objects here... // below code is used for testing, whether // the frame is animating at the specified fps var sinceStart = now - startTime; var currentFps = Math.round((1000 / (sinceStart / ++frameCount)) * 100) / 100; $results.text(\"Elapsed time= \" + Math.round((sinceStart / 1000) * 100) / 100 + \" secs @ \" + currentFps + \" fps.\"); } }</script>Output:The two images show the fps fluctuating around 5 fps, as assumed by the above code." }, { "code": null, "e": 6399, "s": 6317, "text": "To do so, keep track of the current_time and the previous_time. Each time we get:" }, { "code": null, "e": 6448, "s": 6399, "text": "current_time - previous_time > update_interval \n" }, { "code": null, "e": 6533, "s": 6448, "text": "the frame is updated and repainted onto the screen. The code for this is as follows:" }, { "code": "<h1>Controlling requestAnimationFrame to a FPS</h1><h2>This test: Results should be approximately 5 fps</h2><h2 id=\"results\">Results:</h2><canvas id=\"canvas\" width=\"300\" height=\"300\"></canvas> <script> var frameCount = 0; var $results = $(\"#results\"); var fps, fpsInterval, startTime, now, then, elapsed; startAnimating(5); function startAnimating(fps) { fpsInterval = 1000 / fps; then = Date.now(); startTime = then; console.log(startTime); animate(); } function animate() { // request another frame requestAnimationFrame(animate); // calc elapsed time since the last loop now = Date.now(); elapsed = now - then; // if enough time has elapsed, draw the next frame if (elapsed > fpsInterval) { then = now - (elapsed % fpsInterval); // draw animating objects here... // below code is used for testing, whether // the frame is animating at the specified fps var sinceStart = now - startTime; var currentFps = Math.round((1000 / (sinceStart / ++frameCount)) * 100) / 100; $results.text(\"Elapsed time= \" + Math.round((sinceStart / 1000) * 100) / 100 + \" secs @ \" + currentFps + \" fps.\"); } }</script>", "e": 7858, "s": 6533, "text": null }, { "code": null, "e": 7949, "s": 7858, "text": "Output:The two images show the fps fluctuating around 5 fps, as assumed by the above code." }, { "code": null, "e": 7994, "s": 7949, "text": "FPS is 4.99, after 8.61seconds have elapsed:" }, { "code": null, "e": 8040, "s": 7994, "text": "FPS is 5.00, after 9.21 seconds have elapsed:" }, { "code": null, "e": 8298, "s": 8040, "text": "In the above code, two variable current_time and previous_time are used to keep track of the time elapsed since the last update. Whenever the condition is satisfied (change in time is greater than interval time), the frame is updated to animate the objects." }, { "code": null, "e": 8314, "s": 8298, "text": "JavaScript-Misc" }, { "code": null, "e": 8321, "s": 8314, "text": "Picked" }, { "code": null, "e": 8332, "s": 8321, "text": "JavaScript" }, { "code": null, "e": 8349, "s": 8332, "text": "Web Technologies" }, { "code": null, "e": 8447, "s": 8349, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8508, "s": 8447, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8548, "s": 8508, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 8589, "s": 8548, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 8631, "s": 8589, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 8653, "s": 8631, "text": "JavaScript | Promises" }, { "code": null, "e": 8715, "s": 8653, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 8748, "s": 8715, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 8809, "s": 8748, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8859, "s": 8809, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Find the minimum distance between two numbers
20 Jun, 2022 Given an unsorted array arr[] and two numbers x and y, find the minimum distance between x and y in arr[]. The array might also contain duplicates. You may assume that both x and y are different and present in arr[]. Examples: Input: arr[] = {1, 2}, x = 1, y = 2 Output: Minimum distance between 1 and 2 is 1. Explanation: 1 is at index 0 and 2 is at index 1, so the distance is 1 Input: arr[] = {3, 4, 5}, x = 3, y = 5 Output: Minimum distance between 3 and 5 is 2. Explanation:3 is at index 0 and 5 is at index 2, so the distance is 2 Input: arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3}, x = 3, y = 6 Output: Minimum distance between 3 and 6 is 4. Explanation:3 is at index 0 and 6 is at index 5, so the distance is 4 Input: arr[] = {2, 5, 3, 5, 4, 4, 2, 3}, x = 3, y = 2 Output: Minimum distance between 3 and 2 is 1. Explanation:3 is at index 7 and 2 is at index 6, so the distance is 1 Method 1: Approach: The task is to find the distance between two given numbers, So find the distance between any two elements using nested loops. The outer loop for selecting the first element (x) and the inner loop for traversing the array in search for the other element (y) and taking the minimum distance between them. Algorithm: Create a variable m = INT_MAXRun a nested loop, the outer loop runs from start to end (loop counter i), the inner loop runs from i+1 to end (loop counter j).If the ith element is x and jth element is y or vice versa, update m as m = min(m,j-i)Print the value of m as minimum distance Create a variable m = INT_MAXRun a nested loop, the outer loop runs from start to end (loop counter i), the inner loop runs from i+1 to end (loop counter j).If the ith element is x and jth element is y or vice versa, update m as m = min(m,j-i)Print the value of m as minimum distance Create a variable m = INT_MAX Run a nested loop, the outer loop runs from start to end (loop counter i), the inner loop runs from i+1 to end (loop counter j). If the ith element is x and jth element is y or vice versa, update m as m = min(m,j-i) Print the value of m as minimum distance Implementation: C++ C Java Python3 C# PHP Javascript // C++ program to Find the minimum// distance between two numbers#include <bits/stdc++.h>using namespace std; int minDist(int arr[], int n, int x, int y){ int i, j; int min_dist = INT_MAX; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > abs(i - j)) { min_dist = abs(i - j); } } } if (min_dist > n) { return -1; } return min_dist;} /* Driver code */int main(){ int arr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; int y = 6; cout << "Minimum distance between " << x << " and " << y << " is " << minDist(arr, n, x, y) << endl;} // This code is contributed by Shivi_Aggarwal // C program to Find the minimum// distance between two numbers#include <limits.h> // for INT_MAX#include <stdio.h>#include <stdlib.h> // for abs() int minDist(int arr[], int n, int x, int y){ int i, j; int min_dist = INT_MAX; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > abs(i - j)) { min_dist = abs(i - j); } } } if (min_dist > n) { return -1; } return min_dist;} /* Driver program to test above function */int main(){ int arr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 0; int y = 6; printf("Minimum distance between %d and %d is %d\n", x, y, minDist(arr, n, x, y)); return 0;} // Java Program to Find the minimum// distance between two numbersclass MinimumDistance { int minDist(int arr[], int n, int x, int y) { int i, j; int min_dist = Integer.MAX_VALUE; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > Math.abs(i - j)) min_dist = Math.abs(i - j); } } if (min_dist > n) { return -1; } return min_dist; } public static void main(String[] args) { MinimumDistance min = new MinimumDistance(); int arr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 }; int n = arr.length; int x = 0; int y = 6; System.out.println("Minimum distance between " + x + " and " + y + " is " + min.minDist(arr, n, x, y)); }} # Python3 code to Find the minimum# distance between two numbers def minDist(arr, n, x, y): min_dist = 99999999 for i in range(n): for j in range(i + 1, n): if (x == arr[i] and y == arr[j] or y == arr[i] and x == arr[j]) and min_dist > abs(i-j): min_dist = abs(i-j) return min_dist # Driver codearr = [3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3]n = len(arr)x = 3y = 6print("Minimum distance between ", x, " and ", y, "is", minDist(arr, n, x, y)) # This code is contributed by "Abhishek Sharma 44" // C# code to Find the minimum// distance between two numbersusing System; class GFG { static int minDist(int []arr, int n, int x, int y) { int i, j; int min_dist = int.MaxValue; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > Math.Abs(i - j)) min_dist = Math.Abs(i - j); } } return min_dist; } // Driver function public static void Main() { int []arr = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3}; int n = arr.Length; int x = 3; int y = 6; Console.WriteLine("Minimum " + "distance between " + x + " and " + y + " is " + minDist(arr, n, x, y)); }} // This code is contributed by Sam007 <?php// PHP program to Find the minimum// distance between two numbers function minDist($arr, $n, $x, $y){ $i; $j; $min_dist = PHP_INT_MAX; for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { if( ($x == $arr[$i] and $y == $arr[$j] or $y == $arr[$i] and $x == $arr[$j]) and $min_dist > abs($i - $j)) { $min_dist = abs($i - $j); } } } if($min_dist>$n) { return -1; } return $min_dist;} // Driver Code $arr = array(3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3); $n = count($arr); $x = 0; $y = 6; echo "Minimum distance between ",$x, " and ",$y," is "; echo minDist($arr, $n, $x, $y); // This code is contributed by anuj_67.?> <script> // Javascript program to find the minimum// distance between two numbersfunction minDist(arr, n, x, y){ var i, j; var min_dist = Number.MAX_VALUE; for(i = 0; i < n; i++) { for(j = i + 1; j < n; j++) { if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > Math.abs(i - j)) min_dist = Math.abs(i - j); } } if(min_dist>n) { return -1; } return min_dist;} // Driver codevar arr = [ 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 ];var n = arr.length;var x = 3;var y = 6; document.write("Minimum distance between " + x + " and " + y + " is " + minDist(arr, n, x, y)); // This code is contributed by gauravrajput1 </script> Minimum distance between 3 and 6 is 4 Complexity Analysis: Time Complexity: O(n^2), Nested loop is used to traverse the array.Space Complexity: O(1), no extra space is required. Time Complexity: O(n^2), Nested loop is used to traverse the array. Space Complexity: O(1), no extra space is required. Method 2: 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. Approach: So the basic approach is to check only consecutive pairs of x and y. For every element x or y, check the index of the previous occurrence of x or y and if the previous occurring element is not similar to current element update the minimum distance. But a question arises what if an x is preceded by another x and that is preceded by a y, then how to get the minimum distance between pairs. By analyzing closely it can be seen that every x followed by a y or vice versa can only be the closest pair (minimum distance) so ignore all other pairs. Algorithm: Create a variable prev=-1 and m= INT_MAXTraverse through the array from start to end.If the current element is x or y, prev is not equal to -1 and array[prev] is not equal to current element then update m = max(current_index – prev, m), i.e. find the distance between consecutive pairs and update m with it.print the value of m Create a variable prev=-1 and m= INT_MAXTraverse through the array from start to end.If the current element is x or y, prev is not equal to -1 and array[prev] is not equal to current element then update m = max(current_index – prev, m), i.e. find the distance between consecutive pairs and update m with it.print the value of m Create a variable prev=-1 and m= INT_MAX Traverse through the array from start to end. If the current element is x or y, prev is not equal to -1 and array[prev] is not equal to current element then update m = max(current_index – prev, m), i.e. find the distance between consecutive pairs and update m with it. print the value of m Thanks to wgpshashank for suggesting this approach. Implementation. C++ C Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; int minDist(int arr[], int n, int x, int y){ //previous index and min distance int p = -1, min_dist = INT_MAX; for(int i=0 ; i<n ; i++) { if(arr[i]==x || arr[i]==y) { //we will check if p is not equal to -1 and //If the element at current index matches with //the element at index p , If yes then update //the minimum distance if needed if( p != -1 && arr[i] != arr[p]) min_dist = min(min_dist , i-p); //update the previous index p=i; } } //If distance is equal to int max if(min_dist==INT_MAX) return -1; return min_dist;} /* Driver code */int main(){ int arr[] = {3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3}; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; int y = 6; cout << "Minimum distance between " << x << " and " << y << " is "<< minDist(arr, n, x, y) << endl; return 0;} // This code is contributed by Mukul singh. #include <stdio.h>#include <limits.h> // For INT_MAX //returns minimum of two numbersint min(int a ,int b){ if(a < b) return a; return b;} int minDist(int arr[], int n, int x, int y){ //previous index and min distance int i=0,p=-1, min_dist=INT_MAX; for(i=0 ; i<n ; i++) { if(arr[i] ==x || arr[i] == y) { //we will check if p is not equal to -1 and //If the element at current index matches with //the element at index p , If yes then update //the minimum distance if needed if(p != -1 && arr[i] != arr[p]) min_dist = min(min_dist,i-p); //update the previous index p=i; } } //If distance is equal to int max if(min_dist==INT_MAX) return -1; return min_dist;} /* Driver program to test above function */int main(){ int arr[] ={3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3}; int n = sizeof(arr)/sizeof(arr[0]); int x = 3; int y = 6; printf("Minimum distance between %d and %d is %d\n", x, y, minDist(arr, n, x, y)); return 0;} class MinimumDistance{ int minDist(int arr[], int n, int x, int y) { //previous index and min distance int i=0,p=-1, min_dist=Integer.MAX_VALUE; for(i=0 ; i<n ; i++) { if(arr[i] ==x || arr[i] == y) { //we will check if p is not equal to -1 and //If the element at current index matches with //the element at index p , If yes then update //the minimum distance if needed if(p != -1 && arr[i] != arr[p]) min_dist = Math.min(min_dist,i-p); //update the previous index p=i; } } //If distance is equal to int max if(min_dist==Integer.MAX_VALUE) return -1; return min_dist;} /* Driver program to test above functions */ public static void main(String[] args) { MinimumDistance min = new MinimumDistance(); int arr[] = {3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3}; int n = arr.length; int x = 3; int y = 6; System.out.println("Minimum distance between " + x + " and " + y + " is " + min.minDist(arr, n, x, y)); }} import sys def minDist(arr, n, x, y): #previous index and min distance i=0 p=-1 min_dist = sys.maxsize; for i in range(n): if(arr[i] ==x or arr[i] == y): #we will check if p is not equal to -1 and #If the element at current index matches with #the element at index p , If yes then update #the minimum distance if needed if(p != -1 and arr[i] != arr[p]): min_dist = min(min_dist,i-p) #update the previous index p=i #If distance is equal to int max if(min_dist == sys.maxsize): return -1 return min_dist # Driver program to test above function */arr = [3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3]n = len(arr)x = 3y = 6print ("Minimum distance between %d and %d is %d\n"%( x, y,minDist(arr, n, x, y))); # This code is contributed by Shreyanshi Arun. // C# program to Find the minimum// distance between two numbersusing System;class MinimumDistance { static int minDist(int []arr, int n, int x, int y) { //previous index and min distance int i=0,p=-1, min_dist=int.MaxValue; for(i=0 ; i<n ; i++) { if(arr[i] ==x || arr[i] == y) { //we will check if p is not equal to -1 and //If the element at current index matches with //the element at index p , If yes then update //the minimum distance if needed if(p != -1 && arr[i] != arr[p]) min_dist = Math.Min(min_dist,i-p); //update the previous index p=i; } } //If distance is equal to int max if(min_dist==int.MaxValue) return -1; return min_dist;} // Driver Code public static void Main() { int []arr = {3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3}; int n = arr.Length; int x = 3; int y = 6; Console.WriteLine("Minimum distance between " + x + " and " + y + " is " + minDist(arr, n, x, y)); }} // This code is contributed by anuj_67. <?php// PHP program to Find the minimum// distance between two numbers function minDist($arr, $n, $x, $y){ //previous index and min distance $i=0; $p=-1; $min_dist=PHP_INT_MAX; for($i=0 ; $i<$n ; $i++) { if($arr[$i] ==$x || $arr[$i] == $y) { //we will check if p is not equal to -1 and //If the element at current index matches with //the element at index p , If yes then update //the minimum distance if needed if($p != -1 && $arr[$i] != $arr[$p]) $min_dist = min($min_dist,$i-$p); //update the previous index $p=$i; } } //If distance is equal to int max if($min_dist==PHP_INT_MAX) return -1; return $min_dist;} /* Driver program to test above function */ $arr =array(3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3); $n = count($arr); $x = 3; $y = 6; echo "Minimum distance between $x and ", "$y is ", minDist($arr, $n, $x, $y); // This code is contributed by anuj_67.?> <script>function minDist(arr , n , x , y){ // previous index and min distance var i=0,p=-1, min_dist=Number.MAX_VALUE; for(i=0 ; i<n ; i++) { if(arr[i] ==x || arr[i] == y) { // we will check if p is not equal to -1 and // If the element at current index matches with // the element at index p , If yes then update // the minimum distance if needed if(p != -1 && arr[i] != arr[p]) min_dist = Math.min(min_dist,i-p); // update the previous index p=i; } } // If distance is equal to var max if(min_dist==Number.MAX_VALUE) return -1; return min_dist;} /* Driver program to test above functions */ var arr = [3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3]; var n = arr.length; var x = 3; var y = 6; document.write("Minimum distance between " + x + " and " + y + " is " + minDist(arr, n, x, y)); // This code contributed by shikhasingrajput </script> Minimum distance between 3 and 6 is 1 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed. Space Complexity: O(1). As no extra space is required. Method 3: Approach: The problem says that we want a minimum distance between x and y. So the approach is traverse the array and while traversing in array if we got the number as x or y then we will store the difference between indices of previously found x or y and newly find x or y and like this for every time we will try to minimize the difference. Algorithm: Create variables idx1 = -1, idx2 = -1 and min_dist = INT_MAX; Traverse the array from i = 0 to i = n-1 where n is the size of array. While traversing if the current element is x then store index of current element in idx1 or if the current element is y then store index of current element in idx2. If idx1 and idx2 variable are not equal to -1 then store minimum of min_dist, difference of idx1 and idx2 into ans. At the end of traversal, if idx1 or idx2 are still -1(x or y not found in array) then return -1 or else return min_dist. Create variables idx1 = -1, idx2 = -1 and min_dist = INT_MAX; Traverse the array from i = 0 to i = n-1 where n is the size of array. While traversing if the current element is x then store index of current element in idx1 or if the current element is y then store index of current element in idx2. If idx1 and idx2 variable are not equal to -1 then store minimum of min_dist, difference of idx1 and idx2 into ans. At the end of traversal, if idx1 or idx2 are still -1(x or y not found in array) then return -1 or else return min_dist. Implementation: C++ Java // C++ program to Find the minimum// distance between two numbers#include <bits/stdc++.h>using namespace std; int minDist(int arr[], int n, int x, int y){ //idx1 and idx2 will store indices of //x or y and min_dist will store the minimum difference int idx1=-1,idx2=-1,min_dist = INT_MAX; for(int i=0;i<n;i++) { //if current element is x then change idx1 if(arr[i]==x) { idx1=i; } //if current element is y then change idx2 else if(arr[i]==y) { idx2=i; } //if x and y both found in array //then only find the difference and store it in min_dist if(idx1!=-1 && idx2!=-1) min_dist=min(min_dist,abs(idx1-idx2)); } //if left or right did not found in array //then return -1 if(idx1==-1||idx2==-1) return -1; //return the minimum distance else return min_dist;} /* Driver code */int main(){ int arr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; int y = 6; cout << "Minimum distance between " << x << " and " << y << " is " << minDist(arr, n, x, y) << endl;} // Java program to Find the minimum// distance between two numbers public class GFG { static int minDist(int arr[], int n, int x, int y) { // idx1 and idx2 will store indices of // x or y and min_dist will store the minimum // difference int idx1 = -1, idx2 = -1, min_dist = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { // if current element is x then change idx1 if (arr[i] == x) { idx1 = i; } // if current element is y then change idx2 else if (arr[i] == y) { idx2 = i; } // if x and y both found in array // then only find the difference and store it in // min_dist if (idx1 != -1 && idx2 != -1) min_dist = Math.min(min_dist, Math.abs(idx1 - idx2)); } // if left or right did not found in array // then return -1 if (idx1 == -1 || idx2 == -1) return -1; // return the minimum distance else return min_dist; } /* Driver code */ public static void main(String[] args) { int arr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 }; int n = arr.length; int x = 3; int y = 6; System.out.println("Minimum distance between " + x + " and " + y + " is " + minDist(arr, n, x, y)); }} // This code is contributed by Lovely Jain Minimum distance between 3 and 6 is 4 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is required. Space Complexity: O(1). No extra space is required. Find the minimum distance between two numbers | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersFind the minimum distance between two numbers | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 15:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=hoceGcqQczM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem. Sam007 vt_m Shivi_Aggarwal Code_Mech srinam andrew1234 GauravRajput1 shikhasingrajput simmytarika5 akshitsaxenaa09 bhupendrasingh01 aditya942003patil sagartomar9927 jainlovely450 Paytm Arrays Paytm Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Introduction to Arrays Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Subset Sum Problem | DP-25 Introduction to Data Structures Python | Using 2D arrays/lists the right way
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jun, 2022" }, { "code": null, "e": 269, "s": 52, "text": "Given an unsorted array arr[] and two numbers x and y, find the minimum distance between x and y in arr[]. The array might also contain duplicates. You may assume that both x and y are different and present in arr[]." }, { "code": null, "e": 280, "s": 269, "text": "Examples: " }, { "code": null, "e": 959, "s": 280, "text": "Input: arr[] = {1, 2}, x = 1, y = 2\nOutput: Minimum distance between 1 \nand 2 is 1.\nExplanation: 1 is at index 0 and 2 is at \nindex 1, so the distance is 1\n\nInput: arr[] = {3, 4, 5}, x = 3, y = 5\nOutput: Minimum distance between 3 \nand 5 is 2.\nExplanation:3 is at index 0 and 5 is at \nindex 2, so the distance is 2\n\nInput: \narr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3}, \nx = 3, y = 6\nOutput: Minimum distance between 3 \nand 6 is 4.\nExplanation:3 is at index 0 and 6 is at \nindex 5, so the distance is 4\n\nInput: arr[] = {2, 5, 3, 5, 4, 4, 2, 3}, \nx = 3, y = 2\nOutput: Minimum distance between 3 \nand 2 is 1.\nExplanation:3 is at index 7 and 2 is at \nindex 6, so the distance is 1" }, { "code": null, "e": 970, "s": 959, "text": "Method 1: " }, { "code": null, "e": 1283, "s": 970, "text": "Approach: The task is to find the distance between two given numbers, So find the distance between any two elements using nested loops. The outer loop for selecting the first element (x) and the inner loop for traversing the array in search for the other element (y) and taking the minimum distance between them." }, { "code": null, "e": 1578, "s": 1283, "text": "Algorithm: Create a variable m = INT_MAXRun a nested loop, the outer loop runs from start to end (loop counter i), the inner loop runs from i+1 to end (loop counter j).If the ith element is x and jth element is y or vice versa, update m as m = min(m,j-i)Print the value of m as minimum distance" }, { "code": null, "e": 1862, "s": 1578, "text": "Create a variable m = INT_MAXRun a nested loop, the outer loop runs from start to end (loop counter i), the inner loop runs from i+1 to end (loop counter j).If the ith element is x and jth element is y or vice versa, update m as m = min(m,j-i)Print the value of m as minimum distance" }, { "code": null, "e": 1892, "s": 1862, "text": "Create a variable m = INT_MAX" }, { "code": null, "e": 2021, "s": 1892, "text": "Run a nested loop, the outer loop runs from start to end (loop counter i), the inner loop runs from i+1 to end (loop counter j)." }, { "code": null, "e": 2108, "s": 2021, "text": "If the ith element is x and jth element is y or vice versa, update m as m = min(m,j-i)" }, { "code": null, "e": 2149, "s": 2108, "text": "Print the value of m as minimum distance" }, { "code": null, "e": 2165, "s": 2149, "text": "Implementation:" }, { "code": null, "e": 2169, "s": 2165, "text": "C++" }, { "code": null, "e": 2171, "s": 2169, "text": "C" }, { "code": null, "e": 2176, "s": 2171, "text": "Java" }, { "code": null, "e": 2184, "s": 2176, "text": "Python3" }, { "code": null, "e": 2187, "s": 2184, "text": "C#" }, { "code": null, "e": 2191, "s": 2187, "text": "PHP" }, { "code": null, "e": 2202, "s": 2191, "text": "Javascript" }, { "code": "// C++ program to Find the minimum// distance between two numbers#include <bits/stdc++.h>using namespace std; int minDist(int arr[], int n, int x, int y){ int i, j; int min_dist = INT_MAX; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > abs(i - j)) { min_dist = abs(i - j); } } } if (min_dist > n) { return -1; } return min_dist;} /* Driver code */int main(){ int arr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; int y = 6; cout << \"Minimum distance between \" << x << \" and \" << y << \" is \" << minDist(arr, n, x, y) << endl;} // This code is contributed by Shivi_Aggarwal", "e": 3041, "s": 2202, "text": null }, { "code": "// C program to Find the minimum// distance between two numbers#include <limits.h> // for INT_MAX#include <stdio.h>#include <stdlib.h> // for abs() int minDist(int arr[], int n, int x, int y){ int i, j; int min_dist = INT_MAX; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > abs(i - j)) { min_dist = abs(i - j); } } } if (min_dist > n) { return -1; } return min_dist;} /* Driver program to test above function */int main(){ int arr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 0; int y = 6; printf(\"Minimum distance between %d and %d is %d\\n\", x, y, minDist(arr, n, x, y)); return 0;}", "e": 3895, "s": 3041, "text": null }, { "code": "// Java Program to Find the minimum// distance between two numbersclass MinimumDistance { int minDist(int arr[], int n, int x, int y) { int i, j; int min_dist = Integer.MAX_VALUE; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > Math.abs(i - j)) min_dist = Math.abs(i - j); } } if (min_dist > n) { return -1; } return min_dist; } public static void main(String[] args) { MinimumDistance min = new MinimumDistance(); int arr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 }; int n = arr.length; int x = 0; int y = 6; System.out.println(\"Minimum distance between \" + x + \" and \" + y + \" is \" + min.minDist(arr, n, x, y)); }}", "e": 4865, "s": 3895, "text": null }, { "code": "# Python3 code to Find the minimum# distance between two numbers def minDist(arr, n, x, y): min_dist = 99999999 for i in range(n): for j in range(i + 1, n): if (x == arr[i] and y == arr[j] or y == arr[i] and x == arr[j]) and min_dist > abs(i-j): min_dist = abs(i-j) return min_dist # Driver codearr = [3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3]n = len(arr)x = 3y = 6print(\"Minimum distance between \", x, \" and \", y, \"is\", minDist(arr, n, x, y)) # This code is contributed by \"Abhishek Sharma 44\"", "e": 5426, "s": 4865, "text": null }, { "code": "// C# code to Find the minimum// distance between two numbersusing System; class GFG { static int minDist(int []arr, int n, int x, int y) { int i, j; int min_dist = int.MaxValue; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > Math.Abs(i - j)) min_dist = Math.Abs(i - j); } } return min_dist; } // Driver function public static void Main() { int []arr = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3}; int n = arr.Length; int x = 3; int y = 6; Console.WriteLine(\"Minimum \" + \"distance between \" + x + \" and \" + y + \" is \" + minDist(arr, n, x, y)); }} // This code is contributed by Sam007", "e": 6476, "s": 5426, "text": null }, { "code": "<?php// PHP program to Find the minimum// distance between two numbers function minDist($arr, $n, $x, $y){ $i; $j; $min_dist = PHP_INT_MAX; for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { if( ($x == $arr[$i] and $y == $arr[$j] or $y == $arr[$i] and $x == $arr[$j]) and $min_dist > abs($i - $j)) { $min_dist = abs($i - $j); } } } if($min_dist>$n) { return -1; } return $min_dist;} // Driver Code $arr = array(3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3); $n = count($arr); $x = 0; $y = 6; echo \"Minimum distance between \",$x, \" and \",$y,\" is \"; echo minDist($arr, $n, $x, $y); // This code is contributed by anuj_67.?>", "e": 7273, "s": 6476, "text": null }, { "code": "<script> // Javascript program to find the minimum// distance between two numbersfunction minDist(arr, n, x, y){ var i, j; var min_dist = Number.MAX_VALUE; for(i = 0; i < n; i++) { for(j = i + 1; j < n; j++) { if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > Math.abs(i - j)) min_dist = Math.abs(i - j); } } if(min_dist>n) { return -1; } return min_dist;} // Driver codevar arr = [ 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 ];var n = arr.length;var x = 3;var y = 6; document.write(\"Minimum distance between \" + x + \" and \" + y + \" is \" + minDist(arr, n, x, y)); // This code is contributed by gauravrajput1 </script>", "e": 8072, "s": 7273, "text": null }, { "code": null, "e": 8110, "s": 8072, "text": "Minimum distance between 3 and 6 is 4" }, { "code": null, "e": 8250, "s": 8110, "text": "Complexity Analysis: Time Complexity: O(n^2), Nested loop is used to traverse the array.Space Complexity: O(1), no extra space is required." }, { "code": null, "e": 8318, "s": 8250, "text": "Time Complexity: O(n^2), Nested loop is used to traverse the array." }, { "code": null, "e": 8370, "s": 8318, "text": "Space Complexity: O(1), no extra space is required." }, { "code": null, "e": 8381, "s": 8370, "text": "Method 2: " }, { "code": null, "e": 8390, "s": 8381, "text": "Chapters" }, { "code": null, "e": 8417, "s": 8390, "text": "descriptions off, selected" }, { "code": null, "e": 8467, "s": 8417, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 8490, "s": 8467, "text": "captions off, selected" }, { "code": null, "e": 8498, "s": 8490, "text": "English" }, { "code": null, "e": 8522, "s": 8498, "text": "This is a modal window." }, { "code": null, "e": 8591, "s": 8522, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 8613, "s": 8591, "text": "End of dialog window." }, { "code": null, "e": 9167, "s": 8613, "text": "Approach: So the basic approach is to check only consecutive pairs of x and y. For every element x or y, check the index of the previous occurrence of x or y and if the previous occurring element is not similar to current element update the minimum distance. But a question arises what if an x is preceded by another x and that is preceded by a y, then how to get the minimum distance between pairs. By analyzing closely it can be seen that every x followed by a y or vice versa can only be the closest pair (minimum distance) so ignore all other pairs." }, { "code": null, "e": 9506, "s": 9167, "text": "Algorithm: Create a variable prev=-1 and m= INT_MAXTraverse through the array from start to end.If the current element is x or y, prev is not equal to -1 and array[prev] is not equal to current element then update m = max(current_index – prev, m), i.e. find the distance between consecutive pairs and update m with it.print the value of m" }, { "code": null, "e": 9834, "s": 9506, "text": "Create a variable prev=-1 and m= INT_MAXTraverse through the array from start to end.If the current element is x or y, prev is not equal to -1 and array[prev] is not equal to current element then update m = max(current_index – prev, m), i.e. find the distance between consecutive pairs and update m with it.print the value of m" }, { "code": null, "e": 9875, "s": 9834, "text": "Create a variable prev=-1 and m= INT_MAX" }, { "code": null, "e": 9921, "s": 9875, "text": "Traverse through the array from start to end." }, { "code": null, "e": 10144, "s": 9921, "text": "If the current element is x or y, prev is not equal to -1 and array[prev] is not equal to current element then update m = max(current_index – prev, m), i.e. find the distance between consecutive pairs and update m with it." }, { "code": null, "e": 10165, "s": 10144, "text": "print the value of m" }, { "code": null, "e": 10217, "s": 10165, "text": "Thanks to wgpshashank for suggesting this approach." }, { "code": null, "e": 10233, "s": 10217, "text": "Implementation." }, { "code": null, "e": 10237, "s": 10233, "text": "C++" }, { "code": null, "e": 10239, "s": 10237, "text": "C" }, { "code": null, "e": 10244, "s": 10239, "text": "Java" }, { "code": null, "e": 10252, "s": 10244, "text": "Python3" }, { "code": null, "e": 10255, "s": 10252, "text": "C#" }, { "code": null, "e": 10259, "s": 10255, "text": "PHP" }, { "code": null, "e": 10270, "s": 10259, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; int minDist(int arr[], int n, int x, int y){ //previous index and min distance int p = -1, min_dist = INT_MAX; for(int i=0 ; i<n ; i++) { if(arr[i]==x || arr[i]==y) { //we will check if p is not equal to -1 and //If the element at current index matches with //the element at index p , If yes then update //the minimum distance if needed if( p != -1 && arr[i] != arr[p]) min_dist = min(min_dist , i-p); //update the previous index p=i; } } //If distance is equal to int max if(min_dist==INT_MAX) return -1; return min_dist;} /* Driver code */int main(){ int arr[] = {3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3}; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; int y = 6; cout << \"Minimum distance between \" << x << \" and \" << y << \" is \"<< minDist(arr, n, x, y) << endl; return 0;} // This code is contributed by Mukul singh.", "e": 11410, "s": 10270, "text": null }, { "code": "#include <stdio.h>#include <limits.h> // For INT_MAX //returns minimum of two numbersint min(int a ,int b){ if(a < b) return a; return b;} int minDist(int arr[], int n, int x, int y){ //previous index and min distance int i=0,p=-1, min_dist=INT_MAX; for(i=0 ; i<n ; i++) { if(arr[i] ==x || arr[i] == y) { //we will check if p is not equal to -1 and //If the element at current index matches with //the element at index p , If yes then update //the minimum distance if needed if(p != -1 && arr[i] != arr[p]) min_dist = min(min_dist,i-p); //update the previous index p=i; } } //If distance is equal to int max if(min_dist==INT_MAX) return -1; return min_dist;} /* Driver program to test above function */int main(){ int arr[] ={3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3}; int n = sizeof(arr)/sizeof(arr[0]); int x = 3; int y = 6; printf(\"Minimum distance between %d and %d is %d\\n\", x, y, minDist(arr, n, x, y)); return 0;}", "e": 12530, "s": 11410, "text": null }, { "code": "class MinimumDistance{ int minDist(int arr[], int n, int x, int y) { //previous index and min distance int i=0,p=-1, min_dist=Integer.MAX_VALUE; for(i=0 ; i<n ; i++) { if(arr[i] ==x || arr[i] == y) { //we will check if p is not equal to -1 and //If the element at current index matches with //the element at index p , If yes then update //the minimum distance if needed if(p != -1 && arr[i] != arr[p]) min_dist = Math.min(min_dist,i-p); //update the previous index p=i; } } //If distance is equal to int max if(min_dist==Integer.MAX_VALUE) return -1; return min_dist;} /* Driver program to test above functions */ public static void main(String[] args) { MinimumDistance min = new MinimumDistance(); int arr[] = {3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3}; int n = arr.length; int x = 3; int y = 6; System.out.println(\"Minimum distance between \" + x + \" and \" + y + \" is \" + min.minDist(arr, n, x, y)); }}", "e": 13674, "s": 12530, "text": null }, { "code": "import sys def minDist(arr, n, x, y): #previous index and min distance i=0 p=-1 min_dist = sys.maxsize; for i in range(n): if(arr[i] ==x or arr[i] == y): #we will check if p is not equal to -1 and #If the element at current index matches with #the element at index p , If yes then update #the minimum distance if needed if(p != -1 and arr[i] != arr[p]): min_dist = min(min_dist,i-p) #update the previous index p=i #If distance is equal to int max if(min_dist == sys.maxsize): return -1 return min_dist # Driver program to test above function */arr = [3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3]n = len(arr)x = 3y = 6print (\"Minimum distance between %d and %d is %d\\n\"%( x, y,minDist(arr, n, x, y))); # This code is contributed by Shreyanshi Arun.", "e": 14596, "s": 13674, "text": null }, { "code": "// C# program to Find the minimum// distance between two numbersusing System;class MinimumDistance { static int minDist(int []arr, int n, int x, int y) { //previous index and min distance int i=0,p=-1, min_dist=int.MaxValue; for(i=0 ; i<n ; i++) { if(arr[i] ==x || arr[i] == y) { //we will check if p is not equal to -1 and //If the element at current index matches with //the element at index p , If yes then update //the minimum distance if needed if(p != -1 && arr[i] != arr[p]) min_dist = Math.Min(min_dist,i-p); //update the previous index p=i; } } //If distance is equal to int max if(min_dist==int.MaxValue) return -1; return min_dist;} // Driver Code public static void Main() { int []arr = {3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3}; int n = arr.Length; int x = 3; int y = 6; Console.WriteLine(\"Minimum distance between \" + x + \" and \" + y + \" is \" + minDist(arr, n, x, y)); }} // This code is contributed by anuj_67.", "e": 15827, "s": 14596, "text": null }, { "code": "<?php// PHP program to Find the minimum// distance between two numbers function minDist($arr, $n, $x, $y){ //previous index and min distance $i=0; $p=-1; $min_dist=PHP_INT_MAX; for($i=0 ; $i<$n ; $i++) { if($arr[$i] ==$x || $arr[$i] == $y) { //we will check if p is not equal to -1 and //If the element at current index matches with //the element at index p , If yes then update //the minimum distance if needed if($p != -1 && $arr[$i] != $arr[$p]) $min_dist = min($min_dist,$i-$p); //update the previous index $p=$i; } } //If distance is equal to int max if($min_dist==PHP_INT_MAX) return -1; return $min_dist;} /* Driver program to test above function */ $arr =array(3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3); $n = count($arr); $x = 3; $y = 6; echo \"Minimum distance between $x and \", \"$y is \", minDist($arr, $n, $x, $y); // This code is contributed by anuj_67.?>", "e": 16919, "s": 15827, "text": null }, { "code": "<script>function minDist(arr , n , x , y){ // previous index and min distance var i=0,p=-1, min_dist=Number.MAX_VALUE; for(i=0 ; i<n ; i++) { if(arr[i] ==x || arr[i] == y) { // we will check if p is not equal to -1 and // If the element at current index matches with // the element at index p , If yes then update // the minimum distance if needed if(p != -1 && arr[i] != arr[p]) min_dist = Math.min(min_dist,i-p); // update the previous index p=i; } } // If distance is equal to var max if(min_dist==Number.MAX_VALUE) return -1; return min_dist;} /* Driver program to test above functions */ var arr = [3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3]; var n = arr.length; var x = 3; var y = 6; document.write(\"Minimum distance between \" + x + \" and \" + y + \" is \" + minDist(arr, n, x, y)); // This code contributed by shikhasingrajput </script>", "e": 17921, "s": 16919, "text": null }, { "code": null, "e": 17959, "s": 17921, "text": "Minimum distance between 3 and 6 is 1" }, { "code": null, "e": 17980, "s": 17959, "text": "Complexity Analysis:" }, { "code": null, "e": 18046, "s": 17980, "text": "Time Complexity: O(n). Only one traversal of the array is needed." }, { "code": null, "e": 18102, "s": 18046, "text": "Space Complexity: O(1). As no extra space is required. " }, { "code": null, "e": 18112, "s": 18102, "text": "Method 3:" }, { "code": null, "e": 18456, "s": 18112, "text": "Approach: The problem says that we want a minimum distance between x and y. So the approach is traverse the array and while traversing in array if we got the number as x or y then we will store the difference between indices of previously found x or y and newly find x or y and like this for every time we will try to minimize the difference." }, { "code": null, "e": 18468, "s": 18456, "text": "Algorithm: " }, { "code": null, "e": 19041, "s": 18468, "text": " Create variables idx1 = -1, idx2 = -1 and min_dist = INT_MAX; Traverse the array from i = 0 to i = n-1 where n is the size of array. While traversing if the current element is x then store index of current element in idx1 or if the current element is y then store index of current element in idx2. If idx1 and idx2 variable are not equal to -1 then store minimum of min_dist, difference of idx1 and idx2 into ans. At the end of traversal, if idx1 or idx2 are still -1(x or y not found in array) then return -1 or else return min_dist." }, { "code": null, "e": 19106, "s": 19041, "text": " Create variables idx1 = -1, idx2 = -1 and min_dist = INT_MAX;" }, { "code": null, "e": 19180, "s": 19106, "text": " Traverse the array from i = 0 to i = n-1 where n is the size of array." }, { "code": null, "e": 19359, "s": 19180, "text": " While traversing if the current element is x then store index of current element in idx1 or if the current element is y then store index of current element in idx2." }, { "code": null, "e": 19481, "s": 19359, "text": " If idx1 and idx2 variable are not equal to -1 then store minimum of min_dist, difference of idx1 and idx2 into ans." }, { "code": null, "e": 19618, "s": 19481, "text": " At the end of traversal, if idx1 or idx2 are still -1(x or y not found in array) then return -1 or else return min_dist." }, { "code": null, "e": 19634, "s": 19618, "text": "Implementation:" }, { "code": null, "e": 19638, "s": 19634, "text": "C++" }, { "code": null, "e": 19643, "s": 19638, "text": "Java" }, { "code": "// C++ program to Find the minimum// distance between two numbers#include <bits/stdc++.h>using namespace std; int minDist(int arr[], int n, int x, int y){ //idx1 and idx2 will store indices of //x or y and min_dist will store the minimum difference int idx1=-1,idx2=-1,min_dist = INT_MAX; for(int i=0;i<n;i++) { //if current element is x then change idx1 if(arr[i]==x) { idx1=i; } //if current element is y then change idx2 else if(arr[i]==y) { idx2=i; } //if x and y both found in array //then only find the difference and store it in min_dist if(idx1!=-1 && idx2!=-1) min_dist=min(min_dist,abs(idx1-idx2)); } //if left or right did not found in array //then return -1 if(idx1==-1||idx2==-1) return -1; //return the minimum distance else return min_dist;} /* Driver code */int main(){ int arr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; int y = 6; cout << \"Minimum distance between \" << x << \" and \" << y << \" is \" << minDist(arr, n, x, y) << endl;}", "e": 20804, "s": 19643, "text": null }, { "code": "// Java program to Find the minimum// distance between two numbers public class GFG { static int minDist(int arr[], int n, int x, int y) { // idx1 and idx2 will store indices of // x or y and min_dist will store the minimum // difference int idx1 = -1, idx2 = -1, min_dist = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { // if current element is x then change idx1 if (arr[i] == x) { idx1 = i; } // if current element is y then change idx2 else if (arr[i] == y) { idx2 = i; } // if x and y both found in array // then only find the difference and store it in // min_dist if (idx1 != -1 && idx2 != -1) min_dist = Math.min(min_dist, Math.abs(idx1 - idx2)); } // if left or right did not found in array // then return -1 if (idx1 == -1 || idx2 == -1) return -1; // return the minimum distance else return min_dist; } /* Driver code */ public static void main(String[] args) { int arr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 }; int n = arr.length; int x = 3; int y = 6; System.out.println(\"Minimum distance between \" + x + \" and \" + y + \" is \" + minDist(arr, n, x, y)); }} // This code is contributed by Lovely Jain", "e": 22332, "s": 20804, "text": null }, { "code": null, "e": 22370, "s": 22332, "text": "Minimum distance between 3 and 6 is 4" }, { "code": null, "e": 22391, "s": 22370, "text": "Complexity Analysis:" }, { "code": null, "e": 22459, "s": 22391, "text": "Time Complexity: O(n). Only one traversal of the array is required." }, { "code": null, "e": 22511, "s": 22459, "text": "Space Complexity: O(1). No extra space is required." }, { "code": null, "e": 23420, "s": 22511, "text": "Find the minimum distance between two numbers | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersFind the minimum distance between two numbers | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 15:56•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=hoceGcqQczM\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 23538, "s": 23420, "text": "Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem." }, { "code": null, "e": 23545, "s": 23538, "text": "Sam007" }, { "code": null, "e": 23550, "s": 23545, "text": "vt_m" }, { "code": null, "e": 23565, "s": 23550, "text": "Shivi_Aggarwal" }, { "code": null, "e": 23575, "s": 23565, "text": "Code_Mech" }, { "code": null, "e": 23582, "s": 23575, "text": "srinam" }, { "code": null, "e": 23593, "s": 23582, "text": "andrew1234" }, { "code": null, "e": 23607, "s": 23593, "text": "GauravRajput1" }, { "code": null, "e": 23624, "s": 23607, "text": "shikhasingrajput" }, { "code": null, "e": 23637, "s": 23624, "text": "simmytarika5" }, { "code": null, "e": 23653, "s": 23637, "text": "akshitsaxenaa09" }, { "code": null, "e": 23670, "s": 23653, "text": "bhupendrasingh01" }, { "code": null, "e": 23688, "s": 23670, "text": "aditya942003patil" }, { "code": null, "e": 23703, "s": 23688, "text": "sagartomar9927" }, { "code": null, "e": 23717, "s": 23703, "text": "jainlovely450" }, { "code": null, "e": 23723, "s": 23717, "text": "Paytm" }, { "code": null, "e": 23730, "s": 23723, "text": "Arrays" }, { "code": null, "e": 23736, "s": 23730, "text": "Paytm" }, { "code": null, "e": 23743, "s": 23736, "text": "Arrays" }, { "code": null, "e": 23841, "s": 23743, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 23909, "s": 23841, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 23953, "s": 23909, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 23985, "s": 23953, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 24033, "s": 23985, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 24047, "s": 24033, "text": "Linear Search" }, { "code": null, "e": 24070, "s": 24047, "text": "Introduction to Arrays" }, { "code": null, "e": 24155, "s": 24070, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 24182, "s": 24155, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 24214, "s": 24182, "text": "Introduction to Data Structures" } ]
Print all combinations of factors (Ways to factorize)
23 Jun, 2022 Write a program to print all the combinations of factors of given number n. Examples: Input : 16 Output :2 2 2 2 2 2 4 2 8 4 4 Input : 12 Output : 2 2 3 2 6 3 4 To solve this problem we take one array of array of integers or list of list of integers to store all the factors combination possible for the given n. So, to achieve this we can have one recursive function which can store the factors combination in each of its iteration. And each of those list should be stored in the final result list. Below is the implementation of the above approach. 2 2 2 2 2 2 4 2 8 4 4 The code below is pure recursive code for printing all combinations of factors: It uses a vector of integer to store a single list of factors and a vector of integer to store all combinations of factors. Instead of using an iterative loop, it uses the same recursive function to calculate all factor combinations. C++ Java Python3 C# Javascript // C++ program to print all factors combination#include <bits/stdc++.h>using namespace std; // vector of vector for storing// list of factor combinationsvector<vector<int> > factors_combination; // recursive functionvoid compute_factors(int current_no, int n, int product, vector<int> single_list){ // base case: if the product // exceeds our given number; // OR // current_no exceeds half the given n if (current_no > (n / 2) || product > n) return; // if current list of factors // is contributing to n if (product == n) { // storing the list factors_combination.push_back(single_list); // into factors_combination return; } // including current_no in our list single_list.push_back(current_no); // trying to get required // n with including current // current_no compute_factors(current_no, n, product * current_no, single_list); // excluding current_no from our list single_list.pop_back(); // trying to get required n // without including current // current_no compute_factors(current_no + 1, n, product, single_list);} // Driver Codeint main(){ int n = 16; // vector to store single list of factors // eg. 2,2,2,2 is one of the list for n=16 vector<int> single_list; // compute_factors ( starting_no, given_n, // our_current_product, vector ) compute_factors(2, n, 1, single_list); // printing all possible factors stored in // factors_combination for (int i = 0; i < factors_combination.size(); i++) { for (int j = 0; j < factors_combination[i].size(); j++) cout << factors_combination[i][j] << " "; cout << endl; } return 0;} // code contributed by Devendra Kolhe // Java program to print all factors combinationimport java.util.*; class GFG{ // vector of vector for storing// list of factor combinationsstatic Vector<Vector<Integer>> factors_combination = new Vector<Vector<Integer>>(); // Recursive functionstatic void compute_factors(int current_no, int n, int product, Vector<Integer> single_list){ // base case: if the product // exceeds our given number; // OR // current_no exceeds half the given n if (current_no > (n / 2) || product > n) return; // If current list of factors // is contributing to n if (product == n) { // Storing the list factors_combination.add(single_list); // Printing all possible factors stored in // factors_combination for(int i = 0; i < factors_combination.size(); i++) { for(int j = 0; j < factors_combination.get(i).size(); j++) System.out.print(factors_combination.get(i).get(j) + " "); } System.out.println(); factors_combination = new Vector<Vector<Integer>>(); // Into factors_combination return; } // Including current_no in our list single_list.add(current_no); // Trying to get required // n with including current // current_no compute_factors(current_no, n, product * current_no, single_list); // Excluding current_no from our list single_list.remove(single_list.size() - 1); // Trying to get required n // without including current // current_no compute_factors(current_no + 1, n, product, single_list);} // Driver codepublic static void main(String[] args){ int n = 16; // Vector to store single list of factors // eg. 2,2,2,2 is one of the list for n=16 Vector<Integer> single_list = new Vector<Integer>(); // compute_factors ( starting_no, given_n, // our_current_product, vector ) compute_factors(2, n, 1, single_list);}} // This code is contributed by decode2207 # Python3 program to print all factors combination # vector of vector for storing# list of factor combinationsfactors_combination = [] # recursive functiondef compute_factors(current_no, n, product, single_list): global factors_combination # base case: if the product # exceeds our given number; # OR # current_no exceeds half the given n if ((current_no > int(n / 2)) or (product > n)): return # if current list of factors # is contributing to n if (product == n): # storing the list factors_combination.append(single_list) # printing all possible factors stored in # factors_combination for i in range(len(factors_combination)): for j in range(len(factors_combination[i])): print(factors_combination[i][j], end=" ") print() factors_combination = [] # into factors_combination return # including current_no in our list single_list.append(current_no) # trying to get required # n with including current # current_no compute_factors(current_no, n, product * current_no, single_list) # excluding current_no from our list single_list.pop() # trying to get required n # without including current # current_no compute_factors(current_no + 1, n, product, single_list) n = 16 # vector to store single list of factors# eg. 2,2,2,2 is one of the list for n=16single_list = [] # compute_factors ( starting_no, given_n,# our_current_product, vector )compute_factors(2, n, 1, single_list) # This code is contributed by ukasp. // C# program to print all factors combinationusing System;using System.Collections.Generic;class GFG { // vector of vector for storing // list of factor combinations static List<List<int>> factors_combination = new List<List<int>>(); // recursive function static void compute_factors(int current_no, int n, int product, List<int> single_list) { // base case: if the product // exceeds our given number; // OR // current_no exceeds half the given n if (current_no > (n / 2) || product > n) return; // if current list of factors // is contributing to n if (product == n) { // storing the list factors_combination.Add(single_list); // printing all possible factors stored in // factors_combination for(int i = 0; i < factors_combination.Count; i++) { for(int j = 0; j < factors_combination[i].Count; j++) Console.Write(factors_combination[i][j] + " "); } Console.WriteLine(); factors_combination = new List<List<int>>(); // into factors_combination return; } // including current_no in our list single_list.Add(current_no); // trying to get required // n with including current // current_no compute_factors(current_no, n, product * current_no, single_list); // excluding current_no from our list single_list.RemoveAt(single_list.Count - 1); // trying to get required n // without including current // current_no compute_factors(current_no + 1, n, product, single_list); } static void Main() { int n = 16; // vector to store single list of factors // eg. 2,2,2,2 is one of the list for n=16 List<int> single_list = new List<int>(); // compute_factors ( starting_no, given_n, // our_current_product, vector ) compute_factors(2, n, 1, single_list); }} // This code is contributed by divyesh072019. <script> // Javascript program to print all factors combination // vector of vector for storing // list of factor combinations let factors_combination = []; // recursive function function compute_factors(current_no, n, product, single_list) { // base case: if the product // exceeds our given number; // OR // current_no exceeds half the given n if ((current_no > parseInt(n / 2, 10)) || (product > n)) return; // if current list of factors // is contributing to n if (product == n) { // storing the list factors_combination.push(single_list); // printing all possible factors stored in // factors_combination for(let i = 0; i < factors_combination.length; i++) { for(let j = 0; j < factors_combination[i].length; j++) { document.write(factors_combination[i][j] + " "); } } document.write("</br>"); factors_combination = []; // into factors_combination return; } // including current_no in our list single_list.push(current_no); // trying to get required // n with including current // current_no compute_factors(current_no, n, product * current_no, single_list); // excluding current_no from our list single_list.pop(); // trying to get required n // without including current // current_no compute_factors(current_no + 1, n, product, single_list); } let n = 16; // vector to store single list of factors // eg. 2,2,2,2 is one of the list for n=16 let single_list = []; // compute_factors ( starting_no, given_n, // our_current_product, vector ) compute_factors(2, n, 1, single_list); // This code is contributed by suresh07.</script> 2 2 2 2 2 2 4 2 8 4 4 Time Complexity: O(n2) , n is the size of vectorAuxiliary Space: O(n2), n is the size of vector Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above princiraj1992 Atul_kumar_Shrivastava devendrakolhe5 divyeshrabadiya07 divyesh072019 rameshtravel07 decode2207 suresh07 simmytarika5 codewithmini prime-factor Mathematical Recursion Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 128, "s": 52, "text": "Write a program to print all the combinations of factors of given number n." }, { "code": null, "e": 139, "s": 128, "text": "Examples: " }, { "code": null, "e": 261, "s": 139, "text": "Input : 16\nOutput :2 2 2 2 \n 2 2 4 \n 2 8 \n 4 4 \n\nInput : 12\nOutput : 2 2 3\n 2 6\n 3 4" }, { "code": null, "e": 600, "s": 261, "text": "To solve this problem we take one array of array of integers or list of list of integers to store all the factors combination possible for the given n. So, to achieve this we can have one recursive function which can store the factors combination in each of its iteration. And each of those list should be stored in the final result list." }, { "code": null, "e": 651, "s": 600, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 677, "s": 651, "text": "2 2 2 2 \n2 2 4 \n2 8 \n4 4 " }, { "code": null, "e": 757, "s": 677, "text": "The code below is pure recursive code for printing all combinations of factors:" }, { "code": null, "e": 991, "s": 757, "text": "It uses a vector of integer to store a single list of factors and a vector of integer to store all combinations of factors. Instead of using an iterative loop, it uses the same recursive function to calculate all factor combinations." }, { "code": null, "e": 995, "s": 991, "text": "C++" }, { "code": null, "e": 1000, "s": 995, "text": "Java" }, { "code": null, "e": 1008, "s": 1000, "text": "Python3" }, { "code": null, "e": 1011, "s": 1008, "text": "C#" }, { "code": null, "e": 1022, "s": 1011, "text": "Javascript" }, { "code": "// C++ program to print all factors combination#include <bits/stdc++.h>using namespace std; // vector of vector for storing// list of factor combinationsvector<vector<int> > factors_combination; // recursive functionvoid compute_factors(int current_no, int n, int product, vector<int> single_list){ // base case: if the product // exceeds our given number; // OR // current_no exceeds half the given n if (current_no > (n / 2) || product > n) return; // if current list of factors // is contributing to n if (product == n) { // storing the list factors_combination.push_back(single_list); // into factors_combination return; } // including current_no in our list single_list.push_back(current_no); // trying to get required // n with including current // current_no compute_factors(current_no, n, product * current_no, single_list); // excluding current_no from our list single_list.pop_back(); // trying to get required n // without including current // current_no compute_factors(current_no + 1, n, product, single_list);} // Driver Codeint main(){ int n = 16; // vector to store single list of factors // eg. 2,2,2,2 is one of the list for n=16 vector<int> single_list; // compute_factors ( starting_no, given_n, // our_current_product, vector ) compute_factors(2, n, 1, single_list); // printing all possible factors stored in // factors_combination for (int i = 0; i < factors_combination.size(); i++) { for (int j = 0; j < factors_combination[i].size(); j++) cout << factors_combination[i][j] << \" \"; cout << endl; } return 0;} // code contributed by Devendra Kolhe", "e": 2850, "s": 1022, "text": null }, { "code": "// Java program to print all factors combinationimport java.util.*; class GFG{ // vector of vector for storing// list of factor combinationsstatic Vector<Vector<Integer>> factors_combination = new Vector<Vector<Integer>>(); // Recursive functionstatic void compute_factors(int current_no, int n, int product, Vector<Integer> single_list){ // base case: if the product // exceeds our given number; // OR // current_no exceeds half the given n if (current_no > (n / 2) || product > n) return; // If current list of factors // is contributing to n if (product == n) { // Storing the list factors_combination.add(single_list); // Printing all possible factors stored in // factors_combination for(int i = 0; i < factors_combination.size(); i++) { for(int j = 0; j < factors_combination.get(i).size(); j++) System.out.print(factors_combination.get(i).get(j) + \" \"); } System.out.println(); factors_combination = new Vector<Vector<Integer>>(); // Into factors_combination return; } // Including current_no in our list single_list.add(current_no); // Trying to get required // n with including current // current_no compute_factors(current_no, n, product * current_no, single_list); // Excluding current_no from our list single_list.remove(single_list.size() - 1); // Trying to get required n // without including current // current_no compute_factors(current_no + 1, n, product, single_list);} // Driver codepublic static void main(String[] args){ int n = 16; // Vector to store single list of factors // eg. 2,2,2,2 is one of the list for n=16 Vector<Integer> single_list = new Vector<Integer>(); // compute_factors ( starting_no, given_n, // our_current_product, vector ) compute_factors(2, n, 1, single_list);}} // This code is contributed by decode2207", "e": 4942, "s": 2850, "text": null }, { "code": "# Python3 program to print all factors combination # vector of vector for storing# list of factor combinationsfactors_combination = [] # recursive functiondef compute_factors(current_no, n, product, single_list): global factors_combination # base case: if the product # exceeds our given number; # OR # current_no exceeds half the given n if ((current_no > int(n / 2)) or (product > n)): return # if current list of factors # is contributing to n if (product == n): # storing the list factors_combination.append(single_list) # printing all possible factors stored in # factors_combination for i in range(len(factors_combination)): for j in range(len(factors_combination[i])): print(factors_combination[i][j], end=\" \") print() factors_combination = [] # into factors_combination return # including current_no in our list single_list.append(current_no) # trying to get required # n with including current # current_no compute_factors(current_no, n, product * current_no, single_list) # excluding current_no from our list single_list.pop() # trying to get required n # without including current # current_no compute_factors(current_no + 1, n, product, single_list) n = 16 # vector to store single list of factors# eg. 2,2,2,2 is one of the list for n=16single_list = [] # compute_factors ( starting_no, given_n,# our_current_product, vector )compute_factors(2, n, 1, single_list) # This code is contributed by ukasp.", "e": 6539, "s": 4942, "text": null }, { "code": "// C# program to print all factors combinationusing System;using System.Collections.Generic;class GFG { // vector of vector for storing // list of factor combinations static List<List<int>> factors_combination = new List<List<int>>(); // recursive function static void compute_factors(int current_no, int n, int product, List<int> single_list) { // base case: if the product // exceeds our given number; // OR // current_no exceeds half the given n if (current_no > (n / 2) || product > n) return; // if current list of factors // is contributing to n if (product == n) { // storing the list factors_combination.Add(single_list); // printing all possible factors stored in // factors_combination for(int i = 0; i < factors_combination.Count; i++) { for(int j = 0; j < factors_combination[i].Count; j++) Console.Write(factors_combination[i][j] + \" \"); } Console.WriteLine(); factors_combination = new List<List<int>>(); // into factors_combination return; } // including current_no in our list single_list.Add(current_no); // trying to get required // n with including current // current_no compute_factors(current_no, n, product * current_no, single_list); // excluding current_no from our list single_list.RemoveAt(single_list.Count - 1); // trying to get required n // without including current // current_no compute_factors(current_no + 1, n, product, single_list); } static void Main() { int n = 16; // vector to store single list of factors // eg. 2,2,2,2 is one of the list for n=16 List<int> single_list = new List<int>(); // compute_factors ( starting_no, given_n, // our_current_product, vector ) compute_factors(2, n, 1, single_list); }} // This code is contributed by divyesh072019.", "e": 8654, "s": 6539, "text": null }, { "code": "<script> // Javascript program to print all factors combination // vector of vector for storing // list of factor combinations let factors_combination = []; // recursive function function compute_factors(current_no, n, product, single_list) { // base case: if the product // exceeds our given number; // OR // current_no exceeds half the given n if ((current_no > parseInt(n / 2, 10)) || (product > n)) return; // if current list of factors // is contributing to n if (product == n) { // storing the list factors_combination.push(single_list); // printing all possible factors stored in // factors_combination for(let i = 0; i < factors_combination.length; i++) { for(let j = 0; j < factors_combination[i].length; j++) { document.write(factors_combination[i][j] + \" \"); } } document.write(\"</br>\"); factors_combination = []; // into factors_combination return; } // including current_no in our list single_list.push(current_no); // trying to get required // n with including current // current_no compute_factors(current_no, n, product * current_no, single_list); // excluding current_no from our list single_list.pop(); // trying to get required n // without including current // current_no compute_factors(current_no + 1, n, product, single_list); } let n = 16; // vector to store single list of factors // eg. 2,2,2,2 is one of the list for n=16 let single_list = []; // compute_factors ( starting_no, given_n, // our_current_product, vector ) compute_factors(2, n, 1, single_list); // This code is contributed by suresh07.</script>", "e": 10609, "s": 8654, "text": null }, { "code": null, "e": 10635, "s": 10609, "text": "2 2 2 2 \n2 2 4 \n2 8 \n4 4 " }, { "code": null, "e": 10731, "s": 10635, "text": "Time Complexity: O(n2) , n is the size of vectorAuxiliary Space: O(n2), n is the size of vector" }, { "code": null, "e": 10998, "s": 10731, "text": "Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 11012, "s": 10998, "text": "princiraj1992" }, { "code": null, "e": 11035, "s": 11012, "text": "Atul_kumar_Shrivastava" }, { "code": null, "e": 11050, "s": 11035, "text": "devendrakolhe5" }, { "code": null, "e": 11068, "s": 11050, "text": "divyeshrabadiya07" }, { "code": null, "e": 11082, "s": 11068, "text": "divyesh072019" }, { "code": null, "e": 11097, "s": 11082, "text": "rameshtravel07" }, { "code": null, "e": 11108, "s": 11097, "text": "decode2207" }, { "code": null, "e": 11117, "s": 11108, "text": "suresh07" }, { "code": null, "e": 11130, "s": 11117, "text": "simmytarika5" }, { "code": null, "e": 11143, "s": 11130, "text": "codewithmini" }, { "code": null, "e": 11156, "s": 11143, "text": "prime-factor" }, { "code": null, "e": 11169, "s": 11156, "text": "Mathematical" }, { "code": null, "e": 11179, "s": 11169, "text": "Recursion" }, { "code": null, "e": 11192, "s": 11179, "text": "Mathematical" }, { "code": null, "e": 11202, "s": 11192, "text": "Recursion" } ]
Simple DELETE request using fetch API by making custom HTTP library
17 Feb, 2021 Why fetch() API method is used? The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object. We will be taking a fake API which will contain Array as an example and from that API we will show to DELETE data by fetch API method by making custom HTTP library. The API used in this tutorial is: https://jsonplaceholder.typicode.com/users/2 Prerequisites: You should have a basic awareness of HTML, CSS, and JavaScript. Explanation: First we need to create index.html file and paste the below code of index.html file into that. The index.html file includes library.js and app.js files at the bottom of the body tag. Now in library.js file, first create an ES6 class DeleteHTTP and within that class, there is async fetch() function which DELETES the data from the api. There are two stages of await. First for fetch() and then for its response. Whatever response we receive, we return it to the calling function in app.js file.Now in app.js file, first instantiate DeleteHTTP class. Then by http.delete prototype function send URL to the library.js file. Further, in this, there are two promises to be resolved. The first is for any response data and the second is for any error. index.html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>DELETE Request</title></head> <body> <h1> Simple DELETE request using fetch API by making custom HTTP library </h1> <!-- Including library.js and app.js --> <script src="library.js"></script> <script src="app.js"></script></body> </html> library.js // ES6 classclass DeleteHTTP { // Make an HTTP PUT Request async delete(url) { // Awaiting fetch which contains // method, headers and content-type const response = await fetch(url, { method: 'DELETE', headers: { 'Content-type': 'application/json' } }); // Awaiting for the resource to be deleted const resData = 'resource deleted...'; // Return response data return resData; }} Filename: app.js app.js // Instantiating new EasyHTTP classconst http = new DeleteHTTP; // Update Posthttp.delete('https://jsonplaceholder.typicode.com/users/2') // Resolving promise for response data.then(data => console.log(data)) // Resolving promise for error.catch(err => console.log(err)); Output: Open index.html file in the browser then right click-> inspect element->console. The following output you will see for DELETE request: SarveshHiwase JavaScript-Questions JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Feb, 2021" }, { "code": null, "e": 446, "s": 28, "text": "Why fetch() API method is used? The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object. We will be taking a fake API which will contain Array as an example and from that API we will show to DELETE data by fetch API method by making custom HTTP library. The API used in this tutorial is: https://jsonplaceholder.typicode.com/users/2" }, { "code": null, "e": 525, "s": 446, "text": "Prerequisites: You should have a basic awareness of HTML, CSS, and JavaScript." }, { "code": null, "e": 662, "s": 525, "text": "Explanation: First we need to create index.html file and paste the below code of index.html file into that. The index.html file includes" }, { "code": null, "e": 1286, "s": 662, "text": " library.js and app.js files at the bottom of the body tag. Now in library.js file, first create an ES6 class DeleteHTTP and within that class, there is async fetch() function which DELETES the data from the api. There are two stages of await. First for fetch() and then for its response. Whatever response we receive, we return it to the calling function in app.js file.Now in app.js file, first instantiate DeleteHTTP class. Then by http.delete prototype function send URL to the library.js file. Further, in this, there are two promises to be resolved. The first is for any response data and the second is for any error." }, { "code": null, "e": 1297, "s": 1286, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>DELETE Request</title></head> <body> <h1> Simple DELETE request using fetch API by making custom HTTP library </h1> <!-- Including library.js and app.js --> <script src=\"library.js\"></script> <script src=\"app.js\"></script></body> </html>", "e": 1792, "s": 1297, "text": null }, { "code": null, "e": 1803, "s": 1792, "text": "library.js" }, { "code": "// ES6 classclass DeleteHTTP { // Make an HTTP PUT Request async delete(url) { // Awaiting fetch which contains // method, headers and content-type const response = await fetch(url, { method: 'DELETE', headers: { 'Content-type': 'application/json' } }); // Awaiting for the resource to be deleted const resData = 'resource deleted...'; // Return response data return resData; }}", "e": 2305, "s": 1803, "text": null }, { "code": null, "e": 2324, "s": 2305, "text": "Filename: app.js " }, { "code": null, "e": 2331, "s": 2324, "text": "app.js" }, { "code": "// Instantiating new EasyHTTP classconst http = new DeleteHTTP; // Update Posthttp.delete('https://jsonplaceholder.typicode.com/users/2') // Resolving promise for response data.then(data => console.log(data)) // Resolving promise for error.catch(err => console.log(err));", "e": 2606, "s": 2331, "text": null }, { "code": null, "e": 2749, "s": 2606, "text": "Output: Open index.html file in the browser then right click-> inspect element->console. The following output you will see for DELETE request:" }, { "code": null, "e": 2763, "s": 2749, "text": "SarveshHiwase" }, { "code": null, "e": 2784, "s": 2763, "text": "JavaScript-Questions" }, { "code": null, "e": 2795, "s": 2784, "text": "JavaScript" }, { "code": null, "e": 2812, "s": 2795, "text": "Web Technologies" }, { "code": null, "e": 2839, "s": 2812, "text": "Web technologies Questions" }, { "code": null, "e": 2937, "s": 2839, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2998, "s": 2937, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3070, "s": 2998, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3110, "s": 3070, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3151, "s": 3110, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3193, "s": 3151, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3226, "s": 3193, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3288, "s": 3226, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3349, "s": 3288, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3399, "s": 3349, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Numpy.expand_dims() method
17 Sep, 2019 With the help of Numpy.expand_dims() method, we can get the expanded dimensions of an array by using Numpy.expand_dims() method. Syntax : Numpy.expand_dims() Return : Return the expanded array. Example #1 :In this example we can see that using Numpy.expand_dims() method, we are able to get the expanded array using this method. # import numpyimport numpy as np # using Numpy.expand_dims() methodgfg = np.array([1, 2])print(gfg.shape) gfg = np.expand_dims(gfg, axis = 0)print(gfg.shape) Output : (2, )(1, 2) Example #2 : # import numpyimport numpy as np # using Numpy.expand_dims() methodgfg = np.array([[1, 2], [7, 8]])print(gfg.shape) gfg = np.expand_dims(gfg, axis = 0)print(gfg.shape) Output : (2, 2)(1, 2, 2) Python numpy-Basics 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 Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Sep, 2019" }, { "code": null, "e": 157, "s": 28, "text": "With the help of Numpy.expand_dims() method, we can get the expanded dimensions of an array by using Numpy.expand_dims() method." }, { "code": null, "e": 186, "s": 157, "text": "Syntax : Numpy.expand_dims()" }, { "code": null, "e": 222, "s": 186, "text": "Return : Return the expanded array." }, { "code": null, "e": 357, "s": 222, "text": "Example #1 :In this example we can see that using Numpy.expand_dims() method, we are able to get the expanded array using this method." }, { "code": "# import numpyimport numpy as np # using Numpy.expand_dims() methodgfg = np.array([1, 2])print(gfg.shape) gfg = np.expand_dims(gfg, axis = 0)print(gfg.shape)", "e": 517, "s": 357, "text": null }, { "code": null, "e": 526, "s": 517, "text": "Output :" }, { "code": null, "e": 538, "s": 526, "text": "(2, )(1, 2)" }, { "code": null, "e": 551, "s": 538, "text": "Example #2 :" }, { "code": "# import numpyimport numpy as np # using Numpy.expand_dims() methodgfg = np.array([[1, 2], [7, 8]])print(gfg.shape) gfg = np.expand_dims(gfg, axis = 0)print(gfg.shape)", "e": 721, "s": 551, "text": null }, { "code": null, "e": 730, "s": 721, "text": "Output :" }, { "code": null, "e": 746, "s": 730, "text": "(2, 2)(1, 2, 2)" }, { "code": null, "e": 766, "s": 746, "text": "Python numpy-Basics" }, { "code": null, "e": 773, "s": 766, "text": "Python" }, { "code": null, "e": 871, "s": 773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 903, "s": 871, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 930, "s": 903, "text": "Python Classes and Objects" }, { "code": null, "e": 951, "s": 930, "text": "Python OOPs Concepts" }, { "code": null, "e": 974, "s": 951, "text": "Introduction To PYTHON" }, { "code": null, "e": 1030, "s": 974, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1061, "s": 1030, "text": "Python | os.path.join() method" }, { "code": null, "e": 1103, "s": 1061, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1145, "s": 1103, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1184, "s": 1145, "text": "Python | Get unique values from a list" } ]
Difference between Register Mode and Register Indirect Mode
04 Jul, 2022 Prerequisite – Addressing Modes 1. Register Mode: In register addressing mode, the operand is placed in one of the 8-bit or 16-bit general-purpose registers. The data is in the register that is specified by the instruction. Example: MOV R1, R2 Instruction has register R2 and R2 has operand. 2. Register Indirect ode: In register indirect addressing mode, the address of the operand is placed in any one of the registers. The instruction specifies a register that contains the address of the operand. Example: ADD R1, (R2) Instruction has register R2 and R2 has the memory address of operand. Difference between Register Mode and Register Indirect Mode are as follows:time-consumingregisteredregistered annieahujaweb2020 Computer Organization & Architecture Difference Between GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Direct Access Media (DMA) Controller in Computer Architecture Control Characters Architecture of 8085 microprocessor Pin diagram of 8086 microprocessor I2C Communication Protocol Class method vs Static method in Python Difference between BFS and DFS Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jul, 2022" }, { "code": null, "e": 87, "s": 54, "text": "Prerequisite – Addressing Modes " }, { "code": null, "e": 279, "s": 87, "text": "1. Register Mode: In register addressing mode, the operand is placed in one of the 8-bit or 16-bit general-purpose registers. The data is in the register that is specified by the instruction." }, { "code": null, "e": 288, "s": 279, "text": "Example:" }, { "code": null, "e": 300, "s": 288, "text": "MOV R1, R2 " }, { "code": null, "e": 349, "s": 300, "text": "Instruction has register R2 and R2 has operand. " }, { "code": null, "e": 559, "s": 349, "text": "2. Register Indirect ode: In register indirect addressing mode, the address of the operand is placed in any one of the registers. The instruction specifies a register that contains the address of the operand. " }, { "code": null, "e": 568, "s": 559, "text": "Example:" }, { "code": null, "e": 582, "s": 568, "text": "ADD R1, (R2) " }, { "code": null, "e": 653, "s": 582, "text": "Instruction has register R2 and R2 has the memory address of operand. " }, { "code": null, "e": 763, "s": 653, "text": "Difference between Register Mode and Register Indirect Mode are as follows:time-consumingregisteredregistered" }, { "code": null, "e": 781, "s": 763, "text": "annieahujaweb2020" }, { "code": null, "e": 818, "s": 781, "text": "Computer Organization & Architecture" }, { "code": null, "e": 837, "s": 818, "text": "Difference Between" }, { "code": null, "e": 845, "s": 837, "text": "GATE CS" }, { "code": null, "e": 943, "s": 845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1005, "s": 943, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 1024, "s": 1005, "text": "Control Characters" }, { "code": null, "e": 1060, "s": 1024, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 1095, "s": 1060, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 1122, "s": 1095, "text": "I2C Communication Protocol" }, { "code": null, "e": 1162, "s": 1122, "text": "Class method vs Static method in Python" }, { "code": null, "e": 1193, "s": 1162, "text": "Difference between BFS and DFS" }, { "code": null, "e": 1254, "s": 1193, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1322, "s": 1254, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
How to create a Facebook login using an Android App?
23 Feb, 2021 In this article, it is explained how to create an Android App that has a Facebook login in it. There are various social login features to use in Android applications. Here we will learn social login using Facebook, so need to integrate Facebook SDK in project to make use of Facebook login. Below are the various steps on how to do it; First thing you need to do is to have Facebook Developer Account and then create a new app.Install Android Studio(>= 3.0) and then open/create a project where you want to add Facebook login.In your project, add the following code in your Gradle Scripts -> build.gradle (Project).buildscript{ repositories { jcenter() }}Now, add the following code in Gradle Scripts -> build.gradle (Module:app) with the latest version of Facebook Login SDK in your project.dependencies { implementation 'com.facebook.android:facebook-android-sdk:5.0.0'}Sync your projectNow open app -> res -> values -> strings.xml file to add the following lines and replace the [APP_ID] with your APP_ID, which you can get from Facebook Developer console.<string name="facebook_app_id">[APP_ID]</string><string name="fb_login_protocol_scheme">fb[APP_ID]</string>Open app -> manifest -> AndroidManifest.xml file and add this line outside of application element.<uses-permission android:name="android.permission.INTERNET"/>Add this meta-data element inside your application element in AndroidManifest.xml file:<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/><activity android:name="com.facebook.FacebookActivity" android:configChanges="keyboard|keyboardHidden |screenLayout|screenSize |orientation" android:label="@string/app_name" />Now first thing you require is Key Hash, so add these lines in your activity class before Facebook login code:@Overrideprotected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ... printHashKey(); ...} ... public void printHashKey(){ // Add code to print out the key hash try { PackageInfo info = getPackageManager().getPackageInfo( "com.android.facebookloginsample", PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d("KeyHash:", Base64.encodeToString( md.digest(), Base64.DEFAULT)); } } catch (PackageManager.NameNotFoundException e) { } catch (NoSuchAlgorithmException e) { }}Now run your application in your emulator or on your connected device. You will see Key Hash value printed in logcat, save this for later requirement.Go to Facebook Developers console and choose setting -> Basic -> Add Platform (in bottom of page) and a popup will opens up to select a platform. Choose Android as a platform.Add your project package name under ‘Google Play Package Name’. Add class name where login will implement in project like ‘LoginActivity’ and also add the key hash value under ‘Key Hashes’.Now back to android studio, add this custom button in your *.xml layout file:<Button android:id="@+id/button_facebook" style="@style/FacebookLoginButton" android:layout_width="match_parent" android:layout_height="45dp" android:layout_gravity="center_horizontal" android:layout_marginTop="15dp" android:text="Continue With Facebook" android:textAllCaps="false" android:textColor="@android:color/white" />Add this code in app -> res -> styles.xml file:<style name="FacebookLoginButton"> <item name="android:textSize">14sp</item> <item name="android:background">@drawable/facebook_signin_btn</item> <item name="android:paddingTop">11dp</item> <item name="android:paddingBottom">11dp</item> <item name="android:paddingLeft">15dp</item> <item name="android:layout_marginLeft">3dp</item> <item name="android:layout_marginRight">3dp</item> <item name="android:layout_height">wrap_content</item> <item name="android:layout_gravity">center_horizontal</item></style>You can customize this button accordingly or instead of an above custom button, you can use the Facebook default button also as Facebook LoginButton.Make drawable file named ‘bg_button_facebook.xml’ in app -> res -> drawable folder and paste below code:<?xml version="1.0" encoding="utf-8"?><shapexmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle"> <corners android:radius="5dp"/> <solid android:color="#3B5998"/></shape>Now initialize button in *.java file and some code to initialize Facebook SDK also:// Declare variablesprivate Button mButtonFacebook; private CallbackManager callbackManager;private LoginManager loginManager; ... @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ... mButtonFacebook = findViewById(R.id.button_facebook); FacebookSdk.sdkInitialize(MainActivity.this); callbackManager = CallbackManager.Factory.create(); facebookLogin(); ... mButtonFacebook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginManager.logInWithReadPermissions( MainActivity.this, Arrays.asList( "email", "public_profile", "user_birthday")); } }); ...} ...Add ‘facebookLogin’ method outside onCreate() in java file. This is the code for Facebook login response.public void facebookLogin(){ loginManager = LoginManager.getInstance(); callbackManager = CallbackManager.Factory.create(); loginManager .registerCallback( callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { if (object != null) { try { String name = object.getString("name"); String email = object.getString("email"); String fbUserID = object.getString("id"); disconnectFromFacebook(); // do action after Facebook login success // or call your API } catch (JSONException | NullPointerException e) { e.printStackTrace(); } } } }); Bundle parameters = new Bundle(); parameters.putString( "fields", "id, name, email, gender, birthday"); request.setParameters(parameters); request.executeAsync(); } @Override public void onCancel() { Log.v("LoginScreen", "---onCancel"); } @Override public void onError(FacebookException error) { // here write code when get error Log.v("LoginScreen", "----onError: " + error.getMessage()); } });}Now add another required method ‘disconnectFromFacebook’ for login integration, similarly add this to outside onCreate. This is used to disconnect application from Facebook as no need to stay connected.public void disconnectFromFacebook(){ if (AccessToken.getCurrentAccessToken() == null) { return; // already logged out } new GraphRequest( AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest .Callback() { @Override public void onCompleted(GraphResponse graphResponse) { LoginManager.getInstance().logOut(); } }) .executeAsync();}Add ‘onActivityResult’ method outside onCreate in same activity:@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data){ // add this line callbackManager.onActivityResult( requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);}Now you are done with the coding. Run your application in you device or emulator. You can now login with Facebook also in your application.If you want to upload your app on play store, then you have to enable ‘status’ from top right section on Facebook for Developers, for this first add privacy policy url in settings -> Basic as per given in below screenshot. Now save the changes and enable status from dashboard. First thing you need to do is to have Facebook Developer Account and then create a new app. Install Android Studio(>= 3.0) and then open/create a project where you want to add Facebook login. In your project, add the following code in your Gradle Scripts -> build.gradle (Project).buildscript{ repositories { jcenter() }} buildscript{ repositories { jcenter() }} Now, add the following code in Gradle Scripts -> build.gradle (Module:app) with the latest version of Facebook Login SDK in your project.dependencies { implementation 'com.facebook.android:facebook-android-sdk:5.0.0'} dependencies { implementation 'com.facebook.android:facebook-android-sdk:5.0.0'} Sync your project Now open app -> res -> values -> strings.xml file to add the following lines and replace the [APP_ID] with your APP_ID, which you can get from Facebook Developer console.<string name="facebook_app_id">[APP_ID]</string><string name="fb_login_protocol_scheme">fb[APP_ID]</string> <string name="facebook_app_id">[APP_ID]</string><string name="fb_login_protocol_scheme">fb[APP_ID]</string> Open app -> manifest -> AndroidManifest.xml file and add this line outside of application element.<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.INTERNET"/> Add this meta-data element inside your application element in AndroidManifest.xml file:<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/><activity android:name="com.facebook.FacebookActivity" android:configChanges="keyboard|keyboardHidden |screenLayout|screenSize |orientation" android:label="@string/app_name" /> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/><activity android:name="com.facebook.FacebookActivity" android:configChanges="keyboard|keyboardHidden |screenLayout|screenSize |orientation" android:label="@string/app_name" /> Now first thing you require is Key Hash, so add these lines in your activity class before Facebook login code:@Overrideprotected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ... printHashKey(); ...} ... public void printHashKey(){ // Add code to print out the key hash try { PackageInfo info = getPackageManager().getPackageInfo( "com.android.facebookloginsample", PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d("KeyHash:", Base64.encodeToString( md.digest(), Base64.DEFAULT)); } } catch (PackageManager.NameNotFoundException e) { } catch (NoSuchAlgorithmException e) { }} @Overrideprotected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ... printHashKey(); ...} ... public void printHashKey(){ // Add code to print out the key hash try { PackageInfo info = getPackageManager().getPackageInfo( "com.android.facebookloginsample", PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d("KeyHash:", Base64.encodeToString( md.digest(), Base64.DEFAULT)); } } catch (PackageManager.NameNotFoundException e) { } catch (NoSuchAlgorithmException e) { }} Now run your application in your emulator or on your connected device. You will see Key Hash value printed in logcat, save this for later requirement. Go to Facebook Developers console and choose setting -> Basic -> Add Platform (in bottom of page) and a popup will opens up to select a platform. Choose Android as a platform. Add your project package name under ‘Google Play Package Name’. Add class name where login will implement in project like ‘LoginActivity’ and also add the key hash value under ‘Key Hashes’. Now back to android studio, add this custom button in your *.xml layout file:<Button android:id="@+id/button_facebook" style="@style/FacebookLoginButton" android:layout_width="match_parent" android:layout_height="45dp" android:layout_gravity="center_horizontal" android:layout_marginTop="15dp" android:text="Continue With Facebook" android:textAllCaps="false" android:textColor="@android:color/white" /> <Button android:id="@+id/button_facebook" style="@style/FacebookLoginButton" android:layout_width="match_parent" android:layout_height="45dp" android:layout_gravity="center_horizontal" android:layout_marginTop="15dp" android:text="Continue With Facebook" android:textAllCaps="false" android:textColor="@android:color/white" /> Add this code in app -> res -> styles.xml file:<style name="FacebookLoginButton"> <item name="android:textSize">14sp</item> <item name="android:background">@drawable/facebook_signin_btn</item> <item name="android:paddingTop">11dp</item> <item name="android:paddingBottom">11dp</item> <item name="android:paddingLeft">15dp</item> <item name="android:layout_marginLeft">3dp</item> <item name="android:layout_marginRight">3dp</item> <item name="android:layout_height">wrap_content</item> <item name="android:layout_gravity">center_horizontal</item></style> <style name="FacebookLoginButton"> <item name="android:textSize">14sp</item> <item name="android:background">@drawable/facebook_signin_btn</item> <item name="android:paddingTop">11dp</item> <item name="android:paddingBottom">11dp</item> <item name="android:paddingLeft">15dp</item> <item name="android:layout_marginLeft">3dp</item> <item name="android:layout_marginRight">3dp</item> <item name="android:layout_height">wrap_content</item> <item name="android:layout_gravity">center_horizontal</item></style> You can customize this button accordingly or instead of an above custom button, you can use the Facebook default button also as Facebook LoginButton. Make drawable file named ‘bg_button_facebook.xml’ in app -> res -> drawable folder and paste below code:<?xml version="1.0" encoding="utf-8"?><shapexmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle"> <corners android:radius="5dp"/> <solid android:color="#3B5998"/></shape> <?xml version="1.0" encoding="utf-8"?><shapexmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle"> <corners android:radius="5dp"/> <solid android:color="#3B5998"/></shape> Now initialize button in *.java file and some code to initialize Facebook SDK also:// Declare variablesprivate Button mButtonFacebook; private CallbackManager callbackManager;private LoginManager loginManager; ... @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ... mButtonFacebook = findViewById(R.id.button_facebook); FacebookSdk.sdkInitialize(MainActivity.this); callbackManager = CallbackManager.Factory.create(); facebookLogin(); ... mButtonFacebook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginManager.logInWithReadPermissions( MainActivity.this, Arrays.asList( "email", "public_profile", "user_birthday")); } }); ...} ... // Declare variablesprivate Button mButtonFacebook; private CallbackManager callbackManager;private LoginManager loginManager; ... @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ... mButtonFacebook = findViewById(R.id.button_facebook); FacebookSdk.sdkInitialize(MainActivity.this); callbackManager = CallbackManager.Factory.create(); facebookLogin(); ... mButtonFacebook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginManager.logInWithReadPermissions( MainActivity.this, Arrays.asList( "email", "public_profile", "user_birthday")); } }); ...} ... Add ‘facebookLogin’ method outside onCreate() in java file. This is the code for Facebook login response.public void facebookLogin(){ loginManager = LoginManager.getInstance(); callbackManager = CallbackManager.Factory.create(); loginManager .registerCallback( callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { if (object != null) { try { String name = object.getString("name"); String email = object.getString("email"); String fbUserID = object.getString("id"); disconnectFromFacebook(); // do action after Facebook login success // or call your API } catch (JSONException | NullPointerException e) { e.printStackTrace(); } } } }); Bundle parameters = new Bundle(); parameters.putString( "fields", "id, name, email, gender, birthday"); request.setParameters(parameters); request.executeAsync(); } @Override public void onCancel() { Log.v("LoginScreen", "---onCancel"); } @Override public void onError(FacebookException error) { // here write code when get error Log.v("LoginScreen", "----onError: " + error.getMessage()); } });} public void facebookLogin(){ loginManager = LoginManager.getInstance(); callbackManager = CallbackManager.Factory.create(); loginManager .registerCallback( callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { if (object != null) { try { String name = object.getString("name"); String email = object.getString("email"); String fbUserID = object.getString("id"); disconnectFromFacebook(); // do action after Facebook login success // or call your API } catch (JSONException | NullPointerException e) { e.printStackTrace(); } } } }); Bundle parameters = new Bundle(); parameters.putString( "fields", "id, name, email, gender, birthday"); request.setParameters(parameters); request.executeAsync(); } @Override public void onCancel() { Log.v("LoginScreen", "---onCancel"); } @Override public void onError(FacebookException error) { // here write code when get error Log.v("LoginScreen", "----onError: " + error.getMessage()); } });} Now add another required method ‘disconnectFromFacebook’ for login integration, similarly add this to outside onCreate. This is used to disconnect application from Facebook as no need to stay connected.public void disconnectFromFacebook(){ if (AccessToken.getCurrentAccessToken() == null) { return; // already logged out } new GraphRequest( AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest .Callback() { @Override public void onCompleted(GraphResponse graphResponse) { LoginManager.getInstance().logOut(); } }) .executeAsync();} public void disconnectFromFacebook(){ if (AccessToken.getCurrentAccessToken() == null) { return; // already logged out } new GraphRequest( AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest .Callback() { @Override public void onCompleted(GraphResponse graphResponse) { LoginManager.getInstance().logOut(); } }) .executeAsync();} Add ‘onActivityResult’ method outside onCreate in same activity:@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data){ // add this line callbackManager.onActivityResult( requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);} @Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data){ // add this line callbackManager.onActivityResult( requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);} Now you are done with the coding. Run your application in you device or emulator. You can now login with Facebook also in your application. If you want to upload your app on play store, then you have to enable ‘status’ from top right section on Facebook for Developers, for this first add privacy policy url in settings -> Basic as per given in below screenshot. Now save the changes and enable status from dashboard. Android-Misc Picked Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference Between Implicit Intent and Explicit Intent in Android How to Create and Add Data to SQLite Database in Android? Retrofit with Kotlin Coroutine in Android Navigation Drawer in Android Broadcast Receiver in Android With Example Arrays in Java Arrays.sort() in Java with examples Reverse a string in Java Split() String method in Java with examples Queue Interface In Java
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Feb, 2021" }, { "code": null, "e": 123, "s": 28, "text": "In this article, it is explained how to create an Android App that has a Facebook login in it." }, { "code": null, "e": 319, "s": 123, "text": "There are various social login features to use in Android applications. Here we will learn social login using Facebook, so need to integrate Facebook SDK in project to make use of Facebook login." }, { "code": null, "e": 364, "s": 319, "text": "Below are the various steps on how to do it;" }, { "code": null, "e": 9884, "s": 364, "text": "First thing you need to do is to have Facebook Developer Account and then create a new app.Install Android Studio(>= 3.0) and then open/create a project where you want to add Facebook login.In your project, add the following code in your Gradle Scripts -> build.gradle (Project).buildscript{ repositories { jcenter() }}Now, add the following code in Gradle Scripts -> build.gradle (Module:app) with the latest version of Facebook Login SDK in your project.dependencies { implementation 'com.facebook.android:facebook-android-sdk:5.0.0'}Sync your projectNow open app -> res -> values -> strings.xml file to add the following lines and replace the [APP_ID] with your APP_ID, which you can get from Facebook Developer console.<string name=\"facebook_app_id\">[APP_ID]</string><string name=\"fb_login_protocol_scheme\">fb[APP_ID]</string>Open app -> manifest -> AndroidManifest.xml file and add this line outside of application element.<uses-permission android:name=\"android.permission.INTERNET\"/>Add this meta-data element inside your application element in AndroidManifest.xml file:<meta-data android:name=\"com.facebook.sdk.ApplicationId\" android:value=\"@string/facebook_app_id\"/><activity android:name=\"com.facebook.FacebookActivity\" android:configChanges=\"keyboard|keyboardHidden |screenLayout|screenSize |orientation\" android:label=\"@string/app_name\" />Now first thing you require is Key Hash, so add these lines in your activity class before Facebook login code:@Overrideprotected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ... printHashKey(); ...} ... public void printHashKey(){ // Add code to print out the key hash try { PackageInfo info = getPackageManager().getPackageInfo( \"com.android.facebookloginsample\", PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance(\"SHA\"); md.update(signature.toByteArray()); Log.d(\"KeyHash:\", Base64.encodeToString( md.digest(), Base64.DEFAULT)); } } catch (PackageManager.NameNotFoundException e) { } catch (NoSuchAlgorithmException e) { }}Now run your application in your emulator or on your connected device. You will see Key Hash value printed in logcat, save this for later requirement.Go to Facebook Developers console and choose setting -> Basic -> Add Platform (in bottom of page) and a popup will opens up to select a platform. Choose Android as a platform.Add your project package name under ‘Google Play Package Name’. Add class name where login will implement in project like ‘LoginActivity’ and also add the key hash value under ‘Key Hashes’.Now back to android studio, add this custom button in your *.xml layout file:<Button android:id=\"@+id/button_facebook\" style=\"@style/FacebookLoginButton\" android:layout_width=\"match_parent\" android:layout_height=\"45dp\" android:layout_gravity=\"center_horizontal\" android:layout_marginTop=\"15dp\" android:text=\"Continue With Facebook\" android:textAllCaps=\"false\" android:textColor=\"@android:color/white\" />Add this code in app -> res -> styles.xml file:<style name=\"FacebookLoginButton\"> <item name=\"android:textSize\">14sp</item> <item name=\"android:background\">@drawable/facebook_signin_btn</item> <item name=\"android:paddingTop\">11dp</item> <item name=\"android:paddingBottom\">11dp</item> <item name=\"android:paddingLeft\">15dp</item> <item name=\"android:layout_marginLeft\">3dp</item> <item name=\"android:layout_marginRight\">3dp</item> <item name=\"android:layout_height\">wrap_content</item> <item name=\"android:layout_gravity\">center_horizontal</item></style>You can customize this button accordingly or instead of an above custom button, you can use the Facebook default button also as Facebook LoginButton.Make drawable file named ‘bg_button_facebook.xml’ in app -> res -> drawable folder and paste below code:<?xml version=\"1.0\" encoding=\"utf-8\"?><shapexmlns:android=\"http://schemas.android.com/apk/res/android\"android:shape=\"rectangle\"> <corners android:radius=\"5dp\"/> <solid android:color=\"#3B5998\"/></shape>Now initialize button in *.java file and some code to initialize Facebook SDK also:// Declare variablesprivate Button mButtonFacebook; private CallbackManager callbackManager;private LoginManager loginManager; ... @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ... mButtonFacebook = findViewById(R.id.button_facebook); FacebookSdk.sdkInitialize(MainActivity.this); callbackManager = CallbackManager.Factory.create(); facebookLogin(); ... mButtonFacebook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginManager.logInWithReadPermissions( MainActivity.this, Arrays.asList( \"email\", \"public_profile\", \"user_birthday\")); } }); ...} ...Add ‘facebookLogin’ method outside onCreate() in java file. This is the code for Facebook login response.public void facebookLogin(){ loginManager = LoginManager.getInstance(); callbackManager = CallbackManager.Factory.create(); loginManager .registerCallback( callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { if (object != null) { try { String name = object.getString(\"name\"); String email = object.getString(\"email\"); String fbUserID = object.getString(\"id\"); disconnectFromFacebook(); // do action after Facebook login success // or call your API } catch (JSONException | NullPointerException e) { e.printStackTrace(); } } } }); Bundle parameters = new Bundle(); parameters.putString( \"fields\", \"id, name, email, gender, birthday\"); request.setParameters(parameters); request.executeAsync(); } @Override public void onCancel() { Log.v(\"LoginScreen\", \"---onCancel\"); } @Override public void onError(FacebookException error) { // here write code when get error Log.v(\"LoginScreen\", \"----onError: \" + error.getMessage()); } });}Now add another required method ‘disconnectFromFacebook’ for login integration, similarly add this to outside onCreate. This is used to disconnect application from Facebook as no need to stay connected.public void disconnectFromFacebook(){ if (AccessToken.getCurrentAccessToken() == null) { return; // already logged out } new GraphRequest( AccessToken.getCurrentAccessToken(), \"/me/permissions/\", null, HttpMethod.DELETE, new GraphRequest .Callback() { @Override public void onCompleted(GraphResponse graphResponse) { LoginManager.getInstance().logOut(); } }) .executeAsync();}Add ‘onActivityResult’ method outside onCreate in same activity:@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data){ // add this line callbackManager.onActivityResult( requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);}Now you are done with the coding. Run your application in you device or emulator. You can now login with Facebook also in your application.If you want to upload your app on play store, then you have to enable ‘status’ from top right section on Facebook for Developers, for this first add privacy policy url in settings -> Basic as per given in below screenshot. Now save the changes and enable status from dashboard." }, { "code": null, "e": 9976, "s": 9884, "text": "First thing you need to do is to have Facebook Developer Account and then create a new app." }, { "code": null, "e": 10076, "s": 9976, "text": "Install Android Studio(>= 3.0) and then open/create a project where you want to add Facebook login." }, { "code": null, "e": 10219, "s": 10076, "text": "In your project, add the following code in your Gradle Scripts -> build.gradle (Project).buildscript{ repositories { jcenter() }}" }, { "code": "buildscript{ repositories { jcenter() }}", "e": 10273, "s": 10219, "text": null }, { "code": null, "e": 10495, "s": 10273, "text": "Now, add the following code in Gradle Scripts -> build.gradle (Module:app) with the latest version of Facebook Login SDK in your project.dependencies { implementation 'com.facebook.android:facebook-android-sdk:5.0.0'}" }, { "code": "dependencies { implementation 'com.facebook.android:facebook-android-sdk:5.0.0'}", "e": 10580, "s": 10495, "text": null }, { "code": null, "e": 10598, "s": 10580, "text": "Sync your project" }, { "code": null, "e": 10876, "s": 10598, "text": "Now open app -> res -> values -> strings.xml file to add the following lines and replace the [APP_ID] with your APP_ID, which you can get from Facebook Developer console.<string name=\"facebook_app_id\">[APP_ID]</string><string name=\"fb_login_protocol_scheme\">fb[APP_ID]</string>" }, { "code": "<string name=\"facebook_app_id\">[APP_ID]</string><string name=\"fb_login_protocol_scheme\">fb[APP_ID]</string>", "e": 10984, "s": 10876, "text": null }, { "code": null, "e": 11144, "s": 10984, "text": "Open app -> manifest -> AndroidManifest.xml file and add this line outside of application element.<uses-permission android:name=\"android.permission.INTERNET\"/>" }, { "code": "<uses-permission android:name=\"android.permission.INTERNET\"/>", "e": 11206, "s": 11144, "text": null }, { "code": null, "e": 11633, "s": 11206, "text": "Add this meta-data element inside your application element in AndroidManifest.xml file:<meta-data android:name=\"com.facebook.sdk.ApplicationId\" android:value=\"@string/facebook_app_id\"/><activity android:name=\"com.facebook.FacebookActivity\" android:configChanges=\"keyboard|keyboardHidden |screenLayout|screenSize |orientation\" android:label=\"@string/app_name\" />" }, { "code": "<meta-data android:name=\"com.facebook.sdk.ApplicationId\" android:value=\"@string/facebook_app_id\"/><activity android:name=\"com.facebook.FacebookActivity\" android:configChanges=\"keyboard|keyboardHidden |screenLayout|screenSize |orientation\" android:label=\"@string/app_name\" />", "e": 11973, "s": 11633, "text": null }, { "code": null, "e": 12971, "s": 11973, "text": "Now first thing you require is Key Hash, so add these lines in your activity class before Facebook login code:@Overrideprotected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ... printHashKey(); ...} ... public void printHashKey(){ // Add code to print out the key hash try { PackageInfo info = getPackageManager().getPackageInfo( \"com.android.facebookloginsample\", PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance(\"SHA\"); md.update(signature.toByteArray()); Log.d(\"KeyHash:\", Base64.encodeToString( md.digest(), Base64.DEFAULT)); } } catch (PackageManager.NameNotFoundException e) { } catch (NoSuchAlgorithmException e) { }}" }, { "code": "@Overrideprotected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ... printHashKey(); ...} ... public void printHashKey(){ // Add code to print out the key hash try { PackageInfo info = getPackageManager().getPackageInfo( \"com.android.facebookloginsample\", PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance(\"SHA\"); md.update(signature.toByteArray()); Log.d(\"KeyHash:\", Base64.encodeToString( md.digest(), Base64.DEFAULT)); } } catch (PackageManager.NameNotFoundException e) { } catch (NoSuchAlgorithmException e) { }}", "e": 13859, "s": 12971, "text": null }, { "code": null, "e": 14010, "s": 13859, "text": "Now run your application in your emulator or on your connected device. You will see Key Hash value printed in logcat, save this for later requirement." }, { "code": null, "e": 14186, "s": 14010, "text": "Go to Facebook Developers console and choose setting -> Basic -> Add Platform (in bottom of page) and a popup will opens up to select a platform. Choose Android as a platform." }, { "code": null, "e": 14376, "s": 14186, "text": "Add your project package name under ‘Google Play Package Name’. Add class name where login will implement in project like ‘LoginActivity’ and also add the key hash value under ‘Key Hashes’." }, { "code": null, "e": 14807, "s": 14376, "text": "Now back to android studio, add this custom button in your *.xml layout file:<Button android:id=\"@+id/button_facebook\" style=\"@style/FacebookLoginButton\" android:layout_width=\"match_parent\" android:layout_height=\"45dp\" android:layout_gravity=\"center_horizontal\" android:layout_marginTop=\"15dp\" android:text=\"Continue With Facebook\" android:textAllCaps=\"false\" android:textColor=\"@android:color/white\" />" }, { "code": "<Button android:id=\"@+id/button_facebook\" style=\"@style/FacebookLoginButton\" android:layout_width=\"match_parent\" android:layout_height=\"45dp\" android:layout_gravity=\"center_horizontal\" android:layout_marginTop=\"15dp\" android:text=\"Continue With Facebook\" android:textAllCaps=\"false\" android:textColor=\"@android:color/white\" />", "e": 15161, "s": 14807, "text": null }, { "code": null, "e": 15742, "s": 15161, "text": "Add this code in app -> res -> styles.xml file:<style name=\"FacebookLoginButton\"> <item name=\"android:textSize\">14sp</item> <item name=\"android:background\">@drawable/facebook_signin_btn</item> <item name=\"android:paddingTop\">11dp</item> <item name=\"android:paddingBottom\">11dp</item> <item name=\"android:paddingLeft\">15dp</item> <item name=\"android:layout_marginLeft\">3dp</item> <item name=\"android:layout_marginRight\">3dp</item> <item name=\"android:layout_height\">wrap_content</item> <item name=\"android:layout_gravity\">center_horizontal</item></style>" }, { "code": "<style name=\"FacebookLoginButton\"> <item name=\"android:textSize\">14sp</item> <item name=\"android:background\">@drawable/facebook_signin_btn</item> <item name=\"android:paddingTop\">11dp</item> <item name=\"android:paddingBottom\">11dp</item> <item name=\"android:paddingLeft\">15dp</item> <item name=\"android:layout_marginLeft\">3dp</item> <item name=\"android:layout_marginRight\">3dp</item> <item name=\"android:layout_height\">wrap_content</item> <item name=\"android:layout_gravity\">center_horizontal</item></style>", "e": 16276, "s": 15742, "text": null }, { "code": null, "e": 16426, "s": 16276, "text": "You can customize this button accordingly or instead of an above custom button, you can use the Facebook default button also as Facebook LoginButton." }, { "code": null, "e": 16738, "s": 16426, "text": "Make drawable file named ‘bg_button_facebook.xml’ in app -> res -> drawable folder and paste below code:<?xml version=\"1.0\" encoding=\"utf-8\"?><shapexmlns:android=\"http://schemas.android.com/apk/res/android\"android:shape=\"rectangle\"> <corners android:radius=\"5dp\"/> <solid android:color=\"#3B5998\"/></shape>" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shapexmlns:android=\"http://schemas.android.com/apk/res/android\"android:shape=\"rectangle\"> <corners android:radius=\"5dp\"/> <solid android:color=\"#3B5998\"/></shape>", "e": 16946, "s": 16738, "text": null }, { "code": null, "e": 17951, "s": 16946, "text": "Now initialize button in *.java file and some code to initialize Facebook SDK also:// Declare variablesprivate Button mButtonFacebook; private CallbackManager callbackManager;private LoginManager loginManager; ... @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ... mButtonFacebook = findViewById(R.id.button_facebook); FacebookSdk.sdkInitialize(MainActivity.this); callbackManager = CallbackManager.Factory.create(); facebookLogin(); ... mButtonFacebook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginManager.logInWithReadPermissions( MainActivity.this, Arrays.asList( \"email\", \"public_profile\", \"user_birthday\")); } }); ...} ..." }, { "code": "// Declare variablesprivate Button mButtonFacebook; private CallbackManager callbackManager;private LoginManager loginManager; ... @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ... mButtonFacebook = findViewById(R.id.button_facebook); FacebookSdk.sdkInitialize(MainActivity.this); callbackManager = CallbackManager.Factory.create(); facebookLogin(); ... mButtonFacebook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginManager.logInWithReadPermissions( MainActivity.this, Arrays.asList( \"email\", \"public_profile\", \"user_birthday\")); } }); ...} ...", "e": 18873, "s": 17951, "text": null }, { "code": null, "e": 21383, "s": 18873, "text": "Add ‘facebookLogin’ method outside onCreate() in java file. This is the code for Facebook login response.public void facebookLogin(){ loginManager = LoginManager.getInstance(); callbackManager = CallbackManager.Factory.create(); loginManager .registerCallback( callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { if (object != null) { try { String name = object.getString(\"name\"); String email = object.getString(\"email\"); String fbUserID = object.getString(\"id\"); disconnectFromFacebook(); // do action after Facebook login success // or call your API } catch (JSONException | NullPointerException e) { e.printStackTrace(); } } } }); Bundle parameters = new Bundle(); parameters.putString( \"fields\", \"id, name, email, gender, birthday\"); request.setParameters(parameters); request.executeAsync(); } @Override public void onCancel() { Log.v(\"LoginScreen\", \"---onCancel\"); } @Override public void onError(FacebookException error) { // here write code when get error Log.v(\"LoginScreen\", \"----onError: \" + error.getMessage()); } });}" }, { "code": "public void facebookLogin(){ loginManager = LoginManager.getInstance(); callbackManager = CallbackManager.Factory.create(); loginManager .registerCallback( callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { if (object != null) { try { String name = object.getString(\"name\"); String email = object.getString(\"email\"); String fbUserID = object.getString(\"id\"); disconnectFromFacebook(); // do action after Facebook login success // or call your API } catch (JSONException | NullPointerException e) { e.printStackTrace(); } } } }); Bundle parameters = new Bundle(); parameters.putString( \"fields\", \"id, name, email, gender, birthday\"); request.setParameters(parameters); request.executeAsync(); } @Override public void onCancel() { Log.v(\"LoginScreen\", \"---onCancel\"); } @Override public void onError(FacebookException error) { // here write code when get error Log.v(\"LoginScreen\", \"----onError: \" + error.getMessage()); } });}", "e": 23788, "s": 21383, "text": null }, { "code": null, "e": 24528, "s": 23788, "text": "Now add another required method ‘disconnectFromFacebook’ for login integration, similarly add this to outside onCreate. This is used to disconnect application from Facebook as no need to stay connected.public void disconnectFromFacebook(){ if (AccessToken.getCurrentAccessToken() == null) { return; // already logged out } new GraphRequest( AccessToken.getCurrentAccessToken(), \"/me/permissions/\", null, HttpMethod.DELETE, new GraphRequest .Callback() { @Override public void onCompleted(GraphResponse graphResponse) { LoginManager.getInstance().logOut(); } }) .executeAsync();}" }, { "code": "public void disconnectFromFacebook(){ if (AccessToken.getCurrentAccessToken() == null) { return; // already logged out } new GraphRequest( AccessToken.getCurrentAccessToken(), \"/me/permissions/\", null, HttpMethod.DELETE, new GraphRequest .Callback() { @Override public void onCompleted(GraphResponse graphResponse) { LoginManager.getInstance().logOut(); } }) .executeAsync();}", "e": 25066, "s": 24528, "text": null }, { "code": null, "e": 25505, "s": 25066, "text": "Add ‘onActivityResult’ method outside onCreate in same activity:@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data){ // add this line callbackManager.onActivityResult( requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);}" }, { "code": "@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data){ // add this line callbackManager.onActivityResult( requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);}", "e": 25880, "s": 25505, "text": null }, { "code": null, "e": 26020, "s": 25880, "text": "Now you are done with the coding. Run your application in you device or emulator. You can now login with Facebook also in your application." }, { "code": null, "e": 26298, "s": 26020, "text": "If you want to upload your app on play store, then you have to enable ‘status’ from top right section on Facebook for Developers, for this first add privacy policy url in settings -> Basic as per given in below screenshot. Now save the changes and enable status from dashboard." }, { "code": null, "e": 26311, "s": 26298, "text": "Android-Misc" }, { "code": null, "e": 26318, "s": 26311, "text": "Picked" }, { "code": null, "e": 26326, "s": 26318, "text": "Android" }, { "code": null, "e": 26331, "s": 26326, "text": "Java" }, { "code": null, "e": 26336, "s": 26331, "text": "Java" }, { "code": null, "e": 26344, "s": 26336, "text": "Android" }, { "code": null, "e": 26442, "s": 26344, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26508, "s": 26442, "text": "Difference Between Implicit Intent and Explicit Intent in Android" }, { "code": null, "e": 26566, "s": 26508, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 26608, "s": 26566, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 26637, "s": 26608, "text": "Navigation Drawer in Android" }, { "code": null, "e": 26680, "s": 26637, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 26695, "s": 26680, "text": "Arrays in Java" }, { "code": null, "e": 26731, "s": 26695, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 26756, "s": 26731, "text": "Reverse a string in Java" }, { "code": null, "e": 26800, "s": 26756, "text": "Split() String method in Java with examples" } ]
Python Program to get value of a dictionary given by index of maximum value of given key
18 Jul, 2021 Given a dictionary with value as a list, the task is to write a Python program that can find the maximum of any one key and output a similar index column of other key’s values. Approach : Get the maximum of the given key. Get the index of the maximum element found. Check if the index of max is present in the search key, if not, return Result not Possible. Get the element on the search key ( opt_key), which is at the index found in Step 2. Input : test_dict = {“gfg” : [4, 1, 6], “is” : [1, 4, 8], “best” : [9, 10, 1]}, max_search = “best”, opt_key = “gfg” Output : 1 Explanation : 10 is maximum element in best key, which corresponds to 1st index. In gfg, 1st index is 1, hence 1. Input : test_dict = {“gfg” : [4, 10, 6], “is” : [1, 4, 8], “best” : [9, 10, 1]}, max_search = “best”, opt_key = “gfg” Output : 10 Explanation : 10 is maximum element in best key, which corresponds to 1st index. In gfg, 1st index is 10, hence 10. Method 1 : Using index(), max() and lambda In this, we find the maximum of max search key using max() and get its index using index(), and then get the value of index in output key. Example: Python3 # initializing dictionarytest_dict = {"gfg": [4], "is": [1, 4, 8], "best": [9, 10]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing max_search keymax_search = "best" # initializing output keyopt_key = "gfg" # handling case in which maximum index is not # present in output keyif len(test_dict[opt_key]) <= test_dict[max_search].index( max(test_dict[max_search])): res = "Result not possible" # using max() to get of search keyelse: res = max(test_dict[opt_key], key=lambda sub: test_dict[max_search] [test_dict[opt_key].index(sub)]) # printing resultprint("The required output : " + str(res)) Output: The original dictionary is : {‘gfg’: [4], ‘is’: [1, 4, 8], ‘best’: [9, 10]} The required output : Result not possible Method 2 : Using zip() and max() In this, the lists of both the search and output keys are combined using zip(), post that a maximum of one list is found and the corresponding index of output key is returned. Example: Python3 # initializing dictionarytest_dict = {"gfg": [4, 1, 6], "is": [1, 4, 8], "best": [9, 10, 1]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing max_search keymax_search = "best" # initializing output keyopt_key = "gfg" # handling case in which maximum index is not present # in output keyif len(test_dict[opt_key]) <= test_dict[max_search].index( max(test_dict[max_search])): res = "Result not possible" # using max() to get of search key# zip() used for combining listselse: res = max(zip(test_dict[opt_key], test_dict[max_search]), key=lambda sub: sub[1])[0] # printing resultprint("The required output : " + str(res)) Output: The original dictionary is : {‘gfg’: [4, 1, 6], ‘is’: [1, 4, 8], ‘best’: [9, 10, 1]} The required output : 1 Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Split string into list of characters
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2021" }, { "code": null, "e": 205, "s": 28, "text": "Given a dictionary with value as a list, the task is to write a Python program that can find the maximum of any one key and output a similar index column of other key’s values." }, { "code": null, "e": 216, "s": 205, "text": "Approach :" }, { "code": null, "e": 250, "s": 216, "text": "Get the maximum of the given key." }, { "code": null, "e": 294, "s": 250, "text": "Get the index of the maximum element found." }, { "code": null, "e": 386, "s": 294, "text": "Check if the index of max is present in the search key, if not, return Result not Possible." }, { "code": null, "e": 471, "s": 386, "text": "Get the element on the search key ( opt_key), which is at the index found in Step 2." }, { "code": null, "e": 588, "s": 471, "text": "Input : test_dict = {“gfg” : [4, 1, 6], “is” : [1, 4, 8], “best” : [9, 10, 1]}, max_search = “best”, opt_key = “gfg”" }, { "code": null, "e": 599, "s": 588, "text": "Output : 1" }, { "code": null, "e": 713, "s": 599, "text": "Explanation : 10 is maximum element in best key, which corresponds to 1st index. In gfg, 1st index is 1, hence 1." }, { "code": null, "e": 831, "s": 713, "text": "Input : test_dict = {“gfg” : [4, 10, 6], “is” : [1, 4, 8], “best” : [9, 10, 1]}, max_search = “best”, opt_key = “gfg”" }, { "code": null, "e": 843, "s": 831, "text": "Output : 10" }, { "code": null, "e": 959, "s": 843, "text": "Explanation : 10 is maximum element in best key, which corresponds to 1st index. In gfg, 1st index is 10, hence 10." }, { "code": null, "e": 1002, "s": 959, "text": "Method 1 : Using index(), max() and lambda" }, { "code": null, "e": 1142, "s": 1002, "text": "In this, we find the maximum of max search key using max() and get its index using index(), and then get the value of index in output key. " }, { "code": null, "e": 1151, "s": 1142, "text": "Example:" }, { "code": null, "e": 1159, "s": 1151, "text": "Python3" }, { "code": "# initializing dictionarytest_dict = {\"gfg\": [4], \"is\": [1, 4, 8], \"best\": [9, 10]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing max_search keymax_search = \"best\" # initializing output keyopt_key = \"gfg\" # handling case in which maximum index is not # present in output keyif len(test_dict[opt_key]) <= test_dict[max_search].index( max(test_dict[max_search])): res = \"Result not possible\" # using max() to get of search keyelse: res = max(test_dict[opt_key], key=lambda sub: test_dict[max_search] [test_dict[opt_key].index(sub)]) # printing resultprint(\"The required output : \" + str(res))", "e": 1831, "s": 1159, "text": null }, { "code": null, "e": 1839, "s": 1831, "text": "Output:" }, { "code": null, "e": 1915, "s": 1839, "text": "The original dictionary is : {‘gfg’: [4], ‘is’: [1, 4, 8], ‘best’: [9, 10]}" }, { "code": null, "e": 1957, "s": 1915, "text": "The required output : Result not possible" }, { "code": null, "e": 1990, "s": 1957, "text": "Method 2 : Using zip() and max()" }, { "code": null, "e": 2167, "s": 1990, "text": "In this, the lists of both the search and output keys are combined using zip(), post that a maximum of one list is found and the corresponding index of output key is returned. " }, { "code": null, "e": 2176, "s": 2167, "text": "Example:" }, { "code": null, "e": 2184, "s": 2176, "text": "Python3" }, { "code": "# initializing dictionarytest_dict = {\"gfg\": [4, 1, 6], \"is\": [1, 4, 8], \"best\": [9, 10, 1]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing max_search keymax_search = \"best\" # initializing output keyopt_key = \"gfg\" # handling case in which maximum index is not present # in output keyif len(test_dict[opt_key]) <= test_dict[max_search].index( max(test_dict[max_search])): res = \"Result not possible\" # using max() to get of search key# zip() used for combining listselse: res = max(zip(test_dict[opt_key], test_dict[max_search]), key=lambda sub: sub[1])[0] # printing resultprint(\"The required output : \" + str(res))", "e": 2881, "s": 2184, "text": null }, { "code": null, "e": 2889, "s": 2881, "text": "Output:" }, { "code": null, "e": 2974, "s": 2889, "text": "The original dictionary is : {‘gfg’: [4, 1, 6], ‘is’: [1, 4, 8], ‘best’: [9, 10, 1]}" }, { "code": null, "e": 2998, "s": 2974, "text": "The required output : 1" }, { "code": null, "e": 3025, "s": 2998, "text": "Python dictionary-programs" }, { "code": null, "e": 3032, "s": 3025, "text": "Python" }, { "code": null, "e": 3048, "s": 3032, "text": "Python Programs" }, { "code": null, "e": 3146, "s": 3048, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3178, "s": 3146, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3205, "s": 3178, "text": "Python Classes and Objects" }, { "code": null, "e": 3226, "s": 3205, "text": "Python OOPs Concepts" }, { "code": null, "e": 3249, "s": 3226, "text": "Introduction To PYTHON" }, { "code": null, "e": 3305, "s": 3249, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3327, "s": 3305, "text": "Defaultdict in Python" }, { "code": null, "e": 3366, "s": 3327, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3404, "s": 3366, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3441, "s": 3404, "text": "Python Program for Fibonacci numbers" } ]
Write a program to calculate the least common multiple of two numbers JavaScript
We are required to write a function that accepts two numbers and returns their least common multiple. The least common multiple of two numbers a and b is the smallest positive integer that is divisible by both a and b. For example − The LCM of 6 and 8 is 24 because 24 is the smallest positive integer that is divided by both 6 and 8. One of the many ways of calculating LCM of two numbers a and b is by dividing the product of a and b by the greatest integer (also known as greatest common divisor or GCD) that divides both a and b. In case of 6 and 8, their product is 48 and the greatest integer that divides them both is 2 so their LCM is − (6*8)/2 = 24 Having these things clear, now let’s move to the coding part − const lcm = (a, b) => { let min = Math.min(a, b); while(min >= 2){ if(a % min === 0 && b % min === 0){ return (a*b)/min; }; min--; }; return (a*b); }; console.log(lcm(6, 8)); console.log(lcm(16, 18)); console.log(lcm(0, 8)); console.log(lcm(11, 28)); console.log(lcm(18, 34)); Since the greatest integer that exactly divides both the numbers will still be smaller or equal to the smaller of the two numbers, we are calculating LCM for, we run a decrementing loop from the smaller number all the way down to 2. If in our iterations we find any number that divides both the numbers we can guarantee that it’s the largest number that divides them both because we are in a decrementing loop, so we return right there with the LCM. If we iterate through the complete it means that we didn’t found any such number and 1 is the only number that divides them both (in other terms the numbers are co-prime), so we simply return their product. The output in the console will be − 24 144 0 308 306
[ { "code": null, "e": 1289, "s": 1187, "text": "We are required to write a function that accepts two numbers and returns their least common\nmultiple." }, { "code": null, "e": 1406, "s": 1289, "text": "The least common multiple of two numbers a and b is the smallest positive integer that is\ndivisible by both a and b." }, { "code": null, "e": 1522, "s": 1406, "text": "For example − The LCM of 6 and 8 is 24 because 24 is the smallest positive integer that is\ndivided by both 6 and 8." }, { "code": null, "e": 1721, "s": 1522, "text": "One of the many ways of calculating LCM of two numbers a and b is by dividing the product of a\nand b by the greatest integer (also known as greatest common divisor or GCD) that divides both\na and b." }, { "code": null, "e": 1832, "s": 1721, "text": "In case of 6 and 8, their product is 48 and the greatest integer that divides them both is 2 so\ntheir LCM is −" }, { "code": null, "e": 1845, "s": 1832, "text": "(6*8)/2 = 24" }, { "code": null, "e": 1908, "s": 1845, "text": "Having these things clear, now let’s move to the coding part −" }, { "code": null, "e": 2224, "s": 1908, "text": "const lcm = (a, b) => {\n let min = Math.min(a, b);\n while(min >= 2){\n if(a % min === 0 && b % min === 0){\n return (a*b)/min;\n };\n min--;\n };\n return (a*b);\n};\nconsole.log(lcm(6, 8));\nconsole.log(lcm(16, 18));\nconsole.log(lcm(0, 8));\nconsole.log(lcm(11, 28));\nconsole.log(lcm(18, 34));" }, { "code": null, "e": 2457, "s": 2224, "text": "Since the greatest integer that exactly divides both the numbers will still be smaller or equal to\nthe smaller of the two numbers, we are calculating LCM for, we run a decrementing loop from\nthe smaller number all the way down to 2." }, { "code": null, "e": 2674, "s": 2457, "text": "If in our iterations we find any number that divides both the numbers we can guarantee that it’s\nthe largest number that divides them both because we are in a decrementing loop, so we return\nright there with the LCM." }, { "code": null, "e": 2881, "s": 2674, "text": "If we iterate through the complete it means that we didn’t found any such number and 1 is the\nonly number that divides them both (in other terms the numbers are co-prime), so we simply\nreturn their product." }, { "code": null, "e": 2917, "s": 2881, "text": "The output in the console will be −" }, { "code": null, "e": 2934, "s": 2917, "text": "24\n144\n0\n308\n306" } ]
Lodash - GeeksforGeeks
10 Dec, 2021 Lodash is a JavaScript library that works on the top of underscore.js. It helps in working with arrays, strings, objects, numbers, etc. It provides us with various inbuilt functions and uses a functional programming approach which that coding in JavaScript easier to understand because instead of writing repetitive functions, tasks can be accomplished with a single line of code. It also makes it easier to work with objects in JavaScript if they require a lot of manipulation to be done upon them. It provides various inbuilt functions for collections, arrays, to manipulate objects, and other utility methods that we can use directly instead of writing them from scratch. It makes it easier to iterate over the arrays, strings as well as objects. Its modular methods enable the creation of composite functions easier. Installation: It can be used directly using the CDN link or can be installed using npm or yarn. Method 1: We can directly use the file in the browser. Go to the official documentation and copy the lodash.min.js file CDN link and paste this link inside the head section. <script type=”text/JavaScript” src = “https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js”></script> Method 2: We can install it with npm. Make sure that you have Node.js and npm installed. npm install lodash If you are using yarn then you can use the following command: yarn install lodash Now in order to use the Lodash library, you need to require it in the code file. const _ = require("lodash"); Now let’s understand how to use Lodash with the help of the code example. Example: In this example, we will simply create an empty string using the lodash _.stubString() method. index.js Output: "" Empty String Learn more about Lodash.js: Introduction Array Complete Reference Collection Complete Reference Function Complete Reference Lang Complete Reference Math Complete Reference Object Complete Reference Seq Complete Reference– String Complete Reference Util Complete Reference Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Learn C++ Programming Step by Step - A 20 Day Curriculum! Must Do Coding Questions for Product Based Companies Types of Distributed System What is Handle Pruning? How to Install MySQL on Linux? Floyd’s Cycle Finding Algorithm How to count rows with SELECT COUNT(*) with SQLAlchemy? How to Add External JAR File to an IntelliJ IDEA Project? Difference Between NPDA and DPDA
[ { "code": null, "e": 24903, "s": 24875, "text": "\n10 Dec, 2021" }, { "code": null, "e": 25403, "s": 24903, "text": "Lodash is a JavaScript library that works on the top of underscore.js. It helps in working with arrays, strings, objects, numbers, etc. It provides us with various inbuilt functions and uses a functional programming approach which that coding in JavaScript easier to understand because instead of writing repetitive functions, tasks can be accomplished with a single line of code. It also makes it easier to work with objects in JavaScript if they require a lot of manipulation to be done upon them." }, { "code": null, "e": 25724, "s": 25403, "text": "It provides various inbuilt functions for collections, arrays, to manipulate objects, and other utility methods that we can use directly instead of writing them from scratch. It makes it easier to iterate over the arrays, strings as well as objects. Its modular methods enable the creation of composite functions easier." }, { "code": null, "e": 25820, "s": 25724, "text": "Installation: It can be used directly using the CDN link or can be installed using npm or yarn." }, { "code": null, "e": 25994, "s": 25820, "text": "Method 1: We can directly use the file in the browser. Go to the official documentation and copy the lodash.min.js file CDN link and paste this link inside the head section." }, { "code": null, "e": 26101, "s": 25994, "text": "<script type=”text/JavaScript” src = “https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js”></script>" }, { "code": null, "e": 26190, "s": 26101, "text": "Method 2: We can install it with npm. Make sure that you have Node.js and npm installed." }, { "code": null, "e": 26209, "s": 26190, "text": "npm install lodash" }, { "code": null, "e": 26271, "s": 26209, "text": "If you are using yarn then you can use the following command:" }, { "code": null, "e": 26291, "s": 26271, "text": "yarn install lodash" }, { "code": null, "e": 26372, "s": 26291, "text": "Now in order to use the Lodash library, you need to require it in the code file." }, { "code": null, "e": 26402, "s": 26372, "text": "const _ = require(\"lodash\"); " }, { "code": null, "e": 26476, "s": 26402, "text": "Now let’s understand how to use Lodash with the help of the code example." }, { "code": null, "e": 26580, "s": 26476, "text": "Example: In this example, we will simply create an empty string using the lodash _.stubString() method." }, { "code": null, "e": 26589, "s": 26580, "text": "index.js" }, { "code": null, "e": 26597, "s": 26589, "text": "Output:" }, { "code": null, "e": 26613, "s": 26597, "text": "\"\" Empty String" }, { "code": null, "e": 26641, "s": 26613, "text": "Learn more about Lodash.js:" }, { "code": null, "e": 26654, "s": 26641, "text": "Introduction" }, { "code": null, "e": 26679, "s": 26654, "text": "Array Complete Reference" }, { "code": null, "e": 26709, "s": 26679, "text": "Collection Complete Reference" }, { "code": null, "e": 26737, "s": 26709, "text": "Function Complete Reference" }, { "code": null, "e": 26761, "s": 26737, "text": "Lang Complete Reference" }, { "code": null, "e": 26785, "s": 26761, "text": "Math Complete Reference" }, { "code": null, "e": 26811, "s": 26785, "text": "Object Complete Reference" }, { "code": null, "e": 26835, "s": 26811, "text": "Seq Complete Reference–" }, { "code": null, "e": 26861, "s": 26835, "text": "String Complete Reference" }, { "code": null, "e": 26885, "s": 26861, "text": "Util Complete Reference" }, { "code": null, "e": 27009, "s": 26885, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 27107, "s": 27009, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 27181, "s": 27107, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 27239, "s": 27181, "text": "Learn C++ Programming Step by Step - A 20 Day Curriculum!" }, { "code": null, "e": 27292, "s": 27239, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 27320, "s": 27292, "text": "Types of Distributed System" }, { "code": null, "e": 27344, "s": 27320, "text": "What is Handle Pruning?" }, { "code": null, "e": 27375, "s": 27344, "text": "How to Install MySQL on Linux?" }, { "code": null, "e": 27407, "s": 27375, "text": "Floyd’s Cycle Finding Algorithm" }, { "code": null, "e": 27463, "s": 27407, "text": "How to count rows with SELECT COUNT(*) with SQLAlchemy?" }, { "code": null, "e": 27521, "s": 27463, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
How do I automatically download files from a pop up dialog using selenium-python?
We can automatically download files from a pop up dialog using Selenium webdriver with Python. After clicking the download link, a dialog box appears for the user to select various options to Save the file. We have to programmatically configure the path where the download has to be performed such that every time the Firefox browser is launched, the Firefox profile is proper to perform the download at the desired location. Open the address bar of Firefox, and enter about:config and press Enter . All the browser preferences shall be available with Edit and Toggle buttons. We shall use the Firefox Options class to set the download preferences for the browser. from selenium import webdriver from selenium.webdriver.firefox.options import Options #object of Options class op = Options() #save file to path defined for recent download with value 2 op.set_preference("browser.download.folderList",2) #disable display Download Manager window with false value op.set_preference("browser.download.manager.showWhenStarting", False) #download location op.set_preference ("browser.download.dir","C:\\Users\\ghs6kor\\Documents\\Download") #MIME set to save file to disk without asking file type to used to open file op.set_preference ("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream,application/vnd.ms-excel") #set geckodriver.exe path driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe", firefox_options=op) driver.maximize_window() #launch URL driver.get("https://the-internet.herokuapp.com/download"); #click download link l = driver.find_element_by_link_text("xls-sample1.xls") l.click() The file downloaded at the declared location.
[ { "code": null, "e": 1394, "s": 1187, "text": "We can automatically download files from a pop up dialog using Selenium webdriver with Python. After clicking the download link, a dialog box appears for the user to select various options to Save the file." }, { "code": null, "e": 1613, "s": 1394, "text": "We have to programmatically configure the path where the download has to be performed such that every time the Firefox browser is launched, the Firefox profile is proper to perform the download at the desired location." }, { "code": null, "e": 1852, "s": 1613, "text": "Open the address bar of Firefox, and enter about:config and press Enter . All the browser preferences shall be available with Edit and Toggle buttons. We shall use the Firefox Options class to set the download preferences for the browser." }, { "code": null, "e": 2807, "s": 1852, "text": "from selenium import webdriver\nfrom selenium.webdriver.firefox.options import Options\n#object of Options class\nop = Options()\n#save file to path defined for recent download with value 2\nop.set_preference(\"browser.download.folderList\",2)\n#disable display Download Manager window with false value\nop.set_preference(\"browser.download.manager.showWhenStarting\", False)\n#download location\nop.set_preference\n(\"browser.download.dir\",\"C:\\\\Users\\\\ghs6kor\\\\Documents\\\\Download\")\n#MIME set to save file to disk without asking file type to used to open file\nop.set_preference\n(\"browser.helperApps.neverAsk.saveToDisk\",\n\"application/octet-stream,application/vnd.ms-excel\")\n#set geckodriver.exe path\ndriver = webdriver.Firefox(executable_path=\"C:\\\\geckodriver.exe\",\nfirefox_options=op)\ndriver.maximize_window()\n#launch URL\ndriver.get(\"https://the-internet.herokuapp.com/download\");\n#click download link\nl = driver.find_element_by_link_text(\"xls-sample1.xls\")\nl.click()" }, { "code": null, "e": 2853, "s": 2807, "text": "The file downloaded at the declared location." } ]
LZW (Lempel–Ziv–Welch) Compression technique
08 Nov, 2021 Why do we need a Compression Algorithm? There are two categories of compression techniques, lossy and lossless. Whilst each uses different techniques to compress files, both have the same aim: To look for duplicate data in the graphic (GIF for LZW) and use a much more compact data representation. Lossless compression reduces bits by identifying and eliminating statistical redundancy. No information is lost in lossless compression. On the other hand, Lossy compression reduces bits by removing unnecessary or less important information. So we need Data Compression mainly because: Uncompressed data can take up a lot of space, which is not good for limited hard drive space and internet download speeds. While hardware gets better and cheaper, algorithms to reduce data size also help technology evolves. Example: One minute of uncompressed HD video can be over 1 GB. How can we fit a two-hour film on a 25 GB Blu-ray disc? Lossy compression methods include DCT (Discrete Cosine Transform), Vector Quantisation, and Transform Coding while Lossless compression methods include RLE (Run Length Encoding), string-table compression, LZW (Lempel Ziff Welch), and zlib. There Exist several compression Algorithms, but we are concentrating on LZW. What is Lempel–Ziv–Welch (LZW) Algorithm ? The LZW algorithm is a very common compression technique. This algorithm is typically used in GIF and optionally in PDF and TIFF. Unix’s ‘compress’ command, among other uses. It is lossless, meaning no data is lost when compressing. The algorithm is simple to implement and has the potential for very high throughput in hardware implementations. It is the algorithm of the widely used Unix file compression utility compress and is used in the GIF image format.The Idea relies on reoccurring patterns to save data space. LZW is the foremost technique for general-purpose data compression due to its simplicity and versatility. It is the basis of many PC utilities that claim to “double the capacity of your hard drive”. How does it work? LZW compression works by reading a sequence of symbols, grouping the symbols into strings, and converting the strings into codes. Because the codes take up less space than the strings they replace, we get compression. Characteristic features of LZW includes, LZW compression uses a code table, with 4096 as a common choice for the number of table entries. Codes 0-255 in the code table are always assigned to represent single bytes from the input file. When encoding begins the code table contains only the first 256 entries, with the remainder of the table being blanks. Compression is achieved by using codes 256 through 4095 to represent sequences of bytes. As the encoding continues, LZW identifies repeated sequences in the data and adds them to the code table. Decoding is achieved by taking each code from the compressed file and translating it through the code table to find what character or characters it represents. Example: ASCII code. Typically, every character is stored with 8 binary bits, allowing up to 256 unique symbols for the data. This algorithm tries to extend the library to 9 to 12 bits per character. The new unique symbols are made up of combinations of symbols that occurred previously in the string. It does not always compress well, especially with short, diverse strings. But is good for compressing redundant data, and does not have to save the new dictionary with the data: this method can both compress and uncompress data. There are excellent article’s written up already, you can look more in-depth here, and also Mark Nelson’s article is commendable. Implementation The idea of the compression algorithm is the following: as the input data is being processed, a dictionary keeps a correspondence between the longest encountered words and a list of code values. The words are replaced by their corresponding codes and so the input file is compressed. Therefore, the efficiency of the algorithm increases as the number of long, repetitive words in the input data increases. LZW ENCODING * PSEUDOCODE 1 Initialize table with single character strings 2 P = first input character 3 WHILE not end of input stream 4 C = next input character 5 IF P + C is in the string table 6 P = P + C 7 ELSE 8 output the code for P 9 add P + C to the string table 10 P = C 11 END WHILE 12 output code for P Testing the code below : Output : Also, check the code converted by Mark Nelson into C++ style. There is another variation of 6 different versions here. Also, Rosettacode lists several implementations of LZW in different languages. Compression using LZW Example 1: Use the LZW algorithm to compress the string: BABAABAAA The steps involved are systematically shown in the diagram below. LZW Decompression The LZW decompressor creates the same string table during decompression. It starts with the first 256 table entries initialized to single characters. The string table is updated for each character in the input stream, except the first one. Decoding is achieved by reading codes and translating them through the code table being built. LZW Decompression Algorithm * PSEUDOCODE 1 Initialize table with single character strings 2 OLD = first input code 3 output translation of OLD 4 WHILE not end of input stream 5 NEW = next input code 6 IF NEW is not in the string table 7 S = translation of OLD 8 S = S + C 9 ELSE 10 S = translation of NEW 11 output S 12 C = first character of S 13 OLD + C to the string table 14 OLD = NEW 15 END WHILE Example 2: LZW Decompression: Use LZW to decompress the output sequence of : <66><65><256><257><65><260> The steps involved are systematically shown in the diagram below. In this example, 72 bits are represented with 72 bits of data. After a reasonable string table is built, compression improves dramatically. LZW Summary: This algorithm compresses repetitive sequences of data very well. Since the codewords are 12 bits, any single encoded character will expand the data size rather than reduce it. A C++ code for LZW compression both for encoding and decoding is given as follows: C++ #include <bits/stdc++.h>using namespace std;vector<int> encoding(string s1){ cout << "Encoding\n"; unordered_map<string, int> table; for (int i = 0; i <= 255; i++) { string ch = ""; ch += char(i); table[ch] = i; } string p = "", c = ""; p += s1[0]; int code = 256; vector<int> output_code; cout << "String\tOutput_Code\tAddition\n"; for (int i = 0; i < s1.length(); i++) { if (i != s1.length() - 1) c += s1[i + 1]; if (table.find(p + c) != table.end()) { p = p + c; } else { cout << p << "\t" << table[p] << "\t\t" << p + c << "\t" << code << endl; output_code.push_back(table[p]); table[p + c] = code; code++; p = c; } c = ""; } cout << p << "\t" << table[p] << endl; output_code.push_back(table[p]); return output_code;} void decoding(vector<int> op){ cout << "\nDecoding\n"; unordered_map<int, string> table; for (int i = 0; i <= 255; i++) { string ch = ""; ch += char(i); table[i] = ch; } int old = op[0], n; string s = table[old]; string c = ""; c += s[0]; cout << s; int count = 256; for (int i = 0; i < op.size() - 1; i++) { n = op[i + 1]; if (table.find(n) == table.end()) { s = table[old]; s = s + c; } else { s = table[n]; } cout << s; c = ""; c += s[0]; table[count] = table[old] + c; count++; old = n; }}int main(){ string s = "WYS*WYGWYS*WYSWYSG"; vector<int> output_code = encoding(s); cout << "Output Codes are: "; for (int i = 0; i < output_code.size(); i++) { cout << output_code[i] << " "; } cout << endl; decoding(output_code);} Encoding String Output_Code Addition W 87 WY 256 Y 89 YS 257 S 83 S* 258 * 42 *W 259 WY 256 WYG 260 G 71 GW 261 WY 256 WYS 262 S* 258 S*W 263 WYS 262 WYSW 264 WYS 262 WYSG 265 G 71 Output Codes are: 87 89 83 42 256 71 256 258 262 262 71 Decoding WYS*WYGWYS*WYSWYSG Advantages of LZW over Huffman: LZW requires no prior information about the input data stream. LZW can compress the input stream in one single pass. Another advantage of LZW is its simplicity, allowing fast execution. Resources: mit.edu Dave.Marshall duke.edu michael.dipperstein LZW(Youtube) faculty.kfupm.edu.sa github repository(kmeelu) This article is contributed by Amartya Ranjan Saikia. 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. MohitBansal3 KewalShah vaibhavsinghtanwar3 Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Socket Programming in Python GSM in Wireless Communication Differences between IPv4 and IPv6 Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) UDP Server-Client implementation in C Caesar Cipher in Cryptography Advanced Encryption Standard (AES)
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Nov, 2021" }, { "code": null, "e": 92, "s": 52, "text": "Why do we need a Compression Algorithm?" }, { "code": null, "e": 637, "s": 92, "text": "There are two categories of compression techniques, lossy and lossless. Whilst each uses different techniques to compress files, both have the same aim: To look for duplicate data in the graphic (GIF for LZW) and use a much more compact data representation. Lossless compression reduces bits by identifying and eliminating statistical redundancy. No information is lost in lossless compression. On the other hand, Lossy compression reduces bits by removing unnecessary or less important information. So we need Data Compression mainly because: " }, { "code": null, "e": 760, "s": 637, "text": "Uncompressed data can take up a lot of space, which is not good for limited hard drive space and internet download speeds." }, { "code": null, "e": 861, "s": 760, "text": "While hardware gets better and cheaper, algorithms to reduce data size also help technology evolves." }, { "code": null, "e": 980, "s": 861, "text": "Example: One minute of uncompressed HD video can be over 1 GB. How can we fit a two-hour film on a 25 GB Blu-ray disc?" }, { "code": null, "e": 1298, "s": 980, "text": "Lossy compression methods include DCT (Discrete Cosine Transform), Vector Quantisation, and Transform Coding while Lossless compression methods include RLE (Run Length Encoding), string-table compression, LZW (Lempel Ziff Welch), and zlib. There Exist several compression Algorithms, but we are concentrating on LZW. " }, { "code": null, "e": 1341, "s": 1298, "text": "What is Lempel–Ziv–Welch (LZW) Algorithm ?" }, { "code": null, "e": 2061, "s": 1341, "text": "The LZW algorithm is a very common compression technique. This algorithm is typically used in GIF and optionally in PDF and TIFF. Unix’s ‘compress’ command, among other uses. It is lossless, meaning no data is lost when compressing. The algorithm is simple to implement and has the potential for very high throughput in hardware implementations. It is the algorithm of the widely used Unix file compression utility compress and is used in the GIF image format.The Idea relies on reoccurring patterns to save data space. LZW is the foremost technique for general-purpose data compression due to its simplicity and versatility. It is the basis of many PC utilities that claim to “double the capacity of your hard drive”. " }, { "code": null, "e": 2079, "s": 2061, "text": "How does it work?" }, { "code": null, "e": 2339, "s": 2079, "text": "LZW compression works by reading a sequence of symbols, grouping the symbols into strings, and converting the strings into codes. Because the codes take up less space than the strings they replace, we get compression. Characteristic features of LZW includes, " }, { "code": null, "e": 2533, "s": 2339, "text": "LZW compression uses a code table, with 4096 as a common choice for the number of table entries. Codes 0-255 in the code table are always assigned to represent single bytes from the input file." }, { "code": null, "e": 2741, "s": 2533, "text": "When encoding begins the code table contains only the first 256 entries, with the remainder of the table being blanks. Compression is achieved by using codes 256 through 4095 to represent sequences of bytes." }, { "code": null, "e": 2847, "s": 2741, "text": "As the encoding continues, LZW identifies repeated sequences in the data and adds them to the code table." }, { "code": null, "e": 3007, "s": 2847, "text": "Decoding is achieved by taking each code from the compressed file and translating it through the code table to find what character or characters it represents." }, { "code": null, "e": 3669, "s": 3007, "text": "Example: ASCII code. Typically, every character is stored with 8 binary bits, allowing up to 256 unique symbols for the data. This algorithm tries to extend the library to 9 to 12 bits per character. The new unique symbols are made up of combinations of symbols that occurred previously in the string. It does not always compress well, especially with short, diverse strings. But is good for compressing redundant data, and does not have to save the new dictionary with the data: this method can both compress and uncompress data. There are excellent article’s written up already, you can look more in-depth here, and also Mark Nelson’s article is commendable. " }, { "code": null, "e": 3684, "s": 3669, "text": "Implementation" }, { "code": null, "e": 4090, "s": 3684, "text": "The idea of the compression algorithm is the following: as the input data is being processed, a dictionary keeps a correspondence between the longest encountered words and a list of code values. The words are replaced by their corresponding codes and so the input file is compressed. Therefore, the efficiency of the algorithm increases as the number of long, repetitive words in the input data increases." }, { "code": null, "e": 4103, "s": 4090, "text": "LZW ENCODING" }, { "code": null, "e": 4526, "s": 4103, "text": " * PSEUDOCODE\n 1 Initialize table with single character strings\n 2 P = first input character\n 3 WHILE not end of input stream\n 4 C = next input character\n 5 IF P + C is in the string table\n 6 P = P + C\n 7 ELSE\n 8 output the code for P\n 9 add P + C to the string table\n 10 P = C\n 11 END WHILE\n 12 output code for P " }, { "code": null, "e": 4553, "s": 4526, "text": "Testing the code below : " }, { "code": null, "e": 4564, "s": 4553, "text": "Output : " }, { "code": null, "e": 4763, "s": 4564, "text": "Also, check the code converted by Mark Nelson into C++ style. There is another variation of 6 different versions here. Also, Rosettacode lists several implementations of LZW in different languages. " }, { "code": null, "e": 4785, "s": 4763, "text": "Compression using LZW" }, { "code": null, "e": 4919, "s": 4785, "text": "Example 1: Use the LZW algorithm to compress the string: BABAABAAA The steps involved are systematically shown in the diagram below. " }, { "code": null, "e": 4937, "s": 4919, "text": "LZW Decompression" }, { "code": null, "e": 5272, "s": 4937, "text": "The LZW decompressor creates the same string table during decompression. It starts with the first 256 table entries initialized to single characters. The string table is updated for each character in the input stream, except the first one. Decoding is achieved by reading codes and translating them through the code table being built." }, { "code": null, "e": 5300, "s": 5272, "text": "LZW Decompression Algorithm" }, { "code": null, "e": 5776, "s": 5300, "text": "* PSEUDOCODE\n1 Initialize table with single character strings\n2 OLD = first input code\n3 output translation of OLD\n4 WHILE not end of input stream\n5 NEW = next input code\n6 IF NEW is not in the string table\n7 S = translation of OLD\n8 S = S + C\n9 ELSE\n10 S = translation of NEW\n11 output S\n12 C = first character of S\n13 OLD + C to the string table\n14 OLD = NEW\n15 END WHILE" }, { "code": null, "e": 5947, "s": 5776, "text": "Example 2: LZW Decompression: Use LZW to decompress the output sequence of : <66><65><256><257><65><260> The steps involved are systematically shown in the diagram below." }, { "code": null, "e": 6277, "s": 5947, "text": "In this example, 72 bits are represented with 72 bits of data. After a reasonable string table is built, compression improves dramatically. LZW Summary: This algorithm compresses repetitive sequences of data very well. Since the codewords are 12 bits, any single encoded character will expand the data size rather than reduce it." }, { "code": null, "e": 6361, "s": 6277, "text": "A C++ code for LZW compression both for encoding and decoding is given as follows: " }, { "code": null, "e": 6365, "s": 6361, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std;vector<int> encoding(string s1){ cout << \"Encoding\\n\"; unordered_map<string, int> table; for (int i = 0; i <= 255; i++) { string ch = \"\"; ch += char(i); table[ch] = i; } string p = \"\", c = \"\"; p += s1[0]; int code = 256; vector<int> output_code; cout << \"String\\tOutput_Code\\tAddition\\n\"; for (int i = 0; i < s1.length(); i++) { if (i != s1.length() - 1) c += s1[i + 1]; if (table.find(p + c) != table.end()) { p = p + c; } else { cout << p << \"\\t\" << table[p] << \"\\t\\t\" << p + c << \"\\t\" << code << endl; output_code.push_back(table[p]); table[p + c] = code; code++; p = c; } c = \"\"; } cout << p << \"\\t\" << table[p] << endl; output_code.push_back(table[p]); return output_code;} void decoding(vector<int> op){ cout << \"\\nDecoding\\n\"; unordered_map<int, string> table; for (int i = 0; i <= 255; i++) { string ch = \"\"; ch += char(i); table[i] = ch; } int old = op[0], n; string s = table[old]; string c = \"\"; c += s[0]; cout << s; int count = 256; for (int i = 0; i < op.size() - 1; i++) { n = op[i + 1]; if (table.find(n) == table.end()) { s = table[old]; s = s + c; } else { s = table[n]; } cout << s; c = \"\"; c += s[0]; table[count] = table[old] + c; count++; old = n; }}int main(){ string s = \"WYS*WYGWYS*WYSWYSG\"; vector<int> output_code = encoding(s); cout << \"Output Codes are: \"; for (int i = 0; i < output_code.size(); i++) { cout << output_code[i] << \" \"; } cout << endl; decoding(output_code);}", "e": 8208, "s": 6365, "text": null }, { "code": null, "e": 8614, "s": 8208, "text": "Encoding\nString Output_Code Addition\nW 87 WY 256\nY 89 YS 257\nS 83 S* 258\n* 42 *W 259\nWY 256 WYG 260\nG 71 GW 261\nWY 256 WYS 262\nS* 258 S*W 263\nWYS 262 WYSW 264\nWYS 262 WYSG 265\nG 71\nOutput Codes are: 87 89 83 42 256 71 256 258 262 262 71 \n\nDecoding\nWYS*WYGWYS*WYSWYSG" }, { "code": null, "e": 8649, "s": 8616, "text": "Advantages of LZW over Huffman: " }, { "code": null, "e": 8712, "s": 8649, "text": "LZW requires no prior information about the input data stream." }, { "code": null, "e": 8766, "s": 8712, "text": "LZW can compress the input stream in one single pass." }, { "code": null, "e": 8835, "s": 8766, "text": "Another advantage of LZW is its simplicity, allowing fast execution." }, { "code": null, "e": 8848, "s": 8835, "text": "Resources: " }, { "code": null, "e": 8856, "s": 8848, "text": "mit.edu" }, { "code": null, "e": 8870, "s": 8856, "text": "Dave.Marshall" }, { "code": null, "e": 8879, "s": 8870, "text": "duke.edu" }, { "code": null, "e": 8899, "s": 8879, "text": "michael.dipperstein" }, { "code": null, "e": 8912, "s": 8899, "text": "LZW(Youtube)" }, { "code": null, "e": 8933, "s": 8912, "text": "faculty.kfupm.edu.sa" }, { "code": null, "e": 8959, "s": 8933, "text": "github repository(kmeelu)" }, { "code": null, "e": 9389, "s": 8959, "text": "This article is contributed by Amartya Ranjan Saikia. 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": 9402, "s": 9389, "text": "MohitBansal3" }, { "code": null, "e": 9412, "s": 9402, "text": "KewalShah" }, { "code": null, "e": 9432, "s": 9412, "text": "vaibhavsinghtanwar3" }, { "code": null, "e": 9450, "s": 9432, "text": "Computer Networks" }, { "code": null, "e": 9468, "s": 9450, "text": "Computer Networks" }, { "code": null, "e": 9566, "s": 9468, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9595, "s": 9566, "text": "Socket Programming in Python" }, { "code": null, "e": 9625, "s": 9595, "text": "GSM in Wireless Communication" }, { "code": null, "e": 9659, "s": 9625, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 9685, "s": 9659, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 9715, "s": 9685, "text": "Wireless Application Protocol" }, { "code": null, "e": 9755, "s": 9715, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 9793, "s": 9755, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 9823, "s": 9793, "text": "Caesar Cipher in Cryptography" } ]
How to Sort HashSet Elements using Comparable Interface in Java?
01 Dec, 2021 The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means when we iterate the HashSet, there is no guarantee that we get elements in which order they were inserted. To sort HashSet elements using Comparable interface in java first, we create a class Student that implements the Comparable interface. In this class we override the compareTo() method. Pseudo Code: // Student class implements comparable interface class Student implements Comparable<Student> { Integer marks; Student(Integer marks) { this.marks = marks; } // override toString method public String toString() { return (" " + this.marks); } // Override compareTo method to sort LinkedHashSet in ascending order public int compareTo(Student stu) { return this.marks.compareTo(stu.marks); } } And then we pass the set to the TreeSet constructor to sort the elements. // TreeSet to sort LinkedHashSet using comparable TreeSet<Student> tree_set = new TreeSet<>(set); Below is the full implementation of the above approach: Example 1: Java // Java program to demonstrate how to Sort HashSet using// Comparable interface import java.util.*; // Student class implements comparable interfaceclass Student implements Comparable<Student> { Integer marks; Student(Integer marks) { this.marks = marks; } // override toString method public String toString() { return (" " + this.marks); } // Override compareTo method to sort HashSet in // ascending order public int compareTo(Student stu) { return this.marks.compareTo(stu.marks); }} class GFG { public static void main(String[] args) { // New HashSet HashSet<Student> set = new HashSet<>(); // Adding elements to the set set.add(new Student(500)); set.add(new Student(300)); set.add(new Student(400)); set.add(new Student(100)); set.add(new Student(200)); // Print Before sort System.out.println("Before sort elements in ascending order : " + set); // TreeSet to sort HashSet using comparable // interface TreeSet<Student> tree_set = new TreeSet<>(set); // Print after sorting System.out.println("After sort elements in ascending order : " + tree_set); }} Before sort elements in ascending order : [ 300, 400, 500, 200, 100] After sort elements in ascending order : [ 100, 200, 300, 400, 500] Example 2: Java // Java program to demonstrate how to Sort HashSet using// Comparable interface import java.util.*; // Student class implements comparable interfaceclass Student implements Comparable<Student> { Integer marks; Student(Integer marks) { this.marks = marks; } // override toString method public String toString() { return (" " + this.marks); } // Override compareTo method to sort HashSet in // descending order public int compareTo(Student stu) { return stu.marks.compareTo(this.marks); }} class GFG { public static void main(String[] args) { // New HashSet HashSet<Student> set = new HashSet<>(); // Adding elements to the set set.add(new Student(500)); set.add(new Student(300)); set.add(new Student(400)); set.add(new Student(100)); set.add(new Student(200)); // Print Before sort System.out.println("Before sort elements in descending order : " + set); // TreeSet to sort HashSet using comparable // interface TreeSet<Student> tree_set = new TreeSet<>(set); // Print after sorting System.out.println("After sort elements in descending order : " + tree_set); }} Before sort elements in descending order : [ 300, 400, 500, 200, 100] After sort elements in descending order : [ 500, 400, 300, 200, 100] anikakapoor simmytarika5 Java-Collections Java-Comparable java-hashset Picked Java Java Programs Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Dec, 2021" }, { "code": null, "e": 314, "s": 28, "text": "The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means when we iterate the HashSet, there is no guarantee that we get elements in which order they were inserted." }, { "code": null, "e": 499, "s": 314, "text": "To sort HashSet elements using Comparable interface in java first, we create a class Student that implements the Comparable interface. In this class we override the compareTo() method." }, { "code": null, "e": 512, "s": 499, "text": "Pseudo Code:" }, { "code": null, "e": 980, "s": 512, "text": "// Student class implements comparable interface\n\nclass Student implements Comparable<Student> {\n Integer marks;\n \n Student(Integer marks) {\n this.marks = marks;\n }\n \n // override toString method\n public String toString() {\n return (\" \" + this.marks);\n }\n \n // Override compareTo method to sort LinkedHashSet in ascending order\n public int compareTo(Student stu) {\n return this.marks.compareTo(stu.marks);\n }\n}" }, { "code": null, "e": 1054, "s": 980, "text": "And then we pass the set to the TreeSet constructor to sort the elements." }, { "code": null, "e": 1153, "s": 1054, "text": "// TreeSet to sort LinkedHashSet using comparable\n\nTreeSet<Student> tree_set = new TreeSet<>(set);" }, { "code": null, "e": 1209, "s": 1153, "text": "Below is the full implementation of the above approach:" }, { "code": null, "e": 1220, "s": 1209, "text": "Example 1:" }, { "code": null, "e": 1225, "s": 1220, "text": "Java" }, { "code": "// Java program to demonstrate how to Sort HashSet using// Comparable interface import java.util.*; // Student class implements comparable interfaceclass Student implements Comparable<Student> { Integer marks; Student(Integer marks) { this.marks = marks; } // override toString method public String toString() { return (\" \" + this.marks); } // Override compareTo method to sort HashSet in // ascending order public int compareTo(Student stu) { return this.marks.compareTo(stu.marks); }} class GFG { public static void main(String[] args) { // New HashSet HashSet<Student> set = new HashSet<>(); // Adding elements to the set set.add(new Student(500)); set.add(new Student(300)); set.add(new Student(400)); set.add(new Student(100)); set.add(new Student(200)); // Print Before sort System.out.println(\"Before sort elements in ascending order : \" + set); // TreeSet to sort HashSet using comparable // interface TreeSet<Student> tree_set = new TreeSet<>(set); // Print after sorting System.out.println(\"After sort elements in ascending order : \" + tree_set); }}", "e": 2466, "s": 1225, "text": null }, { "code": null, "e": 2611, "s": 2466, "text": "Before sort elements in ascending order : [ 300, 400, 500, 200, 100]\nAfter sort elements in ascending order : [ 100, 200, 300, 400, 500]" }, { "code": null, "e": 2622, "s": 2611, "text": "Example 2:" }, { "code": null, "e": 2627, "s": 2622, "text": "Java" }, { "code": "// Java program to demonstrate how to Sort HashSet using// Comparable interface import java.util.*; // Student class implements comparable interfaceclass Student implements Comparable<Student> { Integer marks; Student(Integer marks) { this.marks = marks; } // override toString method public String toString() { return (\" \" + this.marks); } // Override compareTo method to sort HashSet in // descending order public int compareTo(Student stu) { return stu.marks.compareTo(this.marks); }} class GFG { public static void main(String[] args) { // New HashSet HashSet<Student> set = new HashSet<>(); // Adding elements to the set set.add(new Student(500)); set.add(new Student(300)); set.add(new Student(400)); set.add(new Student(100)); set.add(new Student(200)); // Print Before sort System.out.println(\"Before sort elements in descending order : \" + set); // TreeSet to sort HashSet using comparable // interface TreeSet<Student> tree_set = new TreeSet<>(set); // Print after sorting System.out.println(\"After sort elements in descending order : \" + tree_set); }}", "e": 3871, "s": 2627, "text": null }, { "code": null, "e": 4018, "s": 3871, "text": "Before sort elements in descending order : [ 300, 400, 500, 200, 100]\nAfter sort elements in descending order : [ 500, 400, 300, 200, 100]" }, { "code": null, "e": 4032, "s": 4020, "text": "anikakapoor" }, { "code": null, "e": 4045, "s": 4032, "text": "simmytarika5" }, { "code": null, "e": 4062, "s": 4045, "text": "Java-Collections" }, { "code": null, "e": 4078, "s": 4062, "text": "Java-Comparable" }, { "code": null, "e": 4091, "s": 4078, "text": "java-hashset" }, { "code": null, "e": 4098, "s": 4091, "text": "Picked" }, { "code": null, "e": 4103, "s": 4098, "text": "Java" }, { "code": null, "e": 4117, "s": 4103, "text": "Java Programs" }, { "code": null, "e": 4122, "s": 4117, "text": "Java" }, { "code": null, "e": 4139, "s": 4122, "text": "Java-Collections" }, { "code": null, "e": 4237, "s": 4139, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4252, "s": 4237, "text": "Stream In Java" }, { "code": null, "e": 4273, "s": 4252, "text": "Introduction to Java" }, { "code": null, "e": 4294, "s": 4273, "text": "Constructors in Java" }, { "code": null, "e": 4313, "s": 4294, "text": "Exceptions in Java" }, { "code": null, "e": 4330, "s": 4313, "text": "Generics in Java" }, { "code": null, "e": 4356, "s": 4330, "text": "Java Programming Examples" }, { "code": null, "e": 4390, "s": 4356, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4437, "s": 4390, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4475, "s": 4437, "text": "Factory method design pattern in Java" } ]
How to Break out of multiple loops in Python ?
21 Aug, 2021 In this article, we will see how to break out of multiple loops in Python. For example, we are given a list of lists arr and an integer x. The task is to iterate through each nested list in order and keep displaying the elements until an element equal to x is found. If such an element is found, an appropriate message is displayed and the code must stop displaying any more elements. Input: arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], x = 6 Output: 1 2 3 Element found Input: arr = [[10, 20, 30], [40, 50, 60, 70]], x = 50 Output: 10 20 30 40 Element found A direct approach to this problem is to iterate through all the elements of arr using a for loop and to use a nested for loop to iterate through all the elements of each of the nested lists in arr and keep printing them. If an element equal to x is encountered, the appropriate message is displayed and the code must break out of both the loops. However, if we simply use a single break statement, the code will only terminate the inner loop and the outer loop will continue to run, which we do not want to happen. Python3 def elementInArray(arr, x): # Iterating through all # lists present in arr: for i in arr: # Iterating through all the elements # of each of the nested lists in arr: for j in i: # Checking if any element in the # nested list is equal to x: if j == x: print('Element found') break else: print(j) # Driver Code:arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]x = 4elementInArray(arr, x) Output: 1 2 3 Element found 7 8 9 In the above case, as soon as 4 has been found, the break statement terminated the inner loop and all the other elements of the same nested list (5, 6) have been skipped, but the code didn’t terminate the outer loop which then proceeded to the next nested list and also printed all of its elements. Approach 1: Using the return statement Define a function and place the loops within that function. Using a return statement can directly end the function, thus breaking out of all the loops. Python3 # Python code to break out of# multiple loops by defining a# function and using return statement def elementInArray(arr, x): # Iterating through all # lists present in arr: for i in arr: # Iterating through all the elements # of each of the nested lists in arr: for j in i: # Checking if any element in the # nested list is equal to x and returning # the function if such element is found # else printing the element: if j == x: print('Element found') return else: print(j) # Driver Code:arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]x = 4elementInArray(arr, x) Output: 1 2 3 Element found Approach 2: Using else: continue An easier way to do the same is to use an else block containing a continue statement after the inner loop and then adding a break statement after the else block inside the outer loop. If the inner loop terminates due to a break statement given inside the inner loop, then the else block after the inner loop will not be executed and the break statement after the else block will terminate the outer loop also. On the other hand, if the inner loop completes without encountering any break statement then the else block containing the continue statement will be executed and the outer loop will continue to run. The idea is the same even if the number of loops increases. Python3 # Python code to break out of multiple# loops by using an else block def elementInArray(arr, x): # Iterating through all # lists present in arr: for i in arr: # Iterating through all the elements # of each of the nested lists in arr: for j in i: # Checking if any element in the # nested list is equal to x: if j == x: print('Element found') break else: print(j) # If the inner loop completes without encountering # the break statement then the following else # block will be executed and outer loop will # continue to the next value of i: else: continue # If the inner loop terminates due to the # break statement, the else block will not # be executed and the following break # statement will terminate the outer loop also: break # Driver Code:arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]x = 4elementInArray(arr, x) Output: 1 2 3 Element found Approach 3: Using a flag variable Another way of breaking out of multiple loops is to initialize a flag variable with a False value. The variable can be assigned a True value just before breaking out of the inner loop. The outer loop must contain an if block after the inner loop. The if block must check the value of the flag variable and contain a break statement. If the flag variable is True, then the if block will be executed and will break out of the inner loop also. Else, the outer loop will continue. Python3 # Python code to break out of multiple# loops by using a flag variable def elementInArray(arr, x): flag = False # Defining the flag variable # Iterating through all # lists present in arr: for i in arr: # Iterating through all the elements # of each of the nested lists in arr: for j in i: # Checking if any element in the # nested list is equal to x # and assigning True value to # flag if the condition is met # else printing the element j: if j == x: flag = True print('Element found') break else: print(j) # If the inner loop terminates due to # the break statement and flag is True # then the following if block will # be executed and the break statement in it # will also terminate the outer loop. Else, # the outer loop will continue: if flag == True: break # Driver Code:arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]x = 4elementInArray(arr, x) Output: 1 2 3 Element found prakharguptadpskuwait python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON 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": 53, "s": 25, "text": "\n21 Aug, 2021" }, { "code": null, "e": 438, "s": 53, "text": "In this article, we will see how to break out of multiple loops in Python. For example, we are given a list of lists arr and an integer x. The task is to iterate through each nested list in order and keep displaying the elements until an element equal to x is found. If such an element is found, an appropriate message is displayed and the code must stop displaying any more elements." }, { "code": null, "e": 608, "s": 438, "text": "Input: arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], x = 6\nOutput:\n1\n2\n3\nElement found\nInput: arr = [[10, 20, 30], [40, 50, 60, 70]], x = 50\nOutput:\n10\n20\n30\n40\nElement found" }, { "code": null, "e": 954, "s": 608, "text": "A direct approach to this problem is to iterate through all the elements of arr using a for loop and to use a nested for loop to iterate through all the elements of each of the nested lists in arr and keep printing them. If an element equal to x is encountered, the appropriate message is displayed and the code must break out of both the loops." }, { "code": null, "e": 1124, "s": 954, "text": "However, if we simply use a single break statement, the code will only terminate the inner loop and the outer loop will continue to run, which we do not want to happen. " }, { "code": null, "e": 1132, "s": 1124, "text": "Python3" }, { "code": "def elementInArray(arr, x): # Iterating through all # lists present in arr: for i in arr: # Iterating through all the elements # of each of the nested lists in arr: for j in i: # Checking if any element in the # nested list is equal to x: if j == x: print('Element found') break else: print(j) # Driver Code:arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]x = 4elementInArray(arr, x)", "e": 1636, "s": 1132, "text": null }, { "code": null, "e": 1644, "s": 1636, "text": "Output:" }, { "code": null, "e": 1670, "s": 1644, "text": "1\n2\n3\nElement found\n7\n8\n9" }, { "code": null, "e": 1969, "s": 1670, "text": "In the above case, as soon as 4 has been found, the break statement terminated the inner loop and all the other elements of the same nested list (5, 6) have been skipped, but the code didn’t terminate the outer loop which then proceeded to the next nested list and also printed all of its elements." }, { "code": null, "e": 2008, "s": 1969, "text": "Approach 1: Using the return statement" }, { "code": null, "e": 2160, "s": 2008, "text": "Define a function and place the loops within that function. Using a return statement can directly end the function, thus breaking out of all the loops." }, { "code": null, "e": 2168, "s": 2160, "text": "Python3" }, { "code": "# Python code to break out of# multiple loops by defining a# function and using return statement def elementInArray(arr, x): # Iterating through all # lists present in arr: for i in arr: # Iterating through all the elements # of each of the nested lists in arr: for j in i: # Checking if any element in the # nested list is equal to x and returning # the function if such element is found # else printing the element: if j == x: print('Element found') return else: print(j) # Driver Code:arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]x = 4elementInArray(arr, x)", "e": 2875, "s": 2168, "text": null }, { "code": null, "e": 2883, "s": 2875, "text": "Output:" }, { "code": null, "e": 2903, "s": 2883, "text": "1\n2\n3\nElement found" }, { "code": null, "e": 2936, "s": 2903, "text": "Approach 2: Using else: continue" }, { "code": null, "e": 3606, "s": 2936, "text": "An easier way to do the same is to use an else block containing a continue statement after the inner loop and then adding a break statement after the else block inside the outer loop. If the inner loop terminates due to a break statement given inside the inner loop, then the else block after the inner loop will not be executed and the break statement after the else block will terminate the outer loop also. On the other hand, if the inner loop completes without encountering any break statement then the else block containing the continue statement will be executed and the outer loop will continue to run. The idea is the same even if the number of loops increases." }, { "code": null, "e": 3614, "s": 3606, "text": "Python3" }, { "code": "# Python code to break out of multiple# loops by using an else block def elementInArray(arr, x): # Iterating through all # lists present in arr: for i in arr: # Iterating through all the elements # of each of the nested lists in arr: for j in i: # Checking if any element in the # nested list is equal to x: if j == x: print('Element found') break else: print(j) # If the inner loop completes without encountering # the break statement then the following else # block will be executed and outer loop will # continue to the next value of i: else: continue # If the inner loop terminates due to the # break statement, the else block will not # be executed and the following break # statement will terminate the outer loop also: break # Driver Code:arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]x = 4elementInArray(arr, x)", "e": 4668, "s": 3614, "text": null }, { "code": null, "e": 4676, "s": 4668, "text": "Output:" }, { "code": null, "e": 4696, "s": 4676, "text": "1\n2\n3\nElement found" }, { "code": null, "e": 4730, "s": 4696, "text": "Approach 3: Using a flag variable" }, { "code": null, "e": 5207, "s": 4730, "text": "Another way of breaking out of multiple loops is to initialize a flag variable with a False value. The variable can be assigned a True value just before breaking out of the inner loop. The outer loop must contain an if block after the inner loop. The if block must check the value of the flag variable and contain a break statement. If the flag variable is True, then the if block will be executed and will break out of the inner loop also. Else, the outer loop will continue." }, { "code": null, "e": 5215, "s": 5207, "text": "Python3" }, { "code": "# Python code to break out of multiple# loops by using a flag variable def elementInArray(arr, x): flag = False # Defining the flag variable # Iterating through all # lists present in arr: for i in arr: # Iterating through all the elements # of each of the nested lists in arr: for j in i: # Checking if any element in the # nested list is equal to x # and assigning True value to # flag if the condition is met # else printing the element j: if j == x: flag = True print('Element found') break else: print(j) # If the inner loop terminates due to # the break statement and flag is True # then the following if block will # be executed and the break statement in it # will also terminate the outer loop. Else, # the outer loop will continue: if flag == True: break # Driver Code:arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]x = 4elementInArray(arr, x)", "e": 6320, "s": 5215, "text": null }, { "code": null, "e": 6328, "s": 6320, "text": "Output:" }, { "code": null, "e": 6348, "s": 6328, "text": "1\n2\n3\nElement found" }, { "code": null, "e": 6370, "s": 6348, "text": "prakharguptadpskuwait" }, { "code": null, "e": 6384, "s": 6370, "text": "python-basics" }, { "code": null, "e": 6391, "s": 6384, "text": "Python" }, { "code": null, "e": 6489, "s": 6391, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6521, "s": 6489, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6548, "s": 6521, "text": "Python Classes and Objects" }, { "code": null, "e": 6579, "s": 6548, "text": "Python | os.path.join() method" }, { "code": null, "e": 6600, "s": 6579, "text": "Python OOPs Concepts" }, { "code": null, "e": 6656, "s": 6600, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 6679, "s": 6656, "text": "Introduction To PYTHON" }, { "code": null, "e": 6721, "s": 6679, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 6763, "s": 6721, "text": "Check if element exists in list in Python" }, { "code": null, "e": 6802, "s": 6763, "text": "Python | datetime.timedelta() function" } ]
How to merge R DataFrames of different length ?
06 Aug, 2021 In this article, we will discuss how to combine two dataframes of different length and make one final dataframe in the R Programming language. Create first dataframe Create second dataframe Use any function from the given below and combine them Display dataset so created R has an inbuilt function called merge which combines two dataframe of different lengths automatically. Syntax: merge(dataframe1, dataframe 2) Example: R # 1st Dataframeemp.data <- data.frame( emp_id = c (1:5), emp_name = c("Ryan","Sita","Ram","Raj","Gargi"), salary = c(62.3,151,311.0,429.0,822.25) ) # 2nd Dataframedf2 <- data.frame( height = c ("5'3","5'11","4'9","6"), weight = c(55.8,68,89,42.9) ) merge(emp.data, df2) Output: emp_id emp_name salary height weight 1 1 Ryan 62.30 5’3 55.8 2 2 Sita 151.00 5’3 55.8 3 3 Ram 311.00 5’3 55.8 4 4 Raj 429.00 5’3 55.8 5 5 Gargi 822.25 5’3 55.8 6 1 Ryan 62.30 5’11 68.0 7 2 Sita 151.00 5’11 68.0 8 3 Ram 311.00 5’11 68.0 9 4 Raj 429.00 5’11 68.0 10 5 Gargi 822.25 5’11 68.0 11 1 Ryan 62.30 4’9 89.0 12 2 Sita 151.00 4’9 89.0 13 3 Ram 311.00 4’9 89.0 14 4 Raj 429.00 4’9 89.0 15 5 Gargi 822.25 4’9 89.0 16 1 Ryan 62.30 6 42.9 17 2 Sita 151.00 6 42.9 18 3 Ram 311.00 6 42.9 19 4 Raj 429.00 6 42.9 20 5 Gargi 822.25 6 42.9 In this we will create a column named id for both the dataframes and combine the dataframes by the column id. Syntax: cbind(x1, x2, ..., deparse.level = 1) Parameters: x1, x2: vector, matrix, data frames deparse.level: This value determines how the column names generated. The default value of deparse.level is 1. Example: R # 1st Dataframeemp.data <- data.frame( emp_id = c (1:5), emp_name = c("Ryan","Sita","Ram","Raj","Gargi"), salary = c(62.3,151,311.0,429.0,822.25) ) # 2nd Dataframedf2 <- data.frame( height = c ("5'3","5'11","4'9","6"), weight = c(55.8,68,89,42.9) ) # creating the column id for dataframe 1emp.data = cbind("id"=rownames(emp.data),emp.data) # creating column id for dataframe 2df2 = cbind("id"=rownames(df2),df2) merge(emp.data,df2,all=T) Output : id emp_id emp_name salary height weight 1 1 Ryan 62.30 5’3 55.8 2 2 Sita 151.00 5’11 68.0 3 3 Ram 311.00 4’9 89.0 4 4 Raj 429.00 6 42.9 5 5 Gargi 822.25 <NA> NA adnanirshad158 Picked R DataFrame-Programs R-DataFrame 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? How to filter R DataFrame by values in a column? 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": "\n06 Aug, 2021" }, { "code": null, "e": 172, "s": 28, "text": "In this article, we will discuss how to combine two dataframes of different length and make one final dataframe in the R Programming language. " }, { "code": null, "e": 195, "s": 172, "text": "Create first dataframe" }, { "code": null, "e": 219, "s": 195, "text": "Create second dataframe" }, { "code": null, "e": 274, "s": 219, "text": "Use any function from the given below and combine them" }, { "code": null, "e": 301, "s": 274, "text": "Display dataset so created" }, { "code": null, "e": 405, "s": 301, "text": "R has an inbuilt function called merge which combines two dataframe of different lengths automatically." }, { "code": null, "e": 413, "s": 405, "text": "Syntax:" }, { "code": null, "e": 444, "s": 413, "text": "merge(dataframe1, dataframe 2)" }, { "code": null, "e": 453, "s": 444, "text": "Example:" }, { "code": null, "e": 455, "s": 453, "text": "R" }, { "code": "# 1st Dataframeemp.data <- data.frame( emp_id = c (1:5), emp_name = c(\"Ryan\",\"Sita\",\"Ram\",\"Raj\",\"Gargi\"), salary = c(62.3,151,311.0,429.0,822.25) ) # 2nd Dataframedf2 <- data.frame( height = c (\"5'3\",\"5'11\",\"4'9\",\"6\"), weight = c(55.8,68,89,42.9) ) merge(emp.data, df2)", "e": 751, "s": 455, "text": null }, { "code": null, "e": 762, "s": 754, "text": "Output:" }, { "code": null, "e": 799, "s": 762, "text": "emp_id emp_name salary height weight" }, { "code": null, "e": 839, "s": 799, "text": "1 1 Ryan 62.30 5’3 55.8" }, { "code": null, "e": 879, "s": 839, "text": "2 2 Sita 151.00 5’3 55.8" }, { "code": null, "e": 919, "s": 879, "text": "3 3 Ram 311.00 5’3 55.8" }, { "code": null, "e": 959, "s": 919, "text": "4 4 Raj 429.00 5’3 55.8" }, { "code": null, "e": 999, "s": 959, "text": "5 5 Gargi 822.25 5’3 55.8" }, { "code": null, "e": 1039, "s": 999, "text": "6 1 Ryan 62.30 5’11 68.0" }, { "code": null, "e": 1079, "s": 1039, "text": "7 2 Sita 151.00 5’11 68.0" }, { "code": null, "e": 1119, "s": 1079, "text": "8 3 Ram 311.00 5’11 68.0" }, { "code": null, "e": 1159, "s": 1119, "text": "9 4 Raj 429.00 5’11 68.0" }, { "code": null, "e": 1199, "s": 1159, "text": "10 5 Gargi 822.25 5’11 68.0" }, { "code": null, "e": 1239, "s": 1199, "text": "11 1 Ryan 62.30 4’9 89.0" }, { "code": null, "e": 1279, "s": 1239, "text": "12 2 Sita 151.00 4’9 89.0" }, { "code": null, "e": 1319, "s": 1279, "text": "13 3 Ram 311.00 4’9 89.0" }, { "code": null, "e": 1359, "s": 1319, "text": "14 4 Raj 429.00 4’9 89.0" }, { "code": null, "e": 1399, "s": 1359, "text": "15 5 Gargi 822.25 4’9 89.0" }, { "code": null, "e": 1439, "s": 1399, "text": "16 1 Ryan 62.30 6 42.9" }, { "code": null, "e": 1479, "s": 1439, "text": "17 2 Sita 151.00 6 42.9" }, { "code": null, "e": 1519, "s": 1479, "text": "18 3 Ram 311.00 6 42.9" }, { "code": null, "e": 1559, "s": 1519, "text": "19 4 Raj 429.00 6 42.9" }, { "code": null, "e": 1599, "s": 1559, "text": "20 5 Gargi 822.25 6 42.9" }, { "code": null, "e": 1710, "s": 1599, "text": " In this we will create a column named id for both the dataframes and combine the dataframes by the column id." }, { "code": null, "e": 1756, "s": 1710, "text": "Syntax: cbind(x1, x2, ..., deparse.level = 1)" }, { "code": null, "e": 1768, "s": 1756, "text": "Parameters:" }, { "code": null, "e": 1804, "s": 1768, "text": "x1, x2: vector, matrix, data frames" }, { "code": null, "e": 1914, "s": 1804, "text": "deparse.level: This value determines how the column names generated. The default value of deparse.level is 1." }, { "code": null, "e": 1924, "s": 1914, "text": " Example:" }, { "code": null, "e": 1926, "s": 1924, "text": "R" }, { "code": "# 1st Dataframeemp.data <- data.frame( emp_id = c (1:5), emp_name = c(\"Ryan\",\"Sita\",\"Ram\",\"Raj\",\"Gargi\"), salary = c(62.3,151,311.0,429.0,822.25) ) # 2nd Dataframedf2 <- data.frame( height = c (\"5'3\",\"5'11\",\"4'9\",\"6\"), weight = c(55.8,68,89,42.9) ) # creating the column id for dataframe 1emp.data = cbind(\"id\"=rownames(emp.data),emp.data) # creating column id for dataframe 2df2 = cbind(\"id\"=rownames(df2),df2) merge(emp.data,df2,all=T)", "e": 2390, "s": 1926, "text": null }, { "code": null, "e": 2402, "s": 2393, "text": "Output :" }, { "code": null, "e": 2442, "s": 2402, "text": "id emp_id emp_name salary height weight" }, { "code": null, "e": 2481, "s": 2442, "text": "1 1 Ryan 62.30 5’3 55.8" }, { "code": null, "e": 2521, "s": 2481, "text": "2 2 Sita 151.00 5’11 68.0" }, { "code": null, "e": 2561, "s": 2521, "text": "3 3 Ram 311.00 4’9 89.0" }, { "code": null, "e": 2601, "s": 2561, "text": "4 4 Raj 429.00 6 42.9" }, { "code": null, "e": 2641, "s": 2601, "text": "5 5 Gargi 822.25 <NA> NA" }, { "code": null, "e": 2658, "s": 2643, "text": "adnanirshad158" }, { "code": null, "e": 2665, "s": 2658, "text": "Picked" }, { "code": null, "e": 2686, "s": 2665, "text": "R DataFrame-Programs" }, { "code": null, "e": 2698, "s": 2686, "text": "R-DataFrame" }, { "code": null, "e": 2709, "s": 2698, "text": "R Language" }, { "code": null, "e": 2720, "s": 2709, "text": "R Programs" }, { "code": null, "e": 2818, "s": 2720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2870, "s": 2818, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2928, "s": 2870, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2963, "s": 2928, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3001, "s": 2963, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3050, "s": 3001, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3108, "s": 3050, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3157, "s": 3108, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3200, "s": 3157, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 3238, "s": 3200, "text": "Merge DataFrames by Column Names in R" } ]
Python Bokeh – Making Interactive Legends
28 Jul, 2020 Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. The legend of a graph reflects the data displayed in the graph’s Y-axis. In Bokeh, the legends correspond to glyphs. There are two ways to make legends interactive: Hiding Muting A Glyph can be hidden from the legend by setting the legend click_policy property to “hide”. Example : Python3 # importing the modules from bokeh.plotting import figure, output_file, show # file to save the model output_file("gfg.html") # instantiating the figure object graph = figure(title = "Bokeh Hiding Glyphs") # plotting the graphgraph.vbar(x = 1, top = 5, width = 1, color = "violet", legend_label = "Violet Bar")graph.vbar(x = 2, top = 5, width = 1, color = "green", legend_label = "Green Bar")graph.vbar(x = 3, top = 5, width = 1, color = "yellow", legend_label = "Yellow Bar")graph.vbar(x = 4, top = 5, width = 1, color = "red", legend_label = "Red Bar") # enable hiding of the glyphsgraph.legend.click_policy = "hide" # displaying the model show(graph) Output : Hiding the glyph makes it vanish completely, on the other hand, muting the glyph just de-emphasizes the glyph based on the parameters. A Glyph can be muted from the legend by setting the legend click_policy property to “mute”. Python3 # importing the modules from bokeh.plotting import figure, output_file, show # file to save the model output_file("gfg.html") # instantiating the figure object graph = figure(title = "Bokeh Hiding Glyphs") # plotting the graphgraph.vbar(x = 1, top = 5, width = 1, color = "violet", legend_label = "Violet Bar", muted_alpha=0.2)graph.vbar(x = 2, top = 5, width = 1, color = "green", legend_label = "Green Bar", muted_alpha=0.2)graph.vbar(x = 3, top = 5, width = 1, color = "yellow", legend_label = "Yellow Bar", muted_alpha=0.2)graph.vbar(x = 4, top = 5, width = 1, color = "red", legend_label = "Red Bar", muted_alpha=0.2) # enable hiding of the glyphsgraph.legend.click_policy = "mute" # displaying the model show(graph) Output : Python-Bokeh 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 Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2020" }, { "code": null, "e": 269, "s": 28, "text": "Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity." }, { "code": null, "e": 435, "s": 269, "text": "The legend of a graph reflects the data displayed in the graph’s Y-axis. In Bokeh, the legends correspond to glyphs. There are two ways to make legends interactive: " }, { "code": null, "e": 442, "s": 435, "text": "Hiding" }, { "code": null, "e": 449, "s": 442, "text": "Muting" }, { "code": null, "e": 542, "s": 449, "text": "A Glyph can be hidden from the legend by setting the legend click_policy property to “hide”." }, { "code": null, "e": 552, "s": 542, "text": "Example :" }, { "code": null, "e": 560, "s": 552, "text": "Python3" }, { "code": "# importing the modules from bokeh.plotting import figure, output_file, show # file to save the model output_file(\"gfg.html\") # instantiating the figure object graph = figure(title = \"Bokeh Hiding Glyphs\") # plotting the graphgraph.vbar(x = 1, top = 5, width = 1, color = \"violet\", legend_label = \"Violet Bar\")graph.vbar(x = 2, top = 5, width = 1, color = \"green\", legend_label = \"Green Bar\")graph.vbar(x = 3, top = 5, width = 1, color = \"yellow\", legend_label = \"Yellow Bar\")graph.vbar(x = 4, top = 5, width = 1, color = \"red\", legend_label = \"Red Bar\") # enable hiding of the glyphsgraph.legend.click_policy = \"hide\" # displaying the model show(graph) ", "e": 1314, "s": 560, "text": null }, { "code": null, "e": 1324, "s": 1314, "text": "Output : " }, { "code": null, "e": 1552, "s": 1324, "text": "Hiding the glyph makes it vanish completely, on the other hand, muting the glyph just de-emphasizes the glyph based on the parameters. A Glyph can be muted from the legend by setting the legend click_policy property to “mute”. " }, { "code": null, "e": 1560, "s": 1552, "text": "Python3" }, { "code": "# importing the modules from bokeh.plotting import figure, output_file, show # file to save the model output_file(\"gfg.html\") # instantiating the figure object graph = figure(title = \"Bokeh Hiding Glyphs\") # plotting the graphgraph.vbar(x = 1, top = 5, width = 1, color = \"violet\", legend_label = \"Violet Bar\", muted_alpha=0.2)graph.vbar(x = 2, top = 5, width = 1, color = \"green\", legend_label = \"Green Bar\", muted_alpha=0.2)graph.vbar(x = 3, top = 5, width = 1, color = \"yellow\", legend_label = \"Yellow Bar\", muted_alpha=0.2)graph.vbar(x = 4, top = 5, width = 1, color = \"red\", legend_label = \"Red Bar\", muted_alpha=0.2) # enable hiding of the glyphsgraph.legend.click_policy = \"mute\" # displaying the model show(graph) ", "e": 2422, "s": 1560, "text": null }, { "code": null, "e": 2433, "s": 2422, "text": "Output : " }, { "code": null, "e": 2446, "s": 2433, "text": "Python-Bokeh" }, { "code": null, "e": 2453, "s": 2446, "text": "Python" }, { "code": null, "e": 2551, "s": 2453, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2579, "s": 2551, "text": "Read JSON file using Python" }, { "code": null, "e": 2629, "s": 2579, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2651, "s": 2629, "text": "Python map() function" }, { "code": null, "e": 2695, "s": 2651, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2713, "s": 2695, "text": "Python Dictionary" }, { "code": null, "e": 2755, "s": 2713, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2778, "s": 2755, "text": "Taking input in Python" }, { "code": null, "e": 2800, "s": 2778, "text": "Enumerate() in Python" }, { "code": null, "e": 2835, "s": 2800, "text": "Read a file line by line in Python" } ]
C program to create Indian National Flag using Graphics - GeeksforGeeks
01 Apr, 2021 In this article, we will discuss how to draw the Indian National Flag using Graphics. Approach: Draw a rectangle using the function rectangle(). Equally, divide the above rectangle into three parts by creating the line using the function line(). Draw double lines on each other i.e., draw 4 lines and among them, 2 lines will act as a divider between Red (Light red as there is no direct saffron color present in the graphics library) & White, and the other 2 lines will divide White and Green color. The Ashoka Chakra will be made using the function circle(). To finish, all the spaces will be filled using the functions setfillstyle() and floodfill(). Below is the implementation of the above approach: C // C program for the above approach #include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ // Initialize of gdriver with // DETECT macros initgraph(&gd, &gm, "C:\\turboc3\\bgi"); // Creating the base rectangle line(250, 100, 250, 600); line(250, 100, 250, 600); // Fil the White Color setfillstyle(SOLID_FILL, WHITE); // Create and fill the top strip rectangle(225, 600, 275, 610); rectangle(200, 610, 300, 620); floodfill(227, 608, 15); floodfill(202, 618, 15); // Fill the Light Red Color setfillstyle(SOLID_FILL, LIGHTRED); // Create and fill the ashoka // chakra with Blue rectangle(250, 100, 650, 280); line(250, 160, 650, 160); floodfill(252, 158, 15); // Fill the Blue Color setfillstyle(SOLID_FILL, BLUE); // Create and fill the left // part of the middle strip // Create a Circle circle(450, 190, 30); floodfill(452, 188, 15); // Fill the White Color setfillstyle(SOLID_FILL, WHITE); // Create and fill the right // part of the middle strip line(250, 160, 480, 160); line(250, 220, 480, 220); floodfill(252, 162, 15); // Fill the White Color setfillstyle(SOLID_FILL, WHITE); // Create and fill the bottom // strip line(480, 160, 650, 160); line(480, 220, 650, 220); floodfill(482, 162, 15); // Fill the Green Color setfillstyle(SOLID_FILL, GREEN); line(250, 220, 650, 220); floodfill(252, 278, 15); // Close the initialized gdriver closegraph();} Output: c-graphics computer-graphics C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C 'this' pointer in C++ Exception Handling in C++ Multithreading in C UDP Server-Client implementation in C Strings in C UDP Server-Client implementation in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses
[ { "code": null, "e": 24153, "s": 24125, "text": "\n01 Apr, 2021" }, { "code": null, "e": 24239, "s": 24153, "text": "In this article, we will discuss how to draw the Indian National Flag using Graphics." }, { "code": null, "e": 24249, "s": 24239, "text": "Approach:" }, { "code": null, "e": 24298, "s": 24249, "text": "Draw a rectangle using the function rectangle()." }, { "code": null, "e": 24399, "s": 24298, "text": "Equally, divide the above rectangle into three parts by creating the line using the function line()." }, { "code": null, "e": 24654, "s": 24399, "text": "Draw double lines on each other i.e., draw 4 lines and among them, 2 lines will act as a divider between Red (Light red as there is no direct saffron color present in the graphics library) & White, and the other 2 lines will divide White and Green color." }, { "code": null, "e": 24714, "s": 24654, "text": "The Ashoka Chakra will be made using the function circle()." }, { "code": null, "e": 24807, "s": 24714, "text": "To finish, all the spaces will be filled using the functions setfillstyle() and floodfill()." }, { "code": null, "e": 24858, "s": 24807, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 24860, "s": 24858, "text": "C" }, { "code": "// C program for the above approach #include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ // Initialize of gdriver with // DETECT macros initgraph(&gd, &gm, \"C:\\\\turboc3\\\\bgi\"); // Creating the base rectangle line(250, 100, 250, 600); line(250, 100, 250, 600); // Fil the White Color setfillstyle(SOLID_FILL, WHITE); // Create and fill the top strip rectangle(225, 600, 275, 610); rectangle(200, 610, 300, 620); floodfill(227, 608, 15); floodfill(202, 618, 15); // Fill the Light Red Color setfillstyle(SOLID_FILL, LIGHTRED); // Create and fill the ashoka // chakra with Blue rectangle(250, 100, 650, 280); line(250, 160, 650, 160); floodfill(252, 158, 15); // Fill the Blue Color setfillstyle(SOLID_FILL, BLUE); // Create and fill the left // part of the middle strip // Create a Circle circle(450, 190, 30); floodfill(452, 188, 15); // Fill the White Color setfillstyle(SOLID_FILL, WHITE); // Create and fill the right // part of the middle strip line(250, 160, 480, 160); line(250, 220, 480, 220); floodfill(252, 162, 15); // Fill the White Color setfillstyle(SOLID_FILL, WHITE); // Create and fill the bottom // strip line(480, 160, 650, 160); line(480, 220, 650, 220); floodfill(482, 162, 15); // Fill the Green Color setfillstyle(SOLID_FILL, GREEN); line(250, 220, 650, 220); floodfill(252, 278, 15); // Close the initialized gdriver closegraph();}", "e": 26421, "s": 24860, "text": null }, { "code": null, "e": 26429, "s": 26421, "text": "Output:" }, { "code": null, "e": 26440, "s": 26429, "text": "c-graphics" }, { "code": null, "e": 26458, "s": 26440, "text": "computer-graphics" }, { "code": null, "e": 26469, "s": 26458, "text": "C Language" }, { "code": null, "e": 26480, "s": 26469, "text": "C Programs" }, { "code": null, "e": 26578, "s": 26480, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26587, "s": 26578, "text": "Comments" }, { "code": null, "e": 26600, "s": 26587, "text": "Old Comments" }, { "code": null, "e": 26638, "s": 26600, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26660, "s": 26638, "text": "'this' pointer in C++" }, { "code": null, "e": 26686, "s": 26660, "text": "Exception Handling in C++" }, { "code": null, "e": 26706, "s": 26686, "text": "Multithreading in C" }, { "code": null, "e": 26744, "s": 26706, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26757, "s": 26744, "text": "Strings in C" }, { "code": null, "e": 26795, "s": 26757, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26836, "s": 26795, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26877, "s": 26836, "text": "C Program to read contents of Whole File" } ]
Cassandra - CQL User Defined Datatypes
CQL provides the facility of creating and using user-defined data types. You can create a data type to handle multiple fields. This chapter explains how to create, alter, and delete a user-defined data type. The command CREATE TYPE is used to create a user-defined data type. Its syntax is as follows − CREATE TYPE <keyspace name>. <data typename> ( variable1, variable2). Given below is an example for creating a user-defined data type. In this example, we are creating a card_details data type containing the following details. cqlsh:tutorialspoint> CREATE TYPE card_details ( ... num int, ... pin int, ... name text, ... cvv int, ... phone set<int> ... ); Note − The name used for user-defined data type should not coincide with reserved type names. Use the DESCRIBE command to verify whether the type created has been created or not. CREATE TYPE tutorialspoint.card_details ( num int, pin int, name text, cvv int, phone set<int> ); ALTER TYPE − command is used to alter an existing data type. Using ALTER, you can add a new field or rename an existing field. Use the following syntax to add a new field to an existing user-defined data type. ALTER TYPE typename ADD field_name field_type; The following code adds a new field to the Card_details data type. Here we are adding a new field called email. cqlsh:tutorialspoint> ALTER TYPE card_details ADD email text; Use the DESCRIBE command to verify whether the new field is added or not. cqlsh:tutorialspoint> describe type card_details; CREATE TYPE tutorialspoint.card_details ( num int, pin int, name text, cvv int, phone set<int>, ); Use the following syntax to rename an existing user-defined data type. ALTER TYPE typename RENAME existing_name TO new_name; The following code changes the name of the field in a type. Here we are renaming the field email to mail. cqlsh:tutorialspoint> ALTER TYPE card_details RENAME email TO mail; Use the DESCRIBE command to verify whether the type name changed or not. cqlsh:tutorialspoint> describe type card_details; CREATE TYPE tutorialspoint.card_details ( num int, pin int, name text, cvv int, phone set<int>, mail text ); DROP TYPE is the command used to delete a user-defined data type. Given below is an example to delete a user-defined data type. Before deleting, verify the list of all user-defined data types using DESCRIBE_TYPES command as shown below. cqlsh:tutorialspoint> DESCRIBE TYPES; card_details card From the two types, delete the type named card as shown below. cqlsh:tutorialspoint> drop type card; Use the DESCRIBE command to verify whether the data type dropped or not. cqlsh:tutorialspoint> describe types; card_details 27 Lectures 2 hours Navdeep Kaur 34 Lectures 1.5 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2495, "s": 2287, "text": "CQL provides the facility of creating and using user-defined data types. You can create a data type to handle multiple fields. This chapter explains how to create, alter, and delete a user-defined data type." }, { "code": null, "e": 2590, "s": 2495, "text": "The command CREATE TYPE is used to create a user-defined data type. Its syntax is as follows −" }, { "code": null, "e": 2661, "s": 2590, "text": "CREATE TYPE <keyspace name>. <data typename>\n( variable1, variable2).\n" }, { "code": null, "e": 2818, "s": 2661, "text": "Given below is an example for creating a user-defined data type. In this example, we are creating a card_details data type containing the following details." }, { "code": null, "e": 2963, "s": 2818, "text": "cqlsh:tutorialspoint> CREATE TYPE card_details (\n ... num int,\n ... pin int,\n ... name text,\n ... cvv int,\n ... phone set<int>\n... );\n" }, { "code": null, "e": 3057, "s": 2963, "text": "Note − The name used for user-defined data type should not coincide with reserved type names." }, { "code": null, "e": 3142, "s": 3057, "text": "Use the DESCRIBE command to verify whether the type created has been created or not." }, { "code": null, "e": 3259, "s": 3142, "text": "CREATE TYPE tutorialspoint.card_details (\n num int,\n pin int,\n name text,\n cvv int,\n phone set<int>\n );\n" }, { "code": null, "e": 3386, "s": 3259, "text": "ALTER TYPE − command is used to alter an existing data type. Using ALTER, you can add a new field or rename an existing field." }, { "code": null, "e": 3469, "s": 3386, "text": "Use the following syntax to add a new field to an existing user-defined data type." }, { "code": null, "e": 3518, "s": 3469, "text": "ALTER TYPE typename\nADD field_name field_type; \n" }, { "code": null, "e": 3630, "s": 3518, "text": "The following code adds a new field to the Card_details data type. Here we are adding a new field called email." }, { "code": null, "e": 3693, "s": 3630, "text": "cqlsh:tutorialspoint> ALTER TYPE card_details ADD email text;\n" }, { "code": null, "e": 3767, "s": 3693, "text": "Use the DESCRIBE command to verify whether the new field is added or not." }, { "code": null, "e": 3935, "s": 3767, "text": "cqlsh:tutorialspoint> describe type card_details;\nCREATE TYPE tutorialspoint.card_details (\n num int,\n pin int,\n name text,\n cvv int,\n phone set<int>,\n );\n" }, { "code": null, "e": 4006, "s": 3935, "text": "Use the following syntax to rename an existing user-defined data type." }, { "code": null, "e": 4061, "s": 4006, "text": "ALTER TYPE typename\nRENAME existing_name TO new_name;\n" }, { "code": null, "e": 4167, "s": 4061, "text": "The following code changes the name of the field in a type. Here we are renaming the field email to mail." }, { "code": null, "e": 4236, "s": 4167, "text": "cqlsh:tutorialspoint> ALTER TYPE card_details RENAME email TO mail;\n" }, { "code": null, "e": 4309, "s": 4236, "text": "Use the DESCRIBE command to verify whether the type name changed or not." }, { "code": null, "e": 4490, "s": 4309, "text": "cqlsh:tutorialspoint> describe type card_details;\nCREATE TYPE tutorialspoint.card_details (\n num int,\n pin int,\n name text,\n cvv int,\n phone set<int>,\n mail text\n );\n" }, { "code": null, "e": 4618, "s": 4490, "text": "DROP TYPE is the command used to delete a user-defined data type. Given below is an example to delete a user-defined data type." }, { "code": null, "e": 4727, "s": 4618, "text": "Before deleting, verify the list of all user-defined data types using DESCRIBE_TYPES command as shown below." }, { "code": null, "e": 4784, "s": 4727, "text": "cqlsh:tutorialspoint> DESCRIBE TYPES;\ncard_details card\n" }, { "code": null, "e": 4847, "s": 4784, "text": "From the two types, delete the type named card as shown below." }, { "code": null, "e": 4886, "s": 4847, "text": "cqlsh:tutorialspoint> drop type card;\n" }, { "code": null, "e": 4959, "s": 4886, "text": "Use the DESCRIBE command to verify whether the data type dropped or not." }, { "code": null, "e": 5012, "s": 4959, "text": "cqlsh:tutorialspoint> describe types;\n\ncard_details\n" }, { "code": null, "e": 5045, "s": 5012, "text": "\n 27 Lectures \n 2 hours \n" }, { "code": null, "e": 5059, "s": 5045, "text": " Navdeep Kaur" }, { "code": null, "e": 5094, "s": 5059, "text": "\n 34 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5112, "s": 5094, "text": " Bigdata Engineer" }, { "code": null, "e": 5119, "s": 5112, "text": " Print" }, { "code": null, "e": 5130, "s": 5119, "text": " Add Notes" } ]
How to shrink NumPy, SciPy, Pandas, and Matplotlib for your data product | by Scott Zelenka | Towards Data Science
If you’re a Data Scientist or Python developer deploying data products in a microservice framework, there’s a good chance you need to leverage the common scientific ecosystem modules of NumPy, SciPy, Pandas, or Matplotlib. The “micro” in microservice, suggests you should keep components as tiny as possible. However, these four modules are gargantuan when installed through PIP! Lets explore why NumPy, SciPy, Pandas, Matplotlib are so ginormous when installed through PIP, and devise a strategies (with source code) on how to optimize your data product inside a microservice framework. Most all data products I’ve been involved in are deployed through Docker, so this post will use that framework. Keeping inline with the “micro” of microservice framework, the very first Docker best practice centers around keeping your image size small. If you’re interested in general best practices for reducing the size of your Docker image, there are many posts on Medium. This post is going to focus entirely on shrinking the disk size consumed by NumPy, SciPy, Pandas, and Matplotlib. The general advice you may read on the Internet regarding NumPy, SciPy, Pandas, and Matplotlib, is to install them through your linux package manager (i.e. apt-get install -y python-numpy). However, in practice, those package managers often trail multiple versions behind the official releases published in PIP or GitHub. If your data product requires a specific version of these modules, this simply will not work. The Anaconda distribution does a decent job of compiling these libraries with a smaller footprint than PIP, so why not just use that Python distribution? In my experience, if you’re already at a state where you need a specific version of NumPy, SciPy, Pandas, or Matplotlib, there’s a good chance you need a specific version from another packages as well. The unfortunate news is that those other packages probably wont exist on the Conda repository. So simply using Anaconda or miniconda, and referencing the Conda repository will not satisfy your needs. Not to mention the additional bloat of Anaconda which you don’t need in your Docker image. Remember, we want to keep things as tiny as possible. To view the layer-by-layer impact of commands being ran to build your Docker image, the history command is very helpful: $ docker history shrink_linalgIMAGE CREATED CREATED BY SIZE COMMENT435802ee0f42 About a minute ago /bin/sh -c buildDeps='build-essential gcc gf... 508MB In the above, we can see that the one layer resulted in 508MB, when all we did in that layer was install NumPy, SciPy, Pandas, and Matplotlib with the command: pip install numpy==1.15.1 pandas==0.23.4 scipy==1.1.0 matplotlib==3.0.0 We can also look at the detailed package disk space consumed within the image with the du command: $ docker run shrink_linalg /bin/bash -c "du -sh /usr/local/lib/python3.6/site-packages/* | sort -h"...31M /usr/local/lib/python3.6/site-packages/matplotlib35M /usr/local/lib/python3.6/site-packages/numpy96M /usr/local/lib/python3.6/site-packages/pandas134M /usr/local/lib/python3.6/site-packages/scipy These modules are massive! You could argue that the capabilities of these modules are such that they need that much disk space. But they don’t need to be this large. We can remove a significant portion (up-to 60%) of unnecessary disk space consumed without impacting the performance of the modules themselves! One of the advantages of NumPy and SciPy, are the optimizations that have been done with regards to linear algebra methods. For this, there are a number of LinAlg optimizers. For this post, we’re just using OpenBLAS. But we’ll need to verify that NumPy and SciPy were installed to leverage this library. $ docker run shrink_linalg /bin/bash -c "python -c 'import numpy as np; np.__config__.show();'"...openblas_info: libraries = ['openblas', 'openblas'] library_dirs = ['/usr/lib'] language = c define_macros = [('HAVE_CBLAS', None)]... The important thing here is to have OpenBLAS recognized and mapped to the correct directory. This will enable NumPy and SciPy to leverage the LinAlg optimizations from that library. When installing through PIP within a Docker container, there’s no point in keeping around the cache. Lets add some flags to instruct PIP how to function. — no-cache-dirPIP uses caching to prevent duplicate HTTP requests to pull modules from the repository before installing on the local system. When running inside a Docker image, there’s no need to preserve this cache, so disable it with this flag. — compileCompile Python source files to bytecode. When running inside a Docker image, it’s highly unlikely that you’ll need to debug a mature installed module (such as NumPy, SciPy, Pandas, or Matplotlib). — global-option=build_extTo inform the C compiler we want to add additional flags during compile and link, we need to set these additional “global-option” flags. Python has a wrapper for C-Extension called Cython, which enables developers to write C code in a Python-like syntax. The advantage of this, is that it allows for a lot of the optimization of C, but with the ease of writing Python. NumPy, SciPy, and Pandas leverage Cython a lot! Matplotlib appears to contain some Cython as well, but to a much lesser extent. These compiler flags are passed to the GNU complier installed within your Dockerfile. To cut to the chase, we’re going to investigate only a handful of them: Disable debug statements (-g0)Because we’re sticking our data product into a Docker image, it’s highly unlikely we’ll be doing any real-time debugging of the Cython code from NumPy, SciPy, Pandas, or Matplotlib. Remove symbol files (-Wl, — strip-all)If we’re never going to debug the build of these packages within the Docker image, there’s no sense in keeping around the symbol files required for debugging either. Optimize for nearly all supported optimizations that do not involve a space-speed tradeoff (-O2) or Optimize for disk space (-Os)The challenge with these optimization flags is that while it can increase/decrease the disk size, it also manipulates the run-time performance of the compiled binary! Without explicitly testing the impact it has on our data product, these could be risky (but at the same time, they’re very efficient). Location of header files (-I/usr/include:/usr/local/include)Be explicit in telling GCC where to look for the header files needed to compile the Cython modules. Location of library files (-L/usr/lib:/usr/local/lib)Be explicit in telling GCC where to look for the library files needed to compile the Cython modules. But what’s the impact setting these CFLAG during install via PIP? The lack of debug information may cause experienced developers to raise caution, but if you really need them at a later date, you can always re-build the Docker image with the flag to reproduce any stacktrace or core dump happening. The larger concern is for exceptions which aren’t reproducible .. which would not be diagnosable without the symbol files. But again, nobody does that in a Docker image. Taking the best optimization CFLAG strategy, you can reduce the disk footprint of your Docker image by 60%! For my data products, I simply remove the debug/symbols and don’t perform any additional optimizations. If you’re curious how others perform similar CFLAG optimizations, check out the official Anaconda Recipes for NumPy, SciPy, Pandas, and Matplotlib. These are optimized to work within the Anaconda distribution of Python, and may or may not be relevant for your specific Docker data product deployment. Just because we were able to shrink the compiled binary of each module, we should do a sanity check to validate that the C compiler flags we used didn’t impact the performance of these modules. All of these packages leverage the pytest module, which we didn’t install in our Docker image because it provides no value in production. We can install it and execute the tests from inside though: NumPy tests inside our Docker image: $ docker run shrink_linalg /bin/bash -c "pip install pytest; python -c \"import numpy; numpy.test('full');\""4675 passed ... in 201.90 seconds SciPy tests inside our Docker image: $ docker run shrink_linalg /bin/bash -c "pip install pytest; python -c \"import scipy; scipy.test('full');\""13410 passed ... in 781.44 seconds Pandas tests inside our Docker image: $ docker run shrink_linalg /bin/bash -c "pip install pytest; python -c \"import pandas; pandas.test();\""22350 passed ... in 439.35 seconds There were quite a few tests skipped and xfailed, depending on your data product and/or version installed, these could be expected or you may want to investigate further. In most cases, if it’s not a hard failure it’s likely okay to proceed. Hopefully this will help guide you towards smaller Docker images when your data product requires NumPy, SciPy, Pandas, or Matplotlib! I encourage you to experiment with other CFLAG and test the disk space and unit test performance.
[ { "code": null, "e": 552, "s": 172, "text": "If you’re a Data Scientist or Python developer deploying data products in a microservice framework, there’s a good chance you need to leverage the common scientific ecosystem modules of NumPy, SciPy, Pandas, or Matplotlib. The “micro” in microservice, suggests you should keep components as tiny as possible. However, these four modules are gargantuan when installed through PIP!" }, { "code": null, "e": 760, "s": 552, "text": "Lets explore why NumPy, SciPy, Pandas, Matplotlib are so ginormous when installed through PIP, and devise a strategies (with source code) on how to optimize your data product inside a microservice framework." }, { "code": null, "e": 1250, "s": 760, "text": "Most all data products I’ve been involved in are deployed through Docker, so this post will use that framework. Keeping inline with the “micro” of microservice framework, the very first Docker best practice centers around keeping your image size small. If you’re interested in general best practices for reducing the size of your Docker image, there are many posts on Medium. This post is going to focus entirely on shrinking the disk size consumed by NumPy, SciPy, Pandas, and Matplotlib." }, { "code": null, "e": 1666, "s": 1250, "text": "The general advice you may read on the Internet regarding NumPy, SciPy, Pandas, and Matplotlib, is to install them through your linux package manager (i.e. apt-get install -y python-numpy). However, in practice, those package managers often trail multiple versions behind the official releases published in PIP or GitHub. If your data product requires a specific version of these modules, this simply will not work." }, { "code": null, "e": 2367, "s": 1666, "text": "The Anaconda distribution does a decent job of compiling these libraries with a smaller footprint than PIP, so why not just use that Python distribution? In my experience, if you’re already at a state where you need a specific version of NumPy, SciPy, Pandas, or Matplotlib, there’s a good chance you need a specific version from another packages as well. The unfortunate news is that those other packages probably wont exist on the Conda repository. So simply using Anaconda or miniconda, and referencing the Conda repository will not satisfy your needs. Not to mention the additional bloat of Anaconda which you don’t need in your Docker image. Remember, we want to keep things as tiny as possible." }, { "code": null, "e": 2488, "s": 2367, "text": "To view the layer-by-layer impact of commands being ran to build your Docker image, the history command is very helpful:" }, { "code": null, "e": 2731, "s": 2488, "text": "$ docker history shrink_linalgIMAGE CREATED CREATED BY SIZE COMMENT435802ee0f42 About a minute ago /bin/sh -c buildDeps='build-essential gcc gf... 508MB" }, { "code": null, "e": 2891, "s": 2731, "text": "In the above, we can see that the one layer resulted in 508MB, when all we did in that layer was install NumPy, SciPy, Pandas, and Matplotlib with the command:" }, { "code": null, "e": 2963, "s": 2891, "text": "pip install numpy==1.15.1 pandas==0.23.4 scipy==1.1.0 matplotlib==3.0.0" }, { "code": null, "e": 3062, "s": 2963, "text": "We can also look at the detailed package disk space consumed within the image with the du command:" }, { "code": null, "e": 3364, "s": 3062, "text": "$ docker run shrink_linalg /bin/bash -c \"du -sh /usr/local/lib/python3.6/site-packages/* | sort -h\"...31M /usr/local/lib/python3.6/site-packages/matplotlib35M /usr/local/lib/python3.6/site-packages/numpy96M /usr/local/lib/python3.6/site-packages/pandas134M /usr/local/lib/python3.6/site-packages/scipy" }, { "code": null, "e": 3674, "s": 3364, "text": "These modules are massive! You could argue that the capabilities of these modules are such that they need that much disk space. But they don’t need to be this large. We can remove a significant portion (up-to 60%) of unnecessary disk space consumed without impacting the performance of the modules themselves!" }, { "code": null, "e": 3978, "s": 3674, "text": "One of the advantages of NumPy and SciPy, are the optimizations that have been done with regards to linear algebra methods. For this, there are a number of LinAlg optimizers. For this post, we’re just using OpenBLAS. But we’ll need to verify that NumPy and SciPy were installed to leverage this library." }, { "code": null, "e": 4223, "s": 3978, "text": "$ docker run shrink_linalg /bin/bash -c \"python -c 'import numpy as np; np.__config__.show();'\"...openblas_info: libraries = ['openblas', 'openblas'] library_dirs = ['/usr/lib'] language = c define_macros = [('HAVE_CBLAS', None)]..." }, { "code": null, "e": 4405, "s": 4223, "text": "The important thing here is to have OpenBLAS recognized and mapped to the correct directory. This will enable NumPy and SciPy to leverage the LinAlg optimizations from that library." }, { "code": null, "e": 4559, "s": 4405, "text": "When installing through PIP within a Docker container, there’s no point in keeping around the cache. Lets add some flags to instruct PIP how to function." }, { "code": null, "e": 4806, "s": 4559, "text": "— no-cache-dirPIP uses caching to prevent duplicate HTTP requests to pull modules from the repository before installing on the local system. When running inside a Docker image, there’s no need to preserve this cache, so disable it with this flag." }, { "code": null, "e": 5012, "s": 4806, "text": "— compileCompile Python source files to bytecode. When running inside a Docker image, it’s highly unlikely that you’ll need to debug a mature installed module (such as NumPy, SciPy, Pandas, or Matplotlib)." }, { "code": null, "e": 5174, "s": 5012, "text": "— global-option=build_extTo inform the C compiler we want to add additional flags during compile and link, we need to set these additional “global-option” flags." }, { "code": null, "e": 5534, "s": 5174, "text": "Python has a wrapper for C-Extension called Cython, which enables developers to write C code in a Python-like syntax. The advantage of this, is that it allows for a lot of the optimization of C, but with the ease of writing Python. NumPy, SciPy, and Pandas leverage Cython a lot! Matplotlib appears to contain some Cython as well, but to a much lesser extent." }, { "code": null, "e": 5692, "s": 5534, "text": "These compiler flags are passed to the GNU complier installed within your Dockerfile. To cut to the chase, we’re going to investigate only a handful of them:" }, { "code": null, "e": 5904, "s": 5692, "text": "Disable debug statements (-g0)Because we’re sticking our data product into a Docker image, it’s highly unlikely we’ll be doing any real-time debugging of the Cython code from NumPy, SciPy, Pandas, or Matplotlib." }, { "code": null, "e": 6108, "s": 5904, "text": "Remove symbol files (-Wl, — strip-all)If we’re never going to debug the build of these packages within the Docker image, there’s no sense in keeping around the symbol files required for debugging either." }, { "code": null, "e": 6539, "s": 6108, "text": "Optimize for nearly all supported optimizations that do not involve a space-speed tradeoff (-O2) or Optimize for disk space (-Os)The challenge with these optimization flags is that while it can increase/decrease the disk size, it also manipulates the run-time performance of the compiled binary! Without explicitly testing the impact it has on our data product, these could be risky (but at the same time, they’re very efficient)." }, { "code": null, "e": 6699, "s": 6539, "text": "Location of header files (-I/usr/include:/usr/local/include)Be explicit in telling GCC where to look for the header files needed to compile the Cython modules." }, { "code": null, "e": 6853, "s": 6699, "text": "Location of library files (-L/usr/lib:/usr/local/lib)Be explicit in telling GCC where to look for the library files needed to compile the Cython modules." }, { "code": null, "e": 6919, "s": 6853, "text": "But what’s the impact setting these CFLAG during install via PIP?" }, { "code": null, "e": 7322, "s": 6919, "text": "The lack of debug information may cause experienced developers to raise caution, but if you really need them at a later date, you can always re-build the Docker image with the flag to reproduce any stacktrace or core dump happening. The larger concern is for exceptions which aren’t reproducible .. which would not be diagnosable without the symbol files. But again, nobody does that in a Docker image." }, { "code": null, "e": 7430, "s": 7322, "text": "Taking the best optimization CFLAG strategy, you can reduce the disk footprint of your Docker image by 60%!" }, { "code": null, "e": 7835, "s": 7430, "text": "For my data products, I simply remove the debug/symbols and don’t perform any additional optimizations. If you’re curious how others perform similar CFLAG optimizations, check out the official Anaconda Recipes for NumPy, SciPy, Pandas, and Matplotlib. These are optimized to work within the Anaconda distribution of Python, and may or may not be relevant for your specific Docker data product deployment." }, { "code": null, "e": 8029, "s": 7835, "text": "Just because we were able to shrink the compiled binary of each module, we should do a sanity check to validate that the C compiler flags we used didn’t impact the performance of these modules." }, { "code": null, "e": 8227, "s": 8029, "text": "All of these packages leverage the pytest module, which we didn’t install in our Docker image because it provides no value in production. We can install it and execute the tests from inside though:" }, { "code": null, "e": 8264, "s": 8227, "text": "NumPy tests inside our Docker image:" }, { "code": null, "e": 8407, "s": 8264, "text": "$ docker run shrink_linalg /bin/bash -c \"pip install pytest; python -c \\\"import numpy; numpy.test('full');\\\"\"4675 passed ... in 201.90 seconds" }, { "code": null, "e": 8444, "s": 8407, "text": "SciPy tests inside our Docker image:" }, { "code": null, "e": 8588, "s": 8444, "text": "$ docker run shrink_linalg /bin/bash -c \"pip install pytest; python -c \\\"import scipy; scipy.test('full');\\\"\"13410 passed ... in 781.44 seconds" }, { "code": null, "e": 8626, "s": 8588, "text": "Pandas tests inside our Docker image:" }, { "code": null, "e": 8766, "s": 8626, "text": "$ docker run shrink_linalg /bin/bash -c \"pip install pytest; python -c \\\"import pandas; pandas.test();\\\"\"22350 passed ... in 439.35 seconds" }, { "code": null, "e": 9008, "s": 8766, "text": "There were quite a few tests skipped and xfailed, depending on your data product and/or version installed, these could be expected or you may want to investigate further. In most cases, if it’s not a hard failure it’s likely okay to proceed." } ]
How to catch NotImplementedError Exception in Python?
User-defined base classes can raise NotImplementedError to indicate that a method or behavior needs to be defined by a subclass, simulating an interface. This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method. import sys try: class Super(object): @property def example(self): raise NotImplementedError("Subclasses should implement this!") s = Super() print s.example except Exception as e: print e print sys.exc_type Subclasses should implement this! <type 'exceptions.NotImplementedError'>
[ { "code": null, "e": 1394, "s": 1062, "text": "User-defined base classes can raise NotImplementedError to indicate that a method or behavior needs to be defined by a subclass, simulating an interface. This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method." }, { "code": null, "e": 1646, "s": 1394, "text": "import sys\ntry:\n class Super(object):\n @property\n def example(self):\n raise NotImplementedError(\"Subclasses should implement this!\")\n s = Super()\n print s.example\nexcept Exception as e:\n print e\n print sys.exc_type" }, { "code": null, "e": 1720, "s": 1646, "text": "Subclasses should implement this!\n<type 'exceptions.NotImplementedError'>" } ]
CallableStatement in JDBC Example | prepareCall() Example in JDBC
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to learn bout CallableStatement in JDBC. CallableStatement in JDBC is an interface, which is coming from the java.sql package. We have already discussed in the previous tutorial Steps by Step JDBC program example, statements in JDBC are 3 types. Here we are going to discuss one of the type called CallableStatement. CallableStatement in JDBC is a sub interface of PreparedStatement. CallableStatement in JDBC has all the benefits of PreparedStatement and also it has one more additional feature, that is we can call the procedures or functions of a database. CallableStatement is only for calling a procedure or a function of a database. But it is not for creating a procedure or function. CallableStatement has two syntaxes, one is for executing commands and another is for calling the procedure or function. We can get the CallableStatement object by calling the prepareCall() method on connection object. CallableStatement cstmt = connection.prepareCall("sql command"); CallableStatement cstmt = connection.prepareCall("{call procedure(args)}"); CallableStatement cstmt = connection.prepareCall("{?=call function(args)}"); Creating Procedure in MySql : mysql> delimiter $ mysql> create procedure square(IN a int, OUT b int) -> begin -> set b=a*a; -> end; -> $ Example: package com.onlinetutorialspoint.jdbc; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Types; public class JDBC_Procedures_Example { public static void main(String[] args) throws Exception { Connection connection = null; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/onlinetutorialspoint", "root", "123456"); CallableStatement cStmt = connection.prepareCall("{call square(?,?)}"); cStmt.setInt(1, 20); cStmt.registerOutParameter(2, Types.INTEGER); cStmt.execute(); System.out.println("The Square is : " + cStmt.getInt(2)); cStmt.close(); } } In the above code, we register the out parameter to CallableStatement by using the registerOutParameter(). It is mandatory because if we do not register the “out” parameter, then by default CallableStatement will take all the parameters as “in” parameters. So to inform CallableStatement that it is an out parameter we need to register it. While registering the out parameter, we need to tell the CallableStatement about the parameter type also. CallableStatement can understand only JDBC Types, but not java or database types. In JDBC Types class contains all the JDBC data types. Types is a class in java.sql package. Output : The Square is : 400 Creating Function in MySQL : mysql> DELIMITER $ mysql> CREATE FUNCTION mul(a int, b int) RETURNS INT -> BEGIN -> DECLARE c INT; -> SET c = a*b; -> RETURN c; -> END; -> $ Example: package com.onlinetutorialspoint.jdbc; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Types; class JDBC_Function_Example { public static void main(String[] args) throws Exception { Connection connection = null; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/onlinetutorialspoint", "root", "123456"); CallableStatement cStmt = connection.prepareCall("{?=call mul(?,?)}"); cStmt.registerOutParameter(1, Types.INTEGER); cStmt.setInt(2, 20); cStmt.setInt(3, 60); cStmt.execute(); System.out.println("The Multiplication is : " + cStmt.getInt(1)); cStmt.close(); } } Output: The Multiplication is : 1200 Happy Learning 🙂 JDBC Interview Questions and Answers JDBC Select Program Example JDBC Insert Program Example JDBC Update Program Example JDBC Delete Program Example JDBC PreparedStatement Example Program Insert an Image using JDBC in Mysql DB Read an Image in JDBC Example ResultSetMetaData in JDBC Example DatabaseMetaData in JDBC Example Transaction Management in JDBC Example Batch Processing in JDBC Example JDBC Connection with Properties file JDBC Scrollable ResultSet Example JDBC Updatable ResultSet Example JDBC Interview Questions and Answers JDBC Select Program Example JDBC Insert Program Example JDBC Update Program Example JDBC Delete Program Example JDBC PreparedStatement Example Program Insert an Image using JDBC in Mysql DB Read an Image in JDBC Example ResultSetMetaData in JDBC Example DatabaseMetaData in JDBC Example Transaction Management in JDBC Example Batch Processing in JDBC Example JDBC Connection with Properties file JDBC Scrollable ResultSet Example JDBC Updatable ResultSet Example Δ JDBC Driver Types Step by Step JDBC Program JDBC Select Program JDBC Insert Program JDBC Update Program JDBC Delete Program JDBC Connection – Properties File JDBC PreparedStatement Program JDBC – CallableStatement Example JDBC – Read an Image from DB JDBC – Insert an Image in DB JDBC – Updatable ResultSet JDBC – Scrollable ResultSet JDBC – ResultSetMetaData JDBC – DatabaseMetaData JDBC – Transaction Management JDBC – Batch Processing JDBC Interview Questions
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 746, "s": 398, "text": "In this tutorial, we are going to learn bout CallableStatement in JDBC. CallableStatement in JDBC is an interface, which is coming from the java.sql package. We have already discussed in the previous tutorial Steps by Step JDBC program example, statements in JDBC are 3 types. Here we are going to discuss one of the type called CallableStatement." }, { "code": null, "e": 813, "s": 746, "text": "CallableStatement in JDBC is a sub interface of PreparedStatement." }, { "code": null, "e": 989, "s": 813, "text": "CallableStatement in JDBC has all the benefits of PreparedStatement and also it has one more additional feature, that is we can call the procedures or functions of a database." }, { "code": null, "e": 1120, "s": 989, "text": "CallableStatement is only for calling a procedure or a function of a database. But it is not for creating a procedure or function." }, { "code": null, "e": 1240, "s": 1120, "text": "CallableStatement has two syntaxes, one is for executing commands and another is for calling the procedure or function." }, { "code": null, "e": 1338, "s": 1240, "text": "We can get the CallableStatement object by calling the prepareCall() method on connection object." }, { "code": null, "e": 1403, "s": 1338, "text": "CallableStatement cstmt = connection.prepareCall(\"sql command\");" }, { "code": null, "e": 1479, "s": 1403, "text": "CallableStatement cstmt = connection.prepareCall(\"{call procedure(args)}\");" }, { "code": null, "e": 1556, "s": 1479, "text": "CallableStatement cstmt = connection.prepareCall(\"{?=call function(args)}\");" }, { "code": null, "e": 1586, "s": 1556, "text": "Creating Procedure in MySql :" }, { "code": null, "e": 1693, "s": 1586, "text": "mysql> delimiter $\nmysql> create procedure square(IN a int, OUT b int)\n-> begin\n-> set b=a*a;\n-> end;\n-> $" }, { "code": null, "e": 1702, "s": 1693, "text": "Example:" }, { "code": null, "e": 2493, "s": 1702, "text": "package com.onlinetutorialspoint.jdbc;\nimport java.sql.CallableStatement;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.Types;\n\npublic class JDBC_Procedures_Example {\n\n public static void main(String[] args) throws Exception {\n Connection connection = null;\n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");\n connection = DriverManager.getConnection(\n \"jdbc:mysql://localhost:3306/onlinetutorialspoint\", \"root\",\n \"123456\");\n CallableStatement cStmt = connection.prepareCall(\"{call square(?,?)}\");\n cStmt.setInt(1, 20);\n cStmt.registerOutParameter(2, Types.INTEGER);\n cStmt.execute();\n System.out.println(\"The Square is : \" + cStmt.getInt(2));\n cStmt.close();\n }\n\n}" }, { "code": null, "e": 2834, "s": 2493, "text": "In the above code, we register the out parameter to CallableStatement by using the registerOutParameter(). It is mandatory because if we do not register the “out” parameter, then by default CallableStatement will take all the parameters as “in” parameters. So to inform CallableStatement that it is an out parameter we need to register it." }, { "code": null, "e": 3114, "s": 2834, "text": "While registering the out parameter, we need to tell the CallableStatement about the parameter type also. CallableStatement can understand only JDBC Types, but not java or database types. In JDBC Types class contains all the JDBC data types. Types is a class in java.sql package." }, { "code": null, "e": 3123, "s": 3114, "text": "Output :" }, { "code": null, "e": 3143, "s": 3123, "text": "The Square is : 400" }, { "code": null, "e": 3172, "s": 3143, "text": "Creating Function in MySQL :" }, { "code": null, "e": 3313, "s": 3172, "text": "mysql> DELIMITER $\nmysql> CREATE FUNCTION mul(a int, b int) RETURNS INT\n-> BEGIN\n-> DECLARE c INT;\n-> SET c = a*b;\n-> RETURN c;\n-> END;\n-> $" }, { "code": null, "e": 3322, "s": 3313, "text": "Example:" }, { "code": null, "e": 4141, "s": 3322, "text": "package com.onlinetutorialspoint.jdbc;\n\nimport java.sql.CallableStatement;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.Types;\n\nclass JDBC_Function_Example {\n\n public static void main(String[] args) throws Exception {\n Connection connection = null;\n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");\n connection = DriverManager.getConnection(\n \"jdbc:mysql://localhost:3306/onlinetutorialspoint\", \"root\",\n \"123456\");\n CallableStatement cStmt = connection.prepareCall(\"{?=call mul(?,?)}\");\n\n cStmt.registerOutParameter(1, Types.INTEGER);\n cStmt.setInt(2, 20);\n cStmt.setInt(3, 60);\n cStmt.execute();\n System.out.println(\"The Multiplication is : \" + cStmt.getInt(1));\n cStmt.close();\n }\n}" }, { "code": null, "e": 4149, "s": 4141, "text": "Output:" }, { "code": null, "e": 4178, "s": 4149, "text": "The Multiplication is : 1200" }, { "code": null, "e": 4195, "s": 4178, "text": "Happy Learning 🙂" }, { "code": null, "e": 4697, "s": 4195, "text": "\nJDBC Interview Questions and Answers\nJDBC Select Program Example\nJDBC Insert Program Example\nJDBC Update Program Example\nJDBC Delete Program Example\nJDBC PreparedStatement Example Program\nInsert an Image using JDBC in Mysql DB\nRead an Image in JDBC Example\nResultSetMetaData in JDBC Example\nDatabaseMetaData in JDBC Example\nTransaction Management in JDBC Example\nBatch Processing in JDBC Example\nJDBC Connection with Properties file\nJDBC Scrollable ResultSet Example\nJDBC Updatable ResultSet Example\n" }, { "code": null, "e": 4734, "s": 4697, "text": "JDBC Interview Questions and Answers" }, { "code": null, "e": 4762, "s": 4734, "text": "JDBC Select Program Example" }, { "code": null, "e": 4790, "s": 4762, "text": "JDBC Insert Program Example" }, { "code": null, "e": 4818, "s": 4790, "text": "JDBC Update Program Example" }, { "code": null, "e": 4846, "s": 4818, "text": "JDBC Delete Program Example" }, { "code": null, "e": 4885, "s": 4846, "text": "JDBC PreparedStatement Example Program" }, { "code": null, "e": 4924, "s": 4885, "text": "Insert an Image using JDBC in Mysql DB" }, { "code": null, "e": 4954, "s": 4924, "text": "Read an Image in JDBC Example" }, { "code": null, "e": 4988, "s": 4954, "text": "ResultSetMetaData in JDBC Example" }, { "code": null, "e": 5021, "s": 4988, "text": "DatabaseMetaData in JDBC Example" }, { "code": null, "e": 5060, "s": 5021, "text": "Transaction Management in JDBC Example" }, { "code": null, "e": 5093, "s": 5060, "text": "Batch Processing in JDBC Example" }, { "code": null, "e": 5130, "s": 5093, "text": "JDBC Connection with Properties file" }, { "code": null, "e": 5164, "s": 5130, "text": "JDBC Scrollable ResultSet Example" }, { "code": null, "e": 5197, "s": 5164, "text": "JDBC Updatable ResultSet Example" }, { "code": null, "e": 5203, "s": 5201, "text": "Δ" }, { "code": null, "e": 5222, "s": 5203, "text": " JDBC Driver Types" }, { "code": null, "e": 5249, "s": 5222, "text": " Step by Step JDBC Program" }, { "code": null, "e": 5270, "s": 5249, "text": " JDBC Select Program" }, { "code": null, "e": 5291, "s": 5270, "text": " JDBC Insert Program" }, { "code": null, "e": 5312, "s": 5291, "text": " JDBC Update Program" }, { "code": null, "e": 5333, "s": 5312, "text": " JDBC Delete Program" }, { "code": null, "e": 5368, "s": 5333, "text": " JDBC Connection – Properties File" }, { "code": null, "e": 5400, "s": 5368, "text": " JDBC PreparedStatement Program" }, { "code": null, "e": 5434, "s": 5400, "text": " JDBC – CallableStatement Example" }, { "code": null, "e": 5464, "s": 5434, "text": " JDBC – Read an Image from DB" }, { "code": null, "e": 5494, "s": 5464, "text": " JDBC – Insert an Image in DB" }, { "code": null, "e": 5522, "s": 5494, "text": " JDBC – Updatable ResultSet" }, { "code": null, "e": 5551, "s": 5522, "text": " JDBC – Scrollable ResultSet" }, { "code": null, "e": 5577, "s": 5551, "text": " JDBC – ResultSetMetaData" }, { "code": null, "e": 5602, "s": 5577, "text": " JDBC – DatabaseMetaData" }, { "code": null, "e": 5633, "s": 5602, "text": " JDBC – Transaction Management" }, { "code": null, "e": 5658, "s": 5633, "text": " JDBC – Batch Processing" } ]
PCA clearly explained —When, Why, How to use it and feature importance: A guide in Python | by Serafeim Loukas | Towards Data Science
Principal Components Analysis (PCA) is a well-known unsupervised dimensionality reduction technique that constructs relevant features/variables through linear (linear PCA) or non-linear (kernel PCA) combinations of the original variables (features). In this post, we will only focus on the famous and widely used linear PCA method. The construction of relevant features is achieved by linearly transforming correlated variables into a smaller number of uncorrelated variables. This is done by projecting (dot product) the original data into the reduced PCA space using the eigenvectors of the covariance/correlation matrix aka the principal components (PCs). The resulting projected data are essentially linear combinations of the original data capturing most of the variance in the data (Jolliffe 2002). In summary, PCA is an orthogonal transformation of the data into a series of uncorrelated data living in the reduced PCA space such that the first component explains the most variance in the data with each subsequent component explaining less. PCA technique is particularly useful in processing data where multi-colinearity exists between the features/variables. PCA can be used when the dimensions of the input features are high (e.g. a lot of variables). PCA can be also used for denoising and data compression. Let X be a matrix containing the original data with shape [n_samples, n_features] . Briefly, the PCA analysis consists of the following steps: First, the original input variables stored in X are z-scored such each original variable (column of X) has zero mean and unit standard deviation. The next step involves the construction and eigendecomposition of the covariance matrix Cx= (1/n)X'X(in case of z-scored data the covariance is equal to the correlation matrix since the standard deviation of all features is 1). Eigenvalues are then sorted in a decreasing order representing decreasing variance in the data (the eigenvalues are equal to the variance — I will prove this below using Python in Paragraph 6). Finally, the projection (transformation) of the original normalized data onto the reduced PCA space is obtained by multiplying (dot product) the originally normalized data by the leading eigenvectors of the covariance matrix i.e. the PCs. The new reduced PCA space maximizes the variance of the original data. To visualize the projected data as well as the contribution of the original variables, in a joint plot, we can use the biplot. There is an upper bound of the meaningful components that can be extracted using PCA. This is related to the rank of the covariance/correlation matrix (Cx). Having a data matrix X with shape [n_samples, n_features/n_variables], the covariance/correlation matrix would be [n_features, n_features] with maximum rank equal to min(n_samples, n_features). Thus, we can have at most min(n_samples, n_features)meaningful PC components/dimensions due to the maximum rank of the covariance/correlation matrix. import numpy as npimport matplotlib.pyplot as pltfrom sklearn import datasetsfrom sklearn.decomposition import PCAimport pandas as pdfrom sklearn.preprocessing import StandardScalerplt.style.use('ggplot')# Load the datairis = datasets.load_iris()X = iris.datay = iris.target# Z-score the featuresscaler = StandardScaler()scaler.fit(X)X = scaler.transform(X)# The PCA modelpca = PCA(n_components=2) # estimate only 2 PCsX_new = pca.fit_transform(X) # project the original data into the PCA space Let’s plot the data before and after the PCA transform and also color code each point (sample) using the corresponding class of the flower (y) . fig, axes = plt.subplots(1,2)axes[0].scatter(X[:,0], X[:,1], c=y)axes[0].set_xlabel('x1')axes[0].set_ylabel('x2')axes[0].set_title('Before PCA')axes[1].scatter(X_new[:,0], X_new[:,1], c=y)axes[1].set_xlabel('PC1')axes[1].set_ylabel('PC2')axes[1].set_title('After PCA')plt.show() We can see that in the PCA space, the variance is maximized along PC1 (explains 73% of the variance) and PC2 (explains 22% of the variance). Together, they explain 95%. print(pca.explained_variance_ratio_)# array([0.72962445, 0.22850762]) Assuming that the original input variables stored in X are z-scored such each original variable (column of X) has zero mean and unit standard deviation, we have: Λ matrix above stores the eigenvalues of the covariance matrix of the original space/dataset. The maximum variance proof can be also seen by estimating the covariance matrix of the reduced space: np.cov(X_new.T)array([[2.93808505e+00, 4.83198016e-16], [4.83198016e-16, 9.20164904e-01]]) We observe that these values (on the diagonal we have the variances) are equal to the actual eigenvalues of the covariance stored in pca.explained_variance_: pca.explained_variance_array([2.93808505, 0.9201649 ]) The importance of each feature is reflected by the magnitude of the corresponding values in the eigenvectors (higher magnitude — higher importance). Let’s find the most important features: print(abs( pca.components_ ))[[0.52106591 0.26934744 0.5804131 0.56485654] [0.37741762 0.92329566 0.02449161 0.06694199]] Here, pca.components_ has shape [n_components, n_features] Thus, by looking at the PC1 (first Principal Component) which is the first row [[0.52106591 0.26934744 0.5804131 0.56485654] we can conclude that feature 1, 3 and 4 are the most important for PC1. Similarly, we can state that feature 2 and then 1 are the most important for PC2. To sum up, we look at the absolute values of the eigenvectors’ components corresponding to the k largest eigenvalues. In sklearn the components are sorted by explained variance. The larger they are these absolute values, the more a specific feature contributes to that principal component. The biplot is the best way to visualize all-in-one following a PCA analysis. There is an implementation in R but there is no standard implementation in python so I decided to write my own function for that: def biplot(score, coeff , y): ''' Author: Serafeim Loukas, [email protected] Inputs: score: the projected data coeff: the eigenvectors (PCs) y: the class labels ''' xs = score[:,0] # projection on PC1 ys = score[:,1] # projection on PC2 n = coeff.shape[0] # number of variables plt.figure(figsize=(10,8), dpi=100) classes = np.unique(y) colors = ['g','r','y'] markers=['o','^','x'] for s,l in enumerate(classes): plt.scatter(xs[y==l],ys[y==l], c = colors[s], marker=markers[s]) # color based on group for i in range(n): #plot as arrows the variable scores (each variable has a score for PC1 and one for PC2) plt.arrow(0, 0, coeff[i,0], coeff[i,1], color = 'k', alpha = 0.9,linestyle = '-',linewidth = 1.5, overhang=0.2) plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color = 'k', ha = 'center', va = 'center',fontsize=10) plt.xlabel("PC{}".format(1), size=14) plt.ylabel("PC{}".format(2), size=14) limx= int(xs.max()) + 1 limy= int(ys.max()) + 1 plt.xlim([-limx,limx]) plt.ylim([-limy,limy]) plt.grid() plt.tick_params(axis='both', which='both', labelsize=14) Call the function (make sure to run first the initial blocks of code where we load the iris data and perform the PCA analysis): import matplotlib as mplmpl.rcParams.update(mpl.rcParamsDefault) # reset ggplot style# Call the biplot function for only the first 2 PCsbiplot(X_new[:,0:2], np.transpose(pca.components_[0:2, :]), y)plt.show() We can again verify visually that a) the variance is maximized and b) that feature 1, 3 and 4 are the most important for PC1. Similarly, feature 2 and then 1 are the most important for PC2. Furthermore, arrows (variables/features) that point into the same direction indicate correlation between the variables that they represent whereas, the arrows heading in opposite directions indicate a contrast between the variables they represent. Verify the above using code: # Var 3 and Var 4 are extremely positively correlatednp.corrcoef(X[:,2], X[:,3])[1,0]0.9628654314027957# Var 2and Var 3 are negatively correlatednp.corrcoef(X[:,1], X[:,2])[1,0]-0.42844010433054014 That’s all folks! Hope you liked this article! towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com If you liked and found this article useful, follow me! Questions? Post them as a comment and I will reply as soon as possible. [1] Jolliffe, I. T. Principal component analysis. New York, NY: Springer, 2002. [2] https://en.wikipedia.org/wiki/Principal_component_analysis [3] https://stattrek.com/matrix-algebra/matrix-rank.aspx LinkedIn: https://www.linkedin.com/in/serafeim-loukas/ ResearchGate: https://www.researchgate.net/profile/Serafeim_Loukas EPFL profile: https://people.epfl.ch/serafeim.loukas Stack Overflow: https://stackoverflow.com/users/5025009/seralouk
[ { "code": null, "e": 504, "s": 172, "text": "Principal Components Analysis (PCA) is a well-known unsupervised dimensionality reduction technique that constructs relevant features/variables through linear (linear PCA) or non-linear (kernel PCA) combinations of the original variables (features). In this post, we will only focus on the famous and widely used linear PCA method." }, { "code": null, "e": 831, "s": 504, "text": "The construction of relevant features is achieved by linearly transforming correlated variables into a smaller number of uncorrelated variables. This is done by projecting (dot product) the original data into the reduced PCA space using the eigenvectors of the covariance/correlation matrix aka the principal components (PCs)." }, { "code": null, "e": 977, "s": 831, "text": "The resulting projected data are essentially linear combinations of the original data capturing most of the variance in the data (Jolliffe 2002)." }, { "code": null, "e": 1221, "s": 977, "text": "In summary, PCA is an orthogonal transformation of the data into a series of uncorrelated data living in the reduced PCA space such that the first component explains the most variance in the data with each subsequent component explaining less." }, { "code": null, "e": 1340, "s": 1221, "text": "PCA technique is particularly useful in processing data where multi-colinearity exists between the features/variables." }, { "code": null, "e": 1434, "s": 1340, "text": "PCA can be used when the dimensions of the input features are high (e.g. a lot of variables)." }, { "code": null, "e": 1491, "s": 1434, "text": "PCA can be also used for denoising and data compression." }, { "code": null, "e": 1575, "s": 1491, "text": "Let X be a matrix containing the original data with shape [n_samples, n_features] ." }, { "code": null, "e": 1634, "s": 1575, "text": "Briefly, the PCA analysis consists of the following steps:" }, { "code": null, "e": 1780, "s": 1634, "text": "First, the original input variables stored in X are z-scored such each original variable (column of X) has zero mean and unit standard deviation." }, { "code": null, "e": 2008, "s": 1780, "text": "The next step involves the construction and eigendecomposition of the covariance matrix Cx= (1/n)X'X(in case of z-scored data the covariance is equal to the correlation matrix since the standard deviation of all features is 1)." }, { "code": null, "e": 2202, "s": 2008, "text": "Eigenvalues are then sorted in a decreasing order representing decreasing variance in the data (the eigenvalues are equal to the variance — I will prove this below using Python in Paragraph 6)." }, { "code": null, "e": 2441, "s": 2202, "text": "Finally, the projection (transformation) of the original normalized data onto the reduced PCA space is obtained by multiplying (dot product) the originally normalized data by the leading eigenvectors of the covariance matrix i.e. the PCs." }, { "code": null, "e": 2639, "s": 2441, "text": "The new reduced PCA space maximizes the variance of the original data. To visualize the projected data as well as the contribution of the original variables, in a joint plot, we can use the biplot." }, { "code": null, "e": 2990, "s": 2639, "text": "There is an upper bound of the meaningful components that can be extracted using PCA. This is related to the rank of the covariance/correlation matrix (Cx). Having a data matrix X with shape [n_samples, n_features/n_variables], the covariance/correlation matrix would be [n_features, n_features] with maximum rank equal to min(n_samples, n_features)." }, { "code": null, "e": 3140, "s": 2990, "text": "Thus, we can have at most min(n_samples, n_features)meaningful PC components/dimensions due to the maximum rank of the covariance/correlation matrix." }, { "code": null, "e": 3635, "s": 3140, "text": "import numpy as npimport matplotlib.pyplot as pltfrom sklearn import datasetsfrom sklearn.decomposition import PCAimport pandas as pdfrom sklearn.preprocessing import StandardScalerplt.style.use('ggplot')# Load the datairis = datasets.load_iris()X = iris.datay = iris.target# Z-score the featuresscaler = StandardScaler()scaler.fit(X)X = scaler.transform(X)# The PCA modelpca = PCA(n_components=2) # estimate only 2 PCsX_new = pca.fit_transform(X) # project the original data into the PCA space" }, { "code": null, "e": 3780, "s": 3635, "text": "Let’s plot the data before and after the PCA transform and also color code each point (sample) using the corresponding class of the flower (y) ." }, { "code": null, "e": 4059, "s": 3780, "text": "fig, axes = plt.subplots(1,2)axes[0].scatter(X[:,0], X[:,1], c=y)axes[0].set_xlabel('x1')axes[0].set_ylabel('x2')axes[0].set_title('Before PCA')axes[1].scatter(X_new[:,0], X_new[:,1], c=y)axes[1].set_xlabel('PC1')axes[1].set_ylabel('PC2')axes[1].set_title('After PCA')plt.show()" }, { "code": null, "e": 4228, "s": 4059, "text": "We can see that in the PCA space, the variance is maximized along PC1 (explains 73% of the variance) and PC2 (explains 22% of the variance). Together, they explain 95%." }, { "code": null, "e": 4298, "s": 4228, "text": "print(pca.explained_variance_ratio_)# array([0.72962445, 0.22850762])" }, { "code": null, "e": 4460, "s": 4298, "text": "Assuming that the original input variables stored in X are z-scored such each original variable (column of X) has zero mean and unit standard deviation, we have:" }, { "code": null, "e": 4554, "s": 4460, "text": "Λ matrix above stores the eigenvalues of the covariance matrix of the original space/dataset." }, { "code": null, "e": 4656, "s": 4554, "text": "The maximum variance proof can be also seen by estimating the covariance matrix of the reduced space:" }, { "code": null, "e": 4753, "s": 4656, "text": "np.cov(X_new.T)array([[2.93808505e+00, 4.83198016e-16], [4.83198016e-16, 9.20164904e-01]])" }, { "code": null, "e": 4911, "s": 4753, "text": "We observe that these values (on the diagonal we have the variances) are equal to the actual eigenvalues of the covariance stored in pca.explained_variance_:" }, { "code": null, "e": 4966, "s": 4911, "text": "pca.explained_variance_array([2.93808505, 0.9201649 ])" }, { "code": null, "e": 5115, "s": 4966, "text": "The importance of each feature is reflected by the magnitude of the corresponding values in the eigenvectors (higher magnitude — higher importance)." }, { "code": null, "e": 5155, "s": 5115, "text": "Let’s find the most important features:" }, { "code": null, "e": 5277, "s": 5155, "text": "print(abs( pca.components_ ))[[0.52106591 0.26934744 0.5804131 0.56485654] [0.37741762 0.92329566 0.02449161 0.06694199]]" }, { "code": null, "e": 5415, "s": 5277, "text": "Here, pca.components_ has shape [n_components, n_features] Thus, by looking at the PC1 (first Principal Component) which is the first row" }, { "code": null, "e": 5461, "s": 5415, "text": "[[0.52106591 0.26934744 0.5804131 0.56485654]" }, { "code": null, "e": 5615, "s": 5461, "text": "we can conclude that feature 1, 3 and 4 are the most important for PC1. Similarly, we can state that feature 2 and then 1 are the most important for PC2." }, { "code": null, "e": 5905, "s": 5615, "text": "To sum up, we look at the absolute values of the eigenvectors’ components corresponding to the k largest eigenvalues. In sklearn the components are sorted by explained variance. The larger they are these absolute values, the more a specific feature contributes to that principal component." }, { "code": null, "e": 5982, "s": 5905, "text": "The biplot is the best way to visualize all-in-one following a PCA analysis." }, { "code": null, "e": 6112, "s": 5982, "text": "There is an implementation in R but there is no standard implementation in python so I decided to write my own function for that:" }, { "code": null, "e": 7301, "s": 6112, "text": "def biplot(score, coeff , y): ''' Author: Serafeim Loukas, [email protected] Inputs: score: the projected data coeff: the eigenvectors (PCs) y: the class labels ''' xs = score[:,0] # projection on PC1 ys = score[:,1] # projection on PC2 n = coeff.shape[0] # number of variables plt.figure(figsize=(10,8), dpi=100) classes = np.unique(y) colors = ['g','r','y'] markers=['o','^','x'] for s,l in enumerate(classes): plt.scatter(xs[y==l],ys[y==l], c = colors[s], marker=markers[s]) # color based on group for i in range(n): #plot as arrows the variable scores (each variable has a score for PC1 and one for PC2) plt.arrow(0, 0, coeff[i,0], coeff[i,1], color = 'k', alpha = 0.9,linestyle = '-',linewidth = 1.5, overhang=0.2) plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, \"Var\"+str(i+1), color = 'k', ha = 'center', va = 'center',fontsize=10) plt.xlabel(\"PC{}\".format(1), size=14) plt.ylabel(\"PC{}\".format(2), size=14) limx= int(xs.max()) + 1 limy= int(ys.max()) + 1 plt.xlim([-limx,limx]) plt.ylim([-limy,limy]) plt.grid() plt.tick_params(axis='both', which='both', labelsize=14)" }, { "code": null, "e": 7429, "s": 7301, "text": "Call the function (make sure to run first the initial blocks of code where we load the iris data and perform the PCA analysis):" }, { "code": null, "e": 7638, "s": 7429, "text": "import matplotlib as mplmpl.rcParams.update(mpl.rcParamsDefault) # reset ggplot style# Call the biplot function for only the first 2 PCsbiplot(X_new[:,0:2], np.transpose(pca.components_[0:2, :]), y)plt.show()" }, { "code": null, "e": 7828, "s": 7638, "text": "We can again verify visually that a) the variance is maximized and b) that feature 1, 3 and 4 are the most important for PC1. Similarly, feature 2 and then 1 are the most important for PC2." }, { "code": null, "e": 8076, "s": 7828, "text": "Furthermore, arrows (variables/features) that point into the same direction indicate correlation between the variables that they represent whereas, the arrows heading in opposite directions indicate a contrast between the variables they represent." }, { "code": null, "e": 8105, "s": 8076, "text": "Verify the above using code:" }, { "code": null, "e": 8303, "s": 8105, "text": "# Var 3 and Var 4 are extremely positively correlatednp.corrcoef(X[:,2], X[:,3])[1,0]0.9628654314027957# Var 2and Var 3 are negatively correlatednp.corrcoef(X[:,1], X[:,2])[1,0]-0.42844010433054014" }, { "code": null, "e": 8350, "s": 8303, "text": "That’s all folks! Hope you liked this article!" }, { "code": null, "e": 8373, "s": 8350, "text": "towardsdatascience.com" }, { "code": null, "e": 8396, "s": 8373, "text": "towardsdatascience.com" }, { "code": null, "e": 8419, "s": 8396, "text": "towardsdatascience.com" }, { "code": null, "e": 8442, "s": 8419, "text": "towardsdatascience.com" }, { "code": null, "e": 8465, "s": 8442, "text": "towardsdatascience.com" }, { "code": null, "e": 8520, "s": 8465, "text": "If you liked and found this article useful, follow me!" }, { "code": null, "e": 8592, "s": 8520, "text": "Questions? Post them as a comment and I will reply as soon as possible." }, { "code": null, "e": 8672, "s": 8592, "text": "[1] Jolliffe, I. T. Principal component analysis. New York, NY: Springer, 2002." }, { "code": null, "e": 8735, "s": 8672, "text": "[2] https://en.wikipedia.org/wiki/Principal_component_analysis" }, { "code": null, "e": 8792, "s": 8735, "text": "[3] https://stattrek.com/matrix-algebra/matrix-rank.aspx" }, { "code": null, "e": 8847, "s": 8792, "text": "LinkedIn: https://www.linkedin.com/in/serafeim-loukas/" }, { "code": null, "e": 8914, "s": 8847, "text": "ResearchGate: https://www.researchgate.net/profile/Serafeim_Loukas" }, { "code": null, "e": 8967, "s": 8914, "text": "EPFL profile: https://people.epfl.ch/serafeim.loukas" } ]
A step-by-step guide in designing knowledge-driven models using Bayesian theorem. | by Erdogan Taskesen | Towards Data Science
Data is the fuel for models but you may have witnessed situations where there is no data but solely a domain expert that can very well describe or even predict “the situation” given the circumstances. I will summarize the concepts of knowledge-driven models in terms of Bayesian probabilistic, followed by a hands-on tutorial to demonstrate the steps of converting an expert’s knowledge into a Bayesian model with the goal to make inferences. I will use the Sprinkler system to conceptually explain the steps in the process: from knowledge to model. I will end with a discussion about the challenges of complex knowledge-driven models, and the systematic errors that can occur due to questioning and extracting knowledge. All examples are created using the python library bnlearn. When we talk about knowledge, it is not solely descriptive knowledge such as facts. Knowledge is also a familiarity, awareness, or understanding of someone or something, procedural knowledge (skills), or acquaintance knowledge [1]. Whatever knowledge you have, or want to use, it needs to be presented in a computer interpretable manner if you want to build a computer aided knowledge model. This means that you need to design a system that is built on a sequence of process stages. Or in other words, a sequence goes from the output of the process into the input in the next process. Multiple simple sequences can then be combined into a complex system. We can represent such a system as a graph with nodes and edges. Each node corresponds to a variable and each edge represents conditional dependencies between pairs of variables. In this manner, we can define a model based on the expert’s knowledge, and the best way to do that is with Bayesian models. To answer the question, ‘Can we get experts knowledge into models?’ Well, it depends on how accurate you can represent the knowledge as a graph and how precise you can glue it together by probability theorem a.k.a. Bayesian graphical models. Still, there are some restrictions though. The use of machine learning techniques has become a standard toolkit to obtain useful insights and make predictions in many domains. However, many of the models are data-driven, which means that data is required to learn a model. Incorporating expert’s knowledge in data-driven models is not possible or straightforward to do. However, a branch of machine learning is Bayesian graphical models (a.k.a. Bayesian networks, Bayesian belief networks, Bayes Net, causal probabilistic networks, and Influence diagrams), which can be used to incorporate experts knowledge into models and make inferences. See below some bullet points with the advantages of Bayesian graphical models, which I will stress throughout this article. The possibility to incorporate domain/expert knowledge in a graph. It has a notion of modularity. A complex system is built by combining simpler parts. Graph theory provides intuitively highly interacting sets of variables. Probability theory provides the glue to combine the parts. To make Bayesian graphical models, you need two ingredients: 1. Directed Acyclic Graphs (DAG) and 2. Conditional Probabilistic Tables (CPTs). Only together it can form a representation of the expert’s knowledge. At this point, you know that knowledge can be represented as a systematic process, and can be seen as a graph. In the case of Bayesian models, a graph needs to be represented as a DAG. But what exactly is a DAG? First of all, it stands for Directed Acyclic Graphs and is a network (or graph) with nodes (variables) and edges that are directed. Figure 1 depicts three unique patterns that can be made with three variables (X, Y, Z). Nodes correspond to variables X, Y, Z, and the directed edges (arrows) indicate dependency relationships or conditional distributions. The network is acyclic, which means that no (feedback) loops are allowed. With a DAG, a complex system can be created by combining the (simpler) parts. All DAGs (large or small) are built under the following 3 rules: Edges are conditional dependencies.Edges are directed.Feedback loops are not allowed. Edges are conditional dependencies. Edges are directed. Feedback loops are not allowed. These rules are important because if you would remove the directionality (or arrows), the three DAGs become identical. Or in other words, with the directionality, we can make the DAG identifiable [2]. There are many blogs, articles, and Wikipedia pages that describe the statistics and causality behind the DAGs. What you need to understand is that every Bayesian network can be designed by these three unique patterns, and should be representative of the process you want to model. Designing the DAG is the first part of creating a knowledge-driven model. The second part is defining the Conditional Probabilistic Tables which describe the strength of the relationship at each node in terms of (conditional) probabilities. Probability theory (a.k.a. Bayes theorem or Bayes Rule), forms the fundament for Bayesian networks. Check out this medium article about Bayesian structure learning [3] to read more about the specific parts of Bayes theorem. Although the theorem is applicable here too, there are some differences. First, in a knowledge-driven model, the CPTs are not learned from data (because there is none). Instead, the probabilities need to be derived from the expert by questioning, and subsequently being stored in so-called Conditional Probabilistic Tables (CPT) (also named Conditional Probability Distribution, CPD). I will use CPT and CPD interchangeably throughout this article. The CPTs describes the strength of the relationship at each node in terms of conditional probabilities or priors. The CPTs are then used with the Bayes rule to update model information which allows making inferences. In the next section, I will demonstrate, with the Sprinkler use case, how to exactly fill in the CPT with expert knowledge. But first, there are challenges in converting expert's knowledge into probabilities. When we want to make a knowledge-driven model, it is crucial to extract the right information from the expert. The domain expert will inform about the probability of a successful process and the risks of side effects. It is utterly important that the message is understood as intended to minimize the risk of miscommunication. When talking to experts, many estimated probabilities are communicated verbally, with terms such as ‘very likely’ instead of exact percentages. Make sure that the verbal probability phrase is the same for both sender and receiver in terms of probabilities or percentages. In certain domains there are guidelines that describe terms such as ‘common’ in certain ranges, let say 1–10%. But without background knowledge of the domain, the word ‘common’ can easily be interpreted as a different number [4]. In addition, the interpretation of a probability phrase can be influenced by its context [4]. For instance, compare your numerical interpretation in the next two statements: It will likely rain in Manchester (England) next June. It will likely rain in Barcelona (Spain) next June. Probably, your numerical interpretation of ‘likely’ in the first statement is higher than in the second. Be cautious of contextual misinterpretations as it can also lead to systematic errors and thus incorrect models. An overview figure of probability phrases is shown in Figure 2. ‘Impossible’ seems not always be impossible! A few words about the bnlearn library that is used for all the analysis in this article. The bnlearn library is designed to tackle a few challenges such as: Structure learning: Given the data: Estimate a DAG that captures the dependencies between the variables. Parameter learning: Given the data and DAG: Estimate the (conditional) probability distributions of the individual variables. Inference: Given the learned model: Determine the exact probability values for your queries. What benefits does bnlearn offer over other bayesian analysis implementations? Build on top of the pgmpy library Contains the most-wanted bayesian pipelines Simple and intuitive open source Documentation page Let's start with a simple and intuitive example to demonstrate the building of a real-world model based on an expert's knowledge. In this use case, I will play the role of domain expert of the Sprinkler system. Suppose I have a sprinkler system in my backyard and for the last 1000 days I have eye-witnessed how and when it works. I did not collect any data but I created an intuition about the working. Let’s call this an experts view or domain knowledge. Note that the sprinkler system is a well-known example in Bayesian networks. From my expert’s view, I know some facts about the system; it is sometimes on and sometimes off (isn’t it great). I have seen -very often- that if the sprinkler system is on, the grass is -possibly- wet. However, I also know that rain -almost certainly- results in wet grass too and that the sprinkler system is then -most of the time- off. I know that clouds are -often- present before it starts to rain. Finally, I noticed a -weak- interaction between Sprinkler and Cloudy but I’m not entirely sure. From this point on you need to convert the expert’s knowledge into a model. This can be done systematically by first creating the graph and then define the CPTs that connect the nodes in the graph. There are four nodes in the sprinkler system that you can extract from the expert's view. Each node works with two states: Rain: yes or no, Cloudy: yes or no, Sprinkler system: on or off, and Wet grass: true or false. A complex system is built by combining simpler parts. This means that you don’t need to create or design the whole system at once but first define the simpler parts. The simpler parts are one-to-one relationships. In this step, we will convert the expert’s view into relationships. We know from the expert that: rain depends on the cloudy state, wet grass depends on the rain state but wet grass also depends on the sprinkler state. Finally, we know that sprinkler depends on cloudy. We can make the following four directed one-to-one relationships. Cloudy → Rain Rain → Wet Grass Sprinkler → Wet Grass Cloudy → Sprinkler It is important to realize that there are differences in the strength of the relationships between the one-to-one parts and needs to be defined using the CPTs. But before stepping into the CPTs, let’s first make the DAG using bnlearn. The four directed relationships can now be used to build a graph with nodes and edges. Each node corresponds to a variable and each edge represents a conditional dependency between pairs of variables. In bnlearn, we can assign and graphically represent the relationships between variables. pip install bnlearn In figure 3 is the resulting DAG. We call this a causal DAG because we have assumed that the edges we encoded represent our causal assumptions about the sprinkler system. At this point, the DAG has no knowledge about the underlying dependencies. We can check the CPTs with bn.print(DAG) which will result in the message that “no CPD can be printed”. We need to add knowledge to the DAG with so-called Conditional Probabilistic Tables (CPTs) and we will rely on the expert’s knowledge to fill the CPTs. Knowledge can be added to the DAG with Conditional Probabilistic Tables (CPTs). The sprinkler system is a simple Bayesian network where Wet grass (child node) is influenced by two-parent nodes (Rain and Sprinkler) (see figure 1). The nodes Sprinkler and Rain are influenced by a single node; Cloudy. The Cloudy node is not influenced by any other node. We need to associate each node with a probability function that takes, as input, a particular set of values for the node’s parent variables and gives (as output) the probability of the variable represented by the node. Let’s do this for the four nodes. The Cloudy node has two states (yes or no) and no dependencies. Calculating the probability is relatively straightforward when working with a single random variable. From my expert view across the last 1000 days, I have eye-witnessed 70% of the time cloudy weather (I’m not complaining though, just disappointed). As the probabilities should add up to 1, not cloudy should be 30% of the time. The CPT looks as following: The Rain node has two states and is conditioned by Cloudy, which also has two states. In total, we need to specify 4 conditional probabilities, i.e., the probability of one event given the occurrence of another event. In our case; the probability of the event Rain that occurred given Cloudy. The evidence is thus Cloudy and the variable is Rain. From my expert's view I can tell that when it Rained, it was also Cloudy 80% of the time. I did also see rain 20% of the time without visible clouds (Really? Yes. True story). The Sprinkler node has two states and is conditioned by the two states of Cloudy. In total, we need to specify 4 conditional probabilities. Here we need to define the probability of Sprinkler given the occurrence of Cloudy. The evidence is thus Cloudy and the variable is Rain. I can tell that when the Sprinkler was off, it was Cloudy 90% of the time. The counterpart is thus 10% for Sprinkler is true and Cloudy is true. Other probabilities I’m not sure about, so I will set it to 50% of the time. The wet grass node has two states and is conditioned by two-parent nodes; Rain and Sprinkler. Here we need to define the probability of wet grass given the occurrence of rain and sprinkler. In total, we have to specify 8 conditional probabilities (2 states ^ 3 nodes). As an expert, I am certain, let’s say 99%, about seeing wet grass after raining or sprinkler was on: P(wet grass=1 | rain=1, sprinkler =1) = 0.99. The counterpart is thus P(wet grass=0| rain=1, sprinkler =1) = 1 – 0.99 = 0.01 As an expert, I am entirely sure about no wet grass when it did not rain or the sprinkler was not on: P(wet grass=0 | rain=0, sprinkler =0) = 1. The counterpart is thus: P(wet grass=1 | rain=0, sprinkler =0) = 1 – 1= 0 As an expert, I know that wet grass almost always occurred when it was raining and the sprinkler was off (90%). P(wet grass=1 | rain=1, sprinkler=0) = 0.9. The counterpart is: P(wet grass=0 | rain=1, sprinkler=0) = 1 – 0.9 = 0.1. As an expert, I know that Wet grass almost always occurred when it was not raining and the sprinkler was on (90%). P(wet grass=1 | rain=0, sprinkler =1) = 0.9. The counterpart is: P(wet grass=0 | rain=0, sprinkler =1) = 1 – 0.9 = 0.1. This is it! At this point, we defined the strength of the relationships in the DAG with the CPTs. Now we need to connect the DAG with the CPTs. All the CPTs are created and we can now connect them with the DAG. As a sanity check, the CPTs can be examined using the print_DAG functionality. The DAG with CPTs will now be like Figure 4. Nice work! At this point, you created a model that describes the structure of the data, and the CPTs that quantitatively describe the statistical relationship between each node and its parents. Let’s ask some questions to our model and make inferences! How probable is having wet grass given the sprinkler is off? P(Wet_grass=1 | Sprinkler=0) = 0.6162How probable is a rainy day given sprinkler is off and it is cloudy?P(Rain=1 | Sprinkler=0, Cloudy=1) = 0.8 An advantage of Bayesian networks is that it is intuitively easier for a human to understand direct dependencies and local distributions than complete joint distributions. To make knowledge-driven models, we need two ingredients; the DAG and Conditional Probabilistic Tables (CPTs). Both are derived from the expert by questioning. The DAG describes the structure of the data, and CPTs are needed to quantitatively describe the statistical relationship between each node and its parents. Although such an approach seems reasonable to do, you should be aware of systematic errors that can occur by questioning the expert, and the limitations when building a complex model. In the sprinkler example, we extracted domain expert’s knowledge through personal experience. Although we created a causal diagram, it is hard to fully verify the validity and completeness of the causal diagram. For example, you may have a different perspective on the probabilities and the graph, and you may also be true about that. As an example, I described that: ‘I did also see rain in 20% of the time without visible clouds’. It may be reasonable to argue about such a statement. In opposite, it can also occur that multiple true knowledge models can exist at the same time. In such a case, you may need to combine the probabilities or fight out who is right. The knowledge being used is as rich as the experts experiences and as colored as the experts prejudices. Or in other words, the probabilities we extract by questioning an expert are subjective probabilities [5]. In the sprinkler example, it is sufficient to accept that this notion of probability is personal, it reflects the degree of belief of a particular person at a particular location at a particular time. Question yourself this; will the Sprinkler model change if the expert lives in England compared to Spain? If you want to use such a procedure to design a knowledge-driven model, it is important to understand how people (experts) arrive at probabilistic estimations. In literature it is described that people rarely follow the principles of probability when reasoning about uncertain events, rather they replace the laws of probability with a limited number of heuristics [6, 7], such as representativeness, availability, and adjustment from an anchor. Note that this can lead to systematic errors and to that extent incorrect models. Also, make sure that the verbal probability phrase is the same for both sender and receiver in terms of exact probabilities or percentages. The presented sprinkler system has only a few nodes but Bayesian networks can contain many more nodes with multiple levels of parent-child dependencies. The number of probability distributions required to populate a conditional probability table (CPT) in a Bayesian network, grows exponentially with the number of parent-nodes associated with that table. If the table is to be populated through knowledge elicited from a domain expert then the sheer magnitude of the task forms a considerable cognitive barrier [8]. Too much levels of parent-child dependencies can form a considerable cognitive barrier for the domain expert. For example, if m parent nodes represent Boolean variables, then the probability function is represented by a table of 2^m entries, one entry for each of the possible parent combinations. Be hesitant of creating large graphs (more than 10-15 nodes) as the number of parent-child dependencies can form a considerable cognitive barrier for the domain expert. If you have data for the system that you want to model, it is also possible to learn the structure (DAG), and/or its parameters (CPTs) using structure learning [3]. I will repeat my earlier statement: “Well, it depends on how accurate you can represent the knowledge as a graph and how precise you can glue it together by probability theorem.” This is it. Creating a knowledge-driven model is not easy. It is not only about data modeling but is also about human psychology. Make sure you prepare for the expert interviews. It is better to have multiple short interviews than one long interview. Ask your questions systematically. First design the graph with nodes and edges, then go into the CPTs. Be cautious when discussing probabilities. Understand how the expert derives his probabilities and normalize when required. Check if time and place can differ the outcome. Make sanity checks after building the model. Smile occasionally. Be Safe. Stay Frosty. Cheers, E. If you found this article helpful, help support my content by signing up for a Medium membership using my referral link or follow me to access similar ones. bnlearn github/documentation Let’s connect on LinkedIn Follow me on github Wikipedia, Knowledge Wikipedia, Knowledge 2. Pearl, Judea (2000). Causality: Models, Reasoning, and Inference. Cambridge University Press. ISBN 978 – 0 – 521 – 77362 – 1. OCLC 42291253. 3. E.Taskesen, A Step-by-Step Guide in detecting causal relationships using Bayesian Structure Learning in Python, Medium, 2021 4. Sanne Willems, et al, Variability in the interpretation of probability phrases used in Dutch news articles — a risk for miscommunication, JCOM, 24 March 2020 5. R. Jeffrey, Subjective Probability: The Real Thing, Cambridge University Press, Cambridge, UK, 2004. 6. A. Tversky and D. Kahneman, Judgment under Uncertainty: Heuristics and Biases, Science, 1974 7. Tversky, and D. Kahneman, ‘Judgment under uncertainty: Heuristics and biases,’ in Judgment under Uncertainty: Heuristics and Biases, D. Kahneman, P. Slovic, and A. Tversky, eds., Cambridge University Press, Cambridge, 1982, pp 3–2 8. Balaram Das, Generating Conditional Probabilities for Bayesian Networks: Easing the Knowledge Acquisition Problem. Arxiv
[ { "code": null, "e": 953, "s": 172, "text": "Data is the fuel for models but you may have witnessed situations where there is no data but solely a domain expert that can very well describe or even predict “the situation” given the circumstances. I will summarize the concepts of knowledge-driven models in terms of Bayesian probabilistic, followed by a hands-on tutorial to demonstrate the steps of converting an expert’s knowledge into a Bayesian model with the goal to make inferences. I will use the Sprinkler system to conceptually explain the steps in the process: from knowledge to model. I will end with a discussion about the challenges of complex knowledge-driven models, and the systematic errors that can occur due to questioning and extracting knowledge. All examples are created using the python library bnlearn." }, { "code": null, "e": 1185, "s": 953, "text": "When we talk about knowledge, it is not solely descriptive knowledge such as facts. Knowledge is also a familiarity, awareness, or understanding of someone or something, procedural knowledge (skills), or acquaintance knowledge [1]." }, { "code": null, "e": 1345, "s": 1185, "text": "Whatever knowledge you have, or want to use, it needs to be presented in a computer interpretable manner if you want to build a computer aided knowledge model." }, { "code": null, "e": 2195, "s": 1345, "text": "This means that you need to design a system that is built on a sequence of process stages. Or in other words, a sequence goes from the output of the process into the input in the next process. Multiple simple sequences can then be combined into a complex system. We can represent such a system as a graph with nodes and edges. Each node corresponds to a variable and each edge represents conditional dependencies between pairs of variables. In this manner, we can define a model based on the expert’s knowledge, and the best way to do that is with Bayesian models. To answer the question, ‘Can we get experts knowledge into models?’ Well, it depends on how accurate you can represent the knowledge as a graph and how precise you can glue it together by probability theorem a.k.a. Bayesian graphical models. Still, there are some restrictions though." }, { "code": null, "e": 2917, "s": 2195, "text": "The use of machine learning techniques has become a standard toolkit to obtain useful insights and make predictions in many domains. However, many of the models are data-driven, which means that data is required to learn a model. Incorporating expert’s knowledge in data-driven models is not possible or straightforward to do. However, a branch of machine learning is Bayesian graphical models (a.k.a. Bayesian networks, Bayesian belief networks, Bayes Net, causal probabilistic networks, and Influence diagrams), which can be used to incorporate experts knowledge into models and make inferences. See below some bullet points with the advantages of Bayesian graphical models, which I will stress throughout this article." }, { "code": null, "e": 2984, "s": 2917, "text": "The possibility to incorporate domain/expert knowledge in a graph." }, { "code": null, "e": 3015, "s": 2984, "text": "It has a notion of modularity." }, { "code": null, "e": 3069, "s": 3015, "text": "A complex system is built by combining simpler parts." }, { "code": null, "e": 3141, "s": 3069, "text": "Graph theory provides intuitively highly interacting sets of variables." }, { "code": null, "e": 3200, "s": 3141, "text": "Probability theory provides the glue to combine the parts." }, { "code": null, "e": 3412, "s": 3200, "text": "To make Bayesian graphical models, you need two ingredients: 1. Directed Acyclic Graphs (DAG) and 2. Conditional Probabilistic Tables (CPTs). Only together it can form a representation of the expert’s knowledge." }, { "code": null, "e": 4053, "s": 3412, "text": "At this point, you know that knowledge can be represented as a systematic process, and can be seen as a graph. In the case of Bayesian models, a graph needs to be represented as a DAG. But what exactly is a DAG? First of all, it stands for Directed Acyclic Graphs and is a network (or graph) with nodes (variables) and edges that are directed. Figure 1 depicts three unique patterns that can be made with three variables (X, Y, Z). Nodes correspond to variables X, Y, Z, and the directed edges (arrows) indicate dependency relationships or conditional distributions. The network is acyclic, which means that no (feedback) loops are allowed." }, { "code": null, "e": 4131, "s": 4053, "text": "With a DAG, a complex system can be created by combining the (simpler) parts." }, { "code": null, "e": 4196, "s": 4131, "text": "All DAGs (large or small) are built under the following 3 rules:" }, { "code": null, "e": 4282, "s": 4196, "text": "Edges are conditional dependencies.Edges are directed.Feedback loops are not allowed." }, { "code": null, "e": 4318, "s": 4282, "text": "Edges are conditional dependencies." }, { "code": null, "e": 4338, "s": 4318, "text": "Edges are directed." }, { "code": null, "e": 4370, "s": 4338, "text": "Feedback loops are not allowed." }, { "code": null, "e": 5094, "s": 4370, "text": "These rules are important because if you would remove the directionality (or arrows), the three DAGs become identical. Or in other words, with the directionality, we can make the DAG identifiable [2]. There are many blogs, articles, and Wikipedia pages that describe the statistics and causality behind the DAGs. What you need to understand is that every Bayesian network can be designed by these three unique patterns, and should be representative of the process you want to model. Designing the DAG is the first part of creating a knowledge-driven model. The second part is defining the Conditional Probabilistic Tables which describe the strength of the relationship at each node in terms of (conditional) probabilities." }, { "code": null, "e": 5767, "s": 5094, "text": "Probability theory (a.k.a. Bayes theorem or Bayes Rule), forms the fundament for Bayesian networks. Check out this medium article about Bayesian structure learning [3] to read more about the specific parts of Bayes theorem. Although the theorem is applicable here too, there are some differences. First, in a knowledge-driven model, the CPTs are not learned from data (because there is none). Instead, the probabilities need to be derived from the expert by questioning, and subsequently being stored in so-called Conditional Probabilistic Tables (CPT) (also named Conditional Probability Distribution, CPD). I will use CPT and CPD interchangeably throughout this article." }, { "code": null, "e": 5881, "s": 5767, "text": "The CPTs describes the strength of the relationship at each node in terms of conditional probabilities or priors." }, { "code": null, "e": 6193, "s": 5881, "text": "The CPTs are then used with the Bayes rule to update model information which allows making inferences. In the next section, I will demonstrate, with the Sprinkler use case, how to exactly fill in the CPT with expert knowledge. But first, there are challenges in converting expert's knowledge into probabilities." }, { "code": null, "e": 6664, "s": 6193, "text": "When we want to make a knowledge-driven model, it is crucial to extract the right information from the expert. The domain expert will inform about the probability of a successful process and the risks of side effects. It is utterly important that the message is understood as intended to minimize the risk of miscommunication. When talking to experts, many estimated probabilities are communicated verbally, with terms such as ‘very likely’ instead of exact percentages." }, { "code": null, "e": 6792, "s": 6664, "text": "Make sure that the verbal probability phrase is the same for both sender and receiver in terms of probabilities or percentages." }, { "code": null, "e": 7196, "s": 6792, "text": "In certain domains there are guidelines that describe terms such as ‘common’ in certain ranges, let say 1–10%. But without background knowledge of the domain, the word ‘common’ can easily be interpreted as a different number [4]. In addition, the interpretation of a probability phrase can be influenced by its context [4]. For instance, compare your numerical interpretation in the next two statements:" }, { "code": null, "e": 7251, "s": 7196, "text": "It will likely rain in Manchester (England) next June." }, { "code": null, "e": 7303, "s": 7251, "text": "It will likely rain in Barcelona (Spain) next June." }, { "code": null, "e": 7585, "s": 7303, "text": "Probably, your numerical interpretation of ‘likely’ in the first statement is higher than in the second. Be cautious of contextual misinterpretations as it can also lead to systematic errors and thus incorrect models. An overview figure of probability phrases is shown in Figure 2." }, { "code": null, "e": 7630, "s": 7585, "text": "‘Impossible’ seems not always be impossible!" }, { "code": null, "e": 7787, "s": 7630, "text": "A few words about the bnlearn library that is used for all the analysis in this article. The bnlearn library is designed to tackle a few challenges such as:" }, { "code": null, "e": 7892, "s": 7787, "text": "Structure learning: Given the data: Estimate a DAG that captures the dependencies between the variables." }, { "code": null, "e": 8018, "s": 7892, "text": "Parameter learning: Given the data and DAG: Estimate the (conditional) probability distributions of the individual variables." }, { "code": null, "e": 8111, "s": 8018, "text": "Inference: Given the learned model: Determine the exact probability values for your queries." }, { "code": null, "e": 8190, "s": 8111, "text": "What benefits does bnlearn offer over other bayesian analysis implementations?" }, { "code": null, "e": 8224, "s": 8190, "text": "Build on top of the pgmpy library" }, { "code": null, "e": 8268, "s": 8224, "text": "Contains the most-wanted bayesian pipelines" }, { "code": null, "e": 8289, "s": 8268, "text": "Simple and intuitive" }, { "code": null, "e": 8301, "s": 8289, "text": "open source" }, { "code": null, "e": 8320, "s": 8301, "text": "Documentation page" }, { "code": null, "e": 8531, "s": 8320, "text": "Let's start with a simple and intuitive example to demonstrate the building of a real-world model based on an expert's knowledge. In this use case, I will play the role of domain expert of the Sprinkler system." }, { "code": null, "e": 8854, "s": 8531, "text": "Suppose I have a sprinkler system in my backyard and for the last 1000 days I have eye-witnessed how and when it works. I did not collect any data but I created an intuition about the working. Let’s call this an experts view or domain knowledge. Note that the sprinkler system is a well-known example in Bayesian networks." }, { "code": null, "e": 9356, "s": 8854, "text": "From my expert’s view, I know some facts about the system; it is sometimes on and sometimes off (isn’t it great). I have seen -very often- that if the sprinkler system is on, the grass is -possibly- wet. However, I also know that rain -almost certainly- results in wet grass too and that the sprinkler system is then -most of the time- off. I know that clouds are -often- present before it starts to rain. Finally, I noticed a -weak- interaction between Sprinkler and Cloudy but I’m not entirely sure." }, { "code": null, "e": 9554, "s": 9356, "text": "From this point on you need to convert the expert’s knowledge into a model. This can be done systematically by first creating the graph and then define the CPTs that connect the nodes in the graph." }, { "code": null, "e": 9772, "s": 9554, "text": "There are four nodes in the sprinkler system that you can extract from the expert's view. Each node works with two states: Rain: yes or no, Cloudy: yes or no, Sprinkler system: on or off, and Wet grass: true or false." }, { "code": null, "e": 10322, "s": 9772, "text": "A complex system is built by combining simpler parts. This means that you don’t need to create or design the whole system at once but first define the simpler parts. The simpler parts are one-to-one relationships. In this step, we will convert the expert’s view into relationships. We know from the expert that: rain depends on the cloudy state, wet grass depends on the rain state but wet grass also depends on the sprinkler state. Finally, we know that sprinkler depends on cloudy. We can make the following four directed one-to-one relationships." }, { "code": null, "e": 10336, "s": 10322, "text": "Cloudy → Rain" }, { "code": null, "e": 10353, "s": 10336, "text": "Rain → Wet Grass" }, { "code": null, "e": 10375, "s": 10353, "text": "Sprinkler → Wet Grass" }, { "code": null, "e": 10394, "s": 10375, "text": "Cloudy → Sprinkler" }, { "code": null, "e": 10629, "s": 10394, "text": "It is important to realize that there are differences in the strength of the relationships between the one-to-one parts and needs to be defined using the CPTs. But before stepping into the CPTs, let’s first make the DAG using bnlearn." }, { "code": null, "e": 10919, "s": 10629, "text": "The four directed relationships can now be used to build a graph with nodes and edges. Each node corresponds to a variable and each edge represents a conditional dependency between pairs of variables. In bnlearn, we can assign and graphically represent the relationships between variables." }, { "code": null, "e": 10939, "s": 10919, "text": "pip install bnlearn" }, { "code": null, "e": 11110, "s": 10939, "text": "In figure 3 is the resulting DAG. We call this a causal DAG because we have assumed that the edges we encoded represent our causal assumptions about the sprinkler system." }, { "code": null, "e": 11441, "s": 11110, "text": "At this point, the DAG has no knowledge about the underlying dependencies. We can check the CPTs with bn.print(DAG) which will result in the message that “no CPD can be printed”. We need to add knowledge to the DAG with so-called Conditional Probabilistic Tables (CPTs) and we will rely on the expert’s knowledge to fill the CPTs." }, { "code": null, "e": 11521, "s": 11441, "text": "Knowledge can be added to the DAG with Conditional Probabilistic Tables (CPTs)." }, { "code": null, "e": 11794, "s": 11521, "text": "The sprinkler system is a simple Bayesian network where Wet grass (child node) is influenced by two-parent nodes (Rain and Sprinkler) (see figure 1). The nodes Sprinkler and Rain are influenced by a single node; Cloudy. The Cloudy node is not influenced by any other node." }, { "code": null, "e": 12047, "s": 11794, "text": "We need to associate each node with a probability function that takes, as input, a particular set of values for the node’s parent variables and gives (as output) the probability of the variable represented by the node. Let’s do this for the four nodes." }, { "code": null, "e": 12468, "s": 12047, "text": "The Cloudy node has two states (yes or no) and no dependencies. Calculating the probability is relatively straightforward when working with a single random variable. From my expert view across the last 1000 days, I have eye-witnessed 70% of the time cloudy weather (I’m not complaining though, just disappointed). As the probabilities should add up to 1, not cloudy should be 30% of the time. The CPT looks as following:" }, { "code": null, "e": 12991, "s": 12468, "text": "The Rain node has two states and is conditioned by Cloudy, which also has two states. In total, we need to specify 4 conditional probabilities, i.e., the probability of one event given the occurrence of another event. In our case; the probability of the event Rain that occurred given Cloudy. The evidence is thus Cloudy and the variable is Rain. From my expert's view I can tell that when it Rained, it was also Cloudy 80% of the time. I did also see rain 20% of the time without visible clouds (Really? Yes. True story)." }, { "code": null, "e": 13491, "s": 12991, "text": "The Sprinkler node has two states and is conditioned by the two states of Cloudy. In total, we need to specify 4 conditional probabilities. Here we need to define the probability of Sprinkler given the occurrence of Cloudy. The evidence is thus Cloudy and the variable is Rain. I can tell that when the Sprinkler was off, it was Cloudy 90% of the time. The counterpart is thus 10% for Sprinkler is true and Cloudy is true. Other probabilities I’m not sure about, so I will set it to 50% of the time." }, { "code": null, "e": 13760, "s": 13491, "text": "The wet grass node has two states and is conditioned by two-parent nodes; Rain and Sprinkler. Here we need to define the probability of wet grass given the occurrence of rain and sprinkler. In total, we have to specify 8 conditional probabilities (2 states ^ 3 nodes)." }, { "code": null, "e": 13986, "s": 13760, "text": "As an expert, I am certain, let’s say 99%, about seeing wet grass after raining or sprinkler was on: P(wet grass=1 | rain=1, sprinkler =1) = 0.99. The counterpart is thus P(wet grass=0| rain=1, sprinkler =1) = 1 – 0.99 = 0.01" }, { "code": null, "e": 14205, "s": 13986, "text": "As an expert, I am entirely sure about no wet grass when it did not rain or the sprinkler was not on: P(wet grass=0 | rain=0, sprinkler =0) = 1. The counterpart is thus: P(wet grass=1 | rain=0, sprinkler =0) = 1 – 1= 0" }, { "code": null, "e": 14435, "s": 14205, "text": "As an expert, I know that wet grass almost always occurred when it was raining and the sprinkler was off (90%). P(wet grass=1 | rain=1, sprinkler=0) = 0.9. The counterpart is: P(wet grass=0 | rain=1, sprinkler=0) = 1 – 0.9 = 0.1." }, { "code": null, "e": 14670, "s": 14435, "text": "As an expert, I know that Wet grass almost always occurred when it was not raining and the sprinkler was on (90%). P(wet grass=1 | rain=0, sprinkler =1) = 0.9. The counterpart is: P(wet grass=0 | rain=0, sprinkler =1) = 1 – 0.9 = 0.1." }, { "code": null, "e": 14814, "s": 14670, "text": "This is it! At this point, we defined the strength of the relationships in the DAG with the CPTs. Now we need to connect the DAG with the CPTs." }, { "code": null, "e": 14960, "s": 14814, "text": "All the CPTs are created and we can now connect them with the DAG. As a sanity check, the CPTs can be examined using the print_DAG functionality." }, { "code": null, "e": 15005, "s": 14960, "text": "The DAG with CPTs will now be like Figure 4." }, { "code": null, "e": 15258, "s": 15005, "text": "Nice work! At this point, you created a model that describes the structure of the data, and the CPTs that quantitatively describe the statistical relationship between each node and its parents. Let’s ask some questions to our model and make inferences!" }, { "code": null, "e": 15464, "s": 15258, "text": "How probable is having wet grass given the sprinkler is off? P(Wet_grass=1 | Sprinkler=0) = 0.6162How probable is a rainy day given sprinkler is off and it is cloudy?P(Rain=1 | Sprinkler=0, Cloudy=1) = 0.8" }, { "code": null, "e": 16136, "s": 15464, "text": "An advantage of Bayesian networks is that it is intuitively easier for a human to understand direct dependencies and local distributions than complete joint distributions. To make knowledge-driven models, we need two ingredients; the DAG and Conditional Probabilistic Tables (CPTs). Both are derived from the expert by questioning. The DAG describes the structure of the data, and CPTs are needed to quantitatively describe the statistical relationship between each node and its parents. Although such an approach seems reasonable to do, you should be aware of systematic errors that can occur by questioning the expert, and the limitations when building a complex model." }, { "code": null, "e": 16803, "s": 16136, "text": "In the sprinkler example, we extracted domain expert’s knowledge through personal experience. Although we created a causal diagram, it is hard to fully verify the validity and completeness of the causal diagram. For example, you may have a different perspective on the probabilities and the graph, and you may also be true about that. As an example, I described that: ‘I did also see rain in 20% of the time without visible clouds’. It may be reasonable to argue about such a statement. In opposite, it can also occur that multiple true knowledge models can exist at the same time. In such a case, you may need to combine the probabilities or fight out who is right." }, { "code": null, "e": 16908, "s": 16803, "text": "The knowledge being used is as rich as the experts experiences and as colored as the experts prejudices." }, { "code": null, "e": 17322, "s": 16908, "text": "Or in other words, the probabilities we extract by questioning an expert are subjective probabilities [5]. In the sprinkler example, it is sufficient to accept that this notion of probability is personal, it reflects the degree of belief of a particular person at a particular location at a particular time. Question yourself this; will the Sprinkler model change if the expert lives in England compared to Spain?" }, { "code": null, "e": 17990, "s": 17322, "text": "If you want to use such a procedure to design a knowledge-driven model, it is important to understand how people (experts) arrive at probabilistic estimations. In literature it is described that people rarely follow the principles of probability when reasoning about uncertain events, rather they replace the laws of probability with a limited number of heuristics [6, 7], such as representativeness, availability, and adjustment from an anchor. Note that this can lead to systematic errors and to that extent incorrect models. Also, make sure that the verbal probability phrase is the same for both sender and receiver in terms of exact probabilities or percentages." }, { "code": null, "e": 18506, "s": 17990, "text": "The presented sprinkler system has only a few nodes but Bayesian networks can contain many more nodes with multiple levels of parent-child dependencies. The number of probability distributions required to populate a conditional probability table (CPT) in a Bayesian network, grows exponentially with the number of parent-nodes associated with that table. If the table is to be populated through knowledge elicited from a domain expert then the sheer magnitude of the task forms a considerable cognitive barrier [8]." }, { "code": null, "e": 18616, "s": 18506, "text": "Too much levels of parent-child dependencies can form a considerable cognitive barrier for the domain expert." }, { "code": null, "e": 19138, "s": 18616, "text": "For example, if m parent nodes represent Boolean variables, then the probability function is represented by a table of 2^m entries, one entry for each of the possible parent combinations. Be hesitant of creating large graphs (more than 10-15 nodes) as the number of parent-child dependencies can form a considerable cognitive barrier for the domain expert. If you have data for the system that you want to model, it is also possible to learn the structure (DAG), and/or its parameters (CPTs) using structure learning [3]." }, { "code": null, "e": 19317, "s": 19138, "text": "I will repeat my earlier statement: “Well, it depends on how accurate you can represent the knowledge as a graph and how precise you can glue it together by probability theorem.”" }, { "code": null, "e": 19908, "s": 19317, "text": "This is it. Creating a knowledge-driven model is not easy. It is not only about data modeling but is also about human psychology. Make sure you prepare for the expert interviews. It is better to have multiple short interviews than one long interview. Ask your questions systematically. First design the graph with nodes and edges, then go into the CPTs. Be cautious when discussing probabilities. Understand how the expert derives his probabilities and normalize when required. Check if time and place can differ the outcome. Make sanity checks after building the model. Smile occasionally." }, { "code": null, "e": 19930, "s": 19908, "text": "Be Safe. Stay Frosty." }, { "code": null, "e": 19941, "s": 19930, "text": "Cheers, E." }, { "code": null, "e": 20098, "s": 19941, "text": "If you found this article helpful, help support my content by signing up for a Medium membership using my referral link or follow me to access similar ones." }, { "code": null, "e": 20127, "s": 20098, "text": "bnlearn github/documentation" }, { "code": null, "e": 20153, "s": 20127, "text": "Let’s connect on LinkedIn" }, { "code": null, "e": 20173, "s": 20153, "text": "Follow me on github" }, { "code": null, "e": 20194, "s": 20173, "text": "Wikipedia, Knowledge" }, { "code": null, "e": 20215, "s": 20194, "text": "Wikipedia, Knowledge" }, { "code": null, "e": 20359, "s": 20215, "text": "2. Pearl, Judea (2000). Causality: Models, Reasoning, and Inference. Cambridge University Press. ISBN 978 – 0 – 521 – 77362 – 1. OCLC 42291253." }, { "code": null, "e": 20487, "s": 20359, "text": "3. E.Taskesen, A Step-by-Step Guide in detecting causal relationships using Bayesian Structure Learning in Python, Medium, 2021" }, { "code": null, "e": 20648, "s": 20487, "text": "4. Sanne Willems, et al, Variability in the interpretation of probability phrases used in Dutch news articles — a risk for miscommunication, JCOM, 24 March 2020" }, { "code": null, "e": 20752, "s": 20648, "text": "5. R. Jeffrey, Subjective Probability: The Real Thing, Cambridge University Press, Cambridge, UK, 2004." }, { "code": null, "e": 20848, "s": 20752, "text": "6. A. Tversky and D. Kahneman, Judgment under Uncertainty: Heuristics and Biases, Science, 1974" }, { "code": null, "e": 21082, "s": 20848, "text": "7. Tversky, and D. Kahneman, ‘Judgment under uncertainty: Heuristics and biases,’ in Judgment under Uncertainty: Heuristics and Biases, D. Kahneman, P. Slovic, and A. Tversky, eds., Cambridge University Press, Cambridge, 1982, pp 3–2" } ]
KMP Algorithm for Pattern Searching - GeeksforGeeks
24 Mar, 2021 Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m. Examples: Input: txt[] = "THIS IS A TEST TEXT" pat[] = "TEST" Output: Pattern found at index 10 Input: txt[] = "AABAACAADAABAABA" pat[] = "AABA" Output: Pattern found at index 0 Pattern found at index 9 Pattern found at index 12 Pattern searching is an important problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results. We have discussed Naive pattern searching algorithm in the previous post. The worst case complexity of the Naive algorithm is O(m(n-m+1)). The time complexity of KMP algorithm is O(n) in the worst case. KMP (Knuth Morris Pratt) Pattern SearchingThe Naive pattern searching algorithm doesn’t work well in cases where we see many matching characters followed by a mismatching character. Following are some examples. txt[] = "AAAAAAAAAAAAAAAAAB" pat[] = "AAAAB" txt[] = "ABABABCABABABCABABABC" pat[] = "ABABAC" (not a worst case, but a bad case for Naive) The KMP matching algorithm uses degenerating property (pattern having same sub-patterns appearing more than once in the pattern) of the pattern and improves the worst case complexity to O(n). The basic idea behind KMP’s algorithm is: whenever we detect a mismatch (after some matches), we already know some of the characters in the text of the next window. We take advantage of this information to avoid matching the characters that we know will anyway match. Let us consider below example to understand this. Matching Overview txt = "AAAAABAAABA" pat = "AAAA" We compare first window of txt with pat txt = "AAAAABAAABA" pat = "AAAA" [Initial position] We find a match. This is same as Naive String Matching. In the next step, we compare next window of txt with pat. txt = "AAAAABAAABA" pat = "AAAA" [Pattern shifted one position] This is where KMP does optimization over Naive. In this second window, we only compare fourth A of pattern with fourth character of current window of text to decide whether current window matches or not. Since we know first three characters will anyway match, we skipped matching first three characters. Need of Preprocessing? An important question arises from the above explanation, how to know how many characters to be skipped. To know this, we pre-process pattern and prepare an integer array lps[] that tells us the count of characters to be skipped. Preprocessing Overview: KMP algorithm preprocesses pat[] and constructs an auxiliary lps[] of size m (same as size of pattern) which is used to skip characters while matching. name lps indicates longest proper prefix which is also suffix.. A proper prefix is prefix with whole string not allowed. For example, prefixes of “ABC” are “”, “A”, “AB” and “ABC”. Proper prefixes are “”, “A” and “AB”. Suffixes of the string are “”, “C”, “BC” and “ABC”. We search for lps in sub-patterns. More clearly we focus on sub-strings of patterns that are either prefix and suffix. For each sub-pattern pat[0..i] where i = 0 to m-1, lps[i] stores length of the maximum matching proper prefix which is also a suffix of the sub-pattern pat[0..i]. lps[i] = the longest proper prefix of pat[0..i] which is also a suffix of pat[0..i]. Note : lps[i] could also be defined as longest prefix which is also proper suffix. We need to use properly at one place to make sure that the whole substring is not considered.Examples of lps[] construction: For the pattern “AAAA”, lps[] is [0, 1, 2, 3] For the pattern “ABCDE”, lps[] is [0, 0, 0, 0, 0] For the pattern “AABAACAABAA”, lps[] is [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5] For the pattern “AAACAAAAAC”, lps[] is [0, 1, 2, 0, 1, 2, 3, 3, 3, 4] For the pattern “AAABAAA”, lps[] is [0, 1, 2, 0, 1, 2, 3] Searching Algorithm:Unlike Naive algorithm, where we slide the pattern by one and compare all characters at each shift, we use a value from lps[] to decide the next characters to be matched. The idea is to not match a character that we know will anyway match.How to use lps[] to decide next positions (or to know a number of characters to be skipped)?We start comparison of pat[j] with j = 0 with characters of current window of text.We keep matching characters txt[i] and pat[j] and keep incrementing i and j while pat[j] and txt[i] keep matching.When we see a mismatchWe know that characters pat[0..j-1] match with txt[i-j...i-1] (Note that j starts with 0 and increment it only when there is a match).We also know (from above definition) that lps[j-1] is count of characters of pat[0...j-1] that are both proper prefix and suffix.From above two points, we can conclude that we do not need to match these lps[j-1] characters with txt[i-j...i-1] because we know that these characters will anyway match. Let us consider above example to understand this.txt[] = "AAAAABAAABA" pat[] = "AAAA" lps[] = {0, 1, 2, 3} i = 0, j = 0 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] match, do i++, j++ i = 1, j = 1 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] match, do i++, j++ i = 2, j = 2 txt[] = "AAAAABAAABA" pat[] = "AAAA" pat[i] and pat[j] match, do i++, j++ i = 3, j = 3 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] match, do i++, j++ i = 4, j = 4 Since j == M, print pattern found and reset j, j = lps[j-1] = lps[3] = 3 Here unlike Naive algorithm, we do not match first three characters of this window. Value of lps[j-1] (in above step) gave us index of next character to match. i = 4, j = 3 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] match, do i++, j++ i = 5, j = 4 Since j == M, print pattern found and reset j, j = lps[j-1] = lps[3] = 3 Again unlike Naive algorithm, we do not match first three characters of this window. Value of lps[j-1] (in above step) gave us index of next character to match. i = 5, j = 3 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] do NOT match and j > 0, change only j j = lps[j-1] = lps[2] = 2 i = 5, j = 2 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] do NOT match and j > 0, change only j j = lps[j-1] = lps[1] = 1 i = 5, j = 1 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] do NOT match and j > 0, change only j j = lps[j-1] = lps[0] = 0 i = 5, j = 0 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] do NOT match and j is 0, we do i++. i = 6, j = 0 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] match, do i++ and j++ i = 7, j = 1 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] match, do i++ and j++ We continue this way... C++JavaPythonC#PHPC++// C++ program for implementation of KMP pattern searching// algorithm#include <bits/stdc++.h> void computeLPSArray(char* pat, int M, int* lps); // Prints occurrences of txt[] in pat[]void KMPSearch(char* pat, char* txt){ int M = strlen(pat); int N = strlen(txt); // create lps[] that will hold the longest prefix suffix // values for pattern int lps[M]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] int j = 0; // index for pat[] while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { printf("Found pattern at index %d ", i - j); j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } }} // Fills lps[] for given patttern pat[0..M-1]void computeLPSArray(char* pat, int M, int* lps){ // length of the previous longest prefix suffix int len = 0; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = 0; i++; } } }} // Driver program to test above functionint main(){ char txt[] = "ABABDABACDABABCABAB"; char pat[] = "ABABCABAB"; KMPSearch(pat, txt); return 0;}Java// JAVA program for implementation of KMP pattern// searching algorithm class KMP_String_Matching { void KMPSearch(String pat, String txt) { int M = pat.length(); int N = txt.length(); // create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] while (i < N) { if (pat.charAt(j) == txt.charAt(i)) { j++; i++; } if (j == M) { System.out.println("Found pattern " + "at index " + (i - j)); j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat.charAt(j) != txt.charAt(i)) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } } void computeLPSArray(String pat, int M, int lps[]) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } // Driver program to test above function public static void main(String args[]) { String txt = "ABABDABACDABABCABAB"; String pat = "ABABCABAB"; new KMP_String_Matching().KMPSearch(pat, txt); }}// This code has been contributed by Amit Khandelwal.Python# Python program for KMP Algorithmdef KMPSearch(pat, txt): M = len(pat) N = len(txt) # create lps[] that will hold the longest prefix suffix # values for pattern lps = [0]*M j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps) i = 0 # index for txt[] while i < N: if pat[j] == txt[i]: i += 1 j += 1 if j == M: print ("Found pattern at index " + str(i-j)) j = lps[j-1] # mismatch after j matches elif i < N and pat[j] != txt[i]: # Do not match lps[0..lps[j-1]] characters, # they will match anyway if j != 0: j = lps[j-1] else: i += 1 def computeLPSArray(pat, M, lps): len = 0 # length of the previous longest prefix suffix lps[0] # lps[0] is always 0 i = 1 # the loop calculates lps[i] for i = 1 to M-1 while i < M: if pat[i]== pat[len]: len += 1 lps[i] = len i += 1 else: # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is similar # to search step. if len != 0: len = lps[len-1] # Also, note that we do not increment i here else: lps[i] = 0 i += 1 txt = "ABABDABACDABABCABAB"pat = "ABABCABAB"KMPSearch(pat, txt) # This code is contributed by Bhavya JainC#// C# program for implementation of KMP pattern// searching algorithmusing System; class GFG { void KMPSearch(string pat, string txt) { int M = pat.Length; int N = txt.Length; // create lps[] that will hold the longest // prefix suffix values for pattern int[] lps = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { Console.Write("Found pattern " + "at index " + (i - j)); j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } } void computeLPSArray(string pat, int M, int[] lps) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } // Driver program to test above function public static void Main() { string txt = "ABABDABACDABABCABAB"; string pat = "ABABCABAB"; new GFG().KMPSearch(pat, txt); }} // This code has been contributed by Amit Khandelwal.PHP<?php// PHP program for implementation of KMP pattern searching// algorithm // Prints occurrences of txt[] in pat[]function KMPSearch($pat, $txt){ $M = strlen($pat); $N = strlen($txt); // create lps[] that will hold the longest prefix suffix // values for pattern $lps=array_fill(0,$M,0); // Preprocess the pattern (calculate lps[] array) computeLPSArray($pat, $M, $lps); $i = 0; // index for txt[] $j = 0; // index for pat[] while ($i < $N) { if ($pat[$j] == $txt[$i]) { $j++; $i++; } if ($j == $M) { printf("Found pattern at index ".($i - $j)); $j = $lps[$j - 1]; } // mismatch after j matches else if ($i < $N && $pat[$j] != $txt[$i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if ($j != 0) $j = $lps[$j - 1]; else $i = $i + 1; } }} // Fills lps[] for given patttern pat[0..M-1]function computeLPSArray($pat, $M, &$lps){ // length of the previous longest prefix suffix $len = 0; $lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 $i = 1; while ($i < $M) { if ($pat[$i] == $pat[$len]) { $len++; $lps[$i] = $len; $i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if ($len != 0) { $len = $lps[$len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { $lps[$i] = 0; $i++; } } }} // Driver program to test above function $txt = "ABABDABACDABABCABAB"; $pat = "ABABCABAB"; KMPSearch($pat, $txt); // This code is contributed by chandan_jnu?>Output:Found pattern at index 10Preprocessing Algorithm:In the preprocessing part, we calculate values in lps[]. To do that, we keep track of the length of the longest prefix suffix value (we use len variable for this purpose) for the previous index. We initialize lps[0] and len as 0. If pat[len] and pat[i] match, we increment len by 1 and assign the incremented value to lps[i]. If pat[i] and pat[len] do not match and len is not 0, we update len to lps[len-1]. See computeLPSArray () in the below code for details.Illustration of preprocessing (or construction of lps[])pat[] = "AAACAAAA" len = 0, i = 0. lps[0] is always 0, we move to i = 1 len = 0, i = 1. Since pat[len] and pat[i] match, do len++, store it in lps[i] and do i++. len = 1, lps[1] = 1, i = 2 len = 1, i = 2. Since pat[len] and pat[i] match, do len++, store it in lps[i] and do i++. len = 2, lps[2] = 2, i = 3 len = 2, i = 3. Since pat[len] and pat[i] do not match, and len > 0, set len = lps[len-1] = lps[1] = 1 len = 1, i = 3. Since pat[len] and pat[i] do not match and len > 0, len = lps[len-1] = lps[0] = 0 len = 0, i = 3. Since pat[len] and pat[i] do not match and len = 0, Set lps[3] = 0 and i = 4. We know that characters pat len = 0, i = 4. Since pat[len] and pat[i] match, do len++, store it in lps[i] and do i++. len = 1, lps[4] = 1, i = 5 len = 1, i = 5. Since pat[len] and pat[i] match, do len++, store it in lps[i] and do i++. len = 2, lps[5] = 2, i = 6 len = 2, i = 6. Since pat[len] and pat[i] match, do len++, store it in lps[i] and do i++. len = 3, lps[6] = 3, i = 7 len = 3, i = 7. Since pat[len] and pat[i] do not match and len > 0, set len = lps[len-1] = lps[2] = 2 len = 2, i = 7. Since pat[len] and pat[i] match, do len++, store it in lps[i] and do i++. len = 3, lps[7] = 3, i = 8 We stop here as we have constructed the whole lps[]. YouTubeGeeksforGeeks500K subscribersKMP Algorithm | Searching for Patterns | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 5:25•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=cH-5KcgUcOE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave lps[i] = the longest proper prefix of pat[0..i] which is also a suffix of pat[0..i]. Note : lps[i] could also be defined as longest prefix which is also proper suffix. We need to use properly at one place to make sure that the whole substring is not considered. Examples of lps[] construction: For the pattern “AAAA”, lps[] is [0, 1, 2, 3] For the pattern “ABCDE”, lps[] is [0, 0, 0, 0, 0] For the pattern “AABAACAABAA”, lps[] is [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5] For the pattern “AAACAAAAAC”, lps[] is [0, 1, 2, 0, 1, 2, 3, 3, 3, 4] For the pattern “AAABAAA”, lps[] is [0, 1, 2, 0, 1, 2, 3] Searching Algorithm:Unlike Naive algorithm, where we slide the pattern by one and compare all characters at each shift, we use a value from lps[] to decide the next characters to be matched. The idea is to not match a character that we know will anyway match. How to use lps[] to decide next positions (or to know a number of characters to be skipped)? We start comparison of pat[j] with j = 0 with characters of current window of text. We keep matching characters txt[i] and pat[j] and keep incrementing i and j while pat[j] and txt[i] keep matching. When we see a mismatchWe know that characters pat[0..j-1] match with txt[i-j...i-1] (Note that j starts with 0 and increment it only when there is a match).We also know (from above definition) that lps[j-1] is count of characters of pat[0...j-1] that are both proper prefix and suffix.From above two points, we can conclude that we do not need to match these lps[j-1] characters with txt[i-j...i-1] because we know that these characters will anyway match. Let us consider above example to understand this. We know that characters pat[0..j-1] match with txt[i-j...i-1] (Note that j starts with 0 and increment it only when there is a match). We also know (from above definition) that lps[j-1] is count of characters of pat[0...j-1] that are both proper prefix and suffix. From above two points, we can conclude that we do not need to match these lps[j-1] characters with txt[i-j...i-1] because we know that these characters will anyway match. Let us consider above example to understand this. txt[] = "AAAAABAAABA" pat[] = "AAAA" lps[] = {0, 1, 2, 3} i = 0, j = 0 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] match, do i++, j++ i = 1, j = 1 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] match, do i++, j++ i = 2, j = 2 txt[] = "AAAAABAAABA" pat[] = "AAAA" pat[i] and pat[j] match, do i++, j++ i = 3, j = 3 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] match, do i++, j++ i = 4, j = 4 Since j == M, print pattern found and reset j, j = lps[j-1] = lps[3] = 3 Here unlike Naive algorithm, we do not match first three characters of this window. Value of lps[j-1] (in above step) gave us index of next character to match. i = 4, j = 3 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] match, do i++, j++ i = 5, j = 4 Since j == M, print pattern found and reset j, j = lps[j-1] = lps[3] = 3 Again unlike Naive algorithm, we do not match first three characters of this window. Value of lps[j-1] (in above step) gave us index of next character to match. i = 5, j = 3 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] do NOT match and j > 0, change only j j = lps[j-1] = lps[2] = 2 i = 5, j = 2 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] do NOT match and j > 0, change only j j = lps[j-1] = lps[1] = 1 i = 5, j = 1 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] do NOT match and j > 0, change only j j = lps[j-1] = lps[0] = 0 i = 5, j = 0 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] do NOT match and j is 0, we do i++. i = 6, j = 0 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] match, do i++ and j++ i = 7, j = 1 txt[] = "AAAAABAAABA" pat[] = "AAAA" txt[i] and pat[j] match, do i++ and j++ We continue this way... C++ Java Python C# PHP // C++ program for implementation of KMP pattern searching// algorithm#include <bits/stdc++.h> void computeLPSArray(char* pat, int M, int* lps); // Prints occurrences of txt[] in pat[]void KMPSearch(char* pat, char* txt){ int M = strlen(pat); int N = strlen(txt); // create lps[] that will hold the longest prefix suffix // values for pattern int lps[M]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] int j = 0; // index for pat[] while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { printf("Found pattern at index %d ", i - j); j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } }} // Fills lps[] for given patttern pat[0..M-1]void computeLPSArray(char* pat, int M, int* lps){ // length of the previous longest prefix suffix int len = 0; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = 0; i++; } } }} // Driver program to test above functionint main(){ char txt[] = "ABABDABACDABABCABAB"; char pat[] = "ABABCABAB"; KMPSearch(pat, txt); return 0;} // JAVA program for implementation of KMP pattern// searching algorithm class KMP_String_Matching { void KMPSearch(String pat, String txt) { int M = pat.length(); int N = txt.length(); // create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] while (i < N) { if (pat.charAt(j) == txt.charAt(i)) { j++; i++; } if (j == M) { System.out.println("Found pattern " + "at index " + (i - j)); j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat.charAt(j) != txt.charAt(i)) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } } void computeLPSArray(String pat, int M, int lps[]) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } // Driver program to test above function public static void main(String args[]) { String txt = "ABABDABACDABABCABAB"; String pat = "ABABCABAB"; new KMP_String_Matching().KMPSearch(pat, txt); }}// This code has been contributed by Amit Khandelwal. # Python program for KMP Algorithmdef KMPSearch(pat, txt): M = len(pat) N = len(txt) # create lps[] that will hold the longest prefix suffix # values for pattern lps = [0]*M j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps) i = 0 # index for txt[] while i < N: if pat[j] == txt[i]: i += 1 j += 1 if j == M: print ("Found pattern at index " + str(i-j)) j = lps[j-1] # mismatch after j matches elif i < N and pat[j] != txt[i]: # Do not match lps[0..lps[j-1]] characters, # they will match anyway if j != 0: j = lps[j-1] else: i += 1 def computeLPSArray(pat, M, lps): len = 0 # length of the previous longest prefix suffix lps[0] # lps[0] is always 0 i = 1 # the loop calculates lps[i] for i = 1 to M-1 while i < M: if pat[i]== pat[len]: len += 1 lps[i] = len i += 1 else: # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is similar # to search step. if len != 0: len = lps[len-1] # Also, note that we do not increment i here else: lps[i] = 0 i += 1 txt = "ABABDABACDABABCABAB"pat = "ABABCABAB"KMPSearch(pat, txt) # This code is contributed by Bhavya Jain // C# program for implementation of KMP pattern// searching algorithmusing System; class GFG { void KMPSearch(string pat, string txt) { int M = pat.Length; int N = txt.Length; // create lps[] that will hold the longest // prefix suffix values for pattern int[] lps = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { Console.Write("Found pattern " + "at index " + (i - j)); j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } } void computeLPSArray(string pat, int M, int[] lps) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } // Driver program to test above function public static void Main() { string txt = "ABABDABACDABABCABAB"; string pat = "ABABCABAB"; new GFG().KMPSearch(pat, txt); }} // This code has been contributed by Amit Khandelwal. <?php// PHP program for implementation of KMP pattern searching// algorithm // Prints occurrences of txt[] in pat[]function KMPSearch($pat, $txt){ $M = strlen($pat); $N = strlen($txt); // create lps[] that will hold the longest prefix suffix // values for pattern $lps=array_fill(0,$M,0); // Preprocess the pattern (calculate lps[] array) computeLPSArray($pat, $M, $lps); $i = 0; // index for txt[] $j = 0; // index for pat[] while ($i < $N) { if ($pat[$j] == $txt[$i]) { $j++; $i++; } if ($j == $M) { printf("Found pattern at index ".($i - $j)); $j = $lps[$j - 1]; } // mismatch after j matches else if ($i < $N && $pat[$j] != $txt[$i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if ($j != 0) $j = $lps[$j - 1]; else $i = $i + 1; } }} // Fills lps[] for given patttern pat[0..M-1]function computeLPSArray($pat, $M, &$lps){ // length of the previous longest prefix suffix $len = 0; $lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 $i = 1; while ($i < $M) { if ($pat[$i] == $pat[$len]) { $len++; $lps[$i] = $len; $i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if ($len != 0) { $len = $lps[$len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { $lps[$i] = 0; $i++; } } }} // Driver program to test above function $txt = "ABABDABACDABABCABAB"; $pat = "ABABCABAB"; KMPSearch($pat, $txt); // This code is contributed by chandan_jnu?> Found pattern at index 10 Preprocessing Algorithm:In the preprocessing part, we calculate values in lps[]. To do that, we keep track of the length of the longest prefix suffix value (we use len variable for this purpose) for the previous index. We initialize lps[0] and len as 0. If pat[len] and pat[i] match, we increment len by 1 and assign the incremented value to lps[i]. If pat[i] and pat[len] do not match and len is not 0, we update len to lps[len-1]. See computeLPSArray () in the below code for details. Illustration of preprocessing (or construction of lps[]) pat[] = "AAACAAAA" len = 0, i = 0. lps[0] is always 0, we move to i = 1 len = 0, i = 1. Since pat[len] and pat[i] match, do len++, store it in lps[i] and do i++. len = 1, lps[1] = 1, i = 2 len = 1, i = 2. Since pat[len] and pat[i] match, do len++, store it in lps[i] and do i++. len = 2, lps[2] = 2, i = 3 len = 2, i = 3. Since pat[len] and pat[i] do not match, and len > 0, set len = lps[len-1] = lps[1] = 1 len = 1, i = 3. Since pat[len] and pat[i] do not match and len > 0, len = lps[len-1] = lps[0] = 0 len = 0, i = 3. Since pat[len] and pat[i] do not match and len = 0, Set lps[3] = 0 and i = 4. We know that characters pat len = 0, i = 4. Since pat[len] and pat[i] match, do len++, store it in lps[i] and do i++. len = 1, lps[4] = 1, i = 5 len = 1, i = 5. Since pat[len] and pat[i] match, do len++, store it in lps[i] and do i++. len = 2, lps[5] = 2, i = 6 len = 2, i = 6. Since pat[len] and pat[i] match, do len++, store it in lps[i] and do i++. len = 3, lps[6] = 3, i = 7 len = 3, i = 7. Since pat[len] and pat[i] do not match and len > 0, set len = lps[len-1] = lps[2] = 2 len = 2, i = 7. Since pat[len] and pat[i] match, do len++, store it in lps[i] and do i++. len = 3, lps[7] = 3, i = 8 We stop here as we have constructed the whole lps[]. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal Krushi Raj geekyzeus codekrafter DavidStone1 Chandan_Kumar sonusharma5102001 ashutoshchauhan0206 Accolite Amazon MakeMyTrip MAQ Software Oracle Payu Pattern Searching Strings Accolite Amazon MakeMyTrip Oracle Payu MAQ Software Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Check if a string is substring of another Wildcard Pattern Matching Search a Word in a 2D Grid of characters Check if an URL is valid or not using Regular Expression Frequency of a substring in a string Reverse a string in Java Write a program to reverse an array or string C++ Data Types Python program to check if a string is palindrome or not Different methods to reverse a string in C/C++
[ { "code": null, "e": 34514, "s": 34486, "text": "\n24 Mar, 2021" }, { "code": null, "e": 34688, "s": 34514, "text": "Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m." }, { "code": null, "e": 34698, "s": 34688, "text": "Examples:" }, { "code": null, "e": 34956, "s": 34698, "text": "Input: txt[] = \"THIS IS A TEST TEXT\"\n pat[] = \"TEST\"\nOutput: Pattern found at index 10\n\nInput: txt[] = \"AABAACAADAABAABA\"\n pat[] = \"AABA\"\nOutput: Pattern found at index 0\n Pattern found at index 9\n Pattern found at index 12\n\n" }, { "code": null, "e": 35161, "s": 34956, "text": "Pattern searching is an important problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results." }, { "code": null, "e": 35364, "s": 35161, "text": "We have discussed Naive pattern searching algorithm in the previous post. The worst case complexity of the Naive algorithm is O(m(n-m+1)). The time complexity of KMP algorithm is O(n) in the worst case." }, { "code": null, "e": 35575, "s": 35364, "text": "KMP (Knuth Morris Pratt) Pattern SearchingThe Naive pattern searching algorithm doesn’t work well in cases where we see many matching characters followed by a mismatching character. Following are some examples." }, { "code": null, "e": 35729, "s": 35575, "text": " txt[] = \"AAAAAAAAAAAAAAAAAB\"\n pat[] = \"AAAAB\"\n\n txt[] = \"ABABABCABABABCABABABC\"\n pat[] = \"ABABAC\" (not a worst case, but a bad case for Naive)\n" }, { "code": null, "e": 36239, "s": 35729, "text": "The KMP matching algorithm uses degenerating property (pattern having same sub-patterns appearing more than once in the pattern) of the pattern and improves the worst case complexity to O(n). The basic idea behind KMP’s algorithm is: whenever we detect a mismatch (after some matches), we already know some of the characters in the text of the next window. We take advantage of this information to avoid matching the characters that we know will anyway match. Let us consider below example to understand this." }, { "code": null, "e": 37134, "s": 36239, "text": "Matching Overview\ntxt = \"AAAAABAAABA\" \npat = \"AAAA\"\n\nWe compare first window of txt with pat\ntxt = \"AAAAABAAABA\" \npat = \"AAAA\" [Initial position]\nWe find a match. This is same as Naive String Matching.\n\nIn the next step, we compare next window of txt with pat.\ntxt = \"AAAAABAAABA\" \npat = \"AAAA\" [Pattern shifted one position]\nThis is where KMP does optimization over Naive. In this \nsecond window, we only compare fourth A of pattern\nwith fourth character of current window of text to decide \nwhether current window matches or not. Since we know \nfirst three characters will anyway match, we skipped \nmatching first three characters. \n\nNeed of Preprocessing?\nAn important question arises from the above explanation, \nhow to know how many characters to be skipped. To know this, \nwe pre-process pattern and prepare an integer array \nlps[] that tells us the count of characters to be skipped. \n" }, { "code": null, "e": 37158, "s": 37134, "text": "Preprocessing Overview:" }, { "code": null, "e": 37310, "s": 37158, "text": "KMP algorithm preprocesses pat[] and constructs an auxiliary lps[] of size m (same as size of pattern) which is used to skip characters while matching." }, { "code": null, "e": 37581, "s": 37310, "text": "name lps indicates longest proper prefix which is also suffix.. A proper prefix is prefix with whole string not allowed. For example, prefixes of “ABC” are “”, “A”, “AB” and “ABC”. Proper prefixes are “”, “A” and “AB”. Suffixes of the string are “”, “C”, “BC” and “ABC”." }, { "code": null, "e": 37700, "s": 37581, "text": "We search for lps in sub-patterns. More clearly we focus on sub-strings of patterns that are either prefix and suffix." }, { "code": null, "e": 54389, "s": 37700, "text": "For each sub-pattern pat[0..i] where i = 0 to m-1, lps[i] stores length of the maximum matching proper prefix which is also a suffix of the sub-pattern pat[0..i]. lps[i] = the longest proper prefix of pat[0..i] \n which is also a suffix of pat[0..i]. Note : lps[i] could also be defined as longest prefix which is also proper suffix. We need to use properly at one place to make sure that the whole substring is not considered.Examples of lps[] construction:\nFor the pattern “AAAA”, \nlps[] is [0, 1, 2, 3]\n\nFor the pattern “ABCDE”, \nlps[] is [0, 0, 0, 0, 0]\n\nFor the pattern “AABAACAABAA”, \nlps[] is [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5]\n\nFor the pattern “AAACAAAAAC”, \nlps[] is [0, 1, 2, 0, 1, 2, 3, 3, 3, 4] \n\nFor the pattern “AAABAAA”, \nlps[] is [0, 1, 2, 0, 1, 2, 3]\nSearching Algorithm:Unlike Naive algorithm, where we slide the pattern by one and compare all characters at each shift, we use a value from lps[] to decide the next characters to be matched. The idea is to not match a character that we know will anyway match.How to use lps[] to decide next positions (or to know a number of characters to be skipped)?We start comparison of pat[j] with j = 0 with characters of current window of text.We keep matching characters txt[i] and pat[j] and keep incrementing i and j while pat[j] and txt[i] keep matching.When we see a mismatchWe know that characters pat[0..j-1] match with txt[i-j...i-1] (Note that j starts with 0 and increment it only when there is a match).We also know (from above definition) that lps[j-1] is count of characters of pat[0...j-1] that are both proper prefix and suffix.From above two points, we can conclude that we do not need to match these lps[j-1] characters with txt[i-j...i-1] because we know that these characters will anyway match. Let us consider above example to understand this.txt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\nlps[] = {0, 1, 2, 3} \n\ni = 0, j = 0\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] match, do i++, j++\n\ni = 1, j = 1\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] match, do i++, j++\n\ni = 2, j = 2\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\npat[i] and pat[j] match, do i++, j++\n\ni = 3, j = 3\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] match, do i++, j++\n\ni = 4, j = 4\nSince j == M, print pattern found and reset j,\nj = lps[j-1] = lps[3] = 3\n\nHere unlike Naive algorithm, we do not match first three \ncharacters of this window. Value of lps[j-1] (in above \nstep) gave us index of next character to match.\ni = 4, j = 3\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] match, do i++, j++\n\ni = 5, j = 4\nSince j == M, print pattern found and reset j,\nj = lps[j-1] = lps[3] = 3\n\nAgain unlike Naive algorithm, we do not match first three \ncharacters of this window. Value of lps[j-1] (in above \nstep) gave us index of next character to match.\ni = 5, j = 3\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] do NOT match and j > 0, change only j\nj = lps[j-1] = lps[2] = 2\n\ni = 5, j = 2\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] do NOT match and j > 0, change only j\nj = lps[j-1] = lps[1] = 1 \n\ni = 5, j = 1\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] do NOT match and j > 0, change only j\nj = lps[j-1] = lps[0] = 0\n\ni = 5, j = 0\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] do NOT match and j is 0, we do i++.\n\ni = 6, j = 0\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] match, do i++ and j++\n\ni = 7, j = 1\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] match, do i++ and j++\n\nWe continue this way...\nC++JavaPythonC#PHPC++// C++ program for implementation of KMP pattern searching// algorithm#include <bits/stdc++.h> void computeLPSArray(char* pat, int M, int* lps); // Prints occurrences of txt[] in pat[]void KMPSearch(char* pat, char* txt){ int M = strlen(pat); int N = strlen(txt); // create lps[] that will hold the longest prefix suffix // values for pattern int lps[M]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] int j = 0; // index for pat[] while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { printf(\"Found pattern at index %d \", i - j); j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } }} // Fills lps[] for given patttern pat[0..M-1]void computeLPSArray(char* pat, int M, int* lps){ // length of the previous longest prefix suffix int len = 0; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = 0; i++; } } }} // Driver program to test above functionint main(){ char txt[] = \"ABABDABACDABABCABAB\"; char pat[] = \"ABABCABAB\"; KMPSearch(pat, txt); return 0;}Java// JAVA program for implementation of KMP pattern// searching algorithm class KMP_String_Matching { void KMPSearch(String pat, String txt) { int M = pat.length(); int N = txt.length(); // create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] while (i < N) { if (pat.charAt(j) == txt.charAt(i)) { j++; i++; } if (j == M) { System.out.println(\"Found pattern \" + \"at index \" + (i - j)); j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat.charAt(j) != txt.charAt(i)) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } } void computeLPSArray(String pat, int M, int lps[]) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } // Driver program to test above function public static void main(String args[]) { String txt = \"ABABDABACDABABCABAB\"; String pat = \"ABABCABAB\"; new KMP_String_Matching().KMPSearch(pat, txt); }}// This code has been contributed by Amit Khandelwal.Python# Python program for KMP Algorithmdef KMPSearch(pat, txt): M = len(pat) N = len(txt) # create lps[] that will hold the longest prefix suffix # values for pattern lps = [0]*M j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps) i = 0 # index for txt[] while i < N: if pat[j] == txt[i]: i += 1 j += 1 if j == M: print (\"Found pattern at index \" + str(i-j)) j = lps[j-1] # mismatch after j matches elif i < N and pat[j] != txt[i]: # Do not match lps[0..lps[j-1]] characters, # they will match anyway if j != 0: j = lps[j-1] else: i += 1 def computeLPSArray(pat, M, lps): len = 0 # length of the previous longest prefix suffix lps[0] # lps[0] is always 0 i = 1 # the loop calculates lps[i] for i = 1 to M-1 while i < M: if pat[i]== pat[len]: len += 1 lps[i] = len i += 1 else: # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is similar # to search step. if len != 0: len = lps[len-1] # Also, note that we do not increment i here else: lps[i] = 0 i += 1 txt = \"ABABDABACDABABCABAB\"pat = \"ABABCABAB\"KMPSearch(pat, txt) # This code is contributed by Bhavya JainC#// C# program for implementation of KMP pattern// searching algorithmusing System; class GFG { void KMPSearch(string pat, string txt) { int M = pat.Length; int N = txt.Length; // create lps[] that will hold the longest // prefix suffix values for pattern int[] lps = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { Console.Write(\"Found pattern \" + \"at index \" + (i - j)); j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } } void computeLPSArray(string pat, int M, int[] lps) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } // Driver program to test above function public static void Main() { string txt = \"ABABDABACDABABCABAB\"; string pat = \"ABABCABAB\"; new GFG().KMPSearch(pat, txt); }} // This code has been contributed by Amit Khandelwal.PHP<?php// PHP program for implementation of KMP pattern searching// algorithm // Prints occurrences of txt[] in pat[]function KMPSearch($pat, $txt){ $M = strlen($pat); $N = strlen($txt); // create lps[] that will hold the longest prefix suffix // values for pattern $lps=array_fill(0,$M,0); // Preprocess the pattern (calculate lps[] array) computeLPSArray($pat, $M, $lps); $i = 0; // index for txt[] $j = 0; // index for pat[] while ($i < $N) { if ($pat[$j] == $txt[$i]) { $j++; $i++; } if ($j == $M) { printf(\"Found pattern at index \".($i - $j)); $j = $lps[$j - 1]; } // mismatch after j matches else if ($i < $N && $pat[$j] != $txt[$i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if ($j != 0) $j = $lps[$j - 1]; else $i = $i + 1; } }} // Fills lps[] for given patttern pat[0..M-1]function computeLPSArray($pat, $M, &$lps){ // length of the previous longest prefix suffix $len = 0; $lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 $i = 1; while ($i < $M) { if ($pat[$i] == $pat[$len]) { $len++; $lps[$i] = $len; $i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if ($len != 0) { $len = $lps[$len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { $lps[$i] = 0; $i++; } } }} // Driver program to test above function $txt = \"ABABDABACDABABCABAB\"; $pat = \"ABABCABAB\"; KMPSearch($pat, $txt); // This code is contributed by chandan_jnu?>Output:Found pattern at index 10Preprocessing Algorithm:In the preprocessing part, we calculate values in lps[]. To do that, we keep track of the length of the longest prefix suffix value (we use len variable for this purpose) for the previous index. We initialize lps[0] and len as 0. If pat[len] and pat[i] match, we increment len by 1 and assign the incremented value to lps[i]. If pat[i] and pat[len] do not match and len is not 0, we update len to lps[len-1]. See computeLPSArray () in the below code for details.Illustration of preprocessing (or construction of lps[])pat[] = \"AAACAAAA\"\n\nlen = 0, i = 0.\nlps[0] is always 0, we move \nto i = 1\n\nlen = 0, i = 1.\nSince pat[len] and pat[i] match, do len++, \nstore it in lps[i] and do i++.\nlen = 1, lps[1] = 1, i = 2\n\nlen = 1, i = 2.\nSince pat[len] and pat[i] match, do len++, \nstore it in lps[i] and do i++.\nlen = 2, lps[2] = 2, i = 3\n\nlen = 2, i = 3.\nSince pat[len] and pat[i] do not match, and len > 0, \nset len = lps[len-1] = lps[1] = 1\n\nlen = 1, i = 3.\nSince pat[len] and pat[i] do not match and len > 0, \nlen = lps[len-1] = lps[0] = 0\n\nlen = 0, i = 3.\nSince pat[len] and pat[i] do not match and len = 0, \nSet lps[3] = 0 and i = 4.\nWe know that characters pat\nlen = 0, i = 4.\nSince pat[len] and pat[i] match, do len++, \nstore it in lps[i] and do i++.\nlen = 1, lps[4] = 1, i = 5\n\nlen = 1, i = 5.\nSince pat[len] and pat[i] match, do len++, \nstore it in lps[i] and do i++.\nlen = 2, lps[5] = 2, i = 6\n\nlen = 2, i = 6.\nSince pat[len] and pat[i] match, do len++, \nstore it in lps[i] and do i++.\nlen = 3, lps[6] = 3, i = 7\n\nlen = 3, i = 7.\nSince pat[len] and pat[i] do not match and len > 0,\nset len = lps[len-1] = lps[2] = 2\n\nlen = 2, i = 7.\nSince pat[len] and pat[i] match, do len++, \nstore it in lps[i] and do i++.\nlen = 3, lps[7] = 3, i = 8\n\nWe stop here as we have constructed the whole lps[].\nYouTubeGeeksforGeeks500K subscribersKMP Algorithm | Searching for Patterns | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 5:25•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=cH-5KcgUcOE\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 54493, "s": 54389, "text": " lps[i] = the longest proper prefix of pat[0..i] \n which is also a suffix of pat[0..i]. " }, { "code": null, "e": 54670, "s": 54493, "text": "Note : lps[i] could also be defined as longest prefix which is also proper suffix. We need to use properly at one place to make sure that the whole substring is not considered." }, { "code": null, "e": 55011, "s": 54670, "text": "Examples of lps[] construction:\nFor the pattern “AAAA”, \nlps[] is [0, 1, 2, 3]\n\nFor the pattern “ABCDE”, \nlps[] is [0, 0, 0, 0, 0]\n\nFor the pattern “AABAACAABAA”, \nlps[] is [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5]\n\nFor the pattern “AAACAAAAAC”, \nlps[] is [0, 1, 2, 0, 1, 2, 3, 3, 3, 4] \n\nFor the pattern “AAABAAA”, \nlps[] is [0, 1, 2, 0, 1, 2, 3]\n" }, { "code": null, "e": 55271, "s": 55011, "text": "Searching Algorithm:Unlike Naive algorithm, where we slide the pattern by one and compare all characters at each shift, we use a value from lps[] to decide the next characters to be matched. The idea is to not match a character that we know will anyway match." }, { "code": null, "e": 55364, "s": 55271, "text": "How to use lps[] to decide next positions (or to know a number of characters to be skipped)?" }, { "code": null, "e": 55448, "s": 55364, "text": "We start comparison of pat[j] with j = 0 with characters of current window of text." }, { "code": null, "e": 55563, "s": 55448, "text": "We keep matching characters txt[i] and pat[j] and keep incrementing i and j while pat[j] and txt[i] keep matching." }, { "code": null, "e": 56069, "s": 55563, "text": "When we see a mismatchWe know that characters pat[0..j-1] match with txt[i-j...i-1] (Note that j starts with 0 and increment it only when there is a match).We also know (from above definition) that lps[j-1] is count of characters of pat[0...j-1] that are both proper prefix and suffix.From above two points, we can conclude that we do not need to match these lps[j-1] characters with txt[i-j...i-1] because we know that these characters will anyway match. Let us consider above example to understand this." }, { "code": null, "e": 56204, "s": 56069, "text": "We know that characters pat[0..j-1] match with txt[i-j...i-1] (Note that j starts with 0 and increment it only when there is a match)." }, { "code": null, "e": 56334, "s": 56204, "text": "We also know (from above definition) that lps[j-1] is count of characters of pat[0...j-1] that are both proper prefix and suffix." }, { "code": null, "e": 56555, "s": 56334, "text": "From above two points, we can conclude that we do not need to match these lps[j-1] characters with txt[i-j...i-1] because we know that these characters will anyway match. Let us consider above example to understand this." }, { "code": null, "e": 58305, "s": 56555, "text": "txt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\nlps[] = {0, 1, 2, 3} \n\ni = 0, j = 0\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] match, do i++, j++\n\ni = 1, j = 1\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] match, do i++, j++\n\ni = 2, j = 2\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\npat[i] and pat[j] match, do i++, j++\n\ni = 3, j = 3\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] match, do i++, j++\n\ni = 4, j = 4\nSince j == M, print pattern found and reset j,\nj = lps[j-1] = lps[3] = 3\n\nHere unlike Naive algorithm, we do not match first three \ncharacters of this window. Value of lps[j-1] (in above \nstep) gave us index of next character to match.\ni = 4, j = 3\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] match, do i++, j++\n\ni = 5, j = 4\nSince j == M, print pattern found and reset j,\nj = lps[j-1] = lps[3] = 3\n\nAgain unlike Naive algorithm, we do not match first three \ncharacters of this window. Value of lps[j-1] (in above \nstep) gave us index of next character to match.\ni = 5, j = 3\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] do NOT match and j > 0, change only j\nj = lps[j-1] = lps[2] = 2\n\ni = 5, j = 2\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] do NOT match and j > 0, change only j\nj = lps[j-1] = lps[1] = 1 \n\ni = 5, j = 1\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] do NOT match and j > 0, change only j\nj = lps[j-1] = lps[0] = 0\n\ni = 5, j = 0\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] do NOT match and j is 0, we do i++.\n\ni = 6, j = 0\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] match, do i++ and j++\n\ni = 7, j = 1\ntxt[] = \"AAAAABAAABA\" \npat[] = \"AAAA\"\ntxt[i] and pat[j] match, do i++ and j++\n\nWe continue this way...\n" }, { "code": null, "e": 58309, "s": 58305, "text": "C++" }, { "code": null, "e": 58314, "s": 58309, "text": "Java" }, { "code": null, "e": 58321, "s": 58314, "text": "Python" }, { "code": null, "e": 58324, "s": 58321, "text": "C#" }, { "code": null, "e": 58328, "s": 58324, "text": "PHP" }, { "code": "// C++ program for implementation of KMP pattern searching// algorithm#include <bits/stdc++.h> void computeLPSArray(char* pat, int M, int* lps); // Prints occurrences of txt[] in pat[]void KMPSearch(char* pat, char* txt){ int M = strlen(pat); int N = strlen(txt); // create lps[] that will hold the longest prefix suffix // values for pattern int lps[M]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] int j = 0; // index for pat[] while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { printf(\"Found pattern at index %d \", i - j); j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } }} // Fills lps[] for given patttern pat[0..M-1]void computeLPSArray(char* pat, int M, int* lps){ // length of the previous longest prefix suffix int len = 0; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = 0; i++; } } }} // Driver program to test above functionint main(){ char txt[] = \"ABABDABACDABABCABAB\"; char pat[] = \"ABABCABAB\"; KMPSearch(pat, txt); return 0;}", "e": 60355, "s": 58328, "text": null }, { "code": "// JAVA program for implementation of KMP pattern// searching algorithm class KMP_String_Matching { void KMPSearch(String pat, String txt) { int M = pat.length(); int N = txt.length(); // create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] while (i < N) { if (pat.charAt(j) == txt.charAt(i)) { j++; i++; } if (j == M) { System.out.println(\"Found pattern \" + \"at index \" + (i - j)); j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat.charAt(j) != txt.charAt(i)) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } } void computeLPSArray(String pat, int M, int lps[]) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } // Driver program to test above function public static void main(String args[]) { String txt = \"ABABDABACDABABCABAB\"; String pat = \"ABABCABAB\"; new KMP_String_Matching().KMPSearch(pat, txt); }}// This code has been contributed by Amit Khandelwal.", "e": 62741, "s": 60355, "text": null }, { "code": "# Python program for KMP Algorithmdef KMPSearch(pat, txt): M = len(pat) N = len(txt) # create lps[] that will hold the longest prefix suffix # values for pattern lps = [0]*M j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps) i = 0 # index for txt[] while i < N: if pat[j] == txt[i]: i += 1 j += 1 if j == M: print (\"Found pattern at index \" + str(i-j)) j = lps[j-1] # mismatch after j matches elif i < N and pat[j] != txt[i]: # Do not match lps[0..lps[j-1]] characters, # they will match anyway if j != 0: j = lps[j-1] else: i += 1 def computeLPSArray(pat, M, lps): len = 0 # length of the previous longest prefix suffix lps[0] # lps[0] is always 0 i = 1 # the loop calculates lps[i] for i = 1 to M-1 while i < M: if pat[i]== pat[len]: len += 1 lps[i] = len i += 1 else: # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is similar # to search step. if len != 0: len = lps[len-1] # Also, note that we do not increment i here else: lps[i] = 0 i += 1 txt = \"ABABDABACDABABCABAB\"pat = \"ABABCABAB\"KMPSearch(pat, txt) # This code is contributed by Bhavya Jain", "e": 64242, "s": 62741, "text": null }, { "code": "// C# program for implementation of KMP pattern// searching algorithmusing System; class GFG { void KMPSearch(string pat, string txt) { int M = pat.Length; int N = txt.Length; // create lps[] that will hold the longest // prefix suffix values for pattern int[] lps = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { Console.Write(\"Found pattern \" + \"at index \" + (i - j)); j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } } void computeLPSArray(string pat, int M, int[] lps) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } // Driver program to test above function public static void Main() { string txt = \"ABABDABACDABABCABAB\"; string pat = \"ABABCABAB\"; new GFG().KMPSearch(pat, txt); }} // This code has been contributed by Amit Khandelwal.", "e": 66542, "s": 64242, "text": null }, { "code": "<?php// PHP program for implementation of KMP pattern searching// algorithm // Prints occurrences of txt[] in pat[]function KMPSearch($pat, $txt){ $M = strlen($pat); $N = strlen($txt); // create lps[] that will hold the longest prefix suffix // values for pattern $lps=array_fill(0,$M,0); // Preprocess the pattern (calculate lps[] array) computeLPSArray($pat, $M, $lps); $i = 0; // index for txt[] $j = 0; // index for pat[] while ($i < $N) { if ($pat[$j] == $txt[$i]) { $j++; $i++; } if ($j == $M) { printf(\"Found pattern at index \".($i - $j)); $j = $lps[$j - 1]; } // mismatch after j matches else if ($i < $N && $pat[$j] != $txt[$i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if ($j != 0) $j = $lps[$j - 1]; else $i = $i + 1; } }} // Fills lps[] for given patttern pat[0..M-1]function computeLPSArray($pat, $M, &$lps){ // length of the previous longest prefix suffix $len = 0; $lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 $i = 1; while ($i < $M) { if ($pat[$i] == $pat[$len]) { $len++; $lps[$i] = $len; $i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if ($len != 0) { $len = $lps[$len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { $lps[$i] = 0; $i++; } } }} // Driver program to test above function $txt = \"ABABDABACDABABCABAB\"; $pat = \"ABABCABAB\"; KMPSearch($pat, $txt); // This code is contributed by chandan_jnu?>", "e": 68549, "s": 66542, "text": null }, { "code": null, "e": 68575, "s": 68549, "text": "Found pattern at index 10" }, { "code": null, "e": 69062, "s": 68575, "text": "Preprocessing Algorithm:In the preprocessing part, we calculate values in lps[]. To do that, we keep track of the length of the longest prefix suffix value (we use len variable for this purpose) for the previous index. We initialize lps[0] and len as 0. If pat[len] and pat[i] match, we increment len by 1 and assign the incremented value to lps[i]. If pat[i] and pat[len] do not match and len is not 0, we update len to lps[len-1]. See computeLPSArray () in the below code for details." }, { "code": null, "e": 69119, "s": 69062, "text": "Illustration of preprocessing (or construction of lps[])" }, { "code": null, "e": 70404, "s": 69119, "text": "pat[] = \"AAACAAAA\"\n\nlen = 0, i = 0.\nlps[0] is always 0, we move \nto i = 1\n\nlen = 0, i = 1.\nSince pat[len] and pat[i] match, do len++, \nstore it in lps[i] and do i++.\nlen = 1, lps[1] = 1, i = 2\n\nlen = 1, i = 2.\nSince pat[len] and pat[i] match, do len++, \nstore it in lps[i] and do i++.\nlen = 2, lps[2] = 2, i = 3\n\nlen = 2, i = 3.\nSince pat[len] and pat[i] do not match, and len > 0, \nset len = lps[len-1] = lps[1] = 1\n\nlen = 1, i = 3.\nSince pat[len] and pat[i] do not match and len > 0, \nlen = lps[len-1] = lps[0] = 0\n\nlen = 0, i = 3.\nSince pat[len] and pat[i] do not match and len = 0, \nSet lps[3] = 0 and i = 4.\nWe know that characters pat\nlen = 0, i = 4.\nSince pat[len] and pat[i] match, do len++, \nstore it in lps[i] and do i++.\nlen = 1, lps[4] = 1, i = 5\n\nlen = 1, i = 5.\nSince pat[len] and pat[i] match, do len++, \nstore it in lps[i] and do i++.\nlen = 2, lps[5] = 2, i = 6\n\nlen = 2, i = 6.\nSince pat[len] and pat[i] match, do len++, \nstore it in lps[i] and do i++.\nlen = 3, lps[6] = 3, i = 7\n\nlen = 3, i = 7.\nSince pat[len] and pat[i] do not match and len > 0,\nset len = lps[len-1] = lps[2] = 2\n\nlen = 2, i = 7.\nSince pat[len] and pat[i] match, do len++, \nstore it in lps[i] and do i++.\nlen = 3, lps[7] = 3, i = 8\n\nWe stop here as we have constructed the whole lps[].\n" }, { "code": null, "e": 70529, "s": 70404, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 70542, "s": 70529, "text": "nitin mittal" }, { "code": null, "e": 70553, "s": 70542, "text": "Krushi Raj" }, { "code": null, "e": 70563, "s": 70553, "text": "geekyzeus" }, { "code": null, "e": 70575, "s": 70563, "text": "codekrafter" }, { "code": null, "e": 70587, "s": 70575, "text": "DavidStone1" }, { "code": null, "e": 70601, "s": 70587, "text": "Chandan_Kumar" }, { "code": null, "e": 70619, "s": 70601, "text": "sonusharma5102001" }, { "code": null, "e": 70639, "s": 70619, "text": "ashutoshchauhan0206" }, { "code": null, "e": 70648, "s": 70639, "text": "Accolite" }, { "code": null, "e": 70655, "s": 70648, "text": "Amazon" }, { "code": null, "e": 70666, "s": 70655, "text": "MakeMyTrip" }, { "code": null, "e": 70679, "s": 70666, "text": "MAQ Software" }, { "code": null, "e": 70686, "s": 70679, "text": "Oracle" }, { "code": null, "e": 70691, "s": 70686, "text": "Payu" }, { "code": null, "e": 70709, "s": 70691, "text": "Pattern Searching" }, { "code": null, "e": 70717, "s": 70709, "text": "Strings" }, { "code": null, "e": 70726, "s": 70717, "text": "Accolite" }, { "code": null, "e": 70733, "s": 70726, "text": "Amazon" }, { "code": null, "e": 70744, "s": 70733, "text": "MakeMyTrip" }, { "code": null, "e": 70751, "s": 70744, "text": "Oracle" }, { "code": null, "e": 70756, "s": 70751, "text": "Payu" }, { "code": null, "e": 70769, "s": 70756, "text": "MAQ Software" }, { "code": null, "e": 70777, "s": 70769, "text": "Strings" }, { "code": null, "e": 70795, "s": 70777, "text": "Pattern Searching" }, { "code": null, "e": 70893, "s": 70795, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 70902, "s": 70893, "text": "Comments" }, { "code": null, "e": 70915, "s": 70902, "text": "Old Comments" }, { "code": null, "e": 70957, "s": 70915, "text": "Check if a string is substring of another" }, { "code": null, "e": 70983, "s": 70957, "text": "Wildcard Pattern Matching" }, { "code": null, "e": 71024, "s": 70983, "text": "Search a Word in a 2D Grid of characters" }, { "code": null, "e": 71081, "s": 71024, "text": "Check if an URL is valid or not using Regular Expression" }, { "code": null, "e": 71118, "s": 71081, "text": "Frequency of a substring in a string" }, { "code": null, "e": 71143, "s": 71118, "text": "Reverse a string in Java" }, { "code": null, "e": 71189, "s": 71143, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 71204, "s": 71189, "text": "C++ Data Types" }, { "code": null, "e": 71261, "s": 71204, "text": "Python program to check if a string is palindrome or not" } ]
Serverless Functions and Using AWS Lambda with S3 Buckets | by Abdul Rahman | Towards Data Science
In my previous articles you may have seen me going on and on about deploying code on server instances on the cloud, building services to manage those instances, building a reverse-proxy on top of those services and so on. No doubt that some of you may have wished if you could just write code, deploy it somewhere and not bother about the excessive complexities of setting up and managing server instances. Well, depending on your use case, there might be a solution — Serverless Functions. Serverless functions allow code to be deployed without you allocating any infrastructure for the code to be hosted on. AWS Lambda is an FaaS (Function as a Service) platform that allows you to build serverless functions. AWS Lambda supports most major programming languages like Go, Java, Ruby, Python2 and Python3. For this tutorial, we will be using Python3. Even though they are called “serverless”, they actually run inside a variety of runtime environments on cloud server instances. Serverless functions are stateless, i.e. one execution of a function does not maintain a state that subsequent executions can recognise or use. In other words one execution of a Serverless function does not in any way communicate with another execution. Since serverless functions are time- and resource-limited, they are suitable for short-lived tasks. They provide very little flexibility in terms of allocation of memory, CPU, storage etc. One implication of adopting a certain FaaS platform for going Serverless is that you are stuck with the platform’s vendor for most other cloud services that your serverless functions may interact with. Serverless functions can be used to build a microservices architecture, where your software is built up of smaller, independent microservices that provide specific functionalities. Microservices make it easier for developers to build, test and manage software in an agile way. Microservices are completely separate pieces of your software, so different microservices can be coded, tested and deployed in parallel. It is much easier to pin-point and fix errors in a microservices architecture as you only have to work with the microservice that is malfunctioning. Netflix, for instance, became one of the earliest adopters of a microservices-based architecture when they began moving their software onto AWS cloud in 2009. They currently maintain an API gateway that receives billions of requests daily and is built up of separate microservices for processes like user sign-up, downloading movies etc. By switching to a microservices architecture, Netflix was able to speed up development and testing of its software and easily rollback if errors were encountered. Serverless functions on AWS Lambda or simply Lambda functions can do some really cool things when used in combination with other AWS services, like using Amazon Alexa to turn EC2 instances on and off or lighting bulbs when something’s pushed onto your CodeCommit (or even GitHub) repository. There are 3 ways you can use Lambda in combination with other AWS services: Use other AWS services as triggers to invoke lambda functions*. A lambda function can have multiple triggers using a wide range of AWS services, like an S3 bucket PUT or DELETE event, a call to an API Gateway endpoint etc.Interact with AWS services from inside the lambda function, like adding or deleting data in a DynamoDB database or getting the state of an EC2 instance. You can do this using a variety of SDKs (Software Development Kits) built by AWS, for Java, Python**, Ruby and more in your lambda function’s code. A long list of AWS services can be controlled or communicated with, using these SDKs.Use AWS services as destinations for invocation records of your Lambda function whenever it is invoked. As of today, only 4 AWS services can be used this way: SNS, SQS, EventBridge or Lambda itself. Use other AWS services as triggers to invoke lambda functions*. A lambda function can have multiple triggers using a wide range of AWS services, like an S3 bucket PUT or DELETE event, a call to an API Gateway endpoint etc. Interact with AWS services from inside the lambda function, like adding or deleting data in a DynamoDB database or getting the state of an EC2 instance. You can do this using a variety of SDKs (Software Development Kits) built by AWS, for Java, Python**, Ruby and more in your lambda function’s code. A long list of AWS services can be controlled or communicated with, using these SDKs. Use AWS services as destinations for invocation records of your Lambda function whenever it is invoked. As of today, only 4 AWS services can be used this way: SNS, SQS, EventBridge or Lambda itself. * When a Lambda function is invoked by another AWS service, Lambda passes specific information from that AWS service to the function using an event object. This will include information like what item in which DynamoDB database triggered the Lambda function. ** Boto3 is a python library (or SDK) built by AWS that allows you to interact with AWS services such as EC2, ECS, S3, DynamoDB etc. In this tutorial we will be using Boto3 to manage files inside an AWS S3 bucket. Full documentation for Boto3 can be found here. Pre-requisites for this tutorial: An AWS free-tier account. An S3 bucket is simply a storage space in AWS cloud for any kind of data (Eg., videos, code, AWS templates etc.). Every directory and file inside an S3 bucket can be uniquely identified using a key which is simply it’s path relative to the root directory (which is the bucket itself). For example, “car.jpg” or “images/car.jpg”. Besides being a powerful resource for developing microservices-based software, Lambda functions make highly effective DevOps tools. Let’s look at an example of using Lambda functions with S3 buckets in the first two ways mentioned above to solve a simple DevOps problem :) Say you are receiving XML data from three different gas meters straight into an AWS S3 bucket. You want to sort the XML files into three separate folders based on which gas meter the data comes from. The only way to know the data source is to look inside the XML files, which look like this: <data> <data-source>gas_meter3</data-source> <data-content>bla bla bla</data-content></data> How would you automate this process? This is where AWS lambda could prove handy. Let’s look at how to do this. 1 - Creating an S3 bucket Let’s start by building an empty S3 bucket. All you have to do is to go to the S3 page from your AWS console and click on the “Create bucket” button. Make sure you leave the “Block all public access” checkbox ticked and click on “Create bucket”. Now, add a directory called “unsorted” where all the XML files will be stored initially. Create a .xml file named “testdata.xml” with the following content: <data> <data-source>gas_meter3</data-source> <data-content>bla bla bla</data-content></data> 2 - Creating a Lambda function From the Services tab on the AWS console, click on “Lambda”. From the left pane on the Lambda page, select “Functions” and then “Create Functions”. Select “Author from scratch” and give the function a suitable name. Since I’ll be using Python3, I chose “Python3.8” as the runtime language. There are other versions of Python2 and Python3 available as well. Select a runtime language and click on the “Create function” button. From the list of Lambda functions on the “Functions” page, select the function you just created and you will be taken to the function’s page. Lambda automatically creates an IAM role for you to use with the Lambda function. The IAM role can be found under the “Permissions” tab on the function’s page. You need to ensure that the function’s IAM role has permission to access and/or manage the AWS services you connect to from inside your function. Make sure you add “S3” permissions to the IAM role’s list of permissions, accessible via the IAM console. 3 - Adding a trigger for our Lambda function We want the Lambda function to be invoked every time an XML file is uploaded to the “unsorted” folder. To do this, we will use an S3 bucket PUT event as a trigger for our function. Under the “Designer” section on our Lambda function’s page, click on the “Add trigger” button. Select the “S3” trigger and the bucket you just created. Select “PUT” event type. Set the prefix and suffix as “unsorted/” and “.xml” respectively. Finally, click on “Add”. 4 - Adding code to our Lambda function There are 3 ways you can add code to your Lambda function: Through the code editor available on the console.By uploading a .zip file containing all your code and dependencies.By uploading code from an S3 bucket. Through the code editor available on the console. By uploading a .zip file containing all your code and dependencies. By uploading code from an S3 bucket. We will use the first method for this tutorial. On your function page, go down to the “Function code” section to find the code editor. Copy and paste the following code into the code editor: import jsonimport boto3import uuidfrom urllib.parse import unquote_plusimport xml.etree.ElementTree as ETdef lambda_handler(event, context): s3 = boto3.resource('s3', region_name='')#Replace with your region name #Loops through every file uploaded for record in event['Records']: bucket_name = record['s3']['bucket']['name'] bucket = s3.Bucket(bucket_name) key = unquote_plus(record['s3']['object']['key']) # Temporarily download the xml file for processing tmpkey = key.replace('/', '') download_path = '/tmp/{}{}'.format(uuid.uuid4(), tmpkey) bucket.download_file( key, download_path) machine_id = get_machine_id_from_file(download_path) bucket.upload_file(download_path, machine_id+'/'+key[9:]) s3.Object(bucket_name,key).delete()def get_machine_id_from_file(path): tree = ET.parse(path) root = tree.getroot() return root[0].text Don’t forget to replace the region name. Make sure the handler value is “<filename>.lambda_handler” . The handler value specifies which function contains the main code that Lambda executes. Whenever Lambda runs your function, it passes a context object and an event object to it. This object can be used to get information about the function itself and its invocation, eg., function name, memory limit, log group id etc. The context object can be very useful for logging, monitoring and data analytics usages. As mentioned earlier the event object is used by Lambda to provide specific information to the Lamda function from the AWS service that invoked the function. The information, which originally comes in JSON format, is converted to an object before being passed into the function. In the case of Python, this object is typically a dictionary. In the code above, you can see that the event object has been used to get the name of the S3 bucket and the key of the object inside the S3 bucket that triggered our function. The code above is simple to understand. It does the following: Get info from event object.Download the XML file that caused the Lambda function to be invoked.Process the XML file to find the machine_id from the first line of the XML file.Upload the file back to the S3 bucket, but inside a folder named the value of machine_id.Delete the original file. Get info from event object. Download the XML file that caused the Lambda function to be invoked. Process the XML file to find the machine_id from the first line of the XML file. Upload the file back to the S3 bucket, but inside a folder named the value of machine_id. Delete the original file. Now press the “Deploy” button and our function should be ready to run. 5 - Testing our Lambda function AWS has made it pretty easy to test Lambda functions via the Lambda console. No matter what trigger your Lambda function uses, you can simulate the invocation of your Lambda function using the Test feature on the Lambda console. All this takes is defining what event object will be passed into the function. To help you do this, Lambda provides JSON templates specific to each type of trigger. For example, the template for an S3 PUT event looks like this: { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": "us-west-2", "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "126.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": "example-bucket", "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3:::example-bucket" }, "object": { "key": "test/key", "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ]} To test the Lambda function you just created, you need to configure a test event for your function. To do this, click on the “Select a test event” dropdown right above the Lambda code editor and click on “Configure test event”. From the pop up menu, make sure the “Create new test event” radio button is selected and select the “Amazon S3 Put” event template. You should be provided with JSON data similar to that in the code snippet above. All we are concerned with is the data that is used in our Lambda function, which is the bucket name and the object key. Edit those two values appropriate to the S3 bucket and the XML file you created earlier. Finally give the test event a name and click on “Create”. Now that you have a test event for your Lambda function, all you have to do is click on the“Test” button on top of the code editor. The console will tell you if the function code was executed without any errors. To check if everything worked go to your S3 bucket to see if the XML file has been moved to a newly created “gas-meter3/” directory. As you may have noticed, one downside of testing via the console is that the Lambda function actually communicates with other AWS services. This may cause unintentional changes to your AWS resources or even loss of valuable work. The solution to this is to build and run your lambda functions locally on your machine. Testing Lambda functions locally is not as straightforward. You will need to use tools like SAM CLI and Localstack to do this. 6 - All done! Now your Lambda function should sort any XML files uploaded to the “unsorted” folder on your S3 bucket into separate folders, provided that the XML data is in the format specified in this tutorial. I hope that this article gave you a taste of what is achievable using AWS Lambda and some insight into Serverless Functions in general. Now it’s your time to get creative with AWS Lambda. Thank you for reading!
[ { "code": null, "e": 662, "s": 171, "text": "In my previous articles you may have seen me going on and on about deploying code on server instances on the cloud, building services to manage those instances, building a reverse-proxy on top of those services and so on. No doubt that some of you may have wished if you could just write code, deploy it somewhere and not bother about the excessive complexities of setting up and managing server instances. Well, depending on your use case, there might be a solution — Serverless Functions." }, { "code": null, "e": 1151, "s": 662, "text": "Serverless functions allow code to be deployed without you allocating any infrastructure for the code to be hosted on. AWS Lambda is an FaaS (Function as a Service) platform that allows you to build serverless functions. AWS Lambda supports most major programming languages like Go, Java, Ruby, Python2 and Python3. For this tutorial, we will be using Python3. Even though they are called “serverless”, they actually run inside a variety of runtime environments on cloud server instances." }, { "code": null, "e": 1796, "s": 1151, "text": "Serverless functions are stateless, i.e. one execution of a function does not maintain a state that subsequent executions can recognise or use. In other words one execution of a Serverless function does not in any way communicate with another execution. Since serverless functions are time- and resource-limited, they are suitable for short-lived tasks. They provide very little flexibility in terms of allocation of memory, CPU, storage etc. One implication of adopting a certain FaaS platform for going Serverless is that you are stuck with the platform’s vendor for most other cloud services that your serverless functions may interact with." }, { "code": null, "e": 2359, "s": 1796, "text": "Serverless functions can be used to build a microservices architecture, where your software is built up of smaller, independent microservices that provide specific functionalities. Microservices make it easier for developers to build, test and manage software in an agile way. Microservices are completely separate pieces of your software, so different microservices can be coded, tested and deployed in parallel. It is much easier to pin-point and fix errors in a microservices architecture as you only have to work with the microservice that is malfunctioning." }, { "code": null, "e": 2860, "s": 2359, "text": "Netflix, for instance, became one of the earliest adopters of a microservices-based architecture when they began moving their software onto AWS cloud in 2009. They currently maintain an API gateway that receives billions of requests daily and is built up of separate microservices for processes like user sign-up, downloading movies etc. By switching to a microservices architecture, Netflix was able to speed up development and testing of its software and easily rollback if errors were encountered." }, { "code": null, "e": 3152, "s": 2860, "text": "Serverless functions on AWS Lambda or simply Lambda functions can do some really cool things when used in combination with other AWS services, like using Amazon Alexa to turn EC2 instances on and off or lighting bulbs when something’s pushed onto your CodeCommit (or even GitHub) repository." }, { "code": null, "e": 3228, "s": 3152, "text": "There are 3 ways you can use Lambda in combination with other AWS services:" }, { "code": null, "e": 4035, "s": 3228, "text": "Use other AWS services as triggers to invoke lambda functions*. A lambda function can have multiple triggers using a wide range of AWS services, like an S3 bucket PUT or DELETE event, a call to an API Gateway endpoint etc.Interact with AWS services from inside the lambda function, like adding or deleting data in a DynamoDB database or getting the state of an EC2 instance. You can do this using a variety of SDKs (Software Development Kits) built by AWS, for Java, Python**, Ruby and more in your lambda function’s code. A long list of AWS services can be controlled or communicated with, using these SDKs.Use AWS services as destinations for invocation records of your Lambda function whenever it is invoked. As of today, only 4 AWS services can be used this way: SNS, SQS, EventBridge or Lambda itself." }, { "code": null, "e": 4258, "s": 4035, "text": "Use other AWS services as triggers to invoke lambda functions*. A lambda function can have multiple triggers using a wide range of AWS services, like an S3 bucket PUT or DELETE event, a call to an API Gateway endpoint etc." }, { "code": null, "e": 4645, "s": 4258, "text": "Interact with AWS services from inside the lambda function, like adding or deleting data in a DynamoDB database or getting the state of an EC2 instance. You can do this using a variety of SDKs (Software Development Kits) built by AWS, for Java, Python**, Ruby and more in your lambda function’s code. A long list of AWS services can be controlled or communicated with, using these SDKs." }, { "code": null, "e": 4844, "s": 4645, "text": "Use AWS services as destinations for invocation records of your Lambda function whenever it is invoked. As of today, only 4 AWS services can be used this way: SNS, SQS, EventBridge or Lambda itself." }, { "code": null, "e": 5103, "s": 4844, "text": "* When a Lambda function is invoked by another AWS service, Lambda passes specific information from that AWS service to the function using an event object. This will include information like what item in which DynamoDB database triggered the Lambda function." }, { "code": null, "e": 5365, "s": 5103, "text": "** Boto3 is a python library (or SDK) built by AWS that allows you to interact with AWS services such as EC2, ECS, S3, DynamoDB etc. In this tutorial we will be using Boto3 to manage files inside an AWS S3 bucket. Full documentation for Boto3 can be found here." }, { "code": null, "e": 5425, "s": 5365, "text": "Pre-requisites for this tutorial: An AWS free-tier account." }, { "code": null, "e": 5754, "s": 5425, "text": "An S3 bucket is simply a storage space in AWS cloud for any kind of data (Eg., videos, code, AWS templates etc.). Every directory and file inside an S3 bucket can be uniquely identified using a key which is simply it’s path relative to the root directory (which is the bucket itself). For example, “car.jpg” or “images/car.jpg”." }, { "code": null, "e": 6027, "s": 5754, "text": "Besides being a powerful resource for developing microservices-based software, Lambda functions make highly effective DevOps tools. Let’s look at an example of using Lambda functions with S3 buckets in the first two ways mentioned above to solve a simple DevOps problem :)" }, { "code": null, "e": 6319, "s": 6027, "text": "Say you are receiving XML data from three different gas meters straight into an AWS S3 bucket. You want to sort the XML files into three separate folders based on which gas meter the data comes from. The only way to know the data source is to look inside the XML files, which look like this:" }, { "code": null, "e": 6424, "s": 6319, "text": "<data> <data-source>gas_meter3</data-source> <data-content>bla bla bla</data-content></data>" }, { "code": null, "e": 6535, "s": 6424, "text": "How would you automate this process? This is where AWS lambda could prove handy. Let’s look at how to do this." }, { "code": null, "e": 6561, "s": 6535, "text": "1 - Creating an S3 bucket" }, { "code": null, "e": 6807, "s": 6561, "text": "Let’s start by building an empty S3 bucket. All you have to do is to go to the S3 page from your AWS console and click on the “Create bucket” button. Make sure you leave the “Block all public access” checkbox ticked and click on “Create bucket”." }, { "code": null, "e": 6964, "s": 6807, "text": "Now, add a directory called “unsorted” where all the XML files will be stored initially. Create a .xml file named “testdata.xml” with the following content:" }, { "code": null, "e": 7069, "s": 6964, "text": "<data> <data-source>gas_meter3</data-source> <data-content>bla bla bla</data-content></data>" }, { "code": null, "e": 7100, "s": 7069, "text": "2 - Creating a Lambda function" }, { "code": null, "e": 7248, "s": 7100, "text": "From the Services tab on the AWS console, click on “Lambda”. From the left pane on the Lambda page, select “Functions” and then “Create Functions”." }, { "code": null, "e": 7668, "s": 7248, "text": "Select “Author from scratch” and give the function a suitable name. Since I’ll be using Python3, I chose “Python3.8” as the runtime language. There are other versions of Python2 and Python3 available as well. Select a runtime language and click on the “Create function” button. From the list of Lambda functions on the “Functions” page, select the function you just created and you will be taken to the function’s page." }, { "code": null, "e": 7974, "s": 7668, "text": "Lambda automatically creates an IAM role for you to use with the Lambda function. The IAM role can be found under the “Permissions” tab on the function’s page. You need to ensure that the function’s IAM role has permission to access and/or manage the AWS services you connect to from inside your function." }, { "code": null, "e": 8080, "s": 7974, "text": "Make sure you add “S3” permissions to the IAM role’s list of permissions, accessible via the IAM console." }, { "code": null, "e": 8125, "s": 8080, "text": "3 - Adding a trigger for our Lambda function" }, { "code": null, "e": 8306, "s": 8125, "text": "We want the Lambda function to be invoked every time an XML file is uploaded to the “unsorted” folder. To do this, we will use an S3 bucket PUT event as a trigger for our function." }, { "code": null, "e": 8401, "s": 8306, "text": "Under the “Designer” section on our Lambda function’s page, click on the “Add trigger” button." }, { "code": null, "e": 8574, "s": 8401, "text": "Select the “S3” trigger and the bucket you just created. Select “PUT” event type. Set the prefix and suffix as “unsorted/” and “.xml” respectively. Finally, click on “Add”." }, { "code": null, "e": 8613, "s": 8574, "text": "4 - Adding code to our Lambda function" }, { "code": null, "e": 8672, "s": 8613, "text": "There are 3 ways you can add code to your Lambda function:" }, { "code": null, "e": 8825, "s": 8672, "text": "Through the code editor available on the console.By uploading a .zip file containing all your code and dependencies.By uploading code from an S3 bucket." }, { "code": null, "e": 8875, "s": 8825, "text": "Through the code editor available on the console." }, { "code": null, "e": 8943, "s": 8875, "text": "By uploading a .zip file containing all your code and dependencies." }, { "code": null, "e": 8980, "s": 8943, "text": "By uploading code from an S3 bucket." }, { "code": null, "e": 9115, "s": 8980, "text": "We will use the first method for this tutorial. On your function page, go down to the “Function code” section to find the code editor." }, { "code": null, "e": 9171, "s": 9115, "text": "Copy and paste the following code into the code editor:" }, { "code": null, "e": 10100, "s": 9171, "text": "import jsonimport boto3import uuidfrom urllib.parse import unquote_plusimport xml.etree.ElementTree as ETdef lambda_handler(event, context): s3 = boto3.resource('s3', region_name='')#Replace with your region name #Loops through every file uploaded for record in event['Records']: bucket_name = record['s3']['bucket']['name'] bucket = s3.Bucket(bucket_name) key = unquote_plus(record['s3']['object']['key']) # Temporarily download the xml file for processing tmpkey = key.replace('/', '') download_path = '/tmp/{}{}'.format(uuid.uuid4(), tmpkey) bucket.download_file( key, download_path) machine_id = get_machine_id_from_file(download_path) bucket.upload_file(download_path, machine_id+'/'+key[9:]) s3.Object(bucket_name,key).delete()def get_machine_id_from_file(path): tree = ET.parse(path) root = tree.getroot() return root[0].text" }, { "code": null, "e": 10141, "s": 10100, "text": "Don’t forget to replace the region name." }, { "code": null, "e": 10290, "s": 10141, "text": "Make sure the handler value is “<filename>.lambda_handler” . The handler value specifies which function contains the main code that Lambda executes." }, { "code": null, "e": 10610, "s": 10290, "text": "Whenever Lambda runs your function, it passes a context object and an event object to it. This object can be used to get information about the function itself and its invocation, eg., function name, memory limit, log group id etc. The context object can be very useful for logging, monitoring and data analytics usages." }, { "code": null, "e": 11127, "s": 10610, "text": "As mentioned earlier the event object is used by Lambda to provide specific information to the Lamda function from the AWS service that invoked the function. The information, which originally comes in JSON format, is converted to an object before being passed into the function. In the case of Python, this object is typically a dictionary. In the code above, you can see that the event object has been used to get the name of the S3 bucket and the key of the object inside the S3 bucket that triggered our function." }, { "code": null, "e": 11190, "s": 11127, "text": "The code above is simple to understand. It does the following:" }, { "code": null, "e": 11480, "s": 11190, "text": "Get info from event object.Download the XML file that caused the Lambda function to be invoked.Process the XML file to find the machine_id from the first line of the XML file.Upload the file back to the S3 bucket, but inside a folder named the value of machine_id.Delete the original file." }, { "code": null, "e": 11508, "s": 11480, "text": "Get info from event object." }, { "code": null, "e": 11577, "s": 11508, "text": "Download the XML file that caused the Lambda function to be invoked." }, { "code": null, "e": 11658, "s": 11577, "text": "Process the XML file to find the machine_id from the first line of the XML file." }, { "code": null, "e": 11748, "s": 11658, "text": "Upload the file back to the S3 bucket, but inside a folder named the value of machine_id." }, { "code": null, "e": 11774, "s": 11748, "text": "Delete the original file." }, { "code": null, "e": 11845, "s": 11774, "text": "Now press the “Deploy” button and our function should be ready to run." }, { "code": null, "e": 11877, "s": 11845, "text": "5 - Testing our Lambda function" }, { "code": null, "e": 12334, "s": 11877, "text": "AWS has made it pretty easy to test Lambda functions via the Lambda console. No matter what trigger your Lambda function uses, you can simulate the invocation of your Lambda function using the Test feature on the Lambda console. All this takes is defining what event object will be passed into the function. To help you do this, Lambda provides JSON templates specific to each type of trigger. For example, the template for an S3 PUT event looks like this:" }, { "code": null, "e": 13303, "s": 12334, "text": "{ \"Records\": [ { \"eventVersion\": \"2.0\", \"eventSource\": \"aws:s3\", \"awsRegion\": \"us-west-2\", \"eventTime\": \"1970-01-01T00:00:00.000Z\", \"eventName\": \"ObjectCreated:Put\", \"userIdentity\": { \"principalId\": \"EXAMPLE\" }, \"requestParameters\": { \"sourceIPAddress\": \"126.0.0.1\" }, \"responseElements\": { \"x-amz-request-id\": \"EXAMPLE123456789\", \"x-amz-id-2\": \"EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH\" }, \"s3\": { \"s3SchemaVersion\": \"1.0\", \"configurationId\": \"testConfigRule\", \"bucket\": { \"name\": \"example-bucket\", \"ownerIdentity\": { \"principalId\": \"EXAMPLE\" }, \"arn\": \"arn:aws:s3:::example-bucket\" }, \"object\": { \"key\": \"test/key\", \"size\": 1024, \"eTag\": \"0123456789abcdef0123456789abcdef\", \"sequencer\": \"0A1B2C3D4E5F678901\" } } } ]}" }, { "code": null, "e": 13531, "s": 13303, "text": "To test the Lambda function you just created, you need to configure a test event for your function. To do this, click on the “Select a test event” dropdown right above the Lambda code editor and click on “Configure test event”." }, { "code": null, "e": 14011, "s": 13531, "text": "From the pop up menu, make sure the “Create new test event” radio button is selected and select the “Amazon S3 Put” event template. You should be provided with JSON data similar to that in the code snippet above. All we are concerned with is the data that is used in our Lambda function, which is the bucket name and the object key. Edit those two values appropriate to the S3 bucket and the XML file you created earlier. Finally give the test event a name and click on “Create”." }, { "code": null, "e": 14356, "s": 14011, "text": "Now that you have a test event for your Lambda function, all you have to do is click on the“Test” button on top of the code editor. The console will tell you if the function code was executed without any errors. To check if everything worked go to your S3 bucket to see if the XML file has been moved to a newly created “gas-meter3/” directory." }, { "code": null, "e": 14801, "s": 14356, "text": "As you may have noticed, one downside of testing via the console is that the Lambda function actually communicates with other AWS services. This may cause unintentional changes to your AWS resources or even loss of valuable work. The solution to this is to build and run your lambda functions locally on your machine. Testing Lambda functions locally is not as straightforward. You will need to use tools like SAM CLI and Localstack to do this." }, { "code": null, "e": 14815, "s": 14801, "text": "6 - All done!" }, { "code": null, "e": 15013, "s": 14815, "text": "Now your Lambda function should sort any XML files uploaded to the “unsorted” folder on your S3 bucket into separate folders, provided that the XML data is in the format specified in this tutorial." }, { "code": null, "e": 15201, "s": 15013, "text": "I hope that this article gave you a taste of what is achievable using AWS Lambda and some insight into Serverless Functions in general. Now it’s your time to get creative with AWS Lambda." } ]
Creating a Node.js server
The mostly used core modules of Node.js are − http − used to launch a simple server, send requests http − used to launch a simple server, send requests https − used to launch a ssl secured http server https − used to launch a ssl secured http server path − used to handle path based on operating system path − used to handle path based on operating system fs − It’s a file system handling module fs − It’s a file system handling module os − its used for os related operations os − its used for os related operations Lets build a simple http server using Node.js − Create a javascript file App.js (name it as you like) in an editor like visual studio code . App.js const http = require(‘http’); function reqListener(req, res){ console.log(‘Hello’); } const server = http.createServer(reqListener); server.listen(3000); Explaination We used const keyword instead of var or let to import a module because this variable reference will not changed in file. Require is a reserved keyword in Node, it helps to import pre-defined core modules and used defined modules. Importing pre-defined modules like http does not require to add ./ in front of them. But if requires to import a custom used defined module then it is done as shown below − const user = require(‘./User’); Adding .js extenstion to file in require function is not mandatory for javascript file. But any other file formats will require to add an extension in require function. The imported module http has a createServer method which takes request listener as an parameter. This argument function will be executed on every new http request to Node server. We can use anonymous function or a next-gen javascript arrow function as well in createServer method − Anonymous function in createServer const http = require(‘http’); const server = http.createServer(function(){ console.log(‘Hello’); }); server.listen(3000); Using next-gen Javascript const http = require(‘http’); const server = http.createServer((req, res)=>{ console.log(‘Hello’); }); server.listen(3000); createServer method of http module returns us a server. We can use a listen method on server to run it on a given port. listen method takes port number as an argument. Executing App.js file Open terminal inside folder where App.js is located and run command − node App.js Running this command will keep a event loop running listening for any http request on port 3000. Checking console log messages on terminal Now, open a browser and navigate to localhost:3000, check in terminal console for a log statement. On console of terminal we will see Hello message printed. As of now, we have not returned any response back to browser, so we wont see any output on it. We will see how to return and display response messages on browser in next articles.
[ { "code": null, "e": 1108, "s": 1062, "text": "The mostly used core modules of Node.js are −" }, { "code": null, "e": 1161, "s": 1108, "text": "http − used to launch a simple server, send requests" }, { "code": null, "e": 1214, "s": 1161, "text": "http − used to launch a simple server, send requests" }, { "code": null, "e": 1263, "s": 1214, "text": "https − used to launch a ssl secured http server" }, { "code": null, "e": 1312, "s": 1263, "text": "https − used to launch a ssl secured http server" }, { "code": null, "e": 1365, "s": 1312, "text": "path − used to handle path based on operating system" }, { "code": null, "e": 1418, "s": 1365, "text": "path − used to handle path based on operating system" }, { "code": null, "e": 1458, "s": 1418, "text": "fs − It’s a file system handling module" }, { "code": null, "e": 1498, "s": 1458, "text": "fs − It’s a file system handling module" }, { "code": null, "e": 1538, "s": 1498, "text": "os − its used for os related operations" }, { "code": null, "e": 1578, "s": 1538, "text": "os − its used for os related operations" }, { "code": null, "e": 1626, "s": 1578, "text": "Lets build a simple http server using Node.js −" }, { "code": null, "e": 1719, "s": 1626, "text": "Create a javascript file App.js (name it as you like) in an editor like visual studio code ." }, { "code": null, "e": 1726, "s": 1719, "text": "App.js" }, { "code": null, "e": 1883, "s": 1726, "text": "const http = require(‘http’);\nfunction reqListener(req, res){\n console.log(‘Hello’);\n}\nconst server = http.createServer(reqListener);\nserver.listen(3000);" }, { "code": null, "e": 1896, "s": 1883, "text": "Explaination" }, { "code": null, "e": 2017, "s": 1896, "text": "We used const keyword instead of var or let to import a module because this variable reference will not changed in file." }, { "code": null, "e": 2126, "s": 2017, "text": "Require is a reserved keyword in Node, it helps to import pre-defined core modules and used defined modules." }, { "code": null, "e": 2299, "s": 2126, "text": "Importing pre-defined modules like http does not require to add ./ in front of them. But if requires to import a custom used defined module then it is done as shown below −" }, { "code": null, "e": 2331, "s": 2299, "text": "const user = require(‘./User’);" }, { "code": null, "e": 2500, "s": 2331, "text": "Adding .js extenstion to file in require function is not mandatory for javascript file. But any other file formats will require to add an extension in require function." }, { "code": null, "e": 2679, "s": 2500, "text": "The imported module http has a createServer method which takes request listener as an parameter. This argument function will be executed on every new http request to Node server." }, { "code": null, "e": 2782, "s": 2679, "text": "We can use anonymous function or a next-gen javascript arrow function as well in createServer method −" }, { "code": null, "e": 2817, "s": 2782, "text": "Anonymous function in createServer" }, { "code": null, "e": 2942, "s": 2817, "text": "const http = require(‘http’);\nconst server = http.createServer(function(){\n console.log(‘Hello’);\n});\nserver.listen(3000);" }, { "code": null, "e": 2968, "s": 2942, "text": "Using next-gen Javascript" }, { "code": null, "e": 3095, "s": 2968, "text": "const http = require(‘http’);\nconst server = http.createServer((req, res)=>{\n console.log(‘Hello’);\n});\nserver.listen(3000);" }, { "code": null, "e": 3263, "s": 3095, "text": "createServer method of http module returns us a server. We can use a listen method on server to run it on a given port. listen method takes port number as an argument." }, { "code": null, "e": 3285, "s": 3263, "text": "Executing App.js file" }, { "code": null, "e": 3367, "s": 3285, "text": "Open terminal inside folder where App.js is located and run command − node App.js" }, { "code": null, "e": 3464, "s": 3367, "text": "Running this command will keep a event loop running listening for any http request on port 3000." }, { "code": null, "e": 3506, "s": 3464, "text": "Checking console log messages on terminal" }, { "code": null, "e": 3663, "s": 3506, "text": "Now, open a browser and navigate to localhost:3000, check in terminal console for a log statement. On console of terminal we will see Hello message printed." }, { "code": null, "e": 3843, "s": 3663, "text": "As of now, we have not returned any response back to browser, so we wont see any output on it. We will see how to return and display response messages on browser in next articles." } ]
How to use JavaScript to redirect a webpage after 5 seconds?
To redirect a webpage after 5 seconds, use the setInterval() method to set the time interval. Add the webpage in window.location.href object. You can try to run the following code to learn how to redirect a webpage after 5 seconds − Live Demo <!DOCTYPE html> <html> <body> <script> setTimeout(function(){ window.location.href = 'https://www.tutorialspoint.com/javascript/'; }, 5000); </script> <p>Web page redirects after 5 seconds.</p> </body> </html>
[ { "code": null, "e": 1204, "s": 1062, "text": "To redirect a webpage after 5 seconds, use the setInterval() method to set the time interval. Add the webpage in window.location.href object." }, { "code": null, "e": 1295, "s": 1204, "text": "You can try to run the following code to learn how to redirect a webpage after 5 seconds −" }, { "code": null, "e": 1305, "s": 1295, "text": "Live Demo" }, { "code": null, "e": 1569, "s": 1305, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n setTimeout(function(){\n window.location.href = 'https://www.tutorialspoint.com/javascript/';\n }, 5000);\n </script>\n <p>Web page redirects after 5 seconds.</p>\n </body>\n</html>" } ]
Solve the Logical Expression given by string - GeeksforGeeks
27 May, 2021 Given string str representing a logical expression which consists of the operators | (OR), & (AND),! (NOT) , 0, 1 and, only (i.e. no space between characters). The task is to print the result of the logical expression.Examples: Input: str = “[[0,&,1],|,[!,1]]” Output: 0 [[0,&,1],|,[!,1]] [[0,&,1],|,0] [[0,&,1],|,0] [0,|,0] [0,|,0] [0] 0Input: str = “[!,[[0,&,[!,1]],|,[!,[[!,0],&,1]]]]” Output: 1 Approach: Start traversing the string from the end.If [ found go to Step-3 otherwise push the characters into the stack.Pop characters from the stack until the stack top become”]”. > Insert each popped character into the vector.If the stack top becomes ] after 5 pop operations then the vector will be x, |, y or x, &, y.If the stack top becomes ] after 3 pop operations then the vector will be !, x.Pop ] from the stack top.Perform the respective operations on the vector elements then push the result back into the stack.If the string is fully traversed then return the value at the stack top otherwise go to step 2. Start traversing the string from the end. If [ found go to Step-3 otherwise push the characters into the stack. Pop characters from the stack until the stack top become”]”. > Insert each popped character into the vector.If the stack top becomes ] after 5 pop operations then the vector will be x, |, y or x, &, y.If the stack top becomes ] after 3 pop operations then the vector will be !, x.Pop ] from the stack top. Pop characters from the stack until the stack top become”]”. > Insert each popped character into the vector. If the stack top becomes ] after 5 pop operations then the vector will be x, |, y or x, &, y. If the stack top becomes ] after 3 pop operations then the vector will be !, x. Pop ] from the stack top. Perform the respective operations on the vector elements then push the result back into the stack. If the string is fully traversed then return the value at the stack top otherwise go to step 2. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to solve the logical expression.#include <bits/stdc++.h>using namespace std; // Function to evaluate the logical expressionchar logicalExpressionEvaluation(string str){ stack<char> arr; // traversing string from the end. for (int i = str.length() - 1; i >= 0; i--) { if (str[i] == '[') { vector<char> s; while (arr.top() != ']') { s.push_back(arr.top()); arr.pop(); } arr.pop(); // for NOT operation if (s.size() == 3) { s[2] == '1' ? arr.push('0') : arr.push('1'); } // for AND and OR operation else if (s.size() == 5) { int a = s[0] - 48, b = s[4] - 48, c; s[2] == '&' ? c = a && b : c = a || b; arr.push((char)c + 48); } } else { arr.push(str[i]); } } return arr.top();} // Driver codeint main(){ string str = "[[0,&,1],|,[!,1]]"; cout << logicalExpressionEvaluation(str) << endl; return 0;} // Java program to solve the logical expression.import java.util.*; class GFG{ // Function to evaluate the logical expressionstatic char logicalExpressionEvaluation(String str){ Stack<Character> arr = new Stack<Character>(); // traversing string from the end. for (int i = str.length() - 1; i >= 0; i--) { if (str.charAt(i) == '[') { Vector<Character> s = new Stack<Character>(); while (arr.peek() != ']') { s.add(arr.peek()); arr.pop(); } arr.pop(); // for NOT operation if (s.size() == 3) { arr.push(s.get(2) == '1' ? '0' : '1'); } // for AND and OR operation else if (s.size() == 5) { int a = s.get(0) - 48, b = s.get(4) - 48, c; if(s.get(2) == '&' ) { c = a & b; } else { c = a | b; } arr.push((char)(c + 48)); } } else { arr.push(str.charAt(i)); } } return arr.peek();} // Driver codepublic static void main(String[] args){ String str = "[|,[&,1,[!,0]],[!,[|,[|,1,0],[!,1]]]]"; System.out.println(logicalExpressionEvaluation(str));}} // This code is contributed by 29AjayKumar # Python3 program to solve the# logical expression.import math as mt # Function to evaluate the logical expressiondef logicalExpressionEvaluation(string): arr = list() # traversing string from the end. n = len(string) for i in range(n - 1, -1, -1): if (string[i] == "["): s = list() while (arr[-1] != "]"): s.append(arr[-1]) arr.pop() arr.pop() # for NOT operation if (len(s) == 3): if s[2] == "1": arr.append("0") else: arr.append("1") # for AND and OR operation elif (len(s) == 5): a = int(s[0]) - 48 b = int(s[4]) - 48 c = 0 if s[2] == "&": c = a & b else: c = a | b arr.append((c) + 48) else: arr.append(string[i]) return arr[-1] # Driver codestring= "[|,[&,1,[!,0]],[!,[|,[|,1,0],[!,1]]]]" print(logicalExpressionEvaluation(string)) # This code is contributed# by mohit kumar 29 // C# program to solve the logical expression.using System;using System.Collections.Generic; public class GFG{ // Function to evaluate the logical expressionstatic char logicalExpressionEvaluation(String str){ Stack<char> arr = new Stack<char>(); // traversing string from the end. for (int i = str.Length - 1; i >= 0; i--) { if (str[i] == '[') { List<char> s = new List<char>(); while (arr.Peek() != ']') { s.Add(arr.Peek()); arr.Pop(); } arr.Pop(); // for NOT operation if (s.Count == 3) { arr.Push(s[2] == '1' ? '0' : '1'); } // for AND and OR operation else if (s.Count == 5) { int a = s[0] - 48, b = s[4] - 48, c; if(s[2] == '&' ) { c = a & b; } else { c = a | b; } arr.Push((char)(c + 48)); } } else { arr.Push(str[i]); } } return arr.Peek();} // Driver codepublic static void Main(String[] args){ String str = "[[0,&,1],|,[!,1]]"; Console.WriteLine(logicalExpressionEvaluation(str));}} // This code is contributed by PrinciRaj1992 <script>// Javascript program to solve the logical expression. // Function to evaluate the logical expressionfunction logicalExpressionEvaluation(str){ let arr = []; // traversing string from the end. for (let i = str.length - 1; i >= 0; i--) { if (str[i] == '[') { let s = []; while (arr[arr.length-1] != ']') { s.push(arr[arr.length-1]); arr.pop(); } arr.pop(); // for NOT operation if (s.length == 3) { arr.push(s[2] == '1' ? '0' : '1'); } // for AND and OR operation else if (s.length == 5) { let a = s[0].charCodeAt(0) - 48, b = s[4].charCodeAt(0) - 48, c; if(s[2] == '&' ) { c = a & b; } else { c = a | b; } arr.push(String.fromCharCode(c + 48)); } } else { arr.push(str[i]); } } return arr[arr.length-1];} // Driver codelet str = "[|,[&,1,[!,0]],[!,[|,[|,1,0],[!,1]]]]";document.write(logicalExpressionEvaluation(str)); // This code is contributed by patel2127</script> 0 Time Complexity: O(n) Here, n is the length of the string. Dhirendra121 mohit kumar 29 29AjayKumar princiraj1992 ManishaYadav30 patel2127 programming-puzzle Technical Scripter 2018 Stack Strings Technical Scripter Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inorder Tree Traversal without Recursion Program for Tower of Hanoi Implement a stack using singly linked list Implement Stack using Queues Iterative Depth First Traversal of Graph Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 24733, "s": 24705, "text": "\n27 May, 2021" }, { "code": null, "e": 24963, "s": 24733, "text": "Given string str representing a logical expression which consists of the operators | (OR), & (AND),! (NOT) , 0, 1 and, only (i.e. no space between characters). The task is to print the result of the logical expression.Examples: " }, { "code": null, "e": 25136, "s": 24963, "text": "Input: str = “[[0,&,1],|,[!,1]]” Output: 0 [[0,&,1],|,[!,1]] [[0,&,1],|,0] [[0,&,1],|,0] [0,|,0] [0,|,0] [0] 0Input: str = “[!,[[0,&,[!,1]],|,[!,[[!,0],&,1]]]]” Output: 1 " }, { "code": null, "e": 25150, "s": 25138, "text": "Approach: " }, { "code": null, "e": 25759, "s": 25150, "text": "Start traversing the string from the end.If [ found go to Step-3 otherwise push the characters into the stack.Pop characters from the stack until the stack top become”]”. > Insert each popped character into the vector.If the stack top becomes ] after 5 pop operations then the vector will be x, |, y or x, &, y.If the stack top becomes ] after 3 pop operations then the vector will be !, x.Pop ] from the stack top.Perform the respective operations on the vector elements then push the result back into the stack.If the string is fully traversed then return the value at the stack top otherwise go to step 2." }, { "code": null, "e": 25801, "s": 25759, "text": "Start traversing the string from the end." }, { "code": null, "e": 25871, "s": 25801, "text": "If [ found go to Step-3 otherwise push the characters into the stack." }, { "code": null, "e": 26177, "s": 25871, "text": "Pop characters from the stack until the stack top become”]”. > Insert each popped character into the vector.If the stack top becomes ] after 5 pop operations then the vector will be x, |, y or x, &, y.If the stack top becomes ] after 3 pop operations then the vector will be !, x.Pop ] from the stack top." }, { "code": null, "e": 26286, "s": 26177, "text": "Pop characters from the stack until the stack top become”]”. > Insert each popped character into the vector." }, { "code": null, "e": 26380, "s": 26286, "text": "If the stack top becomes ] after 5 pop operations then the vector will be x, |, y or x, &, y." }, { "code": null, "e": 26460, "s": 26380, "text": "If the stack top becomes ] after 3 pop operations then the vector will be !, x." }, { "code": null, "e": 26486, "s": 26460, "text": "Pop ] from the stack top." }, { "code": null, "e": 26585, "s": 26486, "text": "Perform the respective operations on the vector elements then push the result back into the stack." }, { "code": null, "e": 26681, "s": 26585, "text": "If the string is fully traversed then return the value at the stack top otherwise go to step 2." }, { "code": null, "e": 26734, "s": 26681, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26738, "s": 26734, "text": "C++" }, { "code": null, "e": 26743, "s": 26738, "text": "Java" }, { "code": null, "e": 26751, "s": 26743, "text": "Python3" }, { "code": null, "e": 26754, "s": 26751, "text": "C#" }, { "code": null, "e": 26765, "s": 26754, "text": "Javascript" }, { "code": "// C++ program to solve the logical expression.#include <bits/stdc++.h>using namespace std; // Function to evaluate the logical expressionchar logicalExpressionEvaluation(string str){ stack<char> arr; // traversing string from the end. for (int i = str.length() - 1; i >= 0; i--) { if (str[i] == '[') { vector<char> s; while (arr.top() != ']') { s.push_back(arr.top()); arr.pop(); } arr.pop(); // for NOT operation if (s.size() == 3) { s[2] == '1' ? arr.push('0') : arr.push('1'); } // for AND and OR operation else if (s.size() == 5) { int a = s[0] - 48, b = s[4] - 48, c; s[2] == '&' ? c = a && b : c = a || b; arr.push((char)c + 48); } } else { arr.push(str[i]); } } return arr.top();} // Driver codeint main(){ string str = \"[[0,&,1],|,[!,1]]\"; cout << logicalExpressionEvaluation(str) << endl; return 0;}", "e": 27892, "s": 26765, "text": null }, { "code": "// Java program to solve the logical expression.import java.util.*; class GFG{ // Function to evaluate the logical expressionstatic char logicalExpressionEvaluation(String str){ Stack<Character> arr = new Stack<Character>(); // traversing string from the end. for (int i = str.length() - 1; i >= 0; i--) { if (str.charAt(i) == '[') { Vector<Character> s = new Stack<Character>(); while (arr.peek() != ']') { s.add(arr.peek()); arr.pop(); } arr.pop(); // for NOT operation if (s.size() == 3) { arr.push(s.get(2) == '1' ? '0' : '1'); } // for AND and OR operation else if (s.size() == 5) { int a = s.get(0) - 48, b = s.get(4) - 48, c; if(s.get(2) == '&' ) { c = a & b; } else { c = a | b; } arr.push((char)(c + 48)); } } else { arr.push(str.charAt(i)); } } return arr.peek();} // Driver codepublic static void main(String[] args){ String str = \"[|,[&,1,[!,0]],[!,[|,[|,1,0],[!,1]]]]\"; System.out.println(logicalExpressionEvaluation(str));}} // This code is contributed by 29AjayKumar", "e": 29336, "s": 27892, "text": null }, { "code": "# Python3 program to solve the# logical expression.import math as mt # Function to evaluate the logical expressiondef logicalExpressionEvaluation(string): arr = list() # traversing string from the end. n = len(string) for i in range(n - 1, -1, -1): if (string[i] == \"[\"): s = list() while (arr[-1] != \"]\"): s.append(arr[-1]) arr.pop() arr.pop() # for NOT operation if (len(s) == 3): if s[2] == \"1\": arr.append(\"0\") else: arr.append(\"1\") # for AND and OR operation elif (len(s) == 5): a = int(s[0]) - 48 b = int(s[4]) - 48 c = 0 if s[2] == \"&\": c = a & b else: c = a | b arr.append((c) + 48) else: arr.append(string[i]) return arr[-1] # Driver codestring= \"[|,[&,1,[!,0]],[!,[|,[|,1,0],[!,1]]]]\" print(logicalExpressionEvaluation(string)) # This code is contributed# by mohit kumar 29", "e": 30484, "s": 29336, "text": null }, { "code": "// C# program to solve the logical expression.using System;using System.Collections.Generic; public class GFG{ // Function to evaluate the logical expressionstatic char logicalExpressionEvaluation(String str){ Stack<char> arr = new Stack<char>(); // traversing string from the end. for (int i = str.Length - 1; i >= 0; i--) { if (str[i] == '[') { List<char> s = new List<char>(); while (arr.Peek() != ']') { s.Add(arr.Peek()); arr.Pop(); } arr.Pop(); // for NOT operation if (s.Count == 3) { arr.Push(s[2] == '1' ? '0' : '1'); } // for AND and OR operation else if (s.Count == 5) { int a = s[0] - 48, b = s[4] - 48, c; if(s[2] == '&' ) { c = a & b; } else { c = a | b; } arr.Push((char)(c + 48)); } } else { arr.Push(str[i]); } } return arr.Peek();} // Driver codepublic static void Main(String[] args){ String str = \"[[0,&,1],|,[!,1]]\"; Console.WriteLine(logicalExpressionEvaluation(str));}} // This code is contributed by PrinciRaj1992", "e": 31890, "s": 30484, "text": null }, { "code": "<script>// Javascript program to solve the logical expression. // Function to evaluate the logical expressionfunction logicalExpressionEvaluation(str){ let arr = []; // traversing string from the end. for (let i = str.length - 1; i >= 0; i--) { if (str[i] == '[') { let s = []; while (arr[arr.length-1] != ']') { s.push(arr[arr.length-1]); arr.pop(); } arr.pop(); // for NOT operation if (s.length == 3) { arr.push(s[2] == '1' ? '0' : '1'); } // for AND and OR operation else if (s.length == 5) { let a = s[0].charCodeAt(0) - 48, b = s[4].charCodeAt(0) - 48, c; if(s[2] == '&' ) { c = a & b; } else { c = a | b; } arr.push(String.fromCharCode(c + 48)); } } else { arr.push(str[i]); } } return arr[arr.length-1];} // Driver codelet str = \"[|,[&,1,[!,0]],[!,[|,[|,1,0],[!,1]]]]\";document.write(logicalExpressionEvaluation(str)); // This code is contributed by patel2127</script>", "e": 33276, "s": 31890, "text": null }, { "code": null, "e": 33278, "s": 33276, "text": "0" }, { "code": null, "e": 33338, "s": 33278, "text": "Time Complexity: O(n) Here, n is the length of the string. " }, { "code": null, "e": 33351, "s": 33338, "text": "Dhirendra121" }, { "code": null, "e": 33366, "s": 33351, "text": "mohit kumar 29" }, { "code": null, "e": 33378, "s": 33366, "text": "29AjayKumar" }, { "code": null, "e": 33392, "s": 33378, "text": "princiraj1992" }, { "code": null, "e": 33407, "s": 33392, "text": "ManishaYadav30" }, { "code": null, "e": 33417, "s": 33407, "text": "patel2127" }, { "code": null, "e": 33436, "s": 33417, "text": "programming-puzzle" }, { "code": null, "e": 33460, "s": 33436, "text": "Technical Scripter 2018" }, { "code": null, "e": 33466, "s": 33460, "text": "Stack" }, { "code": null, "e": 33474, "s": 33466, "text": "Strings" }, { "code": null, "e": 33493, "s": 33474, "text": "Technical Scripter" }, { "code": null, "e": 33501, "s": 33493, "text": "Strings" }, { "code": null, "e": 33507, "s": 33501, "text": "Stack" }, { "code": null, "e": 33605, "s": 33507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33614, "s": 33605, "text": "Comments" }, { "code": null, "e": 33627, "s": 33614, "text": "Old Comments" }, { "code": null, "e": 33668, "s": 33627, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 33695, "s": 33668, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 33738, "s": 33695, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 33767, "s": 33738, "text": "Implement Stack using Queues" }, { "code": null, "e": 33808, "s": 33767, "text": "Iterative Depth First Traversal of Graph" }, { "code": null, "e": 33833, "s": 33808, "text": "Reverse a string in Java" }, { "code": null, "e": 33879, "s": 33833, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 33913, "s": 33879, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 33973, "s": 33913, "text": "Write a program to print all permutations of a given string" } ]
Count of distinct characters in a substring by given range for Q queries - GeeksforGeeks
03 Jun, 2021 Given a string S consisting of lower case alphabets of size N and Q queries in the range [L, R], the task is to print the count of distinct characters in the substring by given range for each query. Examples: Input: S = “geeksforgeeks”, Q[][] = {{0, 4}, {3, 7}} Output: 4 5 Explanation: Distinct characters in substring S[0:4] are ‘g’, ‘e’, ‘k’ and ‘s’ Distinct characters in substring in S[3:7] are ‘k’, ‘s’ ‘f’, ‘o’ and ‘r’ Input: S = “geeksforgeeksisacomputerscienceportal”, Q[][] = {{0, 10}, {15, 18}, {12, 20}} Output: 7 4 8 Naive Approach: The idea is to use hashing to maintain the frequency of each character in the given substring and then count the characters with a frequency equal to 1.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program for Naive Approach #include <bits/stdc++.h>using namespace std; void findCount(string s, int L, int R){ // counter to count distinct char int distinct = 0; // Initializing frequency array to // count characters as the appear in // substring S[L:R] int frequency[26] = {}; // Iterating over S[L] to S[R] for (int i = L; i <= R; i++) { // incrementing the count // of s[i] character in frequency array frequency[s[i] - 'a']++; } for (int i = 0; i < 26; i++) { // if frequency of any character is > 0 // then increment the counter if (frequency[i] > 0) distinct++; } cout << distinct << endl;} /* Driver code*/int main(){ string s = "geeksforgeeksisacomputerscienceportal"; int queries = 3; int Q[queries][2] = { { 0, 10 }, { 15, 18 }, { 12, 20 } }; for (int i = 0; i < queries; i++) findCount(s, Q[i][0], Q[i][1]); return 0;} // Java program for the naive approachclass GFG{ static void findCount(String s, int L, int R){ // Counter to count distinct char int distinct = 0; // Initializing frequency array // to count characters as the // appear in subString S[L:R] int []frequency = new int[26]; // Iterating over S[L] to S[R] for(int i = L; i <= R; i++) { // Incrementing the count of s[i] // character in frequency array frequency[s.charAt(i) - 'a']++; } for(int i = 0; i < 26; i++) { // If frequency of any character // is > 0 then increment the counter if (frequency[i] > 0) distinct++; } System.out.print(distinct + "\n");} // Driver codepublic static void main(String[] args){ String s = "geeksforgeeksisa" + "computerscienceportal"; int queries = 3; int Q[][] = { { 0, 10 }, { 15, 18 }, { 12, 20 } }; for(int i = 0; i < queries; i++) findCount(s, Q[i][0], Q[i][1]);}} // This code is contributed by sapnasingh4991 # Python3 program for Naive Approach def findCount(s, L, R): # Counter to count distinct char distinct = 0 # Initializing frequency array to # count characters as the appear in # substring S[L:R] frequency = [0 for i in range(26)] # Iterating over S[L] to S[R] for i in range(L, R + 1, 1): # Incrementing the count of s[i] # character in frequency array frequency[ord(s[i]) - ord('a')] += 1 for i in range(26): # If frequency of any character is > 0 # then increment the counter if (frequency[i] > 0): distinct += 1 print(distinct) # Driver codeif __name__ == '__main__': s = "geeksforgeeksisacomputerscienceportal" queries = 3 Q = [ [ 0, 10 ], [ 15, 18 ], [ 12, 20 ] ] for i in range(queries): findCount(s, Q[i][0], Q[i][1]) # This code is contributed by Bhupendra_Singh // C# program for the naive approachusing System;class GFG{ static void findCount(String s, int L, int R){ // Counter to count distinct char int distinct = 0; // Initializing frequency array // to count characters as the // appear in subString S[L:R] int []frequency = new int[26]; // Iterating over S[L] to S[R] for(int i = L; i <= R; i++) { // Incrementing the count of s[i] // character in frequency array frequency[s[i] - 'a']++; } for(int i = 0; i < 26; i++) { // If frequency of any character // is > 0 then increment the counter if (frequency[i] > 0) distinct++; } Console.Write(distinct + "\n");} // Driver codepublic static void Main(String[] args){ String s = "geeksforgeeksisa" + "computerscienceportal"; int queries = 3; int [,]Q = {{ 0, 10 }, { 15, 18 }, { 12, 20 }}; for(int i = 0; i < queries; i++) findCount(s, Q[i, 0], Q[i, 1]);}} // This code is contributed by sapnasingh4991 <script> // Javascript Program for Naive Approach function findCount(s, L, R){ // counter to count distinct char var distinct = 0; // Initializing frequency array to // count characters as the appear in // substring S[L:R] var frequency = Array(26).fill(0); // Iterating over S[L] to S[R] for (var i = L; i <= R; i++) { // incrementing the count // of s[i] character in frequency array frequency[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } for (var i = 0; i < 26; i++) { // if frequency of any character is > 0 // then increment the counter if (frequency[i] > 0) distinct++; } document.write( distinct + "<br>");} /* Driver code*/var s = "geeksforgeeksisacomputerscienceportal";var queries = 3;var Q = [ [ 0, 10 ], [ 15, 18 ], [ 12, 20 ] ];for (var i = 0; i < queries; i++) findCount(s, Q[i][0], Q[i][1]); </script> 7 4 8 Time Complexity: O(Q×N) Efficient Approach: An efficient approach would be to store the position of each character as they appear in the string in an array. For each given query we will iterate over all the 26 lower case alphabets. If the current letter is in the substring S[L: R], then the first element greater than or equal L in the corresponding position vector should exist and be less than or equal to R i.e, there must be a position value between L and R denoting the presence of the alphabet in the query range.For example: Below is the implementation of the above approach: C++ // C++ Program for Efficient Approach// to count the no. of distinct characters// in a substring using STL #include <bits/stdc++.h>using namespace std; // vector of vector to store// position of all characters// as they appear in stringvector<vector<int> > v(26); void build_position_vector(string s){ for (int i = 0; i < s.size(); i++) { // inserting position of // character as they appear v[s[i] - 'a'].push_back(i); }} void findCount(string s, int L, int R){ build_position_vector(s); // counter to count distinct char int distinct = 0; // iterating over all 26 characters for (int i = 0; i < 26; i++) { // Finding the first element // which is greater than or equal to L auto first = lower_bound( v[i].begin(), v[i].end(), L); // Check if first pointer exists // and is less than or equal to R if (first != v[i].end() && *first <= R) { distinct++; } } cout << distinct << endl;} /* Driver code*/int main(){ string s = "geeksforgeeksisacomputerscienceportal"; int queries = 3; int Q[queries][2] = { { 0, 10 }, { 15, 18 }, { 12, 20 } }; for (int i = 0; i < queries; i++) findCount(s, Q[i][0], Q[i][1]); return 0;} 7 4 8 Time Complexity: O(N + Q logN) bgangwar59 sapnasingh4991 Akanksha_Rai rrrtnx substring Algorithms Arrays Articles Competitive Programming Strings Arrays Strings Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Difference between Informed and Uninformed Search in AI SCAN (Elevator) Disk Scheduling Algorithms Quadratic Probing in Hashing K means Clustering - Introduction Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Largest Sum Contiguous Subarray
[ { "code": null, "e": 24301, "s": 24273, "text": "\n03 Jun, 2021" }, { "code": null, "e": 24500, "s": 24301, "text": "Given a string S consisting of lower case alphabets of size N and Q queries in the range [L, R], the task is to print the count of distinct characters in the substring by given range for each query." }, { "code": null, "e": 24511, "s": 24500, "text": "Examples: " }, { "code": null, "e": 24728, "s": 24511, "text": "Input: S = “geeksforgeeks”, Q[][] = {{0, 4}, {3, 7}} Output: 4 5 Explanation: Distinct characters in substring S[0:4] are ‘g’, ‘e’, ‘k’ and ‘s’ Distinct characters in substring in S[3:7] are ‘k’, ‘s’ ‘f’, ‘o’ and ‘r’" }, { "code": null, "e": 24833, "s": 24728, "text": "Input: S = “geeksforgeeksisacomputerscienceportal”, Q[][] = {{0, 10}, {15, 18}, {12, 20}} Output: 7 4 8 " }, { "code": null, "e": 25053, "s": 24833, "text": "Naive Approach: The idea is to use hashing to maintain the frequency of each character in the given substring and then count the characters with a frequency equal to 1.Below is the implementation of the above approach: " }, { "code": null, "e": 25057, "s": 25053, "text": "C++" }, { "code": null, "e": 25062, "s": 25057, "text": "Java" }, { "code": null, "e": 25070, "s": 25062, "text": "Python3" }, { "code": null, "e": 25073, "s": 25070, "text": "C#" }, { "code": null, "e": 25084, "s": 25073, "text": "Javascript" }, { "code": "// C++ Program for Naive Approach #include <bits/stdc++.h>using namespace std; void findCount(string s, int L, int R){ // counter to count distinct char int distinct = 0; // Initializing frequency array to // count characters as the appear in // substring S[L:R] int frequency[26] = {}; // Iterating over S[L] to S[R] for (int i = L; i <= R; i++) { // incrementing the count // of s[i] character in frequency array frequency[s[i] - 'a']++; } for (int i = 0; i < 26; i++) { // if frequency of any character is > 0 // then increment the counter if (frequency[i] > 0) distinct++; } cout << distinct << endl;} /* Driver code*/int main(){ string s = \"geeksforgeeksisacomputerscienceportal\"; int queries = 3; int Q[queries][2] = { { 0, 10 }, { 15, 18 }, { 12, 20 } }; for (int i = 0; i < queries; i++) findCount(s, Q[i][0], Q[i][1]); return 0;}", "e": 26092, "s": 25084, "text": null }, { "code": "// Java program for the naive approachclass GFG{ static void findCount(String s, int L, int R){ // Counter to count distinct char int distinct = 0; // Initializing frequency array // to count characters as the // appear in subString S[L:R] int []frequency = new int[26]; // Iterating over S[L] to S[R] for(int i = L; i <= R; i++) { // Incrementing the count of s[i] // character in frequency array frequency[s.charAt(i) - 'a']++; } for(int i = 0; i < 26; i++) { // If frequency of any character // is > 0 then increment the counter if (frequency[i] > 0) distinct++; } System.out.print(distinct + \"\\n\");} // Driver codepublic static void main(String[] args){ String s = \"geeksforgeeksisa\" + \"computerscienceportal\"; int queries = 3; int Q[][] = { { 0, 10 }, { 15, 18 }, { 12, 20 } }; for(int i = 0; i < queries; i++) findCount(s, Q[i][0], Q[i][1]);}} // This code is contributed by sapnasingh4991", "e": 27198, "s": 26092, "text": null }, { "code": "# Python3 program for Naive Approach def findCount(s, L, R): # Counter to count distinct char distinct = 0 # Initializing frequency array to # count characters as the appear in # substring S[L:R] frequency = [0 for i in range(26)] # Iterating over S[L] to S[R] for i in range(L, R + 1, 1): # Incrementing the count of s[i] # character in frequency array frequency[ord(s[i]) - ord('a')] += 1 for i in range(26): # If frequency of any character is > 0 # then increment the counter if (frequency[i] > 0): distinct += 1 print(distinct) # Driver codeif __name__ == '__main__': s = \"geeksforgeeksisacomputerscienceportal\" queries = 3 Q = [ [ 0, 10 ], [ 15, 18 ], [ 12, 20 ] ] for i in range(queries): findCount(s, Q[i][0], Q[i][1]) # This code is contributed by Bhupendra_Singh", "e": 28123, "s": 27198, "text": null }, { "code": "// C# program for the naive approachusing System;class GFG{ static void findCount(String s, int L, int R){ // Counter to count distinct char int distinct = 0; // Initializing frequency array // to count characters as the // appear in subString S[L:R] int []frequency = new int[26]; // Iterating over S[L] to S[R] for(int i = L; i <= R; i++) { // Incrementing the count of s[i] // character in frequency array frequency[s[i] - 'a']++; } for(int i = 0; i < 26; i++) { // If frequency of any character // is > 0 then increment the counter if (frequency[i] > 0) distinct++; } Console.Write(distinct + \"\\n\");} // Driver codepublic static void Main(String[] args){ String s = \"geeksforgeeksisa\" + \"computerscienceportal\"; int queries = 3; int [,]Q = {{ 0, 10 }, { 15, 18 }, { 12, 20 }}; for(int i = 0; i < queries; i++) findCount(s, Q[i, 0], Q[i, 1]);}} // This code is contributed by sapnasingh4991", "e": 29233, "s": 28123, "text": null }, { "code": "<script> // Javascript Program for Naive Approach function findCount(s, L, R){ // counter to count distinct char var distinct = 0; // Initializing frequency array to // count characters as the appear in // substring S[L:R] var frequency = Array(26).fill(0); // Iterating over S[L] to S[R] for (var i = L; i <= R; i++) { // incrementing the count // of s[i] character in frequency array frequency[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } for (var i = 0; i < 26; i++) { // if frequency of any character is > 0 // then increment the counter if (frequency[i] > 0) distinct++; } document.write( distinct + \"<br>\");} /* Driver code*/var s = \"geeksforgeeksisacomputerscienceportal\";var queries = 3;var Q = [ [ 0, 10 ], [ 15, 18 ], [ 12, 20 ] ];for (var i = 0; i < queries; i++) findCount(s, Q[i][0], Q[i][1]); </script>", "e": 30191, "s": 29233, "text": null }, { "code": null, "e": 30197, "s": 30191, "text": "7\n4\n8" }, { "code": null, "e": 30224, "s": 30199, "text": "Time Complexity: O(Q×N) " }, { "code": null, "e": 30733, "s": 30224, "text": "Efficient Approach: An efficient approach would be to store the position of each character as they appear in the string in an array. For each given query we will iterate over all the 26 lower case alphabets. If the current letter is in the substring S[L: R], then the first element greater than or equal L in the corresponding position vector should exist and be less than or equal to R i.e, there must be a position value between L and R denoting the presence of the alphabet in the query range.For example:" }, { "code": null, "e": 30785, "s": 30733, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 30789, "s": 30785, "text": "C++" }, { "code": "// C++ Program for Efficient Approach// to count the no. of distinct characters// in a substring using STL #include <bits/stdc++.h>using namespace std; // vector of vector to store// position of all characters// as they appear in stringvector<vector<int> > v(26); void build_position_vector(string s){ for (int i = 0; i < s.size(); i++) { // inserting position of // character as they appear v[s[i] - 'a'].push_back(i); }} void findCount(string s, int L, int R){ build_position_vector(s); // counter to count distinct char int distinct = 0; // iterating over all 26 characters for (int i = 0; i < 26; i++) { // Finding the first element // which is greater than or equal to L auto first = lower_bound( v[i].begin(), v[i].end(), L); // Check if first pointer exists // and is less than or equal to R if (first != v[i].end() && *first <= R) { distinct++; } } cout << distinct << endl;} /* Driver code*/int main(){ string s = \"geeksforgeeksisacomputerscienceportal\"; int queries = 3; int Q[queries][2] = { { 0, 10 }, { 15, 18 }, { 12, 20 } }; for (int i = 0; i < queries; i++) findCount(s, Q[i][0], Q[i][1]); return 0;}", "e": 32128, "s": 30789, "text": null }, { "code": null, "e": 32134, "s": 32128, "text": "7\n4\n8" }, { "code": null, "e": 32168, "s": 32136, "text": "Time Complexity: O(N + Q logN) " }, { "code": null, "e": 32179, "s": 32168, "text": "bgangwar59" }, { "code": null, "e": 32194, "s": 32179, "text": "sapnasingh4991" }, { "code": null, "e": 32207, "s": 32194, "text": "Akanksha_Rai" }, { "code": null, "e": 32214, "s": 32207, "text": "rrrtnx" }, { "code": null, "e": 32224, "s": 32214, "text": "substring" }, { "code": null, "e": 32235, "s": 32224, "text": "Algorithms" }, { "code": null, "e": 32242, "s": 32235, "text": "Arrays" }, { "code": null, "e": 32251, "s": 32242, "text": "Articles" }, { "code": null, "e": 32275, "s": 32251, "text": "Competitive Programming" }, { "code": null, "e": 32283, "s": 32275, "text": "Strings" }, { "code": null, "e": 32290, "s": 32283, "text": "Arrays" }, { "code": null, "e": 32298, "s": 32290, "text": "Strings" }, { "code": null, "e": 32309, "s": 32298, "text": "Algorithms" }, { "code": null, "e": 32407, "s": 32309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32416, "s": 32407, "text": "Comments" }, { "code": null, "e": 32429, "s": 32416, "text": "Old Comments" }, { "code": null, "e": 32454, "s": 32429, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32510, "s": 32454, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 32553, "s": 32510, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 32582, "s": 32553, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 32616, "s": 32582, "text": "K means Clustering - Introduction" }, { "code": null, "e": 32631, "s": 32616, "text": "Arrays in Java" }, { "code": null, "e": 32647, "s": 32631, "text": "Arrays in C/C++" }, { "code": null, "e": 32674, "s": 32647, "text": "Program for array rotation" }, { "code": null, "e": 32722, "s": 32674, "text": "Stack Data Structure (Introduction and Program)" } ]
Tryit Editor v3.7 - Show Java
public class WriteToFile { public static void main(String[] args) { try { FileWriter myWriter = new FileWriter("filename.txt"); myWriter.write("Files in Java might be tricky, but it is fun enough!"); myWriter.close(); System.out.println("Successfully wrote to the file."); } catch (IOException e) { System.out.println("An error occurred.");
[]
Logistic Regression from Scratch. Learn how to build logistic regression... | by Arseny Turin | Towards Data Science
In this post, we’re going to build our own logistic regression model from scratch using Gradient Descent. To test our model we will use “Breast Cancer Wisconsin Dataset” from the sklearn package and predict if the lump is benign or malignant with over 95% accuracy. GitHub repo is here. So let's get started. Essentially logistic regression model consists of two components: sigmoid function and features with weights: The sigmoid function g(z) takes features and weights z as an input and returns a result between 0 and 1. The output of the sigmoid function is an actual prediction ŷ. After the model made a prediction, we can evaluate the result with a cross-entropy loss function: Natural logarithm works in our favor here, because it penalizes heavily if the prediction is far off the true value. For example, if the model predicted value ŷ=0.16 and true y=1, the error is high and vice versa: The loss function consists of the two parts, but we can combine them into a single equation: Here we added y and (1 - y) to cancel out one part over another depending on the output. We will use this function in our model to calculate loss and also in the Gradient Descent part of the model training. Model training is essentially minimization of the loss function. We achieve that with the Gradient Descent technique, which can be broken into a few steps: First, we find derivatives of the loss function with respect to each weight. Derivatives can tell which direction and by how much we should change weight to make the model loss a bit smaller.Updating each weight according to derivative until the local minimum is found, i.e. model doesn’t improve anymore so we can stop. First, we find derivatives of the loss function with respect to each weight. Derivatives can tell which direction and by how much we should change weight to make the model loss a bit smaller. Updating each weight according to derivative until the local minimum is found, i.e. model doesn’t improve anymore so we can stop. This is the most crucial and hardest part. Without derivatives, the model wouldn’t train, so we will go into great detail in this part. At this point we can drop summation function and focus on what's inside: Notation: y — true value, ŷ — predicted value (sigmoid) To find derivatives we’re going to use the chain rule: We use the chain rule when we need to find a derivative of a function that contains another function and so on. In our case, we have a loss function that contains a sigmoid function that contains features and weights. So there are three functions down the line and we’re going to derive them one by one. The derivative of the natural logarithm is quite easy to calculate: Since we have two parts in the equation, we can derive them separately: Now we can combine two parts back together and simplify: This looks pretty good, now we focus on the sigmoid function. According to the chain rule, we have to find the derivative of ŷ (sigmoid). You can find detailed explanations of it’s derivative on the internet because it’s used quite often in machine learning models, so I’ll just write the final result: The last function in the chain is what contains in z — our features and weights. A derivative with respect to each weight (w) would be its feature value (x), for example: (x1 * w1)’ = x1, because derivative of w is 1. According to the chain rule, we multiply each derived function, so we get the following: We are done. In the end, we got quite a compact function which we will use in the Gradient Descent. This part is the breeze comparing to finding derivatives. In programmers language, it’s simply for loop where we constantly updating weights. In this process, we multiply each derived value by the learning rate parameter and then subtract this value from the weight: # example of updating one weightepochs = 50lr = 0.1for _ in range(epochs): w1 -= lr * x1 * (y_hat - y) # y_hat is predicted value The learning rate is usually a small number to control how fast or slow we want to move towards minimization. Let’s take a look at the full code: Breast Cancer Wisconsin Dataset 569 samples and 30 features: After a train-test split model predicted malignant and benign lumps with 97% and 95% accuracy, which is a decent result. The model we created could be used in real-life applications, and it’s great for educational purposes. Though sklearn LogisticRegression will work faster and more accurately, we can keep optimizing what we have and eventually achieve similar performance. Let me know in the comments if you have any questions or recommendations. Thank you for reading,
[ { "code": null, "e": 480, "s": 171, "text": "In this post, we’re going to build our own logistic regression model from scratch using Gradient Descent. To test our model we will use “Breast Cancer Wisconsin Dataset” from the sklearn package and predict if the lump is benign or malignant with over 95% accuracy. GitHub repo is here. So let's get started." }, { "code": null, "e": 590, "s": 480, "text": "Essentially logistic regression model consists of two components: sigmoid function and features with weights:" }, { "code": null, "e": 758, "s": 590, "text": "The sigmoid function g(z) takes features and weights z as an input and returns a result between 0 and 1. The output of the sigmoid function is an actual prediction ŷ." }, { "code": null, "e": 856, "s": 758, "text": "After the model made a prediction, we can evaluate the result with a cross-entropy loss function:" }, { "code": null, "e": 1071, "s": 856, "text": "Natural logarithm works in our favor here, because it penalizes heavily if the prediction is far off the true value. For example, if the model predicted value ŷ=0.16 and true y=1, the error is high and vice versa:" }, { "code": null, "e": 1164, "s": 1071, "text": "The loss function consists of the two parts, but we can combine them into a single equation:" }, { "code": null, "e": 1371, "s": 1164, "text": "Here we added y and (1 - y) to cancel out one part over another depending on the output. We will use this function in our model to calculate loss and also in the Gradient Descent part of the model training." }, { "code": null, "e": 1527, "s": 1371, "text": "Model training is essentially minimization of the loss function. We achieve that with the Gradient Descent technique, which can be broken into a few steps:" }, { "code": null, "e": 1848, "s": 1527, "text": "First, we find derivatives of the loss function with respect to each weight. Derivatives can tell which direction and by how much we should change weight to make the model loss a bit smaller.Updating each weight according to derivative until the local minimum is found, i.e. model doesn’t improve anymore so we can stop." }, { "code": null, "e": 2040, "s": 1848, "text": "First, we find derivatives of the loss function with respect to each weight. Derivatives can tell which direction and by how much we should change weight to make the model loss a bit smaller." }, { "code": null, "e": 2170, "s": 2040, "text": "Updating each weight according to derivative until the local minimum is found, i.e. model doesn’t improve anymore so we can stop." }, { "code": null, "e": 2306, "s": 2170, "text": "This is the most crucial and hardest part. Without derivatives, the model wouldn’t train, so we will go into great detail in this part." }, { "code": null, "e": 2379, "s": 2306, "text": "At this point we can drop summation function and focus on what's inside:" }, { "code": null, "e": 2436, "s": 2379, "text": "Notation: y — true value, ŷ — predicted value (sigmoid)" }, { "code": null, "e": 2491, "s": 2436, "text": "To find derivatives we’re going to use the chain rule:" }, { "code": null, "e": 2795, "s": 2491, "text": "We use the chain rule when we need to find a derivative of a function that contains another function and so on. In our case, we have a loss function that contains a sigmoid function that contains features and weights. So there are three functions down the line and we’re going to derive them one by one." }, { "code": null, "e": 2863, "s": 2795, "text": "The derivative of the natural logarithm is quite easy to calculate:" }, { "code": null, "e": 2935, "s": 2863, "text": "Since we have two parts in the equation, we can derive them separately:" }, { "code": null, "e": 2992, "s": 2935, "text": "Now we can combine two parts back together and simplify:" }, { "code": null, "e": 3054, "s": 2992, "text": "This looks pretty good, now we focus on the sigmoid function." }, { "code": null, "e": 3296, "s": 3054, "text": "According to the chain rule, we have to find the derivative of ŷ (sigmoid). You can find detailed explanations of it’s derivative on the internet because it’s used quite often in machine learning models, so I’ll just write the final result:" }, { "code": null, "e": 3514, "s": 3296, "text": "The last function in the chain is what contains in z — our features and weights. A derivative with respect to each weight (w) would be its feature value (x), for example: (x1 * w1)’ = x1, because derivative of w is 1." }, { "code": null, "e": 3603, "s": 3514, "text": "According to the chain rule, we multiply each derived function, so we get the following:" }, { "code": null, "e": 3703, "s": 3603, "text": "We are done. In the end, we got quite a compact function which we will use in the Gradient Descent." }, { "code": null, "e": 3845, "s": 3703, "text": "This part is the breeze comparing to finding derivatives. In programmers language, it’s simply for loop where we constantly updating weights." }, { "code": null, "e": 3970, "s": 3845, "text": "In this process, we multiply each derived value by the learning rate parameter and then subtract this value from the weight:" }, { "code": null, "e": 4107, "s": 3970, "text": "# example of updating one weightepochs = 50lr = 0.1for _ in range(epochs): w1 -= lr * x1 * (y_hat - y) # y_hat is predicted value" }, { "code": null, "e": 4253, "s": 4107, "text": "The learning rate is usually a small number to control how fast or slow we want to move towards minimization. Let’s take a look at the full code:" }, { "code": null, "e": 4314, "s": 4253, "text": "Breast Cancer Wisconsin Dataset 569 samples and 30 features:" }, { "code": null, "e": 4435, "s": 4314, "text": "After a train-test split model predicted malignant and benign lumps with 97% and 95% accuracy, which is a decent result." }, { "code": null, "e": 4764, "s": 4435, "text": "The model we created could be used in real-life applications, and it’s great for educational purposes. Though sklearn LogisticRegression will work faster and more accurately, we can keep optimizing what we have and eventually achieve similar performance. Let me know in the comments if you have any questions or recommendations." } ]
Custom object detection for non-data scientists — Tensorflow | by Italo José | Towards Data Science
In general terms, at the end of this tutorial you basically will be able to pick up your dataset, load it on jupyter notebook, train and use your model :)The picture above is the result in the example that we are going to play here. This article is just to call you to learn about TF object detection API, but this content is just a poor copy-past from my jupyter notebook, if you want to see something more structured and beautiful, go to my jupyter notebook that there have the same texts that have here, but in a more beautiful and easy to understand that medium :) To begin with, let’s install the dependencies !pip install pillow!pip install lxml!pip install Cython!pip install jupyter!pip install matplotlib!pip install pandas!pip install opencv-python!pip install tensorflow First of all, let’s download the tensorflow models repository, inside this repository has the objection detection api, that we will use to train our ownobject detection model. Everything that we will do, is inside the path models/research/object_detection. !git clone https://github.com/tensorflow/models/%cd models/research/object_detection Here we’re just creating some folders that we will use it later.The command mkdir creates directories !mkdir training!mkdir inference_graph!mkdir -p images/train!mkdir -p images/test Inside the the tensorflow zoo models we can choose a pre-trained model to dowloand and use it to train our own dataset.Inside the tensorlfow zoo models repository’s folder, we have a table that explain how precise the model is (with mAP — mean Average Precision )and how faster this model is.You can choose any model that you want, the process in this tutorial for othersmodels is the same.For this tutorial, I choosed the faster_rcnn_inception_v2_coco_2018_01_28, justbecause I want :) !wget http://download.tensorflow.org/models/object_detection/faster_rcnn_inception_v2_coco_2018_01_28.tar.gz!tar -xvzf faster_rcnn_inception_v2_coco_2018_01_28.tar.gz!rm -rf faster_rcnn_inception_v2_coco_2018_01_28.tar.gz According to the documentation, it is important that we export the PYTHONPATH environment variable with the models, reasearch and slim path import osos.environ['PYTHONPATH'] = "{}/content/obj_detect_api/models:/content/obj_detect_api/models/research:/content/obj_detect_api/models/research/slim".format(os.environ['PYTHONPATH']) Here we have some proto buffers that need to be compiled, remember that it’s compiled, so if you switch machines, you can’t just copy and pastethe files generated by this guy.Being sincere I couldn’t execute these protos from the “/research/object_detection” folder, I tried N ways and it didn’t work, so I simply compiled them from within the “/research” folder.to understand what’s proto buffers is not necessary for this tutorial, but if you wantto learn more about, I recommend you look the documentation, basically it’s textstructures (such as json, xml) containing message structures that you can transformit to some languages, is a little more than that, but for now that’s more than enough for you to follow that article. %cd ..!protoc ./object_detection/protos/*.proto --python_out=. I don’t remember the exact version that the Tensroflow Objection detect APIrequire, but I know from version >= 3.0 works well. !protoc --version So just install it !python3 setup.py build!python3 setup.py install Once we have installed everything, we can run some sample scripts from theTensorflow Object detection API to verify if everything is correct.this code isn’t mine, I copied it from object_detection folder just to make somemodifications ro run it on jupyter notebook. I don’t will explain this code because it’s is justo to test the instalation, we will see a similar code later. Just execute these cells. Warning: Just certify that you are using the Tensorflow >=1.12.0 Obs: Remember that you can leave this article and go to the jupyter notebook, which is better :) If after you execute the cell bellow you can see a dog image and a beach image, everything is working! First of all let’s download our dataset. In this article we will use a dataset from kaggle, but don’t worry, during this tutorial I will direct you to another articl that teaches you how to create your own classified dataset. Before talking about the dataset, I want to just to remember you that in this tutorial we will use datasets in the Pascal-VOC format, this is famous format where you have: Images in jpg, jpeg, png format ... Annotations: .xml files in the following format: <annotation> <folder>GeneratedData_Train</folder> <filename>000001.png</filename> <path>/my/path/GeneratedData_Train/000001.png</path> <source> <database>Unknown</database> </source> <size> <width>224</width> <height>224</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>21</name> <pose>Frontal</pose> <truncated>0</truncated> <difficult>0</difficult> <occluded>0</occluded> <bndbox> <xmin>82</xmin> <xmax>172</xmax> <ymin>88</ymin> <ymax>146</ymax> </bndbox> </object></annotation> For each image, we have an .xml with the same name, example: image001.png -> image001.xmlNote inside this .xml we have others informations about our image like location, size, objects and their locations inside that image... The dataset we are using in this article is the LISA Traffic Light Dataset extracted from kaggle, this dataset contains images and classifications of traffic lights with the following classes: go; stop; warning; goLeft; goForward; stopLeft; warningLeft; But for this tutorial to be simpler, I modified the classes so that we only have: go; stop; warning; After the dowloand, note that we are moving everything into the folder ... / images %cd object_detection!wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=15WlpBbq4EpxUxZeKEAbfI_YJABASpmFs' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=15WlpBbq4EpxUxZeKEAbfI_YJABASpmFs" -O lisa608.zip!unzip -qq ./lisa608.zip!mv images_output/* images/!mv annotations_output/* images/ For this simple tutorial, I do not want to work with many classe, you can do this, but to simplify the process here I will rename all the classes that have “Left” and “Forward” at the end Here I just split my datset in train and test If your annotations are in Pascal-VOC format (as is our case) you will need to convert them into csv. I know, our original dataset was already in csv before, but I’ve converted it to xml just to show you this scenario.Here we iterate about each folder, train, test and validation (if we had data for validation) so we extracted the data: filename width height class xmin ymin xmax ymax and put it on a line from our csv. To use TF Object detection API we will need to follow the TFRecord input format. When we are working with a lot data, it is important to work with a format that is light and fast, one option is to work with the document’s binary, which is exactly what TFRecords does, but in addition it is optimized for working with Tensorflow because it was created for Tensorflow, for example when you are working with a very large dataset and try to load it in memory, obviously you will not get it because you don’t have memory RAM enought to do it, so you will have to work with batches, but if you use the the TFRecords you don’t need works with batches , it abstracts for you how to load the data into memory without you having to program itself. Here there is an article that explains more about how TFRecords works. For each project, some changes must be made in the class_text_to_int () method, note that there is a very simple logical structure where we have to return an integer depending on theclass that is Obs: you can see the whole code from the jupyter notebook. We will also need to input our classes in TF. To do it we will create a .pbtxt file with the following structure: item { id: 1 name: 'stop'} For each class we have an item, for each item we have an id and a name, the Id refers to the id that we use in our TFRecords: def class_text_to_int(row_label): if row_label == 'stop': return 1 elif row_label == 'warning': return 2 elif row_label == 'go': return 3 else: None remember to use the same ids. %%writefile training/labelmap.pbtxtitem { id: 1 name: 'stop'}item { id: 2 name: 'warning'}item { id: 3 name: 'go'} Here we will print the lenth of image folder to use this information later.. import ostest_path = "images/test"len_dir = len(os.listdir(test_path))print("{} imagens inside the {}".format(len_dir, test_path)) The next cell has a file is a configuration file of the neural network, here we have some hyper-paramétros that we must to modify . I copied this configuration file from faster_rcnn_inception_v2_pets.config and edited it with my respectivemodifications, for each deep learning architecture that you will use, you need a different configuration file, you can find all of them here [...]/research/object_detection/samples/configs or if you prefer, access via github. Within these files, some things should be changed, such as: num_classes faster_rcnn { num_classes: 3 fine_tune_checkpoint fine_tune_checkpoint: "/home/<full_path>/research/object_detection/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt" inside the property train_input_reader, change the input_path and the label_map_path to: tf_record_input_reader { input_path: "/<full_path>/research/object_detection/train.record" } label_map_path: "/<full_path>/research/object_detection/training/labelmap.pbtxt"} Remember that the train_input_reader must to be the train.record file. Inside the eval_config property, change the number of instances(images) you have to test (inside the .../images/test folder) in the num_examples property: eval_input_reader: { tf_record_input_reader { input_path: "/full_path/research/object_detection/test.record" } label_map_path: "/full_path/research/object_detection/training/labelmap.pbtxt" Note that I am using test.record instead of train.record Obs: just to remember that you can see the code and already run it all through google colabotory %cd ..!protoc ./object_detection/protos/*.proto --python_out=.%cd object_detection I’m sorry for that, but I was getting a very annoying error where it said that slim lib was not being found, many people said the problem was in my PYTHONPATH environment variable, but I verified a thousand times and did not find the problem, so I solved it by copying all the /research/slim code into the /object_detectionfolder, if anyone identifies what is being done wrong, please comment here below. !cp -a ../slim/. . Let’s train it! %run legacy/train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2.config After training your model, note that inside the /training folder we have a model.ckpt-22230.data-00000-of-00001 file, probably on your machine will have another number, this file is your saved model of your training! !ls training As we have copied the whole /slim folder to the /object_detection, we had overwrited the inference_graph.py file, so here we re-created the file. To learn more about inferences, I recommend these articles that are very good. article 1 Article 2 Let’s run our inference! Remember to change the trained_checkpoint_prefix property to use the model.ckpt-XXX that is inside the / training folder !python3 my_inference_graph.py \--input_type image_tensor \--pipeline_config_path training/faster_rcnn_inception_v2_pets.config \--trained_checkpoint_prefix training/model.ckpt-22230 \--output_directory ./inference_graph We will dowload some test image here to see some results from our model. !wget 'http://marcusquintella.sigonline.com.br/openged/conteudos/1306/001306_59bc593899b85_Semaforos_out_2017.jpg' -O semaforo.png This code is very similar to the test code! import osimport cv2import numpy as npimport tensorflow as tfimport sys# This is needed since the notebook is stored in the object_detection folder.sys.path.append("..") Let’s define some constants and some paths, checkpoint of our model, our labels and more. # Import utilitesfrom utils import label_map_utilfrom utils import visualization_utils as vis_util# Name of the directory containing the object detection module we're usingMODEL_NAME = 'inference_graph'IMAGE_NAME = 'semaforo.png'# Grab path to current working directoryCWD_PATH = os.getcwd()# Path to frozen detection graph .pb file, which contains the model that is used# for object detection.PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')# Path to label map filePATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt')# Path to imagePATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME)# Number of classes the object detector can identifyNUM_CLASSES = 3 here we load our label_maps so that we can make the model prediction depature, for example, know that the number 3 corresponds to the class “go” label_map = label_map_util.load_labelmap(PATH_TO_LABELS)categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)category_index = label_map_util.create_category_index(categories) Let’s load our model and select some layers from our model # Load the Tensorflow model into memory.detection_graph = tf.Graph()with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='')sess = tf.Session(graph=detection_graph)# Define input and output tensors (i.e. data) for the object detection classifier# Input tensor is the imageimage_tensor = detection_graph.get_tensor_by_name('image_tensor:0')# Output tensors are the detection boxes, scores, and classes# Each box represents a part of the image where a particular object was detecteddetection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')# Each score represents level of confidence for each of the objects.# The score is shown on the result image, together with the class label.detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')# Number of objects detectednum_detections = detection_graph.get_tensor_by_name('num_detections:0') below we load the image and run our model, if you do not know anything about Tensorflow, I suggest youread this article (this is a quick article) and read the documentation if you would like more details on how it works for a session within the tensorflow. Some parameters are configurable here, such as line_thickness that define the width of your line and the min_score_thresh that corresponds to the percentage of confidence you want to have Tensoflow say: hey, has an object here with more than X% confidence. (in our case we will use 0.6) Load image using OpenCV and# expand image dimensions to have shape: [1, None, None, 3]# i.e. a single-column array, where each item in the column has the pixel RGB valueimage = cv2.imread(PATH_TO_IMAGE)image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)image_expanded = np.expand_dims(image, axis=0)# Perform the actual detection by running the model with the image as input(boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_expanded})# Draw the results of the detection (aka 'visulaize the results')vis_util.visualize_boxes_and_labels_on_image_array( image, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=8, min_score_thresh=0.6) Let’s print our image with the respective classifications. In a real application it is not necessary to use visualize_boxes_and_labels_on_image_array (), you can use the boxes, classes and scores separately. %matplotlib inlineplt.figure(figsize=(20,10))plt.imshow(image) and here we have the original image image = cv2.imread(PATH_TO_IMAGE)image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)plt.figure(figsize=(20,10))plt.imshow(image) Now you can download this inference and use it on your machine, on the server, wherever you want !zip -r inference_graph.zip /content/obj_detect_api/models/research/object_detection/inference_graph So send it to google drive. !pip install -U -q PyDrivefrom pydrive.auth import GoogleAuthfrom pydrive.drive import GoogleDrivefrom google.colab import authfrom oauth2client.client import GoogleCredentials# 1. Authenticate and create the PyDrive client.auth.authenticate_user()gauth = GoogleAuth()gauth.credentials = GoogleCredentials.get_application_default()drive = GoogleDrive(gauth)model_file = drive.CreateFile({'title' : 'inference_graph.zip'})model_file.SetContentFile('./inference_graph.zip')model_file.Upload()# download to google drivedrive.CreateFile({'id': model_file.get('id')})
[ { "code": null, "e": 405, "s": 172, "text": "In general terms, at the end of this tutorial you basically will be able to pick up your dataset, load it on jupyter notebook, train and use your model :)The picture above is the result in the example that we are going to play here." }, { "code": null, "e": 741, "s": 405, "text": "This article is just to call you to learn about TF object detection API, but this content is just a poor copy-past from my jupyter notebook, if you want to see something more structured and beautiful, go to my jupyter notebook that there have the same texts that have here, but in a more beautiful and easy to understand that medium :)" }, { "code": null, "e": 787, "s": 741, "text": "To begin with, let’s install the dependencies" }, { "code": null, "e": 954, "s": 787, "text": "!pip install pillow!pip install lxml!pip install Cython!pip install jupyter!pip install matplotlib!pip install pandas!pip install opencv-python!pip install tensorflow" }, { "code": null, "e": 1211, "s": 954, "text": "First of all, let’s download the tensorflow models repository, inside this repository has the objection detection api, that we will use to train our ownobject detection model. Everything that we will do, is inside the path models/research/object_detection." }, { "code": null, "e": 1296, "s": 1211, "text": "!git clone https://github.com/tensorflow/models/%cd models/research/object_detection" }, { "code": null, "e": 1398, "s": 1296, "text": "Here we’re just creating some folders that we will use it later.The command mkdir creates directories" }, { "code": null, "e": 1479, "s": 1398, "text": "!mkdir training!mkdir inference_graph!mkdir -p images/train!mkdir -p images/test" }, { "code": null, "e": 1966, "s": 1479, "text": "Inside the the tensorflow zoo models we can choose a pre-trained model to dowloand and use it to train our own dataset.Inside the tensorlfow zoo models repository’s folder, we have a table that explain how precise the model is (with mAP — mean Average Precision )and how faster this model is.You can choose any model that you want, the process in this tutorial for othersmodels is the same.For this tutorial, I choosed the faster_rcnn_inception_v2_coco_2018_01_28, justbecause I want :)" }, { "code": null, "e": 2188, "s": 1966, "text": "!wget http://download.tensorflow.org/models/object_detection/faster_rcnn_inception_v2_coco_2018_01_28.tar.gz!tar -xvzf faster_rcnn_inception_v2_coco_2018_01_28.tar.gz!rm -rf faster_rcnn_inception_v2_coco_2018_01_28.tar.gz" }, { "code": null, "e": 2328, "s": 2188, "text": "According to the documentation, it is important that we export the PYTHONPATH environment variable with the models, reasearch and slim path" }, { "code": null, "e": 2517, "s": 2328, "text": "import osos.environ['PYTHONPATH'] = \"{}/content/obj_detect_api/models:/content/obj_detect_api/models/research:/content/obj_detect_api/models/research/slim\".format(os.environ['PYTHONPATH'])" }, { "code": null, "e": 3247, "s": 2517, "text": "Here we have some proto buffers that need to be compiled, remember that it’s compiled, so if you switch machines, you can’t just copy and pastethe files generated by this guy.Being sincere I couldn’t execute these protos from the “/research/object_detection” folder, I tried N ways and it didn’t work, so I simply compiled them from within the “/research” folder.to understand what’s proto buffers is not necessary for this tutorial, but if you wantto learn more about, I recommend you look the documentation, basically it’s textstructures (such as json, xml) containing message structures that you can transformit to some languages, is a little more than that, but for now that’s more than enough for you to follow that article." }, { "code": null, "e": 3310, "s": 3247, "text": "%cd ..!protoc ./object_detection/protos/*.proto --python_out=." }, { "code": null, "e": 3437, "s": 3310, "text": "I don’t remember the exact version that the Tensroflow Objection detect APIrequire, but I know from version >= 3.0 works well." }, { "code": null, "e": 3455, "s": 3437, "text": "!protoc --version" }, { "code": null, "e": 3474, "s": 3455, "text": "So just install it" }, { "code": null, "e": 3523, "s": 3474, "text": "!python3 setup.py build!python3 setup.py install" }, { "code": null, "e": 3789, "s": 3523, "text": "Once we have installed everything, we can run some sample scripts from theTensorflow Object detection API to verify if everything is correct.this code isn’t mine, I copied it from object_detection folder just to make somemodifications ro run it on jupyter notebook." }, { "code": null, "e": 3901, "s": 3789, "text": "I don’t will explain this code because it’s is justo to test the instalation, we will see a similar code later." }, { "code": null, "e": 3927, "s": 3901, "text": "Just execute these cells." }, { "code": null, "e": 3992, "s": 3927, "text": "Warning: Just certify that you are using the Tensorflow >=1.12.0" }, { "code": null, "e": 4089, "s": 3992, "text": "Obs: Remember that you can leave this article and go to the jupyter notebook, which is better :)" }, { "code": null, "e": 4192, "s": 4089, "text": "If after you execute the cell bellow you can see a dog image and a beach image, everything is working!" }, { "code": null, "e": 4233, "s": 4192, "text": "First of all let’s download our dataset." }, { "code": null, "e": 4418, "s": 4233, "text": "In this article we will use a dataset from kaggle, but don’t worry, during this tutorial I will direct you to another articl that teaches you how to create your own classified dataset." }, { "code": null, "e": 4590, "s": 4418, "text": "Before talking about the dataset, I want to just to remember you that in this tutorial we will use datasets in the Pascal-VOC format, this is famous format where you have:" }, { "code": null, "e": 4626, "s": 4590, "text": "Images in jpg, jpeg, png format ..." }, { "code": null, "e": 4675, "s": 4626, "text": "Annotations: .xml files in the following format:" }, { "code": null, "e": 5333, "s": 4675, "text": "<annotation> <folder>GeneratedData_Train</folder> <filename>000001.png</filename> <path>/my/path/GeneratedData_Train/000001.png</path> <source> <database>Unknown</database> </source> <size> <width>224</width> <height>224</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>21</name> <pose>Frontal</pose> <truncated>0</truncated> <difficult>0</difficult> <occluded>0</occluded> <bndbox> <xmin>82</xmin> <xmax>172</xmax> <ymin>88</ymin> <ymax>146</ymax> </bndbox> </object></annotation>" }, { "code": null, "e": 5558, "s": 5333, "text": "For each image, we have an .xml with the same name, example: image001.png -> image001.xmlNote inside this .xml we have others informations about our image like location, size, objects and their locations inside that image..." }, { "code": null, "e": 5751, "s": 5558, "text": "The dataset we are using in this article is the LISA Traffic Light Dataset extracted from kaggle, this dataset contains images and classifications of traffic lights with the following classes:" }, { "code": null, "e": 5755, "s": 5751, "text": "go;" }, { "code": null, "e": 5761, "s": 5755, "text": "stop;" }, { "code": null, "e": 5770, "s": 5761, "text": "warning;" }, { "code": null, "e": 5778, "s": 5770, "text": "goLeft;" }, { "code": null, "e": 5789, "s": 5778, "text": "goForward;" }, { "code": null, "e": 5799, "s": 5789, "text": "stopLeft;" }, { "code": null, "e": 5812, "s": 5799, "text": "warningLeft;" }, { "code": null, "e": 5894, "s": 5812, "text": "But for this tutorial to be simpler, I modified the classes so that we only have:" }, { "code": null, "e": 5898, "s": 5894, "text": "go;" }, { "code": null, "e": 5904, "s": 5898, "text": "stop;" }, { "code": null, "e": 5913, "s": 5904, "text": "warning;" }, { "code": null, "e": 5997, "s": 5913, "text": "After the dowloand, note that we are moving everything into the folder ... / images" }, { "code": null, "e": 6472, "s": 5997, "text": "%cd object_detection!wget --load-cookies /tmp/cookies.txt \"https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=15WlpBbq4EpxUxZeKEAbfI_YJABASpmFs' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\\1\\n/p')&id=15WlpBbq4EpxUxZeKEAbfI_YJABASpmFs\" -O lisa608.zip!unzip -qq ./lisa608.zip!mv images_output/* images/!mv annotations_output/* images/" }, { "code": null, "e": 6660, "s": 6472, "text": "For this simple tutorial, I do not want to work with many classe, you can do this, but to simplify the process here I will rename all the classes that have “Left” and “Forward” at the end" }, { "code": null, "e": 6706, "s": 6660, "text": "Here I just split my datset in train and test" }, { "code": null, "e": 6808, "s": 6706, "text": "If your annotations are in Pascal-VOC format (as is our case) you will need to convert them into csv." }, { "code": null, "e": 7044, "s": 6808, "text": "I know, our original dataset was already in csv before, but I’ve converted it to xml just to show you this scenario.Here we iterate about each folder, train, test and validation (if we had data for validation) so we extracted the data:" }, { "code": null, "e": 7053, "s": 7044, "text": "filename" }, { "code": null, "e": 7059, "s": 7053, "text": "width" }, { "code": null, "e": 7066, "s": 7059, "text": "height" }, { "code": null, "e": 7072, "s": 7066, "text": "class" }, { "code": null, "e": 7077, "s": 7072, "text": "xmin" }, { "code": null, "e": 7082, "s": 7077, "text": "ymin" }, { "code": null, "e": 7087, "s": 7082, "text": "xmax" }, { "code": null, "e": 7092, "s": 7087, "text": "ymax" }, { "code": null, "e": 7127, "s": 7092, "text": "and put it on a line from our csv." }, { "code": null, "e": 7208, "s": 7127, "text": "To use TF Object detection API we will need to follow the TFRecord input format." }, { "code": null, "e": 7865, "s": 7208, "text": "When we are working with a lot data, it is important to work with a format that is light and fast, one option is to work with the document’s binary, which is exactly what TFRecords does, but in addition it is optimized for working with Tensorflow because it was created for Tensorflow, for example when you are working with a very large dataset and try to load it in memory, obviously you will not get it because you don’t have memory RAM enought to do it, so you will have to work with batches, but if you use the the TFRecords you don’t need works with batches , it abstracts for you how to load the data into memory without you having to program itself." }, { "code": null, "e": 7936, "s": 7865, "text": "Here there is an article that explains more about how TFRecords works." }, { "code": null, "e": 8132, "s": 7936, "text": "For each project, some changes must be made in the class_text_to_int () method, note that there is a very simple logical structure where we have to return an integer depending on theclass that is" }, { "code": null, "e": 8191, "s": 8132, "text": "Obs: you can see the whole code from the jupyter notebook." }, { "code": null, "e": 8305, "s": 8191, "text": "We will also need to input our classes in TF. To do it we will create a .pbtxt file with the following structure:" }, { "code": null, "e": 8334, "s": 8305, "text": "item { id: 1 name: 'stop'}" }, { "code": null, "e": 8460, "s": 8334, "text": "For each class we have an item, for each item we have an id and a name, the Id refers to the id that we use in our TFRecords:" }, { "code": null, "e": 8649, "s": 8460, "text": "def class_text_to_int(row_label): if row_label == 'stop': return 1 elif row_label == 'warning': return 2 elif row_label == 'go': return 3 else: None" }, { "code": null, "e": 8679, "s": 8649, "text": "remember to use the same ids." }, { "code": null, "e": 8800, "s": 8679, "text": "%%writefile training/labelmap.pbtxtitem { id: 1 name: 'stop'}item { id: 2 name: 'warning'}item { id: 3 name: 'go'}" }, { "code": null, "e": 8877, "s": 8800, "text": "Here we will print the lenth of image folder to use this information later.." }, { "code": null, "e": 9008, "s": 8877, "text": "import ostest_path = \"images/test\"len_dir = len(os.listdir(test_path))print(\"{} imagens inside the {}\".format(len_dir, test_path))" }, { "code": null, "e": 9141, "s": 9008, "text": "The next cell has a file is a configuration file of the neural network, here we have some hyper-paramétros that we must to modify ." }, { "code": null, "e": 9474, "s": 9141, "text": "I copied this configuration file from faster_rcnn_inception_v2_pets.config and edited it with my respectivemodifications, for each deep learning architecture that you will use, you need a different configuration file, you can find all of them here [...]/research/object_detection/samples/configs or if you prefer, access via github." }, { "code": null, "e": 9546, "s": 9474, "text": "Within these files, some things should be changed, such as: num_classes" }, { "code": null, "e": 9578, "s": 9546, "text": "faster_rcnn { num_classes: 3" }, { "code": null, "e": 9599, "s": 9578, "text": "fine_tune_checkpoint" }, { "code": null, "e": 9719, "s": 9599, "text": "fine_tune_checkpoint: \"/home/<full_path>/research/object_detection/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt\"" }, { "code": null, "e": 9808, "s": 9719, "text": "inside the property train_input_reader, change the input_path and the label_map_path to:" }, { "code": null, "e": 9988, "s": 9808, "text": "tf_record_input_reader { input_path: \"/<full_path>/research/object_detection/train.record\" } label_map_path: \"/<full_path>/research/object_detection/training/labelmap.pbtxt\"}" }, { "code": null, "e": 10059, "s": 9988, "text": "Remember that the train_input_reader must to be the train.record file." }, { "code": null, "e": 10214, "s": 10059, "text": "Inside the eval_config property, change the number of instances(images) you have to test (inside the .../images/test folder) in the num_examples property:" }, { "code": null, "e": 10410, "s": 10214, "text": "eval_input_reader: { tf_record_input_reader { input_path: \"/full_path/research/object_detection/test.record\" } label_map_path: \"/full_path/research/object_detection/training/labelmap.pbtxt\"" }, { "code": null, "e": 10467, "s": 10410, "text": "Note that I am using test.record instead of train.record" }, { "code": null, "e": 10564, "s": 10467, "text": "Obs: just to remember that you can see the code and already run it all through google colabotory" }, { "code": null, "e": 10647, "s": 10564, "text": "%cd ..!protoc ./object_detection/protos/*.proto --python_out=.%cd object_detection" }, { "code": null, "e": 11052, "s": 10647, "text": "I’m sorry for that, but I was getting a very annoying error where it said that slim lib was not being found, many people said the problem was in my PYTHONPATH environment variable, but I verified a thousand times and did not find the problem, so I solved it by copying all the /research/slim code into the /object_detectionfolder, if anyone identifies what is being done wrong, please comment here below." }, { "code": null, "e": 11071, "s": 11052, "text": "!cp -a ../slim/. ." }, { "code": null, "e": 11087, "s": 11071, "text": "Let’s train it!" }, { "code": null, "e": 11208, "s": 11087, "text": "%run legacy/train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2.config" }, { "code": null, "e": 11425, "s": 11208, "text": "After training your model, note that inside the /training folder we have a model.ckpt-22230.data-00000-of-00001 file, probably on your machine will have another number, this file is your saved model of your training!" }, { "code": null, "e": 11438, "s": 11425, "text": "!ls training" }, { "code": null, "e": 11584, "s": 11438, "text": "As we have copied the whole /slim folder to the /object_detection, we had overwrited the inference_graph.py file, so here we re-created the file." }, { "code": null, "e": 11683, "s": 11584, "text": "To learn more about inferences, I recommend these articles that are very good. article 1 Article 2" }, { "code": null, "e": 11829, "s": 11683, "text": "Let’s run our inference! Remember to change the trained_checkpoint_prefix property to use the model.ckpt-XXX that is inside the / training folder" }, { "code": null, "e": 12050, "s": 11829, "text": "!python3 my_inference_graph.py \\--input_type image_tensor \\--pipeline_config_path training/faster_rcnn_inception_v2_pets.config \\--trained_checkpoint_prefix training/model.ckpt-22230 \\--output_directory ./inference_graph" }, { "code": null, "e": 12123, "s": 12050, "text": "We will dowload some test image here to see some results from our model." }, { "code": null, "e": 12255, "s": 12123, "text": "!wget 'http://marcusquintella.sigonline.com.br/openged/conteudos/1306/001306_59bc593899b85_Semaforos_out_2017.jpg' -O semaforo.png" }, { "code": null, "e": 12299, "s": 12255, "text": "This code is very similar to the test code!" }, { "code": null, "e": 12468, "s": 12299, "text": "import osimport cv2import numpy as npimport tensorflow as tfimport sys# This is needed since the notebook is stored in the object_detection folder.sys.path.append(\"..\")" }, { "code": null, "e": 12558, "s": 12468, "text": "Let’s define some constants and some paths, checkpoint of our model, our labels and more." }, { "code": null, "e": 13251, "s": 12558, "text": "# Import utilitesfrom utils import label_map_utilfrom utils import visualization_utils as vis_util# Name of the directory containing the object detection module we're usingMODEL_NAME = 'inference_graph'IMAGE_NAME = 'semaforo.png'# Grab path to current working directoryCWD_PATH = os.getcwd()# Path to frozen detection graph .pb file, which contains the model that is used# for object detection.PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')# Path to label map filePATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt')# Path to imagePATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME)# Number of classes the object detector can identifyNUM_CLASSES = 3" }, { "code": null, "e": 13396, "s": 13251, "text": "here we load our label_maps so that we can make the model prediction depature, for example, know that the number 3 corresponds to the class “go”" }, { "code": null, "e": 13640, "s": 13396, "text": "label_map = label_map_util.load_labelmap(PATH_TO_LABELS)categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)category_index = label_map_util.create_category_index(categories)" }, { "code": null, "e": 13699, "s": 13640, "text": "Let’s load our model and select some layers from our model" }, { "code": null, "e": 14846, "s": 13699, "text": "# Load the Tensorflow model into memory.detection_graph = tf.Graph()with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='')sess = tf.Session(graph=detection_graph)# Define input and output tensors (i.e. data) for the object detection classifier# Input tensor is the imageimage_tensor = detection_graph.get_tensor_by_name('image_tensor:0')# Output tensors are the detection boxes, scores, and classes# Each box represents a part of the image where a particular object was detecteddetection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')# Each score represents level of confidence for each of the objects.# The score is shown on the result image, together with the class label.detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')# Number of objects detectednum_detections = detection_graph.get_tensor_by_name('num_detections:0')" }, { "code": null, "e": 15103, "s": 14846, "text": "below we load the image and run our model, if you do not know anything about Tensorflow, I suggest youread this article (this is a quick article) and read the documentation if you would like more details on how it works for a session within the tensorflow." }, { "code": null, "e": 15390, "s": 15103, "text": "Some parameters are configurable here, such as line_thickness that define the width of your line and the min_score_thresh that corresponds to the percentage of confidence you want to have Tensoflow say: hey, has an object here with more than X% confidence. (in our case we will use 0.6)" }, { "code": null, "e": 16234, "s": 15390, "text": "Load image using OpenCV and# expand image dimensions to have shape: [1, None, None, 3]# i.e. a single-column array, where each item in the column has the pixel RGB valueimage = cv2.imread(PATH_TO_IMAGE)image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)image_expanded = np.expand_dims(image, axis=0)# Perform the actual detection by running the model with the image as input(boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_expanded})# Draw the results of the detection (aka 'visulaize the results')vis_util.visualize_boxes_and_labels_on_image_array( image, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=8, min_score_thresh=0.6)" }, { "code": null, "e": 16442, "s": 16234, "text": "Let’s print our image with the respective classifications. In a real application it is not necessary to use visualize_boxes_and_labels_on_image_array (), you can use the boxes, classes and scores separately." }, { "code": null, "e": 16505, "s": 16442, "text": "%matplotlib inlineplt.figure(figsize=(20,10))plt.imshow(image)" }, { "code": null, "e": 16541, "s": 16505, "text": "and here we have the original image" }, { "code": null, "e": 16665, "s": 16541, "text": "image = cv2.imread(PATH_TO_IMAGE)image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)plt.figure(figsize=(20,10))plt.imshow(image)" }, { "code": null, "e": 16762, "s": 16665, "text": "Now you can download this inference and use it on your machine, on the server, wherever you want" }, { "code": null, "e": 16863, "s": 16762, "text": "!zip -r inference_graph.zip /content/obj_detect_api/models/research/object_detection/inference_graph" }, { "code": null, "e": 16891, "s": 16863, "text": "So send it to google drive." } ]
Android - LinkedIn Integration
Android allows your application to connect to Linkedin and share data or any kind of updates on Linkedin. This chapter is about integrating Linkedin into your application. There are two ways through which you can integrate Linkedin and share something from your application. These ways are listed below. Linkedin SDK (Scribe) Linkedin SDK (Scribe) Intent Share Intent Share This is the first way of connecting with Linkedin. You have to register your application and then receive some Application Id , and then you have to download the Linkedin SDK and add it to your project. The steps are listed below. Create a new Linkedin application at https://www.linkedin.com/secure/developer. Click on add new application. It is shown below − Now fill in your application name , description and your website url. It is shown below − If everything works fine, you will receive an API key with the secret. Just copy the API key and save it somewhere. It is shown in the image below − Download Linkedin sdk here. Copy the scribe-1.3.0.jar jar into your project libs folder. Once everything is complete, you can run the Linkedin samples which can be found here. Intent share is used to share data between applications. In this strategy, we will not handle the SDK stuff, but let the Linkedin application handles it. We will simply call the Linkedin application and pass the data to share. This way, we can share something on Linkedin. Android provides intent library to share data between activities and applications. In order to use it as share intent, we have to specify the type of the share intent to ACTION_SEND. Its syntax is given below − Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); Next thing you need to is to define the type of data to pass , and then pass the data. Its syntax is given below − shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, from tutorialspoint"); startActivity(Intent.createChooser(shareIntent, "Share your thoughts")); Apart from the these methods , there are other methods available that allows intent handling. They are listed below − addCategory(String category) This method add a new category to the intent. createChooser(Intent target, CharSequence title) Convenience function for creating a ACTION_CHOOSER Intent getAction() This method retrieve the general action to be performed, such as ACTION_VIEW getCategories() This method return the set of all categories in the intent.nt and the current scaling event putExtra(String name, int value) This method add extended data to the intent. toString() This method returns a string containing a concise, human-readable description of this object Here is an example demonstrating the use of IntentShare to share data on Linkedin. It creates a basic application that allows you to share some text on Linkedin. To experiment with this example, you can run this on an actual device or in an emulator. Following is the content of the modified main activity file MainActivity.java. package com.example.sairamkrishna.myapplication; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import java.io.FileNotFoundException; import java.io.InputStream; public class MainActivity extends AppCompatActivity { private ImageView img; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); img = (ImageView) findViewById(R.id.imageView); Button b1 = (Button) findViewById(R.id.button); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent sharingIntent = new Intent(Intent.ACTION_SEND); Uri screenshotUri = Uri.parse("android. resource://comexample.sairamkrishna.myapplication/*"); try { InputStream stream = getContentResolver().openInputStream(screenshotUri); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } sharingIntent.setType("image/jpeg"); sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri); startActivity(Intent.createChooser(sharingIntent, "Share image using")); } }); } } Following is the modified content of the xml res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:textSize="30dp" android:text="Linkedin Share" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tutorials Point" android:id="@+id/textView2" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:textSize="35dp" android:textColor="#ff16ff01" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:layout_below="@+id/textView2" android:layout_centerHorizontal="true" android:src="@drawable/logo"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Share" android:id="@+id/button" android:layout_marginTop="61dp" android:layout_below="@+id/imageView" android:layout_centerHorizontal="true" /> </RelativeLayout> Following is the content of AndroidManifest.xml file. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sairamkrishna.myapplication" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application. Select your mobile device as an option and then check your mobile device which will display your default screen − Now just tap on the image logo and you will see a list of share providers. Now just select Linkedin from that list and then write any message. It is shown in the image below − Now it shows updating information 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3779, "s": 3607, "text": "Android allows your application to connect to Linkedin and share data or any kind of updates on Linkedin. This chapter is about integrating Linkedin into your application." }, { "code": null, "e": 3911, "s": 3779, "text": "There are two ways through which you can integrate Linkedin and share something from your application. These ways are listed below." }, { "code": null, "e": 3933, "s": 3911, "text": "Linkedin SDK (Scribe)" }, { "code": null, "e": 3955, "s": 3933, "text": "Linkedin SDK (Scribe)" }, { "code": null, "e": 3968, "s": 3955, "text": "Intent Share" }, { "code": null, "e": 3981, "s": 3968, "text": "Intent Share" }, { "code": null, "e": 4212, "s": 3981, "text": "This is the first way of connecting with Linkedin. You have to register your application and then receive some Application Id , and then you have to download the Linkedin SDK and add it to your project. The steps are listed below." }, { "code": null, "e": 4342, "s": 4212, "text": "Create a new Linkedin application at https://www.linkedin.com/secure/developer. Click on add new application. It is shown below −" }, { "code": null, "e": 4432, "s": 4342, "text": "Now fill in your application name , description and your website url. It is shown below −" }, { "code": null, "e": 4581, "s": 4432, "text": "If everything works fine, you will receive an API key with the secret. Just copy the API key and save it somewhere. It is shown in the image below −" }, { "code": null, "e": 4671, "s": 4581, "text": "Download Linkedin sdk here. Copy the scribe-1.3.0.jar jar into your project libs folder." }, { "code": null, "e": 4758, "s": 4671, "text": "Once everything is complete, you can run the Linkedin samples which can be found here." }, { "code": null, "e": 5031, "s": 4758, "text": "Intent share is used to share data between applications. In this strategy, we will not handle the SDK stuff, but let the Linkedin application handles it. We will simply call the Linkedin application and pass the data to share. This way, we can share something on Linkedin." }, { "code": null, "e": 5242, "s": 5031, "text": "Android provides intent library to share data between activities and applications. In order to use it as share intent, we have to specify the type of the share intent to ACTION_SEND. Its syntax is given below −" }, { "code": null, "e": 5320, "s": 5242, "text": "Intent shareIntent = new Intent();\nshareIntent.setAction(Intent.ACTION_SEND);" }, { "code": null, "e": 5435, "s": 5320, "text": "Next thing you need to is to define the type of data to pass , and then pass the data. Its syntax is given below −" }, { "code": null, "e": 5614, "s": 5435, "text": "shareIntent.setType(\"text/plain\");\nshareIntent.putExtra(Intent.EXTRA_TEXT, \"Hello, from tutorialspoint\");\nstartActivity(Intent.createChooser(shareIntent, \"Share your thoughts\"));" }, { "code": null, "e": 5732, "s": 5614, "text": "Apart from the these methods , there are other methods available that allows intent handling. They are listed below −" }, { "code": null, "e": 5761, "s": 5732, "text": "addCategory(String category)" }, { "code": null, "e": 5807, "s": 5761, "text": "This method add a new category to the intent." }, { "code": null, "e": 5856, "s": 5807, "text": "createChooser(Intent target, CharSequence title)" }, { "code": null, "e": 5914, "s": 5856, "text": "Convenience function for creating a ACTION_CHOOSER Intent" }, { "code": null, "e": 5926, "s": 5914, "text": "getAction()" }, { "code": null, "e": 6003, "s": 5926, "text": "This method retrieve the general action to be performed, such as ACTION_VIEW" }, { "code": null, "e": 6019, "s": 6003, "text": "getCategories()" }, { "code": null, "e": 6111, "s": 6019, "text": "This method return the set of all categories in the intent.nt and the current scaling event" }, { "code": null, "e": 6144, "s": 6111, "text": "putExtra(String name, int value)" }, { "code": null, "e": 6189, "s": 6144, "text": "This method add extended data to the intent." }, { "code": null, "e": 6200, "s": 6189, "text": "toString()" }, { "code": null, "e": 6293, "s": 6200, "text": "This method returns a string containing a concise, human-readable description of this object" }, { "code": null, "e": 6455, "s": 6293, "text": "Here is an example demonstrating the use of IntentShare to share data on Linkedin. It creates a basic application that allows you to share some text on Linkedin." }, { "code": null, "e": 6544, "s": 6455, "text": "To experiment with this example, you can run this on an actual device or in an emulator." }, { "code": null, "e": 6624, "s": 6544, "text": "Following is the content of the modified main activity file MainActivity.java. " }, { "code": null, "e": 8090, "s": 6624, "text": "package com.example.sairamkrishna.myapplication;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport java.io.FileNotFoundException;\nimport java.io.InputStream;\n\npublic class MainActivity extends AppCompatActivity {\n private ImageView img;\n\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n img = (ImageView) findViewById(R.id.imageView);\n Button b1 = (Button) findViewById(R.id.button);\n\n b1.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent sharingIntent = new Intent(Intent.ACTION_SEND);\n Uri screenshotUri = Uri.parse(\"android.\n resource://comexample.sairamkrishna.myapplication/*\");\n\n try {\n InputStream stream = getContentResolver().openInputStream(screenshotUri);\n } catch (FileNotFoundException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n\n sharingIntent.setType(\"image/jpeg\");\n sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);\n startActivity(Intent.createChooser(sharingIntent, \"Share image using\"));\n }\n });\n }\n}" }, { "code": null, "e": 8165, "s": 8090, "text": "Following is the modified content of the xml res/layout/activity_main.xml." }, { "code": null, "e": 9890, "s": 8165, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout \n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" \n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" \n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" \n tools:context=\".MainActivity\">\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textView\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"30dp\"\n android:text=\"Linkedin Share\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials Point\"\n android:id=\"@+id/textView2\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"35dp\"\n android:textColor=\"#ff16ff01\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:layout_below=\"@+id/textView2\"\n android:layout_centerHorizontal=\"true\"\n android:src=\"@drawable/logo\"/>\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Share\"\n android:id=\"@+id/button\"\n android:layout_marginTop=\"61dp\"\n android:layout_below=\"@+id/imageView\"\n android:layout_centerHorizontal=\"true\" />\n \n</RelativeLayout>" }, { "code": null, "e": 9944, "s": 9890, "text": "Following is the content of AndroidManifest.xml file." }, { "code": null, "e": 10645, "s": 9944, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>" }, { "code": null, "e": 11026, "s": 10645, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application." }, { "code": null, "e": 11140, "s": 11026, "text": "Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 11215, "s": 11140, "text": "Now just tap on the image logo and you will see a list of share providers." }, { "code": null, "e": 11316, "s": 11215, "text": "Now just select Linkedin from that list and then write any message. It is shown in the image below −" }, { "code": null, "e": 11350, "s": 11316, "text": "Now it shows updating information" }, { "code": null, "e": 11385, "s": 11350, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 11397, "s": 11385, "text": " Aditya Dua" }, { "code": null, "e": 11432, "s": 11397, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 11446, "s": 11432, "text": " Sharad Kumar" }, { "code": null, "e": 11478, "s": 11446, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 11495, "s": 11478, "text": " Abhilash Nelson" }, { "code": null, "e": 11530, "s": 11495, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11547, "s": 11530, "text": " Abhilash Nelson" }, { "code": null, "e": 11582, "s": 11547, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11599, "s": 11582, "text": " Abhilash Nelson" }, { "code": null, "e": 11632, "s": 11599, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 11649, "s": 11632, "text": " Abhilash Nelson" }, { "code": null, "e": 11656, "s": 11649, "text": " Print" }, { "code": null, "e": 11667, "s": 11656, "text": " Add Notes" } ]
C program to draw the Olympics Logo using graphics - GeeksforGeeks
14 Apr, 2021 In this article, we will discuss how to design the Olympics Logo using Graphics. Draw five circles according to positions in the logo using the function circle(). To achieve the outline effect, draw 5 smaller circles over it. There is a black circle as well in the logo and to prevent it from blending in, change the background color. Color all the circles and the background to their respective colors using functions setfillstyle() and floodfill(). Below is the implementation of the above approach: C // C program for the above approach #include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ int gd = DETECT, gm; // Initialize of gdriver initgraph(&gd, &gm, "C:\\turboc3\\bgi"); // Create Background color as Grey setfillstyle(SOLID_FILL, DARKGRAY); floodfill(50, 50, 15); // Create two circles in each // another & color Blue setfillstyle(SOLID_FILL, BLUE); circle(300, 300, 100); circle(300, 300, 90); floodfill(202, 300, 15); // Create two circles in each // another & color Yellow setfillstyle(SOLID_FILL, YELLOW); circle(400, 400, 100); circle(400, 400, 90); floodfill(322, 350, 15); floodfill(302, 400, 15); // Create two circles in each // another & color Black setfillstyle(SOLID_FILL, BLACK); circle(520, 300, 100); circle(520, 300, 90); floodfill(442, 350, 15); floodfill(422, 300, 15); // Create two circles in each // another & color Green setfillstyle(SOLID_FILL, GREEN); circle(620, 400, 100); circle(620, 400, 90); floodfill(522, 400, 15); floodfill(542, 350, 15); // Create two circles in each // another & color Red setfillstyle(SOLID_FILL, RED); circle(740, 300, 100); circle(740, 300, 90); floodfill(642, 300, 15); floodfill(662, 350, 15); // Hold the screen for a while getch(); // Close the initialized gdriver closegraph();} Output: c-graphics computer-graphics C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Converting Strings to Numbers in C/C++ Function Pointer in C Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 25733, "s": 25705, "text": "\n14 Apr, 2021" }, { "code": null, "e": 25814, "s": 25733, "text": "In this article, we will discuss how to design the Olympics Logo using Graphics." }, { "code": null, "e": 25896, "s": 25814, "text": "Draw five circles according to positions in the logo using the function circle()." }, { "code": null, "e": 25959, "s": 25896, "text": "To achieve the outline effect, draw 5 smaller circles over it." }, { "code": null, "e": 26068, "s": 25959, "text": "There is a black circle as well in the logo and to prevent it from blending in, change the background color." }, { "code": null, "e": 26184, "s": 26068, "text": "Color all the circles and the background to their respective colors using functions setfillstyle() and floodfill()." }, { "code": null, "e": 26235, "s": 26184, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26237, "s": 26235, "text": "C" }, { "code": "// C program for the above approach #include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ int gd = DETECT, gm; // Initialize of gdriver initgraph(&gd, &gm, \"C:\\\\turboc3\\\\bgi\"); // Create Background color as Grey setfillstyle(SOLID_FILL, DARKGRAY); floodfill(50, 50, 15); // Create two circles in each // another & color Blue setfillstyle(SOLID_FILL, BLUE); circle(300, 300, 100); circle(300, 300, 90); floodfill(202, 300, 15); // Create two circles in each // another & color Yellow setfillstyle(SOLID_FILL, YELLOW); circle(400, 400, 100); circle(400, 400, 90); floodfill(322, 350, 15); floodfill(302, 400, 15); // Create two circles in each // another & color Black setfillstyle(SOLID_FILL, BLACK); circle(520, 300, 100); circle(520, 300, 90); floodfill(442, 350, 15); floodfill(422, 300, 15); // Create two circles in each // another & color Green setfillstyle(SOLID_FILL, GREEN); circle(620, 400, 100); circle(620, 400, 90); floodfill(522, 400, 15); floodfill(542, 350, 15); // Create two circles in each // another & color Red setfillstyle(SOLID_FILL, RED); circle(740, 300, 100); circle(740, 300, 90); floodfill(642, 300, 15); floodfill(662, 350, 15); // Hold the screen for a while getch(); // Close the initialized gdriver closegraph();}", "e": 27665, "s": 26237, "text": null }, { "code": null, "e": 27673, "s": 27665, "text": "Output:" }, { "code": null, "e": 27684, "s": 27673, "text": "c-graphics" }, { "code": null, "e": 27702, "s": 27684, "text": "computer-graphics" }, { "code": null, "e": 27713, "s": 27702, "text": "C Language" }, { "code": null, "e": 27724, "s": 27713, "text": "C Programs" }, { "code": null, "e": 27822, "s": 27724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27839, "s": 27822, "text": "Substring in C++" }, { "code": null, "e": 27874, "s": 27839, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27920, "s": 27874, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 27959, "s": 27920, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 27981, "s": 27959, "text": "Function Pointer in C" }, { "code": null, "e": 27994, "s": 27981, "text": "Strings in C" }, { "code": null, "e": 28035, "s": 27994, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28076, "s": 28035, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28111, "s": 28076, "text": "Header files in C/C++ and its uses" } ]
Node.js Timeout Timer Class - GeeksforGeeks
18 Jun, 2021 The timer module is used for scheduling functions which will be called at some future period of time. It is a global API So, there is no need to import (require(“timers”)) to use it. Timeout Class has an object (setTimeout()/setInterval()) which is created internally to scheduled actions, and (clearTimeout()/clearInterval()) can be passed in order to cancel those scheduled actions. When a timeout is scheduled, By default, the event loop of Node.js will continue running until clearTimeout() is called. The setTimeout() method returns timeout objects that are used to control this default behavior, exports both timeout.ref() and timeout.unref() functions. The four Timeout Class objects are defined below: 1. timeout.hasRef(): (Added in v11.0.0) This timeout object keeps the event loop active until the returned ‘True’ if returned ‘false’ breaks the event loop. Syntax: timeout.hasRef() Return Value <boolean>: This timeout object keeps the event loop active if returned ‘True’. 2. timeout.ref(): (Added in v9.7.0) When the Timeout is active and (timeout.ref()) called then it requests that the Node.js event loop did not exit so long. Anyway, calling this Method multiple times does not have any effect. Syntax: timeout.ref() Return Value <Timeout>: It returns a timeout reference. 3. timeout.refresh() (Added in v10.2.0): This method refreshes the timer without allocating a new JavaScript object. The start time of the timer is set to the current time, and the timer is rescheduled from the previously specified duration to the current time by calling its callback. By using timeout.refresh() on a timer which already called its callback and then it reactivates the timer. Syntax: timeout.refresh() Return Value <Timeout>: It returns the timeout reference. 4. timeout.unref() (Added in v9.7.0) When the Timeout is active it does not require the Node.js event loop to remain active. The callback of the Timeout object is invoked after the process gets exit if any other activity keeps the event loop running. Anyway, calling this Method also multiple times does not have any effect. Syntax: timeout.unref() Return Value <Timeout>: It returns the timeout reference. Example: Filename: index.js Javascript // Node.js program to demonstrate the// Timeout Class methods // Setting Timeout by setTimeout Methodvar Timeout = setTimeout(function alfa() { console.log("0.> Setting Timeout", 12);}); // Printing Timeout.hasRef methodconsole.log("1 =>", Timeout.hasRef());// returns true // Printing Timeout.ref before unrefconsole.log("2 =>", Timeout.ref());Timeout.unref()Timeout.ref()// Returns timer reference // Printing Timeout.refresh before unrefconsole.log("3 =>", Timeout.refresh());// Returns timer reference // Printing Timeout.unref methodconsole.log("4 =>", Timeout.unref());// Returns Timeout reference and sets// hasRef to false // Printing Timeout.hasRef before unrefconsole.log("5 =>", Timeout.hasRef());// Returns false // Clears setInterval TimeoutclearTimeout(Timeout);// Prints after clearing Timeout console.log("6 => Printing after clearing Timeout"); Run index.js file using the following command: node index.js Output: 1 => true 2 => Timeout { _idleTimeout: 1, _idlePrev: [TimersList], _idleNext: [TimersList], _idleStart: 52, _onTimeout: [Function: alfa], _timerArgs: undefined, _repeat: null, _destroyed: false, [Symbol(refed)]: true, [Symbol(asyncId)]: 2, [Symbol(triggerId)]: 1 } 3 => Timeout { _idleTimeout: 1, _idlePrev: [TimersList], _idleNext: [TimersList], _idleStart: 87, _onTimeout: [Function: alfa], _timerArgs: undefined, _repeat: null, _destroyed: false, [Symbol(refed)]: true, [Symbol(asyncId)]: 2, [Symbol(triggerId)]: 1 } 4 => Timeout { _idleTimeout: 1, _idlePrev: [TimersList], _idleNext: [TimersList], _idleStart: 87, _onTimeout: [Function: alfa], _timerArgs: undefined, _repeat: null, _destroyed: false, [Symbol(refed)]: false, [Symbol(asyncId)]: 2, [Symbol(triggerId)]: 1 } 5 => false 6 => Printing after clearing Timeout Reference: https://nodejs.org/api/timers.html#timers_class_timeout saurabh1990aror Node.js-Basics Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 38501, "s": 38473, "text": "\n18 Jun, 2021" }, { "code": null, "e": 38684, "s": 38501, "text": "The timer module is used for scheduling functions which will be called at some future period of time. It is a global API So, there is no need to import (require(“timers”)) to use it." }, { "code": null, "e": 39161, "s": 38684, "text": "Timeout Class has an object (setTimeout()/setInterval()) which is created internally to scheduled actions, and (clearTimeout()/clearInterval()) can be passed in order to cancel those scheduled actions. When a timeout is scheduled, By default, the event loop of Node.js will continue running until clearTimeout() is called. The setTimeout() method returns timeout objects that are used to control this default behavior, exports both timeout.ref() and timeout.unref() functions." }, { "code": null, "e": 39212, "s": 39161, "text": "The four Timeout Class objects are defined below: " }, { "code": null, "e": 39369, "s": 39212, "text": "1. timeout.hasRef(): (Added in v11.0.0) This timeout object keeps the event loop active until the returned ‘True’ if returned ‘false’ breaks the event loop." }, { "code": null, "e": 39377, "s": 39369, "text": "Syntax:" }, { "code": null, "e": 39394, "s": 39377, "text": "timeout.hasRef()" }, { "code": null, "e": 39486, "s": 39394, "text": "Return Value <boolean>: This timeout object keeps the event loop active if returned ‘True’." }, { "code": null, "e": 39712, "s": 39486, "text": "2. timeout.ref(): (Added in v9.7.0) When the Timeout is active and (timeout.ref()) called then it requests that the Node.js event loop did not exit so long. Anyway, calling this Method multiple times does not have any effect." }, { "code": null, "e": 39720, "s": 39712, "text": "Syntax:" }, { "code": null, "e": 39734, "s": 39720, "text": "timeout.ref()" }, { "code": null, "e": 39790, "s": 39734, "text": "Return Value <Timeout>: It returns a timeout reference." }, { "code": null, "e": 40183, "s": 39790, "text": "3. timeout.refresh() (Added in v10.2.0): This method refreshes the timer without allocating a new JavaScript object. The start time of the timer is set to the current time, and the timer is rescheduled from the previously specified duration to the current time by calling its callback. By using timeout.refresh() on a timer which already called its callback and then it reactivates the timer." }, { "code": null, "e": 40191, "s": 40183, "text": "Syntax:" }, { "code": null, "e": 40209, "s": 40191, "text": "timeout.refresh()" }, { "code": null, "e": 40268, "s": 40209, "text": "Return Value <Timeout>: It returns the timeout reference. " }, { "code": null, "e": 40593, "s": 40268, "text": "4. timeout.unref() (Added in v9.7.0) When the Timeout is active it does not require the Node.js event loop to remain active. The callback of the Timeout object is invoked after the process gets exit if any other activity keeps the event loop running. Anyway, calling this Method also multiple times does not have any effect." }, { "code": null, "e": 40601, "s": 40593, "text": "Syntax:" }, { "code": null, "e": 40617, "s": 40601, "text": "timeout.unref()" }, { "code": null, "e": 40675, "s": 40617, "text": "Return Value <Timeout>: It returns the timeout reference." }, { "code": null, "e": 40704, "s": 40675, "text": "Example: Filename: index.js " }, { "code": null, "e": 40715, "s": 40704, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// Timeout Class methods // Setting Timeout by setTimeout Methodvar Timeout = setTimeout(function alfa() { console.log(\"0.> Setting Timeout\", 12);}); // Printing Timeout.hasRef methodconsole.log(\"1 =>\", Timeout.hasRef());// returns true // Printing Timeout.ref before unrefconsole.log(\"2 =>\", Timeout.ref());Timeout.unref()Timeout.ref()// Returns timer reference // Printing Timeout.refresh before unrefconsole.log(\"3 =>\", Timeout.refresh());// Returns timer reference // Printing Timeout.unref methodconsole.log(\"4 =>\", Timeout.unref());// Returns Timeout reference and sets// hasRef to false // Printing Timeout.hasRef before unrefconsole.log(\"5 =>\", Timeout.hasRef());// Returns false // Clears setInterval TimeoutclearTimeout(Timeout);// Prints after clearing Timeout console.log(\"6 => Printing after clearing Timeout\");", "e": 41580, "s": 40715, "text": null }, { "code": null, "e": 41627, "s": 41580, "text": "Run index.js file using the following command:" }, { "code": null, "e": 41641, "s": 41627, "text": "node index.js" }, { "code": null, "e": 41649, "s": 41641, "text": "Output:" }, { "code": null, "e": 42475, "s": 41649, "text": "1 => true 2 => Timeout { _idleTimeout: 1, _idlePrev: [TimersList], _idleNext: [TimersList], _idleStart: 52, _onTimeout: [Function: alfa], _timerArgs: undefined, _repeat: null, _destroyed: false, [Symbol(refed)]: true, [Symbol(asyncId)]: 2, [Symbol(triggerId)]: 1 } 3 => Timeout { _idleTimeout: 1, _idlePrev: [TimersList], _idleNext: [TimersList], _idleStart: 87, _onTimeout: [Function: alfa], _timerArgs: undefined, _repeat: null, _destroyed: false, [Symbol(refed)]: true, [Symbol(asyncId)]: 2, [Symbol(triggerId)]: 1 } 4 => Timeout { _idleTimeout: 1, _idlePrev: [TimersList], _idleNext: [TimersList], _idleStart: 87, _onTimeout: [Function: alfa], _timerArgs: undefined, _repeat: null, _destroyed: false, [Symbol(refed)]: false, [Symbol(asyncId)]: 2, [Symbol(triggerId)]: 1 } 5 => false 6 => Printing after clearing Timeout " }, { "code": null, "e": 42542, "s": 42475, "text": "Reference: https://nodejs.org/api/timers.html#timers_class_timeout" }, { "code": null, "e": 42558, "s": 42542, "text": "saurabh1990aror" }, { "code": null, "e": 42573, "s": 42558, "text": "Node.js-Basics" }, { "code": null, "e": 42581, "s": 42573, "text": "Node.js" }, { "code": null, "e": 42598, "s": 42581, "text": "Web Technologies" }, { "code": null, "e": 42696, "s": 42598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42744, "s": 42696, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 42777, "s": 42744, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 42807, "s": 42777, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 42827, "s": 42807, "text": "How to update NPM ?" }, { "code": null, "e": 42881, "s": 42827, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 42921, "s": 42881, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 42966, "s": 42921, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 43009, "s": 42966, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 43071, "s": 43009, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Reverse the elements only at odd positions in the given Array - GeeksforGeeks
10 May, 2021 Given an array arr[] containing N integers, the task is to rearrange the array such that the odd indexed elements are in reverse order. Examples: Input: arr[] = {5, 7, 6, 2, 9, 18, 11, 15} Output: {5, 15, 6, 18, 9, 2, 11, 7} Explanation: The elements at even index [5, 6, 9, 11] are unchanged and elements at odd index are reversed from [7, 2, 18, 15] to [15, 18, 2, 7]. Input: arr[] = {1, 2, 3, 4, 5, 6} Output: {1, 6, 3, 4, 5, 2} Explanation: The elements at even index are unchanged and elements at odd index are reversed from [2, 4, 6] to [6, 4, 2]. Approach: To solve the problem mentioned above follow the steps given below: Push the elements of odd indexes of the given array into a stack data structure. Replace the current array elements at odd indexes with elements at top of the stack and keep popping until the stack is empty. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to reverse the// elements only at odd positions// in the given Array #include <bits/stdc++.h>using namespace std; // Function to display elementsvoid show(int arr[], int n){ cout << "{"; for (int i = 0; i < n - 1; i++) cout << arr[i] << ", "; cout << arr[n - 1] << "}";} // Function to flip elements// at odd indexesvoid flipHalf(int arr[], int n){ int c = 0; int dup = n; stack<int> st; // Pushing elements at odd indexes // of a array to a stack for (int i = 0; i < n; i++) { int x = arr[i]; if (c % 2 == 1) st.push(x); c++; } c = 0; // Replacing current elements at odd // indexes with element at top of stack for (int i = 0; i < n; i++) { int x = arr[i]; if (c % 2 == 1) { x = st.top(); st.pop(); } arr[i] = x; c++; }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); flipHalf(arr, n); show(arr, n); return 0;} // Java program to reverse the// elements only at odd positions// in the given arrayimport java.io.*;import java.util.*; class GFG { // Function to count the valley points// in the given character arraystatic void show(int arr[], int n){ System.out.print("{"); for(int i = 0; i < n - 1; i++) System.out.print(arr[i] + ", "); System.out.print(arr[n - 1] + "}"); } // Function to flip elements// at odd indexespublic static void flipHalf(int arr[], int n){ int c = 0; int dup = n; Stack<Integer> st = new Stack<>(); // Pushing elements at odd indexes // of a array to a stack for(int i = 0; i < n; i++) { int x = arr[i]; if (c % 2 == 1) { st.push(x); } c++; } c = 0; // Replacing current elements at odd // indexes with element at top of stack for(int i = 0; i < n; i++) { int x = arr[i]; if (c % 2 == 1) { x = st.peek(); st.pop(); } arr[i] = x; c++; }} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = arr.length; flipHalf(arr, n); show(arr, n);} } // This code is contributed by Aman Kumar 27 # Python3 program to reverse the# elements only at odd positions# in the given Array # Function to get top of the stackdef peek_stack(stack): if stack: return stack[-1] # Function to display elementsdef show(arr, n): print("{", end = " ") for i in range(0, n - 1): print(arr[i], ",", end = " ") print(arr[n - 1] , "}") # Function to flip elements# at odd indexesdef flipHalf(arr, n): c = 0 dup = n stack = [] # Pushing elements at odd indexes # of a array to a stack for i in range(0, n): x = arr[i] if c % 2 == 1: stack.append(x) c = c + 1 c = 0 # Replacing current elements at odd # indexes with element at top of stack for i in range(0, n): x = arr[i] if c % 2 == 1: x = peek_stack(stack) stack.pop() arr[i] = x c = c + 1 # Driver Codeif __name__ == "__main__": arr = [ 1, 2, 3, 4, 5, 6 ] n = len(arr) flipHalf(arr, n) show(arr, n) # This code is contributed by akhilsaini // C# program to reverse the// elements only at odd positions// in the given arrayusing System;using System.Collections.Generic; class GFG{ // Function to count the valley points// in the given character arraystatic void show(int []arr, int n){ Console.Write("{"); for(int i = 0; i < n - 1; i++) Console.Write(arr[i] + ", "); Console.Write(arr[n - 1] + "}"); } // Function to flip elements// at odd indexespublic static void flipHalf(int []arr, int n){ int c = 0; int dup = n; Stack<int> st = new Stack<int>(); // Pushing elements at odd indexes // of a array to a stack for(int i = 0; i < n; i++) { int x = arr[i]; if (c % 2 == 1) { st.Push(x); } c++; } c = 0; // Replacing current elements at odd // indexes with element at top of stack for(int i = 0; i < n; i++) { int x = arr[i]; if (c % 2 == 1) { x = st.Peek(); st.Pop(); } arr[i] = x; c++; }} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 4, 5, 6 }; int n = arr.Length; flipHalf(arr, n); show(arr, n);} } // This code is contributed by 29AjayKumar <script> // Javascript program to reverse the // elements only at odd positions // in the given Array // Function to display elements function show(arr, n) { document.write("{"); for (let i = 0; i < n - 1; i++) document.write(arr[i] + ", "); document.write(arr[n - 1] + "}"); } // Function to flip elements // at odd indexes function flipHalf(arr, n) { let c = 0; let dup = n; let st = []; // Pushing elements at odd indexes // of a array to a stack for (let i = 0; i < n; i++) { let x = arr[i]; if (c % 2 == 1) st.push(x); c++; } c = 0; // Replacing current elements at odd // indexes with element at top of stack for (let i = 0; i < n; i++) { let x = arr[i]; if (c % 2 == 1) { x = st[st.length - 1]; st.pop(); } arr[i] = x; c++; } } let arr = [ 1, 2, 3, 4, 5, 6 ]; let n = arr.length; flipHalf(arr, n); show(arr, n); </script> {1, 6, 3, 4, 5, 2} Time complexity: O(N)Auxiliary Space Complexity: O(N/2) 29AjayKumar akhilsaini vaibhavrabadiya117 Reverse Arrays Data Structures Stack Data Structures Arrays Stack Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) Introduction to Algorithms How to Start Learning DSA?
[ { "code": null, "e": 26041, "s": 26013, "text": "\n10 May, 2021" }, { "code": null, "e": 26177, "s": 26041, "text": "Given an array arr[] containing N integers, the task is to rearrange the array such that the odd indexed elements are in reverse order." }, { "code": null, "e": 26187, "s": 26177, "text": "Examples:" }, { "code": null, "e": 26412, "s": 26187, "text": "Input: arr[] = {5, 7, 6, 2, 9, 18, 11, 15} Output: {5, 15, 6, 18, 9, 2, 11, 7} Explanation: The elements at even index [5, 6, 9, 11] are unchanged and elements at odd index are reversed from [7, 2, 18, 15] to [15, 18, 2, 7]." }, { "code": null, "e": 26596, "s": 26412, "text": "Input: arr[] = {1, 2, 3, 4, 5, 6} Output: {1, 6, 3, 4, 5, 2} Explanation: The elements at even index are unchanged and elements at odd index are reversed from [2, 4, 6] to [6, 4, 2]. " }, { "code": null, "e": 26674, "s": 26596, "text": "Approach: To solve the problem mentioned above follow the steps given below: " }, { "code": null, "e": 26755, "s": 26674, "text": "Push the elements of odd indexes of the given array into a stack data structure." }, { "code": null, "e": 26884, "s": 26755, "text": "Replace the current array elements at odd indexes with elements at top of the stack and keep popping until the stack is empty. " }, { "code": null, "e": 26936, "s": 26884, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26940, "s": 26936, "text": "C++" }, { "code": null, "e": 26945, "s": 26940, "text": "Java" }, { "code": null, "e": 26953, "s": 26945, "text": "Python3" }, { "code": null, "e": 26956, "s": 26953, "text": "C#" }, { "code": null, "e": 26967, "s": 26956, "text": "Javascript" }, { "code": "// C++ program to reverse the// elements only at odd positions// in the given Array #include <bits/stdc++.h>using namespace std; // Function to display elementsvoid show(int arr[], int n){ cout << \"{\"; for (int i = 0; i < n - 1; i++) cout << arr[i] << \", \"; cout << arr[n - 1] << \"}\";} // Function to flip elements// at odd indexesvoid flipHalf(int arr[], int n){ int c = 0; int dup = n; stack<int> st; // Pushing elements at odd indexes // of a array to a stack for (int i = 0; i < n; i++) { int x = arr[i]; if (c % 2 == 1) st.push(x); c++; } c = 0; // Replacing current elements at odd // indexes with element at top of stack for (int i = 0; i < n; i++) { int x = arr[i]; if (c % 2 == 1) { x = st.top(); st.pop(); } arr[i] = x; c++; }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); flipHalf(arr, n); show(arr, n); return 0;}", "e": 28014, "s": 26967, "text": null }, { "code": "// Java program to reverse the// elements only at odd positions// in the given arrayimport java.io.*;import java.util.*; class GFG { // Function to count the valley points// in the given character arraystatic void show(int arr[], int n){ System.out.print(\"{\"); for(int i = 0; i < n - 1; i++) System.out.print(arr[i] + \", \"); System.out.print(arr[n - 1] + \"}\"); } // Function to flip elements// at odd indexespublic static void flipHalf(int arr[], int n){ int c = 0; int dup = n; Stack<Integer> st = new Stack<>(); // Pushing elements at odd indexes // of a array to a stack for(int i = 0; i < n; i++) { int x = arr[i]; if (c % 2 == 1) { st.push(x); } c++; } c = 0; // Replacing current elements at odd // indexes with element at top of stack for(int i = 0; i < n; i++) { int x = arr[i]; if (c % 2 == 1) { x = st.peek(); st.pop(); } arr[i] = x; c++; }} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = arr.length; flipHalf(arr, n); show(arr, n);} } // This code is contributed by Aman Kumar 27", "e": 29266, "s": 28014, "text": null }, { "code": "# Python3 program to reverse the# elements only at odd positions# in the given Array # Function to get top of the stackdef peek_stack(stack): if stack: return stack[-1] # Function to display elementsdef show(arr, n): print(\"{\", end = \" \") for i in range(0, n - 1): print(arr[i], \",\", end = \" \") print(arr[n - 1] , \"}\") # Function to flip elements# at odd indexesdef flipHalf(arr, n): c = 0 dup = n stack = [] # Pushing elements at odd indexes # of a array to a stack for i in range(0, n): x = arr[i] if c % 2 == 1: stack.append(x) c = c + 1 c = 0 # Replacing current elements at odd # indexes with element at top of stack for i in range(0, n): x = arr[i] if c % 2 == 1: x = peek_stack(stack) stack.pop() arr[i] = x c = c + 1 # Driver Codeif __name__ == \"__main__\": arr = [ 1, 2, 3, 4, 5, 6 ] n = len(arr) flipHalf(arr, n) show(arr, n) # This code is contributed by akhilsaini", "e": 30362, "s": 29266, "text": null }, { "code": "// C# program to reverse the// elements only at odd positions// in the given arrayusing System;using System.Collections.Generic; class GFG{ // Function to count the valley points// in the given character arraystatic void show(int []arr, int n){ Console.Write(\"{\"); for(int i = 0; i < n - 1; i++) Console.Write(arr[i] + \", \"); Console.Write(arr[n - 1] + \"}\"); } // Function to flip elements// at odd indexespublic static void flipHalf(int []arr, int n){ int c = 0; int dup = n; Stack<int> st = new Stack<int>(); // Pushing elements at odd indexes // of a array to a stack for(int i = 0; i < n; i++) { int x = arr[i]; if (c % 2 == 1) { st.Push(x); } c++; } c = 0; // Replacing current elements at odd // indexes with element at top of stack for(int i = 0; i < n; i++) { int x = arr[i]; if (c % 2 == 1) { x = st.Peek(); st.Pop(); } arr[i] = x; c++; }} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 4, 5, 6 }; int n = arr.Length; flipHalf(arr, n); show(arr, n);} } // This code is contributed by 29AjayKumar", "e": 31630, "s": 30362, "text": null }, { "code": "<script> // Javascript program to reverse the // elements only at odd positions // in the given Array // Function to display elements function show(arr, n) { document.write(\"{\"); for (let i = 0; i < n - 1; i++) document.write(arr[i] + \", \"); document.write(arr[n - 1] + \"}\"); } // Function to flip elements // at odd indexes function flipHalf(arr, n) { let c = 0; let dup = n; let st = []; // Pushing elements at odd indexes // of a array to a stack for (let i = 0; i < n; i++) { let x = arr[i]; if (c % 2 == 1) st.push(x); c++; } c = 0; // Replacing current elements at odd // indexes with element at top of stack for (let i = 0; i < n; i++) { let x = arr[i]; if (c % 2 == 1) { x = st[st.length - 1]; st.pop(); } arr[i] = x; c++; } } let arr = [ 1, 2, 3, 4, 5, 6 ]; let n = arr.length; flipHalf(arr, n); show(arr, n); </script>", "e": 32781, "s": 31630, "text": null }, { "code": null, "e": 32800, "s": 32781, "text": "{1, 6, 3, 4, 5, 2}" }, { "code": null, "e": 32860, "s": 32802, "text": "Time complexity: O(N)Auxiliary Space Complexity: O(N/2) " }, { "code": null, "e": 32872, "s": 32860, "text": "29AjayKumar" }, { "code": null, "e": 32883, "s": 32872, "text": "akhilsaini" }, { "code": null, "e": 32902, "s": 32883, "text": "vaibhavrabadiya117" }, { "code": null, "e": 32910, "s": 32902, "text": "Reverse" }, { "code": null, "e": 32917, "s": 32910, "text": "Arrays" }, { "code": null, "e": 32933, "s": 32917, "text": "Data Structures" }, { "code": null, "e": 32939, "s": 32933, "text": "Stack" }, { "code": null, "e": 32955, "s": 32939, "text": "Data Structures" }, { "code": null, "e": 32962, "s": 32955, "text": "Arrays" }, { "code": null, "e": 32968, "s": 32962, "text": "Stack" }, { "code": null, "e": 32976, "s": 32968, "text": "Reverse" }, { "code": null, "e": 33074, "s": 32976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33101, "s": 33074, "text": "Count pairs with given sum" }, { "code": null, "e": 33132, "s": 33101, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 33157, "s": 33132, "text": "Window Sliding Technique" }, { "code": null, "e": 33195, "s": 33157, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 33216, "s": 33195, "text": "Next Greater Element" }, { "code": null, "e": 33265, "s": 33216, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 33290, "s": 33265, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33346, "s": 33290, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 33373, "s": 33346, "text": "Introduction to Algorithms" } ]
Difference between map, applymap and apply methods in Pandas - GeeksforGeeks
13 Dec, 2018 Pandas library is extensively used for data manipulation and analysis. map(), applymap() and apply() methods are methods of Pandas library. applymap() method only works on a pandas dataframe where function is applied on every element individually. apply() method can be applied both to series and dataframes where function can be applied both series and individual elements based on the type of function provided. map() method only works on a pandas series where type of operation to be applied depends on argument passed as a function, dictionary or a list. Note that the type of Output totally depends on the type of function used as an argument with the given method. Pandas apply() method:This method which can be used on both on a pandas dataframe and series. The function passed as an argument typically works on rows/columns. Code below illustrates how apply() method works on Pandas dataframe. # Importing pandas library with an alias pdimport pandas as pd # Dataframe generationgfg_string = 'geeksforgeeks'gfg_list = 5 * [pd.Series(list(gfg_string))] gfg_df = pd.DataFrame(data = gfg_list)print("Original dataframe:\n" + \ gfg_df.to_string(index = False, header = False), end = '\n\n') # Using apply method for sorting # rows of characters present in # the original dataframenew_gfg_df = gfg_df.apply(lambda x:x.sort_values(), axis = 1) print("Transformed dataframe:\n" + \ new_gfg_df.to_string(index = False, header = False), end = '\n\n') Output: Below Code illustrates how apply() method on Pandas series: # Importing pandas library with an alias pdimport pandas as pd # Series generationgfg_string = 'geeksforgeeks'gfg_series = pd.Series(list(gfg_string))print("Original series\n" + \ gfg_series.to_string(index = False, header = False), end = '\n\n') # Using apply method for converting characters# present in the original seriesnew_gfg_series = gfg_series.apply(str.upper)print("Transformed series:\n" + \ new_gfg_series.to_string(index = False, header = False), end = '\n\n') Output: Pandas applymap() method :This method can be used on a pandas dataframe. The function passed as an argument typically works on elements of the dataframe applymap() is typically used for elementwise operations. Code below illustrates how applymap method works on pandas dataframe: # Importing pandas library with an alias pdimport pandas as pd # DataFrame generationgfg_string = 'geeksforgeeks'gfg_list = 5 * [pd.Series(list(gfg_string))]gfg_df = pd.DataFrame(data = gfg_list) print("Original dataframe:\n" + \ gfg_df.to_string(index = False, header = False), end = '\n\n') # Using applymap method for transforming # characters into uppercase characters # present in the original dataframenew_gfg_df = gfg_df.applymap(str.upper)print("Transformed dataframe:\n" + \ new_gfg_df.to_string(index = False, header = False), end = '\n\n') Output: Pandas map() method :This method is used on series function, list and dictionary passed as an argument. This method is generally used to map values from two series having one column same. Code below illustrates how map method works on pandas series: # Importing pandas library with an alias pdimport pandas as pd # Series generationgfg_string = 'geeksforgeeks'gfg_series = pd.Series(list(gfg_string))print("Original series\n" + \ gfg_series.to_string(index = False, header = False), end = '\n\n') # Using apply method for converting characters# present in the original seriesnew_gfg_series = gfg_series.map(str.upper)print("Transformed series:\n" + \ new_gfg_series.to_string(index = False, header = False), end = '\n\n') Output: pandas-dataframe-program pandas-series-program Picked Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Convert integer to string in Python
[ { "code": null, "e": 25411, "s": 25383, "text": "\n13 Dec, 2018" }, { "code": null, "e": 25551, "s": 25411, "text": "Pandas library is extensively used for data manipulation and analysis. map(), applymap() and apply() methods are methods of Pandas library." }, { "code": null, "e": 25659, "s": 25551, "text": "applymap() method only works on a pandas dataframe where function is applied on every element individually." }, { "code": null, "e": 25825, "s": 25659, "text": "apply() method can be applied both to series and dataframes where function can be applied both series and individual elements based on the type of function provided." }, { "code": null, "e": 25970, "s": 25825, "text": "map() method only works on a pandas series where type of operation to be applied depends on argument passed as a function, dictionary or a list." }, { "code": null, "e": 26082, "s": 25970, "text": "Note that the type of Output totally depends on the type of function used as an argument with the given method." }, { "code": null, "e": 26313, "s": 26082, "text": "Pandas apply() method:This method which can be used on both on a pandas dataframe and series. The function passed as an argument typically works on rows/columns. Code below illustrates how apply() method works on Pandas dataframe." }, { "code": "# Importing pandas library with an alias pdimport pandas as pd # Dataframe generationgfg_string = 'geeksforgeeks'gfg_list = 5 * [pd.Series(list(gfg_string))] gfg_df = pd.DataFrame(data = gfg_list)print(\"Original dataframe:\\n\" + \\ gfg_df.to_string(index = False, header = False), end = '\\n\\n') # Using apply method for sorting # rows of characters present in # the original dataframenew_gfg_df = gfg_df.apply(lambda x:x.sort_values(), axis = 1) print(\"Transformed dataframe:\\n\" + \\ new_gfg_df.to_string(index = False, header = False), end = '\\n\\n')", "e": 26895, "s": 26313, "text": null }, { "code": null, "e": 26903, "s": 26895, "text": "Output:" }, { "code": null, "e": 26963, "s": 26903, "text": "Below Code illustrates how apply() method on Pandas series:" }, { "code": "# Importing pandas library with an alias pdimport pandas as pd # Series generationgfg_string = 'geeksforgeeks'gfg_series = pd.Series(list(gfg_string))print(\"Original series\\n\" + \\ gfg_series.to_string(index = False, header = False), end = '\\n\\n') # Using apply method for converting characters# present in the original seriesnew_gfg_series = gfg_series.apply(str.upper)print(\"Transformed series:\\n\" + \\ new_gfg_series.to_string(index = False, header = False), end = '\\n\\n')", "e": 27479, "s": 26963, "text": null }, { "code": null, "e": 27487, "s": 27479, "text": "Output:" }, { "code": null, "e": 27768, "s": 27487, "text": " Pandas applymap() method :This method can be used on a pandas dataframe. The function passed as an argument typically works on elements of the dataframe applymap() is typically used for elementwise operations. Code below illustrates how applymap method works on pandas dataframe:" }, { "code": "# Importing pandas library with an alias pdimport pandas as pd # DataFrame generationgfg_string = 'geeksforgeeks'gfg_list = 5 * [pd.Series(list(gfg_string))]gfg_df = pd.DataFrame(data = gfg_list) print(\"Original dataframe:\\n\" + \\ gfg_df.to_string(index = False, header = False), end = '\\n\\n') # Using applymap method for transforming # characters into uppercase characters # present in the original dataframenew_gfg_df = gfg_df.applymap(str.upper)print(\"Transformed dataframe:\\n\" + \\ new_gfg_df.to_string(index = False, header = False), end = '\\n\\n')", "e": 28354, "s": 27768, "text": null }, { "code": null, "e": 28362, "s": 28354, "text": "Output:" }, { "code": null, "e": 28612, "s": 28362, "text": "Pandas map() method :This method is used on series function, list and dictionary passed as an argument. This method is generally used to map values from two series having one column same. Code below illustrates how map method works on pandas series:" }, { "code": "# Importing pandas library with an alias pdimport pandas as pd # Series generationgfg_string = 'geeksforgeeks'gfg_series = pd.Series(list(gfg_string))print(\"Original series\\n\" + \\ gfg_series.to_string(index = False, header = False), end = '\\n\\n') # Using apply method for converting characters# present in the original seriesnew_gfg_series = gfg_series.map(str.upper)print(\"Transformed series:\\n\" + \\ new_gfg_series.to_string(index = False, header = False), end = '\\n\\n')", "e": 29126, "s": 28612, "text": null }, { "code": null, "e": 29134, "s": 29126, "text": "Output:" }, { "code": null, "e": 29159, "s": 29134, "text": "pandas-dataframe-program" }, { "code": null, "e": 29181, "s": 29159, "text": "pandas-series-program" }, { "code": null, "e": 29188, "s": 29181, "text": "Picked" }, { "code": null, "e": 29202, "s": 29188, "text": "Python-pandas" }, { "code": null, "e": 29209, "s": 29202, "text": "Python" }, { "code": null, "e": 29307, "s": 29209, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29325, "s": 29307, "text": "Python Dictionary" }, { "code": null, "e": 29360, "s": 29325, "text": "Read a file line by line in Python" }, { "code": null, "e": 29392, "s": 29360, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29414, "s": 29392, "text": "Enumerate() in Python" }, { "code": null, "e": 29456, "s": 29414, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29486, "s": 29456, "text": "Iterate over a list in Python" }, { "code": null, "e": 29512, "s": 29486, "text": "Python String | replace()" }, { "code": null, "e": 29541, "s": 29512, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29585, "s": 29541, "text": "Reading and Writing to text files in Python" } ]
Applications of Pointers in C/C++ - GeeksforGeeks
10 Jul, 2021 Prerequisite : Pointers in C/C++, Memory Layout of C Programs. To pass arguments by reference. Passing by reference serves two purposes (i) To modify variable of function in other. Example to swap two variables; C C++ // C program to demonstrate that we can change// local values of one function in another using pointers. #include <stdio.h> void swap(int* x, int* y){ int temp = *x; *x = *y; *y = temp;} int main(){ int x = 10, y = 20; swap(&x, &y); printf("%d %d\n", x, y); return 0;} // C++ program to demonstrate that we can change// local values of one function in another using// pointers.#include <iostream>using namespace std; void swap(int* x, int* y){ int temp = *x; *x = *y; *y = temp;} int main(){ int x = 10, y = 20; swap(&x, &y); cout << x << " " << y << endl; return 0;} Output : 20 10 (ii) For efficiency purpose. Example passing large structure without reference would create a copy of the structure (hence wastage of space). Note : The above two can also be achieved through References in C++. For accessing array elements. Compiler internally uses pointers to access array elements. C C++ // C program to demonstrate that compiler// internally uses pointer arithmetic to access// array elements. #include <stdio.h> int main(){ int arr[] = { 100, 200, 300, 400 }; // Compiler converts below to *(arr + 2). printf("%d ", arr[2]); // So below also works. printf("%d\n", *(arr + 2)); return 0;} // C++ program to demonstrate that compiler// internally uses pointer arithmetic to access// array elements.#include <iostream>using namespace std; int main(){ int arr[] = { 100, 200, 300, 400 }; // Compiler converts below to *(arr + 2). cout << arr[2] << " "; // So below also works. cout << *(arr + 2) << " "; return 0;} Output : 300 300 To return multiple values. Example returning square and square root of numbers. C C++ // C program to demonstrate that using a pointer// we can return multiple values. #include <math.h>#include <stdio.h> void fun(int n, int* square, double* sq_root){ *square = n * n; *sq_root = sqrt(n);} int main(){ int n = 100; int sq; double sq_root; fun(n, &sq, &sq_root); printf("%d %f\n", sq, sq_root); return 0;} // C++ program to demonstrate that using a pointer// we can return multiple values.#include <bits/stdc++.h>using namespace std; void fun(int n, int* square, double* sq_root){ *square = n * n; *sq_root = sqrt(n);} int main(){ int n = 100; int* sq = new int; double* sq_root = new double; fun(n, sq, sq_root); cout << *sq << " " << *sq_root; return 0;} Output : 10000 10 Dynamic memory allocation : We can use pointers to dynamically allocate memory. The advantage of dynamically allocated memory is, it is not deleted until we explicitly delete it. C C++ // C program to dynamically allocate an// array of given size. #include <stdio.h>#include <stdlib.h>int* createArr(int n){ int* arr = (int*)(malloc(n * sizeof(int))); return arr;} int main(){ int* pt = createArr(10); return 0;} // C++ program to dynamically allocate an// array of given size.#include <iostream>using namespace std; int* createArr(int n){ return new int[n];} int main(){ int* pt = createArr(10); return 0;} To implement data structures. Example linked list, tree, etc. We cannot use C++ references to implement these data structures because references are fixed to a location (For example, we can not traverse a linked list using references) To do system level programming where memory addresses are useful. For example shared memory used by multiple threads. For more examples, see IPC through shared memory, Socket Programming in C/C++, etc RishabhPrabhu SimarpreetSinghAneja sarthak8858 vijendraniyer C-Pointers cpp-pointer C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Converting Strings to Numbers in C/C++ Core Dump (Segmentation fault) in C/C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Operator Overloading in C++ Templates in C++ with Examples
[ { "code": null, "e": 25673, "s": 25645, "text": "\n10 Jul, 2021" }, { "code": null, "e": 25738, "s": 25673, "text": "Prerequisite : Pointers in C/C++, Memory Layout of C Programs. " }, { "code": null, "e": 25811, "s": 25738, "text": "To pass arguments by reference. Passing by reference serves two purposes" }, { "code": null, "e": 25888, "s": 25811, "text": "(i) To modify variable of function in other. Example to swap two variables; " }, { "code": null, "e": 25890, "s": 25888, "text": "C" }, { "code": null, "e": 25894, "s": 25890, "text": "C++" }, { "code": "// C program to demonstrate that we can change// local values of one function in another using pointers. #include <stdio.h> void swap(int* x, int* y){ int temp = *x; *x = *y; *y = temp;} int main(){ int x = 10, y = 20; swap(&x, &y); printf(\"%d %d\\n\", x, y); return 0;}", "e": 26184, "s": 25894, "text": null }, { "code": "// C++ program to demonstrate that we can change// local values of one function in another using// pointers.#include <iostream>using namespace std; void swap(int* x, int* y){ int temp = *x; *x = *y; *y = temp;} int main(){ int x = 10, y = 20; swap(&x, &y); cout << x << \" \" << y << endl; return 0;}", "e": 26504, "s": 26184, "text": null }, { "code": null, "e": 26513, "s": 26504, "text": "Output :" }, { "code": null, "e": 26519, "s": 26513, "text": "20 10" }, { "code": null, "e": 26732, "s": 26519, "text": "(ii) For efficiency purpose. Example passing large structure without reference would create a copy of the structure (hence wastage of space). Note : The above two can also be achieved through References in C++. " }, { "code": null, "e": 26824, "s": 26732, "text": "For accessing array elements. Compiler internally uses pointers to access array elements. " }, { "code": null, "e": 26826, "s": 26824, "text": "C" }, { "code": null, "e": 26830, "s": 26826, "text": "C++" }, { "code": "// C program to demonstrate that compiler// internally uses pointer arithmetic to access// array elements. #include <stdio.h> int main(){ int arr[] = { 100, 200, 300, 400 }; // Compiler converts below to *(arr + 2). printf(\"%d \", arr[2]); // So below also works. printf(\"%d\\n\", *(arr + 2)); return 0;}", "e": 27153, "s": 26830, "text": null }, { "code": "// C++ program to demonstrate that compiler// internally uses pointer arithmetic to access// array elements.#include <iostream>using namespace std; int main(){ int arr[] = { 100, 200, 300, 400 }; // Compiler converts below to *(arr + 2). cout << arr[2] << \" \"; // So below also works. cout << *(arr + 2) << \" \"; return 0;}", "e": 27497, "s": 27153, "text": null }, { "code": null, "e": 27506, "s": 27497, "text": "Output :" }, { "code": null, "e": 27514, "s": 27506, "text": "300 300" }, { "code": null, "e": 27597, "s": 27516, "text": "To return multiple values. Example returning square and square root of numbers. " }, { "code": null, "e": 27599, "s": 27597, "text": "C" }, { "code": null, "e": 27603, "s": 27599, "text": "C++" }, { "code": "// C program to demonstrate that using a pointer// we can return multiple values. #include <math.h>#include <stdio.h> void fun(int n, int* square, double* sq_root){ *square = n * n; *sq_root = sqrt(n);} int main(){ int n = 100; int sq; double sq_root; fun(n, &sq, &sq_root); printf(\"%d %f\\n\", sq, sq_root); return 0;}", "e": 27947, "s": 27603, "text": null }, { "code": "// C++ program to demonstrate that using a pointer// we can return multiple values.#include <bits/stdc++.h>using namespace std; void fun(int n, int* square, double* sq_root){ *square = n * n; *sq_root = sqrt(n);} int main(){ int n = 100; int* sq = new int; double* sq_root = new double; fun(n, sq, sq_root); cout << *sq << \" \" << *sq_root; return 0;}", "e": 28323, "s": 27947, "text": null }, { "code": null, "e": 28332, "s": 28323, "text": "Output :" }, { "code": null, "e": 28341, "s": 28332, "text": "10000 10" }, { "code": null, "e": 28523, "s": 28343, "text": "Dynamic memory allocation : We can use pointers to dynamically allocate memory. The advantage of dynamically allocated memory is, it is not deleted until we explicitly delete it. " }, { "code": null, "e": 28525, "s": 28523, "text": "C" }, { "code": null, "e": 28529, "s": 28525, "text": "C++" }, { "code": "// C program to dynamically allocate an// array of given size. #include <stdio.h>#include <stdlib.h>int* createArr(int n){ int* arr = (int*)(malloc(n * sizeof(int))); return arr;} int main(){ int* pt = createArr(10); return 0;}", "e": 28769, "s": 28529, "text": null }, { "code": "// C++ program to dynamically allocate an// array of given size.#include <iostream>using namespace std; int* createArr(int n){ return new int[n];} int main(){ int* pt = createArr(10); return 0;}", "e": 28973, "s": 28769, "text": null }, { "code": null, "e": 29210, "s": 28975, "text": "To implement data structures. Example linked list, tree, etc. We cannot use C++ references to implement these data structures because references are fixed to a location (For example, we can not traverse a linked list using references)" }, { "code": null, "e": 29411, "s": 29210, "text": "To do system level programming where memory addresses are useful. For example shared memory used by multiple threads. For more examples, see IPC through shared memory, Socket Programming in C/C++, etc" }, { "code": null, "e": 29427, "s": 29413, "text": "RishabhPrabhu" }, { "code": null, "e": 29448, "s": 29427, "text": "SimarpreetSinghAneja" }, { "code": null, "e": 29460, "s": 29448, "text": "sarthak8858" }, { "code": null, "e": 29474, "s": 29460, "text": "vijendraniyer" }, { "code": null, "e": 29485, "s": 29474, "text": "C-Pointers" }, { "code": null, "e": 29497, "s": 29485, "text": "cpp-pointer" }, { "code": null, "e": 29508, "s": 29497, "text": "C Language" }, { "code": null, "e": 29512, "s": 29508, "text": "C++" }, { "code": null, "e": 29516, "s": 29512, "text": "CPP" }, { "code": null, "e": 29614, "s": 29516, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29631, "s": 29614, "text": "Substring in C++" }, { "code": null, "e": 29666, "s": 29631, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 29712, "s": 29666, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 29751, "s": 29712, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 29791, "s": 29751, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 29809, "s": 29791, "text": "Vector in C++ STL" }, { "code": null, "e": 29855, "s": 29809, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 29898, "s": 29855, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 29926, "s": 29898, "text": "Operator Overloading in C++" } ]
How to create bullets using <li> elements ? - GeeksforGeeks
08 Jun, 2020 We know that, whether it may be an ordered list or unordered list they come along with a numbering. It may be: Bullets Squares Decimal Roman etc. There are numerous options that we can use, but the question comes what property does this depend upon? In CSS, for tags like <ol> and <ul>, there is a property called list-style-type. Approach: The list-style-type property determines whether bullets, squares, or decimal etc come with li elements. To change or understand how it impacts the HTML is to use CSS targeting the selector <ul> or <ol>. Syntax: CSS targeting <li> elements: ol { list-style-type: decimal } ul { list-style-type: disc } Let’s understand with examples: The default list-style-type for ordered list is Decimal and unordered is Disc. As evident from the above code.Example:<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width"> <title>Lists</title></head><body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html>Output:With the default styling, <ol> tag comes with Decimal and <ul> comes with Disc/Bullets as defined in CSS above.From here we understand how bullets come to <li> elements, but we can also change them to something else as well.Now we know from where bullets come in list elements, we can change it accordingly. Let’s set it to Roman Numerals in Ordered List and Square in Unordered List.Example:<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width"> <title>Lists</title> <style> ol{ list-style-type: upper-roman } ul{ list-style-type: square }</style></head> <body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html>Output:Here we can clearly see bullets/disc are replaced with square and decimals with Roman Numerals. The default list-style-type for ordered list is Decimal and unordered is Disc. As evident from the above code.Example:<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width"> <title>Lists</title></head><body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html>Output:With the default styling, <ol> tag comes with Decimal and <ul> comes with Disc/Bullets as defined in CSS above.From here we understand how bullets come to <li> elements, but we can also change them to something else as well. Example:<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width"> <title>Lists</title></head><body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html> <!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width"> <title>Lists</title></head><body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html> Output:With the default styling, <ol> tag comes with Decimal and <ul> comes with Disc/Bullets as defined in CSS above.From here we understand how bullets come to <li> elements, but we can also change them to something else as well. With the default styling, <ol> tag comes with Decimal and <ul> comes with Disc/Bullets as defined in CSS above. From here we understand how bullets come to <li> elements, but we can also change them to something else as well. Now we know from where bullets come in list elements, we can change it accordingly. Let’s set it to Roman Numerals in Ordered List and Square in Unordered List.Example:<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width"> <title>Lists</title> <style> ol{ list-style-type: upper-roman } ul{ list-style-type: square }</style></head> <body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html>Output:Here we can clearly see bullets/disc are replaced with square and decimals with Roman Numerals. Example:<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width"> <title>Lists</title> <style> ol{ list-style-type: upper-roman } ul{ list-style-type: square }</style></head> <body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html> <!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width"> <title>Lists</title> <style> ol{ list-style-type: upper-roman } ul{ list-style-type: square }</style></head> <body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html> Output:Here we can clearly see bullets/disc are replaced with square and decimals with Roman Numerals. Here we can clearly see bullets/disc are replaced with square and decimals with Roman Numerals. Complete Code: <!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content ="width=device-width"> <title>Lists</title></head> <body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul> <p>Ordered List:</p> <ol style="list-style-type: upper-roman;"> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul style="list-style-type: square;"> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html> Output: Using both Default and Custom Inline CSS Similarly, we can change the list-style-type to numerous types: upper-alphalower-alphanonecircleand many more.... upper-alpha lower-alpha none circleand many more.... and many more.... Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc Picked CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26647, "s": 26619, "text": "\n08 Jun, 2020" }, { "code": null, "e": 26747, "s": 26647, "text": "We know that, whether it may be an ordered list or unordered list they come along with a numbering." }, { "code": null, "e": 26758, "s": 26747, "text": "It may be:" }, { "code": null, "e": 26766, "s": 26758, "text": "Bullets" }, { "code": null, "e": 26774, "s": 26766, "text": "Squares" }, { "code": null, "e": 26782, "s": 26774, "text": "Decimal" }, { "code": null, "e": 26793, "s": 26782, "text": "Roman etc." }, { "code": null, "e": 26897, "s": 26793, "text": "There are numerous options that we can use, but the question comes what property does this depend upon?" }, { "code": null, "e": 26978, "s": 26897, "text": "In CSS, for tags like <ol> and <ul>, there is a property called list-style-type." }, { "code": null, "e": 27191, "s": 26978, "text": "Approach: The list-style-type property determines whether bullets, squares, or decimal etc come with li elements. To change or understand how it impacts the HTML is to use CSS targeting the selector <ul> or <ol>." }, { "code": null, "e": 27228, "s": 27191, "text": "Syntax: CSS targeting <li> elements:" }, { "code": null, "e": 27302, "s": 27228, "text": "ol {\n list-style-type: decimal\n}\nul {\n list-style-type: disc\n} \n" }, { "code": null, "e": 27334, "s": 27302, "text": "Let’s understand with examples:" }, { "code": null, "e": 28776, "s": 27334, "text": "The default list-style-type for ordered list is Decimal and unordered is Disc. As evident from the above code.Example:<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width\"> <title>Lists</title></head><body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html>Output:With the default styling, <ol> tag comes with Decimal and <ul> comes with Disc/Bullets as defined in CSS above.From here we understand how bullets come to <li> elements, but we can also change them to something else as well.Now we know from where bullets come in list elements, we can change it accordingly. Let’s set it to Roman Numerals in Ordered List and Square in Unordered List.Example:<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width\"> <title>Lists</title> <style> ol{ list-style-type: upper-roman } ul{ list-style-type: square }</style></head> <body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html>Output:Here we can clearly see bullets/disc are replaced with square and decimals with Roman Numerals." }, { "code": null, "e": 29484, "s": 28776, "text": "The default list-style-type for ordered list is Decimal and unordered is Disc. As evident from the above code.Example:<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width\"> <title>Lists</title></head><body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html>Output:With the default styling, <ol> tag comes with Decimal and <ul> comes with Disc/Bullets as defined in CSS above.From here we understand how bullets come to <li> elements, but we can also change them to something else as well." }, { "code": null, "e": 29851, "s": 29484, "text": "Example:<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width\"> <title>Lists</title></head><body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html>" }, { "code": "<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width\"> <title>Lists</title></head><body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html>", "e": 30210, "s": 29851, "text": null }, { "code": null, "e": 30442, "s": 30210, "text": "Output:With the default styling, <ol> tag comes with Decimal and <ul> comes with Disc/Bullets as defined in CSS above.From here we understand how bullets come to <li> elements, but we can also change them to something else as well." }, { "code": null, "e": 30554, "s": 30442, "text": "With the default styling, <ol> tag comes with Decimal and <ul> comes with Disc/Bullets as defined in CSS above." }, { "code": null, "e": 30668, "s": 30554, "text": "From here we understand how bullets come to <li> elements, but we can also change them to something else as well." }, { "code": null, "e": 31403, "s": 30668, "text": "Now we know from where bullets come in list elements, we can change it accordingly. Let’s set it to Roman Numerals in Ordered List and Square in Unordered List.Example:<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width\"> <title>Lists</title> <style> ol{ list-style-type: upper-roman } ul{ list-style-type: square }</style></head> <body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html>Output:Here we can clearly see bullets/disc are replaced with square and decimals with Roman Numerals." }, { "code": null, "e": 31876, "s": 31403, "text": "Example:<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width\"> <title>Lists</title> <style> ol{ list-style-type: upper-roman } ul{ list-style-type: square }</style></head> <body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html>" }, { "code": "<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width\"> <title>Lists</title> <style> ol{ list-style-type: upper-roman } ul{ list-style-type: square }</style></head> <body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html>", "e": 32341, "s": 31876, "text": null }, { "code": null, "e": 32444, "s": 32341, "text": "Output:Here we can clearly see bullets/disc are replaced with square and decimals with Roman Numerals." }, { "code": null, "e": 32540, "s": 32444, "text": "Here we can clearly see bullets/disc are replaced with square and decimals with Roman Numerals." }, { "code": null, "e": 32555, "s": 32540, "text": "Complete Code:" }, { "code": "<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content =\"width=device-width\"> <title>Lists</title></head> <body> <p>Ordered List:</p> <ol> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul> <p>Ordered List:</p> <ol style=\"list-style-type: upper-roman;\"> <li>Eggs</li> <li>Bacon</li> <li>Leeks</li> </ol> <p>Unordered List:</p> <ul style=\"list-style-type: square;\"> <li>Coriander</li> <li>Basil</li> <li>Onion</li> </ul></body></html> ", "e": 33217, "s": 32555, "text": null }, { "code": null, "e": 33225, "s": 33217, "text": "Output:" }, { "code": null, "e": 33266, "s": 33225, "text": "Using both Default and Custom Inline CSS" }, { "code": null, "e": 33330, "s": 33266, "text": "Similarly, we can change the list-style-type to numerous types:" }, { "code": null, "e": 33380, "s": 33330, "text": "upper-alphalower-alphanonecircleand many more...." }, { "code": null, "e": 33392, "s": 33380, "text": "upper-alpha" }, { "code": null, "e": 33404, "s": 33392, "text": "lower-alpha" }, { "code": null, "e": 33409, "s": 33404, "text": "none" }, { "code": null, "e": 33433, "s": 33409, "text": "circleand many more...." }, { "code": null, "e": 33451, "s": 33433, "text": "and many more...." }, { "code": null, "e": 33588, "s": 33451, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 33597, "s": 33588, "text": "CSS-Misc" }, { "code": null, "e": 33607, "s": 33597, "text": "HTML-Misc" }, { "code": null, "e": 33614, "s": 33607, "text": "Picked" }, { "code": null, "e": 33618, "s": 33614, "text": "CSS" }, { "code": null, "e": 33623, "s": 33618, "text": "HTML" }, { "code": null, "e": 33640, "s": 33623, "text": "Web Technologies" }, { "code": null, "e": 33667, "s": 33640, "text": "Web technologies Questions" }, { "code": null, "e": 33672, "s": 33667, "text": "HTML" }, { "code": null, "e": 33770, "s": 33672, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33809, "s": 33770, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 33846, "s": 33809, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 33875, "s": 33846, "text": "Form validation using jQuery" }, { "code": null, "e": 33917, "s": 33875, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 33952, "s": 33917, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 34012, "s": 33952, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 34065, "s": 34012, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 34126, "s": 34065, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 34150, "s": 34126, "text": "REST API (Introduction)" } ]
Python object() method - GeeksforGeeks
22 Sep, 2021 Python object() function returns the empty object, and the Python object takes no parameters. In python, each variable to which we assign a value/container is treated as an object. Object in itself is a class. Let’s discuss the properties and demonstration of how this class can be utilized for day-day programming. Syntax : object() Parameters : None Returns : Object of featureless class. Acts as base for all object Python3 # Python 3 code to demonstrate# working of object() # declaring the object of class objectobj = object() # printing its typeprint("The type of object class object is : ")print(type(obj)) # printing its attributesprint("The attributes of its class are : ")print(dir(obj)) Output: The type of object class object is : The attributes of its class are : [‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__le__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’] Objects of object class cannot add new attributes to it. These objects are uniquely made and do not equate to one other, i.e don’t return true once compared. the object acts as a base class for all the custom objects that we make. Python3 # Python 3 code to demonstrate# properties of object() # declaring the objects of class objectobj1 = object()obj2 = object() # checking for object equalityprint("Is obj1 equal to obj2 : " + str(obj1 == obj2)) # trying to add attribute to objectobj1.name = "GeeksforGeeks" Output: Is obj1 equal to obj2 : False Exception: Traceback (most recent call last): File "/home/46b67ee266145958c7cc22d9ee0ae759.py", line 12, in obj1.name = "GeeksforGeeks" AttributeError: 'object' object has no attribute 'name' kumar_satyam Python-Built-in-functions python-object Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25509, "s": 25481, "text": "\n22 Sep, 2021" }, { "code": null, "e": 25603, "s": 25509, "text": "Python object() function returns the empty object, and the Python object takes no parameters." }, { "code": null, "e": 25825, "s": 25603, "text": "In python, each variable to which we assign a value/container is treated as an object. Object in itself is a class. Let’s discuss the properties and demonstration of how this class can be utilized for day-day programming." }, { "code": null, "e": 25843, "s": 25825, "text": "Syntax : object()" }, { "code": null, "e": 25862, "s": 25843, "text": "Parameters : None" }, { "code": null, "e": 25929, "s": 25862, "text": "Returns : Object of featureless class. Acts as base for all object" }, { "code": null, "e": 25937, "s": 25929, "text": "Python3" }, { "code": "# Python 3 code to demonstrate# working of object() # declaring the object of class objectobj = object() # printing its typeprint(\"The type of object class object is : \")print(type(obj)) # printing its attributesprint(\"The attributes of its class are : \")print(dir(obj))", "e": 26208, "s": 25937, "text": null }, { "code": null, "e": 26217, "s": 26208, "text": "Output: " }, { "code": null, "e": 26572, "s": 26217, "text": "The type of object class object is : The attributes of its class are : [‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__le__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’] " }, { "code": null, "e": 26629, "s": 26572, "text": "Objects of object class cannot add new attributes to it." }, { "code": null, "e": 26730, "s": 26629, "text": "These objects are uniquely made and do not equate to one other, i.e don’t return true once compared." }, { "code": null, "e": 26803, "s": 26730, "text": "the object acts as a base class for all the custom objects that we make." }, { "code": null, "e": 26811, "s": 26803, "text": "Python3" }, { "code": "# Python 3 code to demonstrate# properties of object() # declaring the objects of class objectobj1 = object()obj2 = object() # checking for object equalityprint(\"Is obj1 equal to obj2 : \" + str(obj1 == obj2)) # trying to add attribute to objectobj1.name = \"GeeksforGeeks\"", "e": 27083, "s": 26811, "text": null }, { "code": null, "e": 27092, "s": 27083, "text": "Output: " }, { "code": null, "e": 27122, "s": 27092, "text": "Is obj1 equal to obj2 : False" }, { "code": null, "e": 27133, "s": 27122, "text": "Exception:" }, { "code": null, "e": 27321, "s": 27133, "text": "Traceback (most recent call last):\n File \"/home/46b67ee266145958c7cc22d9ee0ae759.py\", line 12, in \n obj1.name = \"GeeksforGeeks\"\nAttributeError: 'object' object has no attribute 'name'" }, { "code": null, "e": 27334, "s": 27321, "text": "kumar_satyam" }, { "code": null, "e": 27360, "s": 27334, "text": "Python-Built-in-functions" }, { "code": null, "e": 27374, "s": 27360, "text": "python-object" }, { "code": null, "e": 27381, "s": 27374, "text": "Python" }, { "code": null, "e": 27479, "s": 27381, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27497, "s": 27479, "text": "Python Dictionary" }, { "code": null, "e": 27532, "s": 27497, "text": "Read a file line by line in Python" }, { "code": null, "e": 27564, "s": 27532, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27586, "s": 27564, "text": "Enumerate() in Python" }, { "code": null, "e": 27628, "s": 27586, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27658, "s": 27628, "text": "Iterate over a list in Python" }, { "code": null, "e": 27684, "s": 27658, "text": "Python String | replace()" }, { "code": null, "e": 27713, "s": 27684, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27757, "s": 27713, "text": "Reading and Writing to text files in Python" } ]
Ring Counter in Digital Logic - GeeksforGeeks
22 Apr, 2022 Ring counter is a typical application of Shift register. Ring counter is almost same as the shift counter. The only change is that the output of the last flip-flop is connected to the input of the first flip-flop in case of ring counter but in case of shift resister it is taken as output. Except this all the other things are same. No. of states in Ring counter = No. of flip-flop used So, for designing 4-bit Ring counter we need 4 flip-flop. In this diagram, we can see that the clock pulse (CLK) is applied to all the flip-flop simultaneously. Therefore, it is a Synchronous Counter. Also, here we use Overriding input (ORI) to each flip-flop. Preset (PR) and Clear (CLR) are used as ORI. When PR is 0, then the output is 1. And when CLR is 0, then the output is 0. Both PR and CLR are active low signal that is always works in value 0. PR = 0, Q = 1 CLR = 0, Q = 0 These two values are always fixed. They are independent with the value of input D and the Clock pulse (CLK). Working – Here, ORI is connected to Preset (PR) in FF-0 and it is connected to Clear (CLR) in FF-1, FF-2, and FF-3. Thus, output Q = 1 is generated at FF-0 and rest of the flip-flop generate output Q = 0. This output Q = 1 at FF-0 is known as Pre-set 1 which is used to form the ring in the Ring Counter. This Preseted 1 is generated by making ORI low and that time Clock (CLK) becomes don’t care. After that ORI made to high and apply low clock pulse signal as the Clock (CLK) is negative edge triggered. After that, at each clock pulse the preseted 1 is shifted to the next flip-flop and thus form Ring. From the above table, we can say that there are 4 states in 4-bit Ring Counter. 4 states are: 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 In this way can design 4-bit Ring Counter using four D flip-flops. Types of Ring Counter – There are two types of Ring Counter: Straight Ring Counter – It is also known as One hot Counter. In this counter, the output of the last flip-flop is connected to the input of the first flip-flip. The main point of this Counter is that it circulates a single one (or zero) bit around the ring. Here, we use Preset (PR) in the first flip-flop and Clock (CLK) for the last three flip-flop.Twisted Ring Counter – It is also known as switch-tail ring counter, walking ring counter or Johnson counter. It connects the complement of the output of the last shift register to the input of the first register and circulates a stream of ones followed by zeros around the ring. Here, we use Clock (CLK) for all the flip-flops. Straight Ring Counter – It is also known as One hot Counter. In this counter, the output of the last flip-flop is connected to the input of the first flip-flip. The main point of this Counter is that it circulates a single one (or zero) bit around the ring. Here, we use Preset (PR) in the first flip-flop and Clock (CLK) for the last three flip-flop. Twisted Ring Counter – It is also known as switch-tail ring counter, walking ring counter or Johnson counter. It connects the complement of the output of the last shift register to the input of the first register and circulates a stream of ones followed by zeros around the ring. Here, we use Clock (CLK) for all the flip-flops. chabilkansal mgalindorivera Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. IEEE Standard 754 Floating Point Numbers 4-bit binary Adder-Subtractor Difference between Unipolar, Polar and Bipolar Line Coding Schemes Difference between RAM and ROM Introduction to memory and memory units Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 28081, "s": 28053, "text": "\n22 Apr, 2022" }, { "code": null, "e": 28414, "s": 28081, "text": "Ring counter is a typical application of Shift register. Ring counter is almost same as the shift counter. The only change is that the output of the last flip-flop is connected to the input of the first flip-flop in case of ring counter but in case of shift resister it is taken as output. Except this all the other things are same." }, { "code": null, "e": 28469, "s": 28414, "text": " No. of states in Ring counter = No. of flip-flop used" }, { "code": null, "e": 28924, "s": 28469, "text": "So, for designing 4-bit Ring counter we need 4 flip-flop. In this diagram, we can see that the clock pulse (CLK) is applied to all the flip-flop simultaneously. Therefore, it is a Synchronous Counter. Also, here we use Overriding input (ORI) to each flip-flop. Preset (PR) and Clear (CLR) are used as ORI. When PR is 0, then the output is 1. And when CLR is 0, then the output is 0. Both PR and CLR are active low signal that is always works in value 0." }, { "code": null, "e": 28953, "s": 28924, "text": "PR = 0, Q = 1\nCLR = 0, Q = 0" }, { "code": null, "e": 29749, "s": 28953, "text": "These two values are always fixed. They are independent with the value of input D and the Clock pulse (CLK). Working – Here, ORI is connected to Preset (PR) in FF-0 and it is connected to Clear (CLR) in FF-1, FF-2, and FF-3. Thus, output Q = 1 is generated at FF-0 and rest of the flip-flop generate output Q = 0. This output Q = 1 at FF-0 is known as Pre-set 1 which is used to form the ring in the Ring Counter. This Preseted 1 is generated by making ORI low and that time Clock (CLK) becomes don’t care. After that ORI made to high and apply low clock pulse signal as the Clock (CLK) is negative edge triggered. After that, at each clock pulse the preseted 1 is shifted to the next flip-flop and thus form Ring. From the above table, we can say that there are 4 states in 4-bit Ring Counter." }, { "code": null, "e": 29803, "s": 29749, "text": "4 states are:\n 1 0 0 0\n 0 1 0 0\n 0 0 1 0\n 0 0 0 1" }, { "code": null, "e": 29931, "s": 29803, "text": "In this way can design 4-bit Ring Counter using four D flip-flops. Types of Ring Counter – There are two types of Ring Counter:" }, { "code": null, "e": 30613, "s": 29931, "text": "Straight Ring Counter – It is also known as One hot Counter. In this counter, the output of the last flip-flop is connected to the input of the first flip-flip. The main point of this Counter is that it circulates a single one (or zero) bit around the ring. Here, we use Preset (PR) in the first flip-flop and Clock (CLK) for the last three flip-flop.Twisted Ring Counter – It is also known as switch-tail ring counter, walking ring counter or Johnson counter. It connects the complement of the output of the last shift register to the input of the first register and circulates a stream of ones followed by zeros around the ring. Here, we use Clock (CLK) for all the flip-flops." }, { "code": null, "e": 30966, "s": 30613, "text": "Straight Ring Counter – It is also known as One hot Counter. In this counter, the output of the last flip-flop is connected to the input of the first flip-flip. The main point of this Counter is that it circulates a single one (or zero) bit around the ring. Here, we use Preset (PR) in the first flip-flop and Clock (CLK) for the last three flip-flop." }, { "code": null, "e": 31296, "s": 30966, "text": "Twisted Ring Counter – It is also known as switch-tail ring counter, walking ring counter or Johnson counter. It connects the complement of the output of the last shift register to the input of the first register and circulates a stream of ones followed by zeros around the ring. Here, we use Clock (CLK) for all the flip-flops." }, { "code": null, "e": 31309, "s": 31296, "text": "chabilkansal" }, { "code": null, "e": 31324, "s": 31309, "text": "mgalindorivera" }, { "code": null, "e": 31359, "s": 31324, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 31367, "s": 31359, "text": "GATE CS" }, { "code": null, "e": 31465, "s": 31367, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31506, "s": 31465, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 31536, "s": 31506, "text": "4-bit binary Adder-Subtractor" }, { "code": null, "e": 31603, "s": 31536, "text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes" }, { "code": null, "e": 31634, "s": 31603, "text": "Difference between RAM and ROM" }, { "code": null, "e": 31674, "s": 31634, "text": "Introduction to memory and memory units" }, { "code": null, "e": 31694, "s": 31674, "text": "Layers of OSI Model" }, { "code": null, "e": 31718, "s": 31694, "text": "ACID Properties in DBMS" }, { "code": null, "e": 31731, "s": 31718, "text": "TCP/IP Model" }, { "code": null, "e": 31758, "s": 31731, "text": "Types of Operating Systems" } ]
Python | Pandas.melt() - GeeksforGeeks
03 Jan, 2022 To make analysis of data in table easier, we can reshape the data into a more computer-friendly form using Pandas in Python. Pandas.melt() is one of the function to do so..Pandas.melt() unpivots a DataFrame from wide format to long format.melt() function is useful to message a DataFrame into a format where one or more columns are identifier variables, while all other columns, considered measured variables, are unpivoted to the row axis, leaving just two non-identifier columns, variable and value.Syntax : pandas.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None) Parameters: frame : DataFrameid_vars[tuple, list, or ndarray, optional] : Column(s) to use as identifier variables.value_vars[tuple, list, or ndarray, optional]: Column(s) to unpivot. If not specified, uses all columns that are not set as id_vars.var_name[scalar]: Name to use for the ‘variable’ column. If None it uses frame.columns.name or ‘variable’.value_name[scalar, default ‘value’]: Name to use for the ‘value’ column.col_level[int or string, optional]: If columns are a MultiIndex then use this level to melt. Example: Python3 # Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'Name': {0: 'John', 1: 'Bob', 2: 'Shiela'}, 'Course': {0: 'Masters', 1: 'Graduate', 2: 'Graduate'}, 'Age': {0: 27, 1: 23, 2: 21}})df Python3 # Name is id_vars and Course is value_varspd.melt(df, id_vars =['Name'], value_vars =['Course']) Python3 # multiple unpivot columnspd.melt(df, id_vars =['Name'], value_vars =['Course', 'Age']) Python3 # Names of ‘variable’ and ‘value’ columns can be customizedpd.melt(df, id_vars =['Name'], value_vars =['Course'], var_name ='ChangedVarname', value_name ='ChangedValname') surindertarika1234 Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26157, "s": 26129, "text": "\n03 Jan, 2022" }, { "code": null, "e": 26667, "s": 26157, "text": "To make analysis of data in table easier, we can reshape the data into a more computer-friendly form using Pandas in Python. Pandas.melt() is one of the function to do so..Pandas.melt() unpivots a DataFrame from wide format to long format.melt() function is useful to message a DataFrame into a format where one or more columns are identifier variables, while all other columns, considered measured variables, are unpivoted to the row axis, leaving just two non-identifier columns, variable and value.Syntax :" }, { "code": null, "e": 26769, "s": 26667, "text": "pandas.melt(frame, id_vars=None, value_vars=None,\n var_name=None, value_name='value', col_level=None)" }, { "code": null, "e": 26781, "s": 26769, "text": "Parameters:" }, { "code": null, "e": 27287, "s": 26781, "text": "frame : DataFrameid_vars[tuple, list, or ndarray, optional] : Column(s) to use as identifier variables.value_vars[tuple, list, or ndarray, optional]: Column(s) to unpivot. If not specified, uses all columns that are not set as id_vars.var_name[scalar]: Name to use for the ‘variable’ column. If None it uses frame.columns.name or ‘variable’.value_name[scalar, default ‘value’]: Name to use for the ‘value’ column.col_level[int or string, optional]: If columns are a MultiIndex then use this level to melt." }, { "code": null, "e": 27296, "s": 27287, "text": "Example:" }, { "code": null, "e": 27304, "s": 27296, "text": "Python3" }, { "code": "# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'Name': {0: 'John', 1: 'Bob', 2: 'Shiela'}, 'Course': {0: 'Masters', 1: 'Graduate', 2: 'Graduate'}, 'Age': {0: 27, 1: 23, 2: 21}})df", "e": 27588, "s": 27304, "text": null }, { "code": null, "e": 27598, "s": 27590, "text": "Python3" }, { "code": "# Name is id_vars and Course is value_varspd.melt(df, id_vars =['Name'], value_vars =['Course'])", "e": 27695, "s": 27598, "text": null }, { "code": null, "e": 27705, "s": 27697, "text": "Python3" }, { "code": "# multiple unpivot columnspd.melt(df, id_vars =['Name'], value_vars =['Course', 'Age'])", "e": 27793, "s": 27705, "text": null }, { "code": null, "e": 27801, "s": 27793, "text": "Python3" }, { "code": "# Names of ‘variable’ and ‘value’ columns can be customizedpd.melt(df, id_vars =['Name'], value_vars =['Course'], var_name ='ChangedVarname', value_name ='ChangedValname')", "e": 27986, "s": 27801, "text": null }, { "code": null, "e": 28005, "s": 27986, "text": "surindertarika1234" }, { "code": null, "e": 28029, "s": 28005, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28043, "s": 28029, "text": "Python-pandas" }, { "code": null, "e": 28050, "s": 28043, "text": "Python" }, { "code": null, "e": 28148, "s": 28050, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28166, "s": 28148, "text": "Python Dictionary" }, { "code": null, "e": 28201, "s": 28166, "text": "Read a file line by line in Python" }, { "code": null, "e": 28233, "s": 28201, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28255, "s": 28233, "text": "Enumerate() in Python" }, { "code": null, "e": 28297, "s": 28255, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28327, "s": 28297, "text": "Iterate over a list in Python" }, { "code": null, "e": 28353, "s": 28327, "text": "Python String | replace()" }, { "code": null, "e": 28382, "s": 28353, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28426, "s": 28382, "text": "Reading and Writing to text files in Python" } ]
Most asked Computer Science Subjects Interview Questions in Amazon, Microsoft, Flipkart - GeeksforGeeks
17 Mar, 2022 This article contains a list of most asked questions from Operating Systems, Computer Networks and DBMS in the interviews of the top product based companies like Amazon, Microsoft, Flipkart, Paytm etc. Operating System: Process Introduction What is a microprocessor?Explain the internal architecture of a RAM.How compiler compiles the interlinked libraries?Explain the implementation of virtual methods, dynamic binding, vtables etc. What is a microprocessor?Explain the internal architecture of a RAM.How compiler compiles the interlinked libraries?Explain the implementation of virtual methods, dynamic binding, vtables etc. What is a microprocessor? Explain the internal architecture of a RAM. How compiler compiles the interlinked libraries? Explain the implementation of virtual methods, dynamic binding, vtables etc. Multithreading What is Multithreading?What is the difference between a thread and a process? What is Multithreading?What is the difference between a thread and a process? What is Multithreading? What is the difference between a thread and a process? Process Scheduling FCFS Scheduling.Shortest Job First Scheduling.SRTF Scheduling.LRTF Scheduling.Priority Scheduling.Round Robin scheduling FCFS Scheduling.Shortest Job First Scheduling.SRTF Scheduling.LRTF Scheduling.Priority Scheduling.Round Robin scheduling FCFS Scheduling. Shortest Job First Scheduling. SRTF Scheduling. LRTF Scheduling. Priority Scheduling. Round Robin scheduling Process Synchronization & Deadlock What is a Semaphore and a Mutex?Explain the Producer-Consumer problem.What is Deadlock?What are the four necessary conditions for Deadlock?What is Critical Section?Explain the Banker’s Algorithm.What are Spinlocks? What is a Semaphore and a Mutex?Explain the Producer-Consumer problem.What is Deadlock?What are the four necessary conditions for Deadlock?What is Critical Section?Explain the Banker’s Algorithm.What are Spinlocks? What is a Semaphore and a Mutex? Explain the Producer-Consumer problem. What is Deadlock? What are the four necessary conditions for Deadlock? What is Critical Section? Explain the Banker’s Algorithm. What are Spinlocks? Memory Management What is Cache?Where does cache lies in an Operating System?Difference between Cache and HashMap.Explain Demand paging and thrashing.What is Segmentation?In which memory, the laptop password is being saved?How will you analyze Out of memory exceptions in your application?Explain internal fragmentation and external fragmentation.Difference between the associative mapping and direct mapping in a cache.If RAM size is 4GB, if 4 processes of size 2GB are launched! What happens? (Ans: This can be done using Virtual Memory)If process size is not limited by the size of main memory then what is its limitation? (Ans: This can be done using Logical Address Space)Explain how memory location is accessedWhat is Paging and Why do we need Paging?What is a Page Table?What is TLB? What is Cache?Where does cache lies in an Operating System?Difference between Cache and HashMap.Explain Demand paging and thrashing.What is Segmentation?In which memory, the laptop password is being saved?How will you analyze Out of memory exceptions in your application?Explain internal fragmentation and external fragmentation.Difference between the associative mapping and direct mapping in a cache.If RAM size is 4GB, if 4 processes of size 2GB are launched! What happens? (Ans: This can be done using Virtual Memory)If process size is not limited by the size of main memory then what is its limitation? (Ans: This can be done using Logical Address Space)Explain how memory location is accessedWhat is Paging and Why do we need Paging?What is a Page Table?What is TLB? What is Cache? Where does cache lies in an Operating System? Difference between Cache and HashMap. Explain Demand paging and thrashing. What is Segmentation? In which memory, the laptop password is being saved? How will you analyze Out of memory exceptions in your application? Explain internal fragmentation and external fragmentation. Difference between the associative mapping and direct mapping in a cache. If RAM size is 4GB, if 4 processes of size 2GB are launched! What happens? (Ans: This can be done using Virtual Memory) If process size is not limited by the size of main memory then what is its limitation? (Ans: This can be done using Logical Address Space) Explain how memory location is accessed What is Paging and Why do we need Paging? What is a Page Table? What is TLB? DBMS: Properties of RDBMS? ACID properties Keys in DBMS. Difference between Vertical and Horizontal Scaling. Sharding DML, DCL, DDL, TCL and their commands. Indexing in DBMS. What is normalization and de-normalization and why do we need it? Normal Forms Conflict Serializability Can Primary key contain two entities? (Ans: No, there is one and only one primary key in any relationship. Refer this) Concurrency Control SQL queries (related to nested query). Insertion in B trees Types of JOIN in DBMS. Difference between INNER and OUTER JOIN. Write a SQL query to retrieve furniture from database whose dimensions(Width, Height, Length) match with the given dimension. Ans. Ans. SELECT * FROM Furnitures WHERE Furnitures.Length = GivenLength AND Furnitures.Breadth = GivenBreadth AND Furnitures.Height = GivenHeight Print the second largest number in the table. Explain 3 tier architecture and 2 tier architectures. Write a SQL query to find the 4th maximum element from a table Computer Networks: What is TCP? Name layers of the OSI Model with protocols belonging to the layers What is the significance of Data Link Layer What is Access Points APs model? What does the network layer do In which layer are the Routers? What are the different types of delays? Explain Firewalls? What are the different types of firewall? What does transport layer do IPv4 vs IPv6 What is the difference b/w private IP and Public IP? Explain in detail 3 way Handshaking What is Cryptography and what are the Encryption Methods? What are the Application layer protocols? Explain DNS On entering a URL in a browser, explain the detailed procedure in which the request is handled by the browser and the result is obtained for the given search query. How will you create persistent connections between the server and the client? Explain server-side loadbalancer What is FTP? How is FTP different from Secure FTP? What is SMTP Explain the Working of HTTP and HTTPs. Where are ports? What Port numbers of different protocols How to prevent SYN DDoS attack? If you are looking for video content to prepare your CS Subjects like OS, DBMS, and CN for an SDE Interview of any product or service bases company then refer to our One Course For All Subjects i.e. OS DBMS CN For SDE Interview Preparation. This course has pre-recorded premium lecture videos by Mr. Sandeep Jain and theoretical concepts designed by experts. The course also has Most Asked Interview Questions for practice to provide the ultimate learning experience. This is a self-paced course which implies that you can complete the course at your own pace! kalrap615 pravesh25pandey GFG Sheets Computer Networks CS - Placements DBMS Operating Systems Operating Systems Computer Networks DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. RSA Algorithm in Cryptography Differences between TCP and UDP TCP Server-Client implementation in C Data encryption standard (DES) | Set 1 Differences between IPv4 and IPv6 Applications of linked list data structure TCS Interview Questions Hotel Management System Count of substrings of length K with exactly K distinct characters Minimum Cost Maximum Flow from a Graph using Bellman Ford Algorithm
[ { "code": null, "e": 25856, "s": 25828, "text": "\n17 Mar, 2022" }, { "code": null, "e": 26059, "s": 25856, "text": "This article contains a list of most asked questions from Operating Systems, Computer Networks and DBMS in the interviews of the top product based companies like Amazon, Microsoft, Flipkart, Paytm etc. " }, { "code": null, "e": 26077, "s": 26059, "text": "Operating System:" }, { "code": null, "e": 26291, "s": 26077, "text": "Process Introduction What is a microprocessor?Explain the internal architecture of a RAM.How compiler compiles the interlinked libraries?Explain the implementation of virtual methods, dynamic binding, vtables etc." }, { "code": null, "e": 26484, "s": 26291, "text": "What is a microprocessor?Explain the internal architecture of a RAM.How compiler compiles the interlinked libraries?Explain the implementation of virtual methods, dynamic binding, vtables etc." }, { "code": null, "e": 26510, "s": 26484, "text": "What is a microprocessor?" }, { "code": null, "e": 26554, "s": 26510, "text": "Explain the internal architecture of a RAM." }, { "code": null, "e": 26603, "s": 26554, "text": "How compiler compiles the interlinked libraries?" }, { "code": null, "e": 26680, "s": 26603, "text": "Explain the implementation of virtual methods, dynamic binding, vtables etc." }, { "code": null, "e": 26773, "s": 26680, "text": "Multithreading What is Multithreading?What is the difference between a thread and a process?" }, { "code": null, "e": 26851, "s": 26773, "text": "What is Multithreading?What is the difference between a thread and a process?" }, { "code": null, "e": 26875, "s": 26851, "text": "What is Multithreading?" }, { "code": null, "e": 26930, "s": 26875, "text": "What is the difference between a thread and a process?" }, { "code": null, "e": 27070, "s": 26930, "text": "Process Scheduling FCFS Scheduling.Shortest Job First Scheduling.SRTF Scheduling.LRTF Scheduling.Priority Scheduling.Round Robin scheduling" }, { "code": null, "e": 27191, "s": 27070, "text": "FCFS Scheduling.Shortest Job First Scheduling.SRTF Scheduling.LRTF Scheduling.Priority Scheduling.Round Robin scheduling" }, { "code": null, "e": 27208, "s": 27191, "text": "FCFS Scheduling." }, { "code": null, "e": 27239, "s": 27208, "text": "Shortest Job First Scheduling." }, { "code": null, "e": 27256, "s": 27239, "text": "SRTF Scheduling." }, { "code": null, "e": 27273, "s": 27256, "text": "LRTF Scheduling." }, { "code": null, "e": 27294, "s": 27273, "text": "Priority Scheduling." }, { "code": null, "e": 27317, "s": 27294, "text": "Round Robin scheduling" }, { "code": null, "e": 27567, "s": 27317, "text": "Process Synchronization & Deadlock What is a Semaphore and a Mutex?Explain the Producer-Consumer problem.What is Deadlock?What are the four necessary conditions for Deadlock?What is Critical Section?Explain the Banker’s Algorithm.What are Spinlocks?" }, { "code": null, "e": 27782, "s": 27567, "text": "What is a Semaphore and a Mutex?Explain the Producer-Consumer problem.What is Deadlock?What are the four necessary conditions for Deadlock?What is Critical Section?Explain the Banker’s Algorithm.What are Spinlocks?" }, { "code": null, "e": 27815, "s": 27782, "text": "What is a Semaphore and a Mutex?" }, { "code": null, "e": 27854, "s": 27815, "text": "Explain the Producer-Consumer problem." }, { "code": null, "e": 27872, "s": 27854, "text": "What is Deadlock?" }, { "code": null, "e": 27925, "s": 27872, "text": "What are the four necessary conditions for Deadlock?" }, { "code": null, "e": 27951, "s": 27925, "text": "What is Critical Section?" }, { "code": null, "e": 27983, "s": 27951, "text": "Explain the Banker’s Algorithm." }, { "code": null, "e": 28003, "s": 27983, "text": "What are Spinlocks?" }, { "code": null, "e": 28794, "s": 28003, "text": "Memory Management What is Cache?Where does cache lies in an Operating System?Difference between Cache and HashMap.Explain Demand paging and thrashing.What is Segmentation?In which memory, the laptop password is being saved?How will you analyze Out of memory exceptions in your application?Explain internal fragmentation and external fragmentation.Difference between the associative mapping and direct mapping in a cache.If RAM size is 4GB, if 4 processes of size 2GB are launched! What happens? (Ans: This can be done using Virtual Memory)If process size is not limited by the size of main memory then what is its limitation? (Ans: This can be done using Logical Address Space)Explain how memory location is accessedWhat is Paging and Why do we need Paging?What is a Page Table?What is TLB?" }, { "code": null, "e": 29567, "s": 28794, "text": "What is Cache?Where does cache lies in an Operating System?Difference between Cache and HashMap.Explain Demand paging and thrashing.What is Segmentation?In which memory, the laptop password is being saved?How will you analyze Out of memory exceptions in your application?Explain internal fragmentation and external fragmentation.Difference between the associative mapping and direct mapping in a cache.If RAM size is 4GB, if 4 processes of size 2GB are launched! What happens? (Ans: This can be done using Virtual Memory)If process size is not limited by the size of main memory then what is its limitation? (Ans: This can be done using Logical Address Space)Explain how memory location is accessedWhat is Paging and Why do we need Paging?What is a Page Table?What is TLB?" }, { "code": null, "e": 29582, "s": 29567, "text": "What is Cache?" }, { "code": null, "e": 29628, "s": 29582, "text": "Where does cache lies in an Operating System?" }, { "code": null, "e": 29666, "s": 29628, "text": "Difference between Cache and HashMap." }, { "code": null, "e": 29703, "s": 29666, "text": "Explain Demand paging and thrashing." }, { "code": null, "e": 29725, "s": 29703, "text": "What is Segmentation?" }, { "code": null, "e": 29778, "s": 29725, "text": "In which memory, the laptop password is being saved?" }, { "code": null, "e": 29845, "s": 29778, "text": "How will you analyze Out of memory exceptions in your application?" }, { "code": null, "e": 29904, "s": 29845, "text": "Explain internal fragmentation and external fragmentation." }, { "code": null, "e": 29978, "s": 29904, "text": "Difference between the associative mapping and direct mapping in a cache." }, { "code": null, "e": 30098, "s": 29978, "text": "If RAM size is 4GB, if 4 processes of size 2GB are launched! What happens? (Ans: This can be done using Virtual Memory)" }, { "code": null, "e": 30237, "s": 30098, "text": "If process size is not limited by the size of main memory then what is its limitation? (Ans: This can be done using Logical Address Space)" }, { "code": null, "e": 30277, "s": 30237, "text": "Explain how memory location is accessed" }, { "code": null, "e": 30319, "s": 30277, "text": "What is Paging and Why do we need Paging?" }, { "code": null, "e": 30341, "s": 30319, "text": "What is a Page Table?" }, { "code": null, "e": 30354, "s": 30341, "text": "What is TLB?" }, { "code": null, "e": 30360, "s": 30354, "text": "DBMS:" }, { "code": null, "e": 30381, "s": 30360, "text": "Properties of RDBMS?" }, { "code": null, "e": 30397, "s": 30381, "text": "ACID properties" }, { "code": null, "e": 30411, "s": 30397, "text": "Keys in DBMS." }, { "code": null, "e": 30463, "s": 30411, "text": "Difference between Vertical and Horizontal Scaling." }, { "code": null, "e": 30472, "s": 30463, "text": "Sharding" }, { "code": null, "e": 30511, "s": 30472, "text": "DML, DCL, DDL, TCL and their commands." }, { "code": null, "e": 30529, "s": 30511, "text": "Indexing in DBMS." }, { "code": null, "e": 30595, "s": 30529, "text": "What is normalization and de-normalization and why do we need it?" }, { "code": null, "e": 30608, "s": 30595, "text": "Normal Forms" }, { "code": null, "e": 30633, "s": 30608, "text": "Conflict Serializability" }, { "code": null, "e": 30752, "s": 30633, "text": "Can Primary key contain two entities? (Ans: No, there is one and only one primary key in any relationship. Refer this)" }, { "code": null, "e": 30772, "s": 30752, "text": "Concurrency Control" }, { "code": null, "e": 30811, "s": 30772, "text": "SQL queries (related to nested query)." }, { "code": null, "e": 30832, "s": 30811, "text": "Insertion in B trees" }, { "code": null, "e": 30855, "s": 30832, "text": "Types of JOIN in DBMS." }, { "code": null, "e": 30896, "s": 30855, "text": "Difference between INNER and OUTER JOIN." }, { "code": null, "e": 31027, "s": 30896, "text": "Write a SQL query to retrieve furniture from database whose dimensions(Width, Height, Length) match with the given dimension. Ans." }, { "code": null, "e": 31032, "s": 31027, "text": "Ans." }, { "code": null, "e": 31173, "s": 31032, "text": "SELECT *\nFROM Furnitures\nWHERE Furnitures.Length = GivenLength\n AND Furnitures.Breadth = GivenBreadth\n AND Furnitures.Height = GivenHeight" }, { "code": null, "e": 31219, "s": 31173, "text": "Print the second largest number in the table." }, { "code": null, "e": 31273, "s": 31219, "text": "Explain 3 tier architecture and 2 tier architectures." }, { "code": null, "e": 31336, "s": 31273, "text": "Write a SQL query to find the 4th maximum element from a table" }, { "code": null, "e": 31356, "s": 31336, "text": "Computer Networks: " }, { "code": null, "e": 31369, "s": 31356, "text": "What is TCP?" }, { "code": null, "e": 31437, "s": 31369, "text": "Name layers of the OSI Model with protocols belonging to the layers" }, { "code": null, "e": 31481, "s": 31437, "text": "What is the significance of Data Link Layer" }, { "code": null, "e": 31514, "s": 31481, "text": "What is Access Points APs model?" }, { "code": null, "e": 31545, "s": 31514, "text": "What does the network layer do" }, { "code": null, "e": 31577, "s": 31545, "text": "In which layer are the Routers?" }, { "code": null, "e": 31617, "s": 31577, "text": "What are the different types of delays?" }, { "code": null, "e": 31636, "s": 31617, "text": "Explain Firewalls?" }, { "code": null, "e": 31678, "s": 31636, "text": "What are the different types of firewall?" }, { "code": null, "e": 31707, "s": 31678, "text": "What does transport layer do" }, { "code": null, "e": 31720, "s": 31707, "text": "IPv4 vs IPv6" }, { "code": null, "e": 31773, "s": 31720, "text": "What is the difference b/w private IP and Public IP?" }, { "code": null, "e": 31809, "s": 31773, "text": "Explain in detail 3 way Handshaking" }, { "code": null, "e": 31867, "s": 31809, "text": "What is Cryptography and what are the Encryption Methods?" }, { "code": null, "e": 31909, "s": 31867, "text": "What are the Application layer protocols?" }, { "code": null, "e": 31921, "s": 31909, "text": "Explain DNS" }, { "code": null, "e": 32086, "s": 31921, "text": "On entering a URL in a browser, explain the detailed procedure in which the request is handled by the browser and the result is obtained for the given search query." }, { "code": null, "e": 32164, "s": 32086, "text": "How will you create persistent connections between the server and the client?" }, { "code": null, "e": 32197, "s": 32164, "text": "Explain server-side loadbalancer" }, { "code": null, "e": 32248, "s": 32197, "text": "What is FTP? How is FTP different from Secure FTP?" }, { "code": null, "e": 32261, "s": 32248, "text": "What is SMTP" }, { "code": null, "e": 32300, "s": 32261, "text": "Explain the Working of HTTP and HTTPs." }, { "code": null, "e": 32317, "s": 32300, "text": "Where are ports?" }, { "code": null, "e": 32358, "s": 32317, "text": "What Port numbers of different protocols" }, { "code": null, "e": 32390, "s": 32358, "text": "How to prevent SYN DDoS attack?" }, { "code": null, "e": 32631, "s": 32390, "text": "If you are looking for video content to prepare your CS Subjects like OS, DBMS, and CN for an SDE Interview of any product or service bases company then refer to our One Course For All Subjects i.e. OS DBMS CN For SDE Interview Preparation." }, { "code": null, "e": 32951, "s": 32631, "text": "This course has pre-recorded premium lecture videos by Mr. Sandeep Jain and theoretical concepts designed by experts. The course also has Most Asked Interview Questions for practice to provide the ultimate learning experience. This is a self-paced course which implies that you can complete the course at your own pace!" }, { "code": null, "e": 32961, "s": 32951, "text": "kalrap615" }, { "code": null, "e": 32977, "s": 32961, "text": "pravesh25pandey" }, { "code": null, "e": 32988, "s": 32977, "text": "GFG Sheets" }, { "code": null, "e": 33006, "s": 32988, "text": "Computer Networks" }, { "code": null, "e": 33022, "s": 33006, "text": "CS - Placements" }, { "code": null, "e": 33027, "s": 33022, "text": "DBMS" }, { "code": null, "e": 33045, "s": 33027, "text": "Operating Systems" }, { "code": null, "e": 33063, "s": 33045, "text": "Operating Systems" }, { "code": null, "e": 33081, "s": 33063, "text": "Computer Networks" }, { "code": null, "e": 33086, "s": 33081, "text": "DBMS" }, { "code": null, "e": 33184, "s": 33086, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33214, "s": 33184, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 33246, "s": 33214, "text": "Differences between TCP and UDP" }, { "code": null, "e": 33284, "s": 33246, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 33323, "s": 33284, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 33357, "s": 33323, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 33400, "s": 33357, "text": "Applications of linked list data structure" }, { "code": null, "e": 33424, "s": 33400, "text": "TCS Interview Questions" }, { "code": null, "e": 33448, "s": 33424, "text": "Hotel Management System" }, { "code": null, "e": 33515, "s": 33448, "text": "Count of substrings of length K with exactly K distinct characters" } ]
Python3 Program for Mean of range in array - GeeksforGeeks
13 Jan, 2022 Given an array of n integers. You are given q queries. Write a program to print the floor value of mean in range l to r for each query in a new line. Examples : Input : arr[] = {1, 2, 3, 4, 5} q = 3 0 2 1 3 0 4 Output : 2 3 3 Here for 0 to 2 (1 + 2 + 3) / 3 = 2 Input : arr[] = {6, 7, 8, 10} q = 2 0 3 1 2 Output : 7 7 Naive Approach: We can run loop for each query l to r and find sum and number of elements in range. After this we can print floor of mean for each query. Python3 # Python 3 program to find floor value# of mean in range l to rimport math # To find mean of range in l to rdef findMean(arr, l, r): # Both sum and count are # initialize to 0 sum, count = 0, 0 # To calculate sum and number # of elements in range l to r for i in range(l, r + 1): sum += arr[i] count += 1 # Calculate floor value of mean mean = math.floor(sum / count) # Returns mean of array # in range l to r return mean # Driver Codearr = [ 1, 2, 3, 4, 5 ] print(findMean(arr, 0, 2))print(findMean(arr, 1, 3))print(findMean(arr, 0, 4)) # This code is contributed # by PrinciRaj1992 Output : 2 3 3 Time Complexity: O(n) Efficient Approach: We can find sum of numbers using numbers using prefix sum. The prefixSum[i] denotes the sum of first i elements. So sum of numbers in range l to r will be prefixSum[r] – prefixSum[l-1]. Number of elements in range l to r will be r – l + 1. So we can now print mean of range l to r in O(1). Python3 # Python3 program to find floor value# of mean in range l to rimport math as mt MAX = 1000005prefixSum = [0 for i in range(MAX)] # To calculate prefixSum of arraydef calculatePrefixSum(arr, n): # Calculate prefix sum of array prefixSum[0] = arr[0] for i in range(1,n): prefixSum[i] = prefixSum[i - 1] + arr[i] # To return floor of mean# in range l to rdef findMean(l, r): if (l == 0): return mt.floor(prefixSum[r] / (r + 1)) # Sum of elements in range l to # r is prefixSum[r] - prefixSum[l-1] # Number of elements in range # l to r is r - l + 1 return (mt.floor((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1))) # Driver Codearr = [1, 2, 3, 4, 5] n = len(arr) calculatePrefixSum(arr, n)print(findMean(0, 2))print(findMean(1, 3))print(findMean(0, 4)) # This code is contributed by Mohit Kumar Output: 2 3 3 Please refer complete article on Mean of range in array for more details! array-range-queries prefix-sum Arrays Python prefix-sum Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 26041, "s": 26013, "text": "\n13 Jan, 2022" }, { "code": null, "e": 26191, "s": 26041, "text": "Given an array of n integers. You are given q queries. Write a program to print the floor value of mean in range l to r for each query in a new line." }, { "code": null, "e": 26203, "s": 26191, "text": "Examples : " }, { "code": null, "e": 26445, "s": 26203, "text": "Input : arr[] = {1, 2, 3, 4, 5}\n q = 3\n 0 2\n 1 3\n 0 4\nOutput : 2\n 3\n 3\nHere for 0 to 2 (1 + 2 + 3) / 3 = 2\n\nInput : arr[] = {6, 7, 8, 10}\n q = 2\n 0 3\n 1 2\nOutput : 7\n 7" }, { "code": null, "e": 26601, "s": 26445, "text": "Naive Approach: We can run loop for each query l to r and find sum and number of elements in range. After this we can print floor of mean for each query. " }, { "code": null, "e": 26609, "s": 26601, "text": "Python3" }, { "code": "# Python 3 program to find floor value# of mean in range l to rimport math # To find mean of range in l to rdef findMean(arr, l, r): # Both sum and count are # initialize to 0 sum, count = 0, 0 # To calculate sum and number # of elements in range l to r for i in range(l, r + 1): sum += arr[i] count += 1 # Calculate floor value of mean mean = math.floor(sum / count) # Returns mean of array # in range l to r return mean # Driver Codearr = [ 1, 2, 3, 4, 5 ] print(findMean(arr, 0, 2))print(findMean(arr, 1, 3))print(findMean(arr, 0, 4)) # This code is contributed # by PrinciRaj1992", "e": 27264, "s": 26609, "text": null }, { "code": null, "e": 27274, "s": 27264, "text": "Output : " }, { "code": null, "e": 27280, "s": 27274, "text": "2\n3\n3" }, { "code": null, "e": 27302, "s": 27280, "text": "Time Complexity: O(n)" }, { "code": null, "e": 27613, "s": 27302, "text": "Efficient Approach: We can find sum of numbers using numbers using prefix sum. The prefixSum[i] denotes the sum of first i elements. So sum of numbers in range l to r will be prefixSum[r] – prefixSum[l-1]. Number of elements in range l to r will be r – l + 1. So we can now print mean of range l to r in O(1). " }, { "code": null, "e": 27621, "s": 27613, "text": "Python3" }, { "code": "# Python3 program to find floor value# of mean in range l to rimport math as mt MAX = 1000005prefixSum = [0 for i in range(MAX)] # To calculate prefixSum of arraydef calculatePrefixSum(arr, n): # Calculate prefix sum of array prefixSum[0] = arr[0] for i in range(1,n): prefixSum[i] = prefixSum[i - 1] + arr[i] # To return floor of mean# in range l to rdef findMean(l, r): if (l == 0): return mt.floor(prefixSum[r] / (r + 1)) # Sum of elements in range l to # r is prefixSum[r] - prefixSum[l-1] # Number of elements in range # l to r is r - l + 1 return (mt.floor((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1))) # Driver Codearr = [1, 2, 3, 4, 5] n = len(arr) calculatePrefixSum(arr, n)print(findMean(0, 2))print(findMean(1, 3))print(findMean(0, 4)) # This code is contributed by Mohit Kumar", "e": 28517, "s": 27621, "text": null }, { "code": null, "e": 28526, "s": 28517, "text": "Output: " }, { "code": null, "e": 28532, "s": 28526, "text": "2\n3\n3" }, { "code": null, "e": 28606, "s": 28532, "text": "Please refer complete article on Mean of range in array for more details!" }, { "code": null, "e": 28626, "s": 28606, "text": "array-range-queries" }, { "code": null, "e": 28637, "s": 28626, "text": "prefix-sum" }, { "code": null, "e": 28644, "s": 28637, "text": "Arrays" }, { "code": null, "e": 28651, "s": 28644, "text": "Python" }, { "code": null, "e": 28662, "s": 28651, "text": "prefix-sum" }, { "code": null, "e": 28669, "s": 28662, "text": "Arrays" }, { "code": null, "e": 28767, "s": 28669, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28794, "s": 28767, "text": "Count pairs with given sum" }, { "code": null, "e": 28825, "s": 28794, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 28850, "s": 28825, "text": "Window Sliding Technique" }, { "code": null, "e": 28888, "s": 28850, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 28909, "s": 28888, "text": "Next Greater Element" }, { "code": null, "e": 28937, "s": 28909, "text": "Read JSON file using Python" }, { "code": null, "e": 28987, "s": 28937, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29009, "s": 28987, "text": "Python map() function" } ]
Python program to find Cumulative sum of a list - GeeksforGeeks
20 Aug, 2020 The problem statement asks to produce a new list whose i^{th} element will be equal to the sum of the (i + 1) elements. Examples : Input : list = [10, 20, 30, 40, 50] Output : [10, 30, 60, 100, 150] Input : list = [4, 10, 15, 18, 20] Output : [4, 14, 29, 47, 67] Approach 1 : We will use the concept of list comprehension and list slicing to get the cumulative sum of the list. The list comprehension has been used to access each element from the list and slicing has been done to access the elements from start to the i+1 element. We have used the sum() method to sum up the elements of the list from start to i+1.Below is the implementation of the above approach : Python3 # Python code to get the Cumulative sum of a listdef Cumulative(lists): cu_list = [] length = len(lists) cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)] return cu_list[1:] # Driver Codelists = [10, 20, 30, 40, 50]print (Cumulative(lists)) Output : [10, 30, 60, 100, 150] Approach 2: Python3 list=[10,20,30,40,50]new_list=[]j=0for i in range(0,len(list)): j+=list[i] new_list.append(j) print(new_list)#code given by Divyanshu singh Output : [10, 30, 60, 100, 150] kaushikkakdey divyanshusingh9314 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. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 26252, "s": 26224, "text": "\n20 Aug, 2020" }, { "code": null, "e": 26372, "s": 26252, "text": "The problem statement asks to produce a new list whose i^{th} element will be equal to the sum of the (i + 1) elements." }, { "code": null, "e": 26385, "s": 26372, "text": "Examples : " }, { "code": null, "e": 26520, "s": 26385, "text": "Input : list = [10, 20, 30, 40, 50]\nOutput : [10, 30, 60, 100, 150]\n\nInput : list = [4, 10, 15, 18, 20]\nOutput : [4, 14, 29, 47, 67]\n\n" }, { "code": null, "e": 26928, "s": 26522, "text": "Approach 1 : We will use the concept of list comprehension and list slicing to get the cumulative sum of the list. The list comprehension has been used to access each element from the list and slicing has been done to access the elements from start to the i+1 element. We have used the sum() method to sum up the elements of the list from start to i+1.Below is the implementation of the above approach : " }, { "code": null, "e": 26936, "s": 26928, "text": "Python3" }, { "code": "# Python code to get the Cumulative sum of a listdef Cumulative(lists): cu_list = [] length = len(lists) cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)] return cu_list[1:] # Driver Codelists = [10, 20, 30, 40, 50]print (Cumulative(lists))", "e": 27197, "s": 26936, "text": null }, { "code": null, "e": 27208, "s": 27197, "text": "Output : " }, { "code": null, "e": 27233, "s": 27208, "text": "[10, 30, 60, 100, 150]\n\n" }, { "code": null, "e": 27246, "s": 27233, "text": "Approach 2: " }, { "code": null, "e": 27254, "s": 27246, "text": "Python3" }, { "code": "list=[10,20,30,40,50]new_list=[]j=0for i in range(0,len(list)): j+=list[i] new_list.append(j) print(new_list)#code given by Divyanshu singh", "e": 27404, "s": 27254, "text": null }, { "code": null, "e": 27415, "s": 27404, "text": "Output : " }, { "code": null, "e": 27440, "s": 27415, "text": "[10, 30, 60, 100, 150]\n\n" }, { "code": null, "e": 27456, "s": 27442, "text": "kaushikkakdey" }, { "code": null, "e": 27475, "s": 27456, "text": "divyanshusingh9314" }, { "code": null, "e": 27496, "s": 27475, "text": "Python list-programs" }, { "code": null, "e": 27508, "s": 27496, "text": "python-list" }, { "code": null, "e": 27515, "s": 27508, "text": "Python" }, { "code": null, "e": 27531, "s": 27515, "text": "Python Programs" }, { "code": null, "e": 27543, "s": 27531, "text": "python-list" }, { "code": null, "e": 27641, "s": 27543, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27673, "s": 27641, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27695, "s": 27673, "text": "Enumerate() in Python" }, { "code": null, "e": 27737, "s": 27695, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27763, "s": 27737, "text": "Python String | replace()" }, { "code": null, "e": 27792, "s": 27763, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27814, "s": 27792, "text": "Defaultdict in Python" }, { "code": null, "e": 27853, "s": 27814, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27899, "s": 27853, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27937, "s": 27899, "text": "Python | Convert a list to dictionary" } ]
PHP | Factorial of a number - GeeksforGeeks
09 Mar, 2018 We already know how to get the factorial of a number in other languages. Let’s see how this is done in PHP using both recursive and non-recursive ways. Examples: Input : 5 Output : 120 Input : 10 Output : 3628800 Method 1: Iterative wayIn this method, we simply used the for loop to iterate over the sequence of numbers to get the factorial. <?php// PHP code to get the factorial of a number// function to get factorial in iterative wayfunction Factorial($number){ $factorial = 1; for ($i = 1; $i <= $number; $i++){ $factorial = $factorial * $i; } return $factorial;} // Driver Code$number = 10;$fact = Factorial($number);echo "Factorial = $fact";?> Output: 3628800 Method 2: Use of recursionIn this method we are calling the same method to get the sequence of the factorial. <?php// PHP code to get the factorial of a number// function to get factorial in iterative wayfunction Factorial($number){ if($number <= 1){ return 1; } else{ return $number * Factorial($number - 1); } } // Driver Code$number = 10;$fact = Factorial($number);echo "Factorial = $fact";?> Output: 3628800 PHP-basics PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26195, "s": 26167, "text": "\n09 Mar, 2018" }, { "code": null, "e": 26347, "s": 26195, "text": "We already know how to get the factorial of a number in other languages. Let’s see how this is done in PHP using both recursive and non-recursive ways." }, { "code": null, "e": 26357, "s": 26347, "text": "Examples:" }, { "code": null, "e": 26410, "s": 26357, "text": "Input : 5\nOutput : 120\n\nInput : 10\nOutput : 3628800\n" }, { "code": null, "e": 26539, "s": 26410, "text": "Method 1: Iterative wayIn this method, we simply used the for loop to iterate over the sequence of numbers to get the factorial." }, { "code": "<?php// PHP code to get the factorial of a number// function to get factorial in iterative wayfunction Factorial($number){ $factorial = 1; for ($i = 1; $i <= $number; $i++){ $factorial = $factorial * $i; } return $factorial;} // Driver Code$number = 10;$fact = Factorial($number);echo \"Factorial = $fact\";?>", "e": 26865, "s": 26539, "text": null }, { "code": null, "e": 26873, "s": 26865, "text": "Output:" }, { "code": null, "e": 26882, "s": 26873, "text": "3628800\n" }, { "code": null, "e": 26992, "s": 26882, "text": "Method 2: Use of recursionIn this method we are calling the same method to get the sequence of the factorial." }, { "code": "<?php// PHP code to get the factorial of a number// function to get factorial in iterative wayfunction Factorial($number){ if($number <= 1){ return 1; } else{ return $number * Factorial($number - 1); } } // Driver Code$number = 10;$fact = Factorial($number);echo \"Factorial = $fact\";?>", "e": 27316, "s": 26992, "text": null }, { "code": null, "e": 27324, "s": 27316, "text": "Output:" }, { "code": null, "e": 27333, "s": 27324, "text": "3628800\n" }, { "code": null, "e": 27344, "s": 27333, "text": "PHP-basics" }, { "code": null, "e": 27348, "s": 27344, "text": "PHP" }, { "code": null, "e": 27365, "s": 27348, "text": "Web Technologies" }, { "code": null, "e": 27369, "s": 27365, "text": "PHP" }, { "code": null, "e": 27467, "s": 27369, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27517, "s": 27467, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27557, "s": 27517, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27618, "s": 27557, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27668, "s": 27618, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 27713, "s": 27668, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27753, "s": 27713, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27786, "s": 27753, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27831, "s": 27786, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27874, "s": 27831, "text": "How to fetch data from an API in ReactJS ?" } ]
Difference between getc(), getchar(), getch() and getche() - GeeksforGeeks
13 Dec, 2018 All of these functions read a character from input and return an integer value. The integer is returned to accommodate a special value used to indicate failure. The value EOF is generally used for this purpose. getc():It reads a single character from a given input stream and returns the corresponding integer value (typically ASCII value of read character) on success. It returns EOF on failure. Syntax: int getc(FILE *stream); Example: // Example for getc() in C#include <stdio.h>int main(){ printf("%c", getc(stdin)); return(0);} Input: g (press enter key) Output: g An Example Application : C program to compare two files and report mismatches getchar():The difference between getc() and getchar() is getc() can read from any input stream, but getchar() reads from standard input. So getchar() is equivalent to getc(stdin). Syntax: int getchar(void); Example: // Example for getchar() in C#include <stdio.h>int main(){ printf("%c", getchar()); return 0;} Input: g(press enter key) Output: g getch():getch() is a nonstandard function and is present in conio.h header file which is mostly used by MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it defined by POSIX (Source: http://en.wikipedia.org/wiki/Conio.h)Like above functions, it reads also a single character from keyboard. But it does not use any buffer, so the entered character is immediately returned without waiting for the enter key.Syntax: int getch(); Example: // Example for getch() in C#include <stdio.h>#include <conio.h>int main(){ printf("%c", getch()); return 0;} Input: g (Without enter key) Output: Program terminates immediately. But when you use DOS shell in Turbo C, it shows a single g, i.e., 'g' getche()Like getch(), this is also a non-standard function present in conio.h. It reads a single character from the keyboard and displays immediately on output screen without waiting for enter key. Syntax: int getche(void); Example: #include <stdio.h>#include <conio.h>// Example for getche() in Cint main(){ printf("%c", getche()); return 0;} Input: g(without enter key as it is not buffered) Output: Program terminates immediately. But when you use DOS shell in Turbo C, double g, i.e., 'gg' This article is contributed by Vankayala Karunakar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-Input and Output Quiz c-input-output C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C Substring in C++ fork() in C std::string class in C++ Enumeration (or enum) in C Command line arguments in C/C++ TCP Server-Client implementation in C Different methods to reverse a string in C/C++ Structures in C Exception Handling in C++
[ { "code": null, "e": 25759, "s": 25731, "text": "\n13 Dec, 2018" }, { "code": null, "e": 25970, "s": 25759, "text": "All of these functions read a character from input and return an integer value. The integer is returned to accommodate a special value used to indicate failure. The value EOF is generally used for this purpose." }, { "code": null, "e": 26156, "s": 25970, "text": "getc():It reads a single character from a given input stream and returns the corresponding integer value (typically ASCII value of read character) on success. It returns EOF on failure." }, { "code": null, "e": 26164, "s": 26156, "text": "Syntax:" }, { "code": null, "e": 26189, "s": 26164, "text": "int getc(FILE *stream); " }, { "code": null, "e": 26198, "s": 26189, "text": "Example:" }, { "code": "// Example for getc() in C#include <stdio.h>int main(){ printf(\"%c\", getc(stdin)); return(0);}", "e": 26297, "s": 26198, "text": null }, { "code": null, "e": 26335, "s": 26297, "text": "Input: g (press enter key)\nOutput: g " }, { "code": null, "e": 26413, "s": 26335, "text": "An Example Application : C program to compare two files and report mismatches" }, { "code": null, "e": 26593, "s": 26413, "text": "getchar():The difference between getc() and getchar() is getc() can read from any input stream, but getchar() reads from standard input. So getchar() is equivalent to getc(stdin)." }, { "code": null, "e": 26601, "s": 26593, "text": "Syntax:" }, { "code": null, "e": 26621, "s": 26601, "text": "int getchar(void); " }, { "code": null, "e": 26630, "s": 26621, "text": "Example:" }, { "code": "// Example for getchar() in C#include <stdio.h>int main(){ printf(\"%c\", getchar()); return 0;}", "e": 26729, "s": 26630, "text": null }, { "code": null, "e": 26766, "s": 26729, "text": "Input: g(press enter key)\nOutput: g " }, { "code": null, "e": 27218, "s": 26766, "text": "getch():getch() is a nonstandard function and is present in conio.h header file which is mostly used by MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it defined by POSIX (Source: http://en.wikipedia.org/wiki/Conio.h)Like above functions, it reads also a single character from keyboard. But it does not use any buffer, so the entered character is immediately returned without waiting for the enter key.Syntax:" }, { "code": null, "e": 27231, "s": 27218, "text": "int getch();" }, { "code": null, "e": 27240, "s": 27231, "text": "Example:" }, { "code": "// Example for getch() in C#include <stdio.h>#include <conio.h>int main(){ printf(\"%c\", getch()); return 0;}", "e": 27356, "s": 27240, "text": null }, { "code": null, "e": 27513, "s": 27356, "text": "Input: g (Without enter key)\nOutput: Program terminates immediately.\n But when you use DOS shell in Turbo C, \n it shows a single g, i.e., 'g'" }, { "code": null, "e": 27711, "s": 27513, "text": "getche()Like getch(), this is also a non-standard function present in conio.h. It reads a single character from the keyboard and displays immediately on output screen without waiting for enter key." }, { "code": null, "e": 27719, "s": 27711, "text": "Syntax:" }, { "code": null, "e": 27738, "s": 27719, "text": "int getche(void); " }, { "code": null, "e": 27747, "s": 27738, "text": "Example:" }, { "code": "#include <stdio.h>#include <conio.h>// Example for getche() in Cint main(){ printf(\"%c\", getche()); return 0;}", "e": 27860, "s": 27747, "text": null }, { "code": null, "e": 28027, "s": 27860, "text": "Input: g(without enter key as it is not buffered)\nOutput: Program terminates immediately.\n But when you use DOS shell in Turbo C, \n double g, i.e., 'gg'" }, { "code": null, "e": 28204, "s": 28027, "text": "This article is contributed by Vankayala Karunakar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28228, "s": 28204, "text": "C-Input and Output Quiz" }, { "code": null, "e": 28243, "s": 28228, "text": "c-input-output" }, { "code": null, "e": 28254, "s": 28243, "text": "C Language" }, { "code": null, "e": 28352, "s": 28254, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28374, "s": 28352, "text": "Function Pointer in C" }, { "code": null, "e": 28391, "s": 28374, "text": "Substring in C++" }, { "code": null, "e": 28403, "s": 28391, "text": "fork() in C" }, { "code": null, "e": 28428, "s": 28403, "text": "std::string class in C++" }, { "code": null, "e": 28455, "s": 28428, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 28487, "s": 28455, "text": "Command line arguments in C/C++" }, { "code": null, "e": 28525, "s": 28487, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28572, "s": 28525, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 28588, "s": 28572, "text": "Structures in C" } ]
Structure of C++ Program - GeeksforGeeks
15 Dec, 2020 The C++ program is written using a specific template structure. The structure of the program written in C++ language is as follows: This section comes first and is used to document the logic of the program that the programmer going to code. It can be also used to write for purpose of the program. Whatever written in the documentation section is the comment and is not compiled by the compiler. Documentation Section is optional since the program can execute without them. Below is the snippet of the same: C++ /* This is a C++ program to find the factorial of a number The basic requirement for writing this program is to have knowledge of loops To find the factorial of number iterate over range from number to one*/ The linking section contains two parts: Header Files: Generally, a program includes various programming elements like built-in functions, classes, keywords, constants, operators, etc. that are already defined in the standard C++ library. In order to use such pre-defined elements in a program, an appropriate header must be included in the program. Standard headers are specified in a program through the preprocessor directive #include. In Figure, the iostream header is used. When the compiler processes the instruction #include<iostream>, it includes the contents of the stream in the program. This enables the programmer to use standard input, output, and error facilities that are provided only through the standard streams defined in <iostream>. These standard streams process data as a stream of characters, that is, data is read and displayed in a continuous flow. The standard streams defined in <iostream> are listed here. #include<iostream> Namespaces: A namespace permits grouping of various entities like classes, objects, functions, and various C++ tokens, etc. under a single name. Any user can create separate namespaces of its own and can use them in any other program. In the below snippets, namespace std contains declarations for cout, cin, endl, etc. statements. using namespace std; Namespaces can be accessed in multiple ways:using namespace std;using std :: cout; using namespace std; using std :: cout; It is used to declare some constants and assign them some value. In this section, anyone can define your own datatype using primitive data types. In #define is a compiler directive which tells the compiler whenever the message is found replace it with “Factorial\n” . typedef int K; this statement telling the compiler that whenever you will encounter K replace it by int and as you have declared k as datatype you cannot use it as an identifier. Here the variables and the class definitions which are going to be used in the program are declared to make them global. The scope of the variable declared in this section lasts until the entire program terminates. These variables are accessible within the user-defined functions also. It contains all the functions which our main functions need. Usually, this section contains the User-defined functions. This part of the program can be written after the main function but for this, write the function prototype in this section for the function which for you are going to write code after the main function. C++ // Function to implement the// factorial of number numint factorial(k& num){ // Iterate over the loop from // num to one for (k i = 1; i <= num; i++) { fact *= i; } // Return the factorial calculated return fact;} The main function tells the compiler where to start the execution of the program. The execution of the program starts with the main function. All the statements that are to be executed are written in the main function. The compiler executes all the instructions which are written in the curly braces {} which encloses the body of the main function. Once all instructions from the main function are executed control comes out of the main function and the program terminates and no further execution occur. Below is the program to illustrate this: C++ // Documentation Section/* This is a C++ program to find the factorial of a number The basic requirement for writing this program is to have knowledge of loops To find the factorial of a number iterate over the range from number to 1*/ // Linking Section#include <iostream>using namespace std; // Defination Section#define msg "FACTORIAL\n"typedef int k; // Global Declaration Sectionk num = 0, fact = 1, storeFactorial = 0; // Function Sectionk factorial(k& num){ // Iterate over the loop from // num to one for (k i = 1; i <= num; i++) { fact *= i; } // Return the factorial return fact;} // Main Functionint main(){ // Given number Num k Num = 5; // Function Call storeFactorial = factorial(Num); cout << msg; // Print the factorial cout << Num << "! = " << storeFactorial << endl; return 0;} FACTORIAL 5! = 120 Articles C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Docker - COPY Instruction Time complexities of different data structures SQL | Date functions Difference between Class and Object Vector in C++ STL Arrays in C/C++ Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL)
[ { "code": null, "e": 25666, "s": 25638, "text": "\n15 Dec, 2020" }, { "code": null, "e": 25798, "s": 25666, "text": "The C++ program is written using a specific template structure. The structure of the program written in C++ language is as follows:" }, { "code": null, "e": 25907, "s": 25798, "text": "This section comes first and is used to document the logic of the program that the programmer going to code." }, { "code": null, "e": 25964, "s": 25907, "text": "It can be also used to write for purpose of the program." }, { "code": null, "e": 26062, "s": 25964, "text": "Whatever written in the documentation section is the comment and is not compiled by the compiler." }, { "code": null, "e": 26174, "s": 26062, "text": "Documentation Section is optional since the program can execute without them. Below is the snippet of the same:" }, { "code": null, "e": 26178, "s": 26174, "text": "C++" }, { "code": "/* This is a C++ program to find the factorial of a number The basic requirement for writing this program is to have knowledge of loops To find the factorial of number iterate over range from number to one*/", "e": 26413, "s": 26178, "text": null }, { "code": null, "e": 26453, "s": 26413, "text": "The linking section contains two parts:" }, { "code": null, "e": 26467, "s": 26453, "text": "Header Files:" }, { "code": null, "e": 26651, "s": 26467, "text": "Generally, a program includes various programming elements like built-in functions, classes, keywords, constants, operators, etc. that are already defined in the standard C++ library." }, { "code": null, "e": 26762, "s": 26651, "text": "In order to use such pre-defined elements in a program, an appropriate header must be included in the program." }, { "code": null, "e": 27346, "s": 26762, "text": "Standard headers are specified in a program through the preprocessor directive #include. In Figure, the iostream header is used. When the compiler processes the instruction #include<iostream>, it includes the contents of the stream in the program. This enables the programmer to use standard input, output, and error facilities that are provided only through the standard streams defined in <iostream>. These standard streams process data as a stream of characters, that is, data is read and displayed in a continuous flow. The standard streams defined in <iostream> are listed here." }, { "code": null, "e": 27365, "s": 27346, "text": "#include<iostream>" }, { "code": null, "e": 27377, "s": 27365, "text": "Namespaces:" }, { "code": null, "e": 27510, "s": 27377, "text": "A namespace permits grouping of various entities like classes, objects, functions, and various C++ tokens, etc. under a single name." }, { "code": null, "e": 27600, "s": 27510, "text": "Any user can create separate namespaces of its own and can use them in any other program." }, { "code": null, "e": 27697, "s": 27600, "text": "In the below snippets, namespace std contains declarations for cout, cin, endl, etc. statements." }, { "code": null, "e": 27718, "s": 27697, "text": "using namespace std;" }, { "code": null, "e": 27801, "s": 27718, "text": "Namespaces can be accessed in multiple ways:using namespace std;using std :: cout;" }, { "code": null, "e": 27822, "s": 27801, "text": "using namespace std;" }, { "code": null, "e": 27841, "s": 27822, "text": "using std :: cout;" }, { "code": null, "e": 27906, "s": 27841, "text": "It is used to declare some constants and assign them some value." }, { "code": null, "e": 27987, "s": 27906, "text": "In this section, anyone can define your own datatype using primitive data types." }, { "code": null, "e": 28110, "s": 27987, "text": "In #define is a compiler directive which tells the compiler whenever the message is found replace it with “Factorial\\n” ." }, { "code": null, "e": 28289, "s": 28110, "text": "typedef int K; this statement telling the compiler that whenever you will encounter K replace it by int and as you have declared k as datatype you cannot use it as an identifier." }, { "code": null, "e": 28410, "s": 28289, "text": "Here the variables and the class definitions which are going to be used in the program are declared to make them global." }, { "code": null, "e": 28504, "s": 28410, "text": "The scope of the variable declared in this section lasts until the entire program terminates." }, { "code": null, "e": 28575, "s": 28504, "text": "These variables are accessible within the user-defined functions also." }, { "code": null, "e": 28636, "s": 28575, "text": "It contains all the functions which our main functions need." }, { "code": null, "e": 28695, "s": 28636, "text": "Usually, this section contains the User-defined functions." }, { "code": null, "e": 28898, "s": 28695, "text": "This part of the program can be written after the main function but for this, write the function prototype in this section for the function which for you are going to write code after the main function." }, { "code": null, "e": 28902, "s": 28898, "text": "C++" }, { "code": "// Function to implement the// factorial of number numint factorial(k& num){ // Iterate over the loop from // num to one for (k i = 1; i <= num; i++) { fact *= i; } // Return the factorial calculated return fact;}", "e": 29143, "s": 28902, "text": null }, { "code": null, "e": 29285, "s": 29143, "text": "The main function tells the compiler where to start the execution of the program. The execution of the program starts with the main function." }, { "code": null, "e": 29362, "s": 29285, "text": "All the statements that are to be executed are written in the main function." }, { "code": null, "e": 29492, "s": 29362, "text": "The compiler executes all the instructions which are written in the curly braces {} which encloses the body of the main function." }, { "code": null, "e": 29648, "s": 29492, "text": "Once all instructions from the main function are executed control comes out of the main function and the program terminates and no further execution occur." }, { "code": null, "e": 29689, "s": 29648, "text": "Below is the program to illustrate this:" }, { "code": null, "e": 29693, "s": 29689, "text": "C++" }, { "code": "// Documentation Section/* This is a C++ program to find the factorial of a number The basic requirement for writing this program is to have knowledge of loops To find the factorial of a number iterate over the range from number to 1*/ // Linking Section#include <iostream>using namespace std; // Defination Section#define msg \"FACTORIAL\\n\"typedef int k; // Global Declaration Sectionk num = 0, fact = 1, storeFactorial = 0; // Function Sectionk factorial(k& num){ // Iterate over the loop from // num to one for (k i = 1; i <= num; i++) { fact *= i; } // Return the factorial return fact;} // Main Functionint main(){ // Given number Num k Num = 5; // Function Call storeFactorial = factorial(Num); cout << msg; // Print the factorial cout << Num << \"! = \" << storeFactorial << endl; return 0;}", "e": 30575, "s": 29693, "text": null }, { "code": null, "e": 30595, "s": 30575, "text": "FACTORIAL\n5! = 120\n" }, { "code": null, "e": 30604, "s": 30595, "text": "Articles" }, { "code": null, "e": 30608, "s": 30604, "text": "C++" }, { "code": null, "e": 30621, "s": 30608, "text": "C++ Programs" }, { "code": null, "e": 30625, "s": 30621, "text": "CPP" }, { "code": null, "e": 30723, "s": 30625, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30760, "s": 30723, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 30786, "s": 30760, "text": "Docker - COPY Instruction" }, { "code": null, "e": 30833, "s": 30786, "text": "Time complexities of different data structures" }, { "code": null, "e": 30854, "s": 30833, "text": "SQL | Date functions" }, { "code": null, "e": 30890, "s": 30854, "text": "Difference between Class and Object" }, { "code": null, "e": 30908, "s": 30890, "text": "Vector in C++ STL" }, { "code": null, "e": 30924, "s": 30908, "text": "Arrays in C/C++" }, { "code": null, "e": 30943, "s": 30924, "text": "Inheritance in C++" }, { "code": null, "e": 30989, "s": 30943, "text": "Initialize a vector in C++ (6 different ways)" } ]
R - Waffle Chart - GeeksforGeeks
17 May, 2020 A waffle chart shows progress towards a target or a completion percentage. Waffle Charts are a great way of visualizing data in relation to a whole, to highlight progress against a given threshold, or when dealing with populations too varied for pie charts. A lot of times, these are used as an alternative to the pie charts. It also has a niche for showing parts-to-whole contribution. It doesn’t misrepresent or distort a data point (which a pie chart is sometimes guilty of doing). Waffle Charts are mainly used when composing parts of a whole, or when comparing progress against a goal. These charts usually follow other kinds of data visualization for helping the understanding of the audience. For example, you might want a Waffle Chart when plotting how the expenses of a company are composed by each type of expense, or when classifying percentages of a population at a given moment. Waffle charts are also known as Squared Pie Charts. The individual values will be summed up and each that will be the total number of squares in the grid. ggplot2 is a specialized library made to create visually pleasing data visualizations. The ggplot2 package has the capability to plot simple as well as complex graphs based on the problem statement. To install ggplot2 package in R Studio use the following command: install.packages("ggplot2") RStudio will execute the command and return the following output in the Console: Waffle is a ggplot2 extension designed to create Waffle charts with a simple syntax. To install waffle package in R Studio use the following command: install.packages("waffle") RStudio will execute the command and return the following output in the Console: Load the libraries in R Studio: library(ggplot2) library(waffle) Let’s take the dataset of 91822 persons categorized as: Infants <1 = 16467Children <11 = 30098Teens 12-17 = 20354Adults 18+ = 12456Elderly 65+ = 12456 Create a vector of data: expenses <- c(`Infants: <1(16467) `=16467, `Children: <11(30098) `=30098, `Teens: 12-17(20354)`=20354, `Adults:18+(12456) `=12456, `Elderly: 65+(12456) `=12456) Here we have created a vector with name expenses We will get the following output after the execution of this command in R Studio. Now let’s plot our waffle chart. Our parameters are the following: Plot the waffle chart: waffle(expenses/1000, rows=5, size=0.6, colors=c("#44D2AC", "#E48B8B", "#B67093", "#3A9ABD", "#CFE252"), title="Age Groups bifurcation", xlab="1 square = 1000 persons") This code will generate the following waffle chart- The waffle chart created by the following code is- R-Charts R-Graphs R-plots R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Printing Output of an R Program K-Means Clustering in R Programming
[ { "code": null, "e": 25909, "s": 25881, "text": "\n17 May, 2020" }, { "code": null, "e": 26394, "s": 25909, "text": "A waffle chart shows progress towards a target or a completion percentage. Waffle Charts are a great way of visualizing data in relation to a whole, to highlight progress against a given threshold, or when dealing with populations too varied for pie charts. A lot of times, these are used as an alternative to the pie charts. It also has a niche for showing parts-to-whole contribution. It doesn’t misrepresent or distort a data point (which a pie chart is sometimes guilty of doing)." }, { "code": null, "e": 26956, "s": 26394, "text": "Waffle Charts are mainly used when composing parts of a whole, or when comparing progress against a goal. These charts usually follow other kinds of data visualization for helping the understanding of the audience. For example, you might want a Waffle Chart when plotting how the expenses of a company are composed by each type of expense, or when classifying percentages of a population at a given moment. Waffle charts are also known as Squared Pie Charts. The individual values will be summed up and each that will be the total number of squares in the grid." }, { "code": null, "e": 27155, "s": 26956, "text": "ggplot2 is a specialized library made to create visually pleasing data visualizations. The ggplot2 package has the capability to plot simple as well as complex graphs based on the problem statement." }, { "code": null, "e": 27221, "s": 27155, "text": "To install ggplot2 package in R Studio use the following command:" }, { "code": null, "e": 27249, "s": 27221, "text": "install.packages(\"ggplot2\")" }, { "code": null, "e": 27330, "s": 27249, "text": "RStudio will execute the command and return the following output in the Console:" }, { "code": null, "e": 27415, "s": 27330, "text": "Waffle is a ggplot2 extension designed to create Waffle charts with a simple syntax." }, { "code": null, "e": 27480, "s": 27415, "text": "To install waffle package in R Studio use the following command:" }, { "code": null, "e": 27507, "s": 27480, "text": "install.packages(\"waffle\")" }, { "code": null, "e": 27588, "s": 27507, "text": "RStudio will execute the command and return the following output in the Console:" }, { "code": null, "e": 27620, "s": 27588, "text": "Load the libraries in R Studio:" }, { "code": null, "e": 27653, "s": 27620, "text": "library(ggplot2)\nlibrary(waffle)" }, { "code": null, "e": 27709, "s": 27653, "text": "Let’s take the dataset of 91822 persons categorized as:" }, { "code": null, "e": 27804, "s": 27709, "text": "Infants <1 = 16467Children <11 = 30098Teens 12-17 = 20354Adults 18+ = 12456Elderly 65+ = 12456" }, { "code": null, "e": 27830, "s": 27804, "text": " Create a vector of data:" }, { "code": "expenses <- c(`Infants: <1(16467) `=16467, `Children: <11(30098) `=30098, `Teens: 12-17(20354)`=20354, `Adults:18+(12456) `=12456, `Elderly: 65+(12456) `=12456)", "e": 28018, "s": 27830, "text": null }, { "code": null, "e": 28067, "s": 28018, "text": "Here we have created a vector with name expenses" }, { "code": null, "e": 28149, "s": 28067, "text": "We will get the following output after the execution of this command in R Studio." }, { "code": null, "e": 28216, "s": 28149, "text": "Now let’s plot our waffle chart. Our parameters are the following:" }, { "code": null, "e": 28239, "s": 28216, "text": "Plot the waffle chart:" }, { "code": "waffle(expenses/1000, rows=5, size=0.6, colors=c(\"#44D2AC\", \"#E48B8B\", \"#B67093\", \"#3A9ABD\", \"#CFE252\"), title=\"Age Groups bifurcation\", xlab=\"1 square = 1000 persons\")", "e": 28445, "s": 28239, "text": null }, { "code": null, "e": 28497, "s": 28445, "text": "This code will generate the following waffle chart-" }, { "code": null, "e": 28548, "s": 28497, "text": "The waffle chart created by the following code is-" }, { "code": null, "e": 28557, "s": 28548, "text": "R-Charts" }, { "code": null, "e": 28566, "s": 28557, "text": "R-Graphs" }, { "code": null, "e": 28574, "s": 28566, "text": "R-plots" }, { "code": null, "e": 28587, "s": 28574, "text": "R-Statistics" }, { "code": null, "e": 28598, "s": 28587, "text": "R Language" }, { "code": null, "e": 28696, "s": 28598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28754, "s": 28696, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 28806, "s": 28754, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 28838, "s": 28806, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 28882, "s": 28838, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 28934, "s": 28882, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28969, "s": 28934, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29007, "s": 28969, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29065, "s": 29007, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29097, "s": 29065, "text": "Printing Output of an R Program" } ]
max() and min() in Python - GeeksforGeeks
17 Jun, 2021 This article brings you a very interesting and lesser-known function of Python, namely max() and min(). Now when compared to their C++ counterpart, which only allows two arguments, that too strictly being float, int or char, these functions are not only limited to 2 elements, but can hold many elements as arguments and also support strings in their arguments, hence allowing to display lexicographically smallest or largest string as well. Detailed functionality are explained below. This function is used to compute the maximum of the values passed in its argument and lexicographically largest value if strings are passed as arguments. Syntax : max(a,b,c,..,key,default) Parameters : a,b,c,.. : similar type of data. key : key function where the iterables are passed and comparison is performed default : default value is passed if the given iterable is empty Return Value : Returns the maximum of all the arguments. Exceptions : Returns TypeError when conflicting types are compared. Python3 # Python code to demonstrate the working of# max() # printing the maximum of 4,12,43.3,19,100print("Maximum of 4,12,43.3,19 and 100 is : ",end="")print (max( 4,12,43.3,19,100 ) ) Output : Maximum of 4,12,43.3,19 and 100 is : 100 This function is used to compute the minimum of the values passed in its argument and lexicographically smallest value if strings are passed as arguments. Syntax : min(a,b,c,.., key,default) Parameters : a,b,c,.. : similar type of data. key : key function where the iterables are passed and comparison is performed default : default value is passed if the given iterable is empty Return Value : Returns the minimum of all the arguments. Exceptions : Returns TypeError when conflicting types are compared. Python3 # Python code to demonstrate the working of# min() # printing the minimum of 4,12,43.3,19,100print("Minimum of 4,12,43.3,19 and 100 is : ",end="")print (min( 4,12,43.3,19,100 ) ) Output : Minimum of 4,12,43.3,19 and 100 is : 4 1. TypeError : These functions throw TypeError when conflicting data types are compared. Python3 # Python code to demonstrate the Exception of# min() and max() # printing the minimum of 4,12,43.3,19, "GeeksforGeeks"# Throws Exceptionprint("Minimum of 4,12,43.3,19 and GeeksforGeeks is : ",end="")print (min( 4,12,43.3,19,"GeeksforGeeks" ) ) Output : Minimum of 4,12,43.3,19 and GeeksforGeeks is : Runtime Error : Traceback (most recent call last): File "/home/b5da1d7f834a267f94fbbefe1b31a83c.py", line 7, in print (min( 4,12,43.3,19,"GeeksforGeeks" ) ) TypeError: unorderable types: str() < int() One of the practical application among many are finding lexicographically largest and smallest of Strings i.e String appearing first in dictionary or last. Python3 # Python code to demonstrate the Application of# min() and max() # printing the word occurring 1st among these in dict.# "geeks", "manjeet", "algorithm", "programming"print("The word occurring 1st in dict. among given is : ",end="")print (min( "geeks", "manjeet", "algorithm", "programming" ) ) # printing the word occurring last among these in dict.# "geeks", "manjeet", "algorithm", "programming"print("The word occurring last in dict. among given is : ",end="")print (max( "geeks", "manjeet", "algorithm", "programming" ) ) Output : The word occurring 1st in dict. among given is : algorithm The word occurring last in dict. among given is : programming This article is contributed by Manjeet Singh. 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. shubham_singh somanyusamal clintra Python-Built-in-functions Python-Library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 26245, "s": 26217, "text": "\n17 Jun, 2021" }, { "code": null, "e": 26732, "s": 26245, "text": "This article brings you a very interesting and lesser-known function of Python, namely max() and min(). Now when compared to their C++ counterpart, which only allows two arguments, that too strictly being float, int or char, these functions are not only limited to 2 elements, but can hold many elements as arguments and also support strings in their arguments, hence allowing to display lexicographically smallest or largest string as well. Detailed functionality are explained below. " }, { "code": null, "e": 26887, "s": 26732, "text": "This function is used to compute the maximum of the values passed in its argument and lexicographically largest value if strings are passed as arguments. " }, { "code": null, "e": 27241, "s": 26887, "text": "Syntax : \nmax(a,b,c,..,key,default)\nParameters : \na,b,c,.. : similar type of data.\nkey : key function where the iterables are passed and comparison is performed\ndefault : default value is passed if the given iterable is empty\nReturn Value : \nReturns the maximum of all the arguments.\nExceptions : \nReturns TypeError when conflicting types are compared." }, { "code": null, "e": 27251, "s": 27243, "text": "Python3" }, { "code": "# Python code to demonstrate the working of# max() # printing the maximum of 4,12,43.3,19,100print(\"Maximum of 4,12,43.3,19 and 100 is : \",end=\"\")print (max( 4,12,43.3,19,100 ) )", "e": 27430, "s": 27251, "text": null }, { "code": null, "e": 27441, "s": 27430, "text": "Output : " }, { "code": null, "e": 27482, "s": 27441, "text": "Maximum of 4,12,43.3,19 and 100 is : 100" }, { "code": null, "e": 27640, "s": 27484, "text": "This function is used to compute the minimum of the values passed in its argument and lexicographically smallest value if strings are passed as arguments. " }, { "code": null, "e": 27995, "s": 27640, "text": "Syntax : \nmin(a,b,c,.., key,default)\nParameters : \na,b,c,.. : similar type of data.\nkey : key function where the iterables are passed and comparison is performed\ndefault : default value is passed if the given iterable is empty\nReturn Value : \nReturns the minimum of all the arguments.\nExceptions : \nReturns TypeError when conflicting types are compared." }, { "code": null, "e": 28005, "s": 27997, "text": "Python3" }, { "code": "# Python code to demonstrate the working of# min() # printing the minimum of 4,12,43.3,19,100print(\"Minimum of 4,12,43.3,19 and 100 is : \",end=\"\")print (min( 4,12,43.3,19,100 ) )", "e": 28184, "s": 28005, "text": null }, { "code": null, "e": 28195, "s": 28184, "text": "Output : " }, { "code": null, "e": 28234, "s": 28195, "text": "Minimum of 4,12,43.3,19 and 100 is : 4" }, { "code": null, "e": 28326, "s": 28236, "text": "1. TypeError : These functions throw TypeError when conflicting data types are compared. " }, { "code": null, "e": 28334, "s": 28326, "text": "Python3" }, { "code": "# Python code to demonstrate the Exception of# min() and max() # printing the minimum of 4,12,43.3,19, \"GeeksforGeeks\"# Throws Exceptionprint(\"Minimum of 4,12,43.3,19 and GeeksforGeeks is : \",end=\"\")print (min( 4,12,43.3,19,\"GeeksforGeeks\" ) )", "e": 28578, "s": 28334, "text": null }, { "code": null, "e": 28589, "s": 28578, "text": "Output : " }, { "code": null, "e": 28637, "s": 28589, "text": "Minimum of 4,12,43.3,19 and GeeksforGeeks is : " }, { "code": null, "e": 28655, "s": 28637, "text": "Runtime Error : " }, { "code": null, "e": 28847, "s": 28655, "text": "Traceback (most recent call last):\n File \"/home/b5da1d7f834a267f94fbbefe1b31a83c.py\", line 7, in \n print (min( 4,12,43.3,19,\"GeeksforGeeks\" ) )\nTypeError: unorderable types: str() < int()" }, { "code": null, "e": 29006, "s": 28849, "text": "One of the practical application among many are finding lexicographically largest and smallest of Strings i.e String appearing first in dictionary or last. " }, { "code": null, "e": 29014, "s": 29006, "text": "Python3" }, { "code": "# Python code to demonstrate the Application of# min() and max() # printing the word occurring 1st among these in dict.# \"geeks\", \"manjeet\", \"algorithm\", \"programming\"print(\"The word occurring 1st in dict. among given is : \",end=\"\")print (min( \"geeks\", \"manjeet\", \"algorithm\", \"programming\" ) ) # printing the word occurring last among these in dict.# \"geeks\", \"manjeet\", \"algorithm\", \"programming\"print(\"The word occurring last in dict. among given is : \",end=\"\")print (max( \"geeks\", \"manjeet\", \"algorithm\", \"programming\" ) )", "e": 29541, "s": 29014, "text": null }, { "code": null, "e": 29552, "s": 29541, "text": "Output : " }, { "code": null, "e": 29673, "s": 29552, "text": "The word occurring 1st in dict. among given is : algorithm\nThe word occurring last in dict. among given is : programming" }, { "code": null, "e": 30095, "s": 29673, "text": "This article is contributed by Manjeet Singh. 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": 30109, "s": 30095, "text": "shubham_singh" }, { "code": null, "e": 30122, "s": 30109, "text": "somanyusamal" }, { "code": null, "e": 30130, "s": 30122, "text": "clintra" }, { "code": null, "e": 30156, "s": 30130, "text": "Python-Built-in-functions" }, { "code": null, "e": 30171, "s": 30156, "text": "Python-Library" }, { "code": null, "e": 30178, "s": 30171, "text": "Python" }, { "code": null, "e": 30276, "s": 30178, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30294, "s": 30276, "text": "Python Dictionary" }, { "code": null, "e": 30326, "s": 30294, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30348, "s": 30326, "text": "Enumerate() in Python" }, { "code": null, "e": 30390, "s": 30348, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30416, "s": 30390, "text": "Python String | replace()" }, { "code": null, "e": 30445, "s": 30416, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30489, "s": 30445, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30526, "s": 30489, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30562, "s": 30526, "text": "Convert integer to string in Python" } ]
CSS to put icon inside an input element in a form - GeeksforGeeks
10 May, 2022 To add icon inside the input element the <i> tag and <span> tag are used widely to add icons on the webpages. To add any icons on the webpages or in some specific area, it needs the fontawesome link inside the head tag. The fontawesome icon can be placed by using the fa prefix before the icon’s name. fontawesome link: https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css Note: No downloading or installation is required. Example-1: html <!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> .input-icons i { position: absolute; } .input-icons { width: 100%; margin-bottom: 10px; } .icon { padding: 10px; min-width: 40px; } .input-field { width: 100%; padding: 10px; text-align: center; } </style></head> <body> <h3> Icons inside the input element </h3> <div style="max-width:400px;margin:auto"> <div class="input-icons"> <i class="fa fa-user icon"></i> <input class="input-field" type="text"> <i class="fa fa-instagram icon"></i> <input class="input-field" type="text"> <i class="fa fa-envelope icon"></i> <input class="input-field" type="text"> <i class="fa fa-youtube icon"></i> <input class="input-field" type="text"> <i class="fa fa-facebook icon"></i> <input class="input-field" type="text"> </div> </div></body> </html> Output: Example-2: html <!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> .input-icons i { position: absolute; } .input-icons { width: 100%; margin-bottom: 10px; } .icon { padding: 10px; color: green; min-width: 50px; text-align: center; } .input-field { width: 100%; padding: 10px; text-align: center; } h2 { color: green; } </style></head> <body> <center> <form style="max-width:450px;margin:auto"> <h2>GeeksforGeeks</h2> <div class="input-icons"> <i class="fa fa-user icon"> </i> <input class="input-field" type="text" placeholder="Username"> </div> <div class="input-icons"> <i class="fa fa-envelope icon"> </i> <input class="input-field" type="text" placeholder="Email"> </div> <div class="input-icons"> <i class="fa fa-key icon"> </i> <input class="input-field" type="password" placeholder="Password"> </div> </form> </center></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. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hardikkoriintern Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? How to set space between the flexbox ? Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS Form validation using jQuery How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26717, "s": 26689, "text": "\n10 May, 2022" }, { "code": null, "e": 27020, "s": 26717, "text": "To add icon inside the input element the <i> tag and <span> tag are used widely to add icons on the webpages. To add any icons on the webpages or in some specific area, it needs the fontawesome link inside the head tag. The fontawesome icon can be placed by using the fa prefix before the icon’s name. " }, { "code": null, "e": 27122, "s": 27020, "text": "fontawesome link: https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css " }, { "code": null, "e": 27173, "s": 27122, "text": "Note: No downloading or installation is required. " }, { "code": null, "e": 27185, "s": 27173, "text": "Example-1: " }, { "code": null, "e": 27190, "s": 27185, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <style> .input-icons i { position: absolute; } .input-icons { width: 100%; margin-bottom: 10px; } .icon { padding: 10px; min-width: 40px; } .input-field { width: 100%; padding: 10px; text-align: center; } </style></head> <body> <h3> Icons inside the input element </h3> <div style=\"max-width:400px;margin:auto\"> <div class=\"input-icons\"> <i class=\"fa fa-user icon\"></i> <input class=\"input-field\" type=\"text\"> <i class=\"fa fa-instagram icon\"></i> <input class=\"input-field\" type=\"text\"> <i class=\"fa fa-envelope icon\"></i> <input class=\"input-field\" type=\"text\"> <i class=\"fa fa-youtube icon\"></i> <input class=\"input-field\" type=\"text\"> <i class=\"fa fa-facebook icon\"></i> <input class=\"input-field\" type=\"text\"> </div> </div></body> </html>", "e": 28402, "s": 27190, "text": null }, { "code": null, "e": 28410, "s": 28402, "text": "Output:" }, { "code": null, "e": 28467, "s": 28455, "text": "Example-2: " }, { "code": null, "e": 28472, "s": 28467, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <style> .input-icons i { position: absolute; } .input-icons { width: 100%; margin-bottom: 10px; } .icon { padding: 10px; color: green; min-width: 50px; text-align: center; } .input-field { width: 100%; padding: 10px; text-align: center; } h2 { color: green; } </style></head> <body> <center> <form style=\"max-width:450px;margin:auto\"> <h2>GeeksforGeeks</h2> <div class=\"input-icons\"> <i class=\"fa fa-user icon\"> </i> <input class=\"input-field\" type=\"text\" placeholder=\"Username\"> </div> <div class=\"input-icons\"> <i class=\"fa fa-envelope icon\"> </i> <input class=\"input-field\" type=\"text\" placeholder=\"Email\"> </div> <div class=\"input-icons\"> <i class=\"fa fa-key icon\"> </i> <input class=\"input-field\" type=\"password\" placeholder=\"Password\"> </div> </form> </center></body> </html>", "e": 30002, "s": 28472, "text": null }, { "code": null, "e": 30010, "s": 30002, "text": "Output:" }, { "code": null, "e": 30257, "s": 30070, "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": 30394, "s": 30257, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 30411, "s": 30394, "text": "hardikkoriintern" }, { "code": null, "e": 30418, "s": 30411, "text": "Picked" }, { "code": null, "e": 30422, "s": 30418, "text": "CSS" }, { "code": null, "e": 30427, "s": 30422, "text": "HTML" }, { "code": null, "e": 30444, "s": 30427, "text": "Web Technologies" }, { "code": null, "e": 30449, "s": 30444, "text": "HTML" }, { "code": null, "e": 30547, "s": 30449, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30602, "s": 30547, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 30641, "s": 30602, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 30678, "s": 30641, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30719, "s": 30678, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 30748, "s": 30719, "text": "Form validation using jQuery" }, { "code": null, "e": 30808, "s": 30748, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30861, "s": 30808, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 30922, "s": 30861, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 30946, "s": 30922, "text": "REST API (Introduction)" } ]
CSS | #id Selector - GeeksforGeeks
03 Jan, 2019 The #id selector is used to set the style of given id. The id attribute is the unique identifier in HTML document. The id selector is used with # character. Syntax: #id { // CSS property } Example: <!DOCTYPE html><html> <head> <title>#id selector</title> <!-- CSS property using id attribute --> <style> #gfg1 { color:green; text-align:center; } #gfg2 { text-align:center; } </style> </head> <body> <!-- id attribute declare here --> <h1 id = "gfg1">GeeksforGeeks</h1> <h2 id = "gfg2">#id selector</h2> </body></html> Output: Supported Browsers: The browser supported by id selector are listed below: Google Chrome Internet Explorer Firefox Safari Opera CSS-Selectors Picked Technical Scripter 2018 CSS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 29316, "s": 29288, "text": "\n03 Jan, 2019" }, { "code": null, "e": 29473, "s": 29316, "text": "The #id selector is used to set the style of given id. The id attribute is the unique identifier in HTML document. The id selector is used with # character." }, { "code": null, "e": 29481, "s": 29473, "text": "Syntax:" }, { "code": null, "e": 29509, "s": 29481, "text": "#id {\n // CSS property\n}" }, { "code": null, "e": 29518, "s": 29509, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>#id selector</title> <!-- CSS property using id attribute --> <style> #gfg1 { color:green; text-align:center; } #gfg2 { text-align:center; } </style> </head> <body> <!-- id attribute declare here --> <h1 id = \"gfg1\">GeeksforGeeks</h1> <h2 id = \"gfg2\">#id selector</h2> </body></html>", "e": 30014, "s": 29518, "text": null }, { "code": null, "e": 30022, "s": 30014, "text": "Output:" }, { "code": null, "e": 30097, "s": 30022, "text": "Supported Browsers: The browser supported by id selector are listed below:" }, { "code": null, "e": 30111, "s": 30097, "text": "Google Chrome" }, { "code": null, "e": 30129, "s": 30111, "text": "Internet Explorer" }, { "code": null, "e": 30137, "s": 30129, "text": "Firefox" }, { "code": null, "e": 30144, "s": 30137, "text": "Safari" }, { "code": null, "e": 30150, "s": 30144, "text": "Opera" }, { "code": null, "e": 30164, "s": 30150, "text": "CSS-Selectors" }, { "code": null, "e": 30171, "s": 30164, "text": "Picked" }, { "code": null, "e": 30195, "s": 30171, "text": "Technical Scripter 2018" }, { "code": null, "e": 30199, "s": 30195, "text": "CSS" }, { "code": null, "e": 30218, "s": 30199, "text": "Technical Scripter" }, { "code": null, "e": 30235, "s": 30218, "text": "Web Technologies" }, { "code": null, "e": 30333, "s": 30235, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30383, "s": 30333, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 30445, "s": 30383, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30493, "s": 30445, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 30551, "s": 30493, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 30606, "s": 30551, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 30646, "s": 30606, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30679, "s": 30646, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30724, "s": 30679, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30767, "s": 30724, "text": "How to fetch data from an API in ReactJS ?" } ]
Check if given string can be formed by two other strings or their permutations - GeeksforGeeks
08 Jun, 2021 Given a string str and an array of strings arr[], the task is to check if the given string can be formed by any of the string pairs from the array or their permutations. Examples: Input: str = “amazon”, arr[] = {“loa”, “azo”, “ft”, “amn”, “lka”} Output: Yes The chosen strings are “amn” and “azo” which can be rearranged as “amazon”. Input: str = “geeksforgeeks”, arr[] = {“geeks”, “geek”, “for”} Output: No Method 1: We sort the given string first, then run two nested loops and select two strings from the given array at a time and concatenate them and then sort the resultant string. After sorting, we check if it is equal to our given sorted string. Hence, overall time complexity will be O(n * mlogm) where n is the size of the given array and m is the length of the strings (maximum). Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorbool isPossible(vector<string> v, string str){ // Sort the given string sort(str.begin(), str.end()); // Select two strings at a time from given vector for (int i = 0; i < v.size() - 1; i++) { for (int j = i + 1; j < v.size(); j++) { // Get the concatenated string string temp = v[i] + v[j]; // Sort the resultant string sort(temp.begin(), temp.end()); // If the resultant string is equal // to the given string str if (temp.compare(str) == 0) { return true; } } } // No valid pair found return false;} // Driver codeint main(){ string str = "amazon"; vector<string> v{ "fds", "oxq", "zoa", "epw", "amn" }; if (isPossible(v, str)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorstatic boolean isPossible(Vector<String> v, String str){ // Sort the given string str = sortString(str); // Select two strings at a time from given vector for (int i = 0; i < v.size() - 1; i++) { for (int j = i + 1; j < v.size(); j++) { // Get the concatenated string String temp = v.get(i) + v.get(j); // Sort the resultant string temp = sortString(temp); // If the resultant string is equal // to the given string str if (temp.compareTo(str) == 0) { return true; } } } // No valid pair found return false;} // Method to sort a string alphabeticallypublic static String sortString(String inputString){ // convert input string to char array char tempArray[] = inputString.toCharArray(); // sort tempArray Arrays.sort(tempArray); // return new sorted string return new String(tempArray);} // Driver codepublic static void main(String[] args){ String str = "amazon"; String []arr = { "fds", "oxq", "zoa", "epw", "amn" }; Vector<String> v = new Vector<String>(Arrays.asList(arr)); if (isPossible(v, str)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by Rajput-Ji # Python3 implementation of the approach # Function that returns true if str can be# generated from any permutation of the# two strings selected from the given vectordef isPossible(v, string ) : char_list = list(string) # Sort the given string char_list.sort() # Select two strings at a time from given vector for i in range(len(v)-1) : for j in range(len(v)) : # Get the concatenated string temp = v[i] + v[j]; # Sort the resultant string temp_list = list(temp) temp_list.sort() # If the resultant string is equal # to the given string str if (temp_list == char_list) : return True; # No valid pair found return False; # Driver codeif __name__ == "__main__" : string = "amazon"; v = [ "fds", "oxq", "zoa", "epw", "amn" ]; if (isPossible(v, string)): print("Yes"); else : print("No"); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorstatic Boolean isPossible(List<String> v, String str){ // Sort the given string str = sortString(str); // Select two strings at a time from given vector for (int i = 0; i <v.Count - 1; i++) { for (int j = i + 1; j <v.Count; j++) { // Get the concatenated string String temp = v[i] + v[j]; // Sort the resultant string temp = sortString(temp); // If the resultant string is equal // to the given string str if (temp.CompareTo(str) == 0) { return true; } } } // No valid pair found return false;} // Method to sort a string alphabeticallypublic static String sortString(String inputString){ // convert input string to char array char []tempArray = inputString.ToCharArray(); // sort tempArray Array.Sort(tempArray); // return new sorted string return new String(tempArray);} // Driver codepublic static void Main(String[] args){ String str = "amazon"; String []arr = { "fds", "oxq", "zoa", "epw", "amn" }; List<String> v = new List<String>(arr); if (isPossible(v, str)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by Princi Singh <script> // Javascript implementation of the approach // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorfunction isPossible(v, str){ // Sort the given string str = str.split('').sort().join(''); // Select two strings at a time from given vector for (var i = 0; i < v.length - 1; i++) { for (var j = i + 1; j < v.length; j++) { // Get the concatenated string var temp = v[i] + v[j]; // Sort the resultant string temp = temp.split('').sort().join(''); // If the resultant string is equal // to the given string str if (temp === (str)) { return true; } } } // No valid pair found return false;} // Driver codevar str = "amazon";var v = ["fds", "oxq", "zoa", "epw", "amn"];if (isPossible(v, str)) document.write( "Yes");else document.write( "No"); </script> Yes Method 2: Counting sort can be used to reduce the running time of the above approach. Counting sort uses a table to store the count of each character. We have 26 alphabets, hence we make an array of size 26 to store counts of each character in the string. Then take the characters in increasing order to get the sorted string. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define MAX 26 // Function to sort the given string// using counting sortvoid countingsort(string& s){ // Array to store the count of each character int count[MAX] = { 0 }; for (int i = 0; i < s.length(); i++) { count[s[i] - 'a']++; } int index = 0; // Insert characters in the string // in increasing order for (int i = 0; i < MAX; i++) { int j = 0; while (j < count[i]) { s[index++] = i + 'a'; j++; } }} // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorbool isPossible(vector<string> v, string str){ // Sort the given string countingsort(str); // Select two strings at a time from given vector for (int i = 0; i < v.size() - 1; i++) { for (int j = i + 1; j < v.size(); j++) { // Get the concatenated string string temp = v[i] + v[j]; // Sort the resultant string countingsort(temp); // If the resultant string is equal // to the given string str if (temp.compare(str) == 0) { return true; } } } // No valid pair found return false;} // Driver codeint main(){ string str = "amazon"; vector<string> v{ "fds", "oxq", "zoa", "epw", "amn" }; if (isPossible(v, str)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation of the approachimport java.util.*; class GFG{static int MAX = 26; // Function to sort the given string// using counting sortstatic String countingsort(char[] s){ // Array to store the count of each character int []count = new int[MAX]; for (int i = 0; i < s.length; i++) { count[s[i] - 'a']++; } int index = 0; // Insert characters in the string // in increasing order for (int i = 0; i < MAX; i++) { int j = 0; while (j < count[i]) { s[index++] = (char)(i + 'a'); j++; } } return String.valueOf(s);} // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorstatic boolean isPossible(Vector<String> v, String str){ // Sort the given string str=countingsort(str.toCharArray()); // Select two strings at a time from given vector for (int i = 0; i < v.size() - 1; i++) { for (int j = i + 1; j < v.size(); j++) { // Get the concatenated string String temp = v.get(i) + v.get(j); // Sort the resultant string temp = countingsort(temp.toCharArray()); // If the resultant string is equal // to the given string str if (temp.equals(str)) { return true; } } } // No valid pair found return false;} // Driver codepublic static void main(String[] args){ String str = "amazon"; String []arr = { "fds", "oxq", "zoa", "epw", "amn" }; Vector<String> v = new Vector<String>(Arrays.asList(arr)); if (isPossible(v, str)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by 29AjayKumar # Python 3 implementation of the approachMAX = 26 # Function to sort the given string# using counting sortdef countingsort(s): # Array to store the count of each character count = [0 for i in range(MAX)] for i in range(len(s)): count[ord(s[i]) - ord('a')] += 1 index = 0 # Insert characters in the string # in increasing order for i in range(MAX): j = 0 while (j < count[i]): s = s.replace(s[index],chr(97+i)) index += 1 j += 1 # Function that returns true if str can be# generated from any permutation of the# two strings selected from the given vectordef isPossible(v, str1): # Sort the given string countingsort(str1); # Select two strings at a time from given vector for i in range(len(v)-1): for j in range(i + 1,len(v),1): # Get the concatenated string temp = v[i] + v[j] # Sort the resultant string countingsort(temp) # If the resultant string is equal # to the given string str if (temp == str1): return False # No valid pair found return True # Driver codeif __name__ == '__main__': str1 = "amazon" v = ["fds", "oxq", "zoa", "epw", "amn"] if (isPossible(v, str1)): print("Yes") else: print("No") # This code is contributed by# Surendra_Gangwar // C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{static int MAX = 26; // Function to sort the given string// using counting sortstatic String countingsort(char[] s){ // Array to store the count of each character int []count = new int[MAX]; for (int i = 0; i < s.Length; i++) { count[s[i] - 'a']++; } int index = 0; // Insert characters in the string // in increasing order for (int i = 0; i < MAX; i++) { int j = 0; while (j < count[i]) { s[index++] = (char)(i + 'a'); j++; } } return String.Join("", s);} // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorstatic Boolean isPossible(List<String> v, String str){ // Sort the given string str = countingsort(str.ToCharArray()); // Select two strings at a time from given vector for (int i = 0; i < v.Count - 1; i++) { for (int j = i + 1; j < v.Count; j++) { // Get the concatenated string String temp = v[i] + v[j]; // Sort the resultant string temp = countingsort(temp.ToCharArray()); // If the resultant string is equal // to the given string str if (temp.Equals(str)) { return true; } } } // No valid pair found return false;} // Driver codepublic static void Main(String[] args){ String str = "amazon"; String []arr = { "fds", "oxq", "zoa", "epw", "amn" }; List<String> v = new List<String>(arr); if (isPossible(v, str)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of the approach let MAX = 26; // Function to sort the given string // using counting sort function countingsort(s) { // Array to store the count of each character let count = new Array(MAX); count.fill(0); for (let i = 0; i < s.length; i++) { count[s[i].charCodeAt() - 'a'.charCodeAt()]++; } let index = 0; // Insert characters in the string // in increasing order for (let i = 0; i < MAX; i++) { let j = 0; while (j < count[i]) { s[index++] = String.fromCharCode(i + 'a'.charCodeAt()); j++; } } return s.join(""); } // Function that returns true if str can be // generated from any permutation of the // two strings selected from the given vector function isPossible(v, str) { // Sort the given string str = countingsort(str.split('')); // Select two strings at a time from given vector for (let i = 0; i < v.length - 1; i++) { for (let j = i + 1; j < v.length; j++) { // Get the concatenated string let temp = v[i] + v[j]; // Sort the resultant string temp = countingsort(temp.split('')); // If the resultant string is equal // to the given string str if (temp == str) { return true; } } } // No valid pair found return false; } let str = "amazon"; let v = [ "fds", "oxq", "zoa", "epw", "amn" ]; if (isPossible(v, str)) document.write("Yes"); else document.write("No"); </script> Yes Rajput-Ji ankthon SURENDRA_GANGWAR princi singh 29AjayKumar princiraj1992 rutvik_56 divyeshrabadiya07 counting-sort Arrays Searching Sorting Strings Arrays Searching Strings Sorting 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 Introduction to Arrays Multidimensional Arrays in Java Linear Search Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 26657, "s": 26629, "text": "\n08 Jun, 2021" }, { "code": null, "e": 26827, "s": 26657, "text": "Given a string str and an array of strings arr[], the task is to check if the given string can be formed by any of the string pairs from the array or their permutations." }, { "code": null, "e": 26838, "s": 26827, "text": "Examples: " }, { "code": null, "e": 26992, "s": 26838, "text": "Input: str = “amazon”, arr[] = {“loa”, “azo”, “ft”, “amn”, “lka”} Output: Yes The chosen strings are “amn” and “azo” which can be rearranged as “amazon”." }, { "code": null, "e": 27068, "s": 26992, "text": "Input: str = “geeksforgeeks”, arr[] = {“geeks”, “geek”, “for”} Output: No " }, { "code": null, "e": 27451, "s": 27068, "text": "Method 1: We sort the given string first, then run two nested loops and select two strings from the given array at a time and concatenate them and then sort the resultant string. After sorting, we check if it is equal to our given sorted string. Hence, overall time complexity will be O(n * mlogm) where n is the size of the given array and m is the length of the strings (maximum)." }, { "code": null, "e": 27503, "s": 27451, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27507, "s": 27503, "text": "C++" }, { "code": null, "e": 27512, "s": 27507, "text": "Java" }, { "code": null, "e": 27520, "s": 27512, "text": "Python3" }, { "code": null, "e": 27523, "s": 27520, "text": "C#" }, { "code": null, "e": 27534, "s": 27523, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorbool isPossible(vector<string> v, string str){ // Sort the given string sort(str.begin(), str.end()); // Select two strings at a time from given vector for (int i = 0; i < v.size() - 1; i++) { for (int j = i + 1; j < v.size(); j++) { // Get the concatenated string string temp = v[i] + v[j]; // Sort the resultant string sort(temp.begin(), temp.end()); // If the resultant string is equal // to the given string str if (temp.compare(str) == 0) { return true; } } } // No valid pair found return false;} // Driver codeint main(){ string str = \"amazon\"; vector<string> v{ \"fds\", \"oxq\", \"zoa\", \"epw\", \"amn\" }; if (isPossible(v, str)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 28595, "s": 27534, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorstatic boolean isPossible(Vector<String> v, String str){ // Sort the given string str = sortString(str); // Select two strings at a time from given vector for (int i = 0; i < v.size() - 1; i++) { for (int j = i + 1; j < v.size(); j++) { // Get the concatenated string String temp = v.get(i) + v.get(j); // Sort the resultant string temp = sortString(temp); // If the resultant string is equal // to the given string str if (temp.compareTo(str) == 0) { return true; } } } // No valid pair found return false;} // Method to sort a string alphabeticallypublic static String sortString(String inputString){ // convert input string to char array char tempArray[] = inputString.toCharArray(); // sort tempArray Arrays.sort(tempArray); // return new sorted string return new String(tempArray);} // Driver codepublic static void main(String[] args){ String str = \"amazon\"; String []arr = { \"fds\", \"oxq\", \"zoa\", \"epw\", \"amn\" }; Vector<String> v = new Vector<String>(Arrays.asList(arr)); if (isPossible(v, str)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by Rajput-Ji", "e": 30118, "s": 28595, "text": null }, { "code": "# Python3 implementation of the approach # Function that returns true if str can be# generated from any permutation of the# two strings selected from the given vectordef isPossible(v, string ) : char_list = list(string) # Sort the given string char_list.sort() # Select two strings at a time from given vector for i in range(len(v)-1) : for j in range(len(v)) : # Get the concatenated string temp = v[i] + v[j]; # Sort the resultant string temp_list = list(temp) temp_list.sort() # If the resultant string is equal # to the given string str if (temp_list == char_list) : return True; # No valid pair found return False; # Driver codeif __name__ == \"__main__\" : string = \"amazon\"; v = [ \"fds\", \"oxq\", \"zoa\", \"epw\", \"amn\" ]; if (isPossible(v, string)): print(\"Yes\"); else : print(\"No\"); # This code is contributed by AnkitRai01", "e": 31182, "s": 30118, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorstatic Boolean isPossible(List<String> v, String str){ // Sort the given string str = sortString(str); // Select two strings at a time from given vector for (int i = 0; i <v.Count - 1; i++) { for (int j = i + 1; j <v.Count; j++) { // Get the concatenated string String temp = v[i] + v[j]; // Sort the resultant string temp = sortString(temp); // If the resultant string is equal // to the given string str if (temp.CompareTo(str) == 0) { return true; } } } // No valid pair found return false;} // Method to sort a string alphabeticallypublic static String sortString(String inputString){ // convert input string to char array char []tempArray = inputString.ToCharArray(); // sort tempArray Array.Sort(tempArray); // return new sorted string return new String(tempArray);} // Driver codepublic static void Main(String[] args){ String str = \"amazon\"; String []arr = { \"fds\", \"oxq\", \"zoa\", \"epw\", \"amn\" }; List<String> v = new List<String>(arr); if (isPossible(v, str)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by Princi Singh", "e": 32697, "s": 31182, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorfunction isPossible(v, str){ // Sort the given string str = str.split('').sort().join(''); // Select two strings at a time from given vector for (var i = 0; i < v.length - 1; i++) { for (var j = i + 1; j < v.length; j++) { // Get the concatenated string var temp = v[i] + v[j]; // Sort the resultant string temp = temp.split('').sort().join(''); // If the resultant string is equal // to the given string str if (temp === (str)) { return true; } } } // No valid pair found return false;} // Driver codevar str = \"amazon\";var v = [\"fds\", \"oxq\", \"zoa\", \"epw\", \"amn\"];if (isPossible(v, str)) document.write( \"Yes\");else document.write( \"No\"); </script>", "e": 33680, "s": 32697, "text": null }, { "code": null, "e": 33684, "s": 33680, "text": "Yes" }, { "code": null, "e": 34013, "s": 33686, "text": "Method 2: Counting sort can be used to reduce the running time of the above approach. Counting sort uses a table to store the count of each character. We have 26 alphabets, hence we make an array of size 26 to store counts of each character in the string. Then take the characters in increasing order to get the sorted string." }, { "code": null, "e": 34065, "s": 34013, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 34069, "s": 34065, "text": "C++" }, { "code": null, "e": 34074, "s": 34069, "text": "Java" }, { "code": null, "e": 34082, "s": 34074, "text": "Python3" }, { "code": null, "e": 34085, "s": 34082, "text": "C#" }, { "code": null, "e": 34096, "s": 34085, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define MAX 26 // Function to sort the given string// using counting sortvoid countingsort(string& s){ // Array to store the count of each character int count[MAX] = { 0 }; for (int i = 0; i < s.length(); i++) { count[s[i] - 'a']++; } int index = 0; // Insert characters in the string // in increasing order for (int i = 0; i < MAX; i++) { int j = 0; while (j < count[i]) { s[index++] = i + 'a'; j++; } }} // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorbool isPossible(vector<string> v, string str){ // Sort the given string countingsort(str); // Select two strings at a time from given vector for (int i = 0; i < v.size() - 1; i++) { for (int j = i + 1; j < v.size(); j++) { // Get the concatenated string string temp = v[i] + v[j]; // Sort the resultant string countingsort(temp); // If the resultant string is equal // to the given string str if (temp.compare(str) == 0) { return true; } } } // No valid pair found return false;} // Driver codeint main(){ string str = \"amazon\"; vector<string> v{ \"fds\", \"oxq\", \"zoa\", \"epw\", \"amn\" }; if (isPossible(v, str)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 35617, "s": 34096, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{static int MAX = 26; // Function to sort the given string// using counting sortstatic String countingsort(char[] s){ // Array to store the count of each character int []count = new int[MAX]; for (int i = 0; i < s.length; i++) { count[s[i] - 'a']++; } int index = 0; // Insert characters in the string // in increasing order for (int i = 0; i < MAX; i++) { int j = 0; while (j < count[i]) { s[index++] = (char)(i + 'a'); j++; } } return String.valueOf(s);} // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorstatic boolean isPossible(Vector<String> v, String str){ // Sort the given string str=countingsort(str.toCharArray()); // Select two strings at a time from given vector for (int i = 0; i < v.size() - 1; i++) { for (int j = i + 1; j < v.size(); j++) { // Get the concatenated string String temp = v.get(i) + v.get(j); // Sort the resultant string temp = countingsort(temp.toCharArray()); // If the resultant string is equal // to the given string str if (temp.equals(str)) { return true; } } } // No valid pair found return false;} // Driver codepublic static void main(String[] args){ String str = \"amazon\"; String []arr = { \"fds\", \"oxq\", \"zoa\", \"epw\", \"amn\" }; Vector<String> v = new Vector<String>(Arrays.asList(arr)); if (isPossible(v, str)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by 29AjayKumar", "e": 37447, "s": 35617, "text": null }, { "code": "# Python 3 implementation of the approachMAX = 26 # Function to sort the given string# using counting sortdef countingsort(s): # Array to store the count of each character count = [0 for i in range(MAX)] for i in range(len(s)): count[ord(s[i]) - ord('a')] += 1 index = 0 # Insert characters in the string # in increasing order for i in range(MAX): j = 0 while (j < count[i]): s = s.replace(s[index],chr(97+i)) index += 1 j += 1 # Function that returns true if str can be# generated from any permutation of the# two strings selected from the given vectordef isPossible(v, str1): # Sort the given string countingsort(str1); # Select two strings at a time from given vector for i in range(len(v)-1): for j in range(i + 1,len(v),1): # Get the concatenated string temp = v[i] + v[j] # Sort the resultant string countingsort(temp) # If the resultant string is equal # to the given string str if (temp == str1): return False # No valid pair found return True # Driver codeif __name__ == '__main__': str1 = \"amazon\" v = [\"fds\", \"oxq\", \"zoa\", \"epw\", \"amn\"] if (isPossible(v, str1)): print(\"Yes\") else: print(\"No\") # This code is contributed by# Surendra_Gangwar", "e": 38850, "s": 37447, "text": null }, { "code": "// C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{static int MAX = 26; // Function to sort the given string// using counting sortstatic String countingsort(char[] s){ // Array to store the count of each character int []count = new int[MAX]; for (int i = 0; i < s.Length; i++) { count[s[i] - 'a']++; } int index = 0; // Insert characters in the string // in increasing order for (int i = 0; i < MAX; i++) { int j = 0; while (j < count[i]) { s[index++] = (char)(i + 'a'); j++; } } return String.Join(\"\", s);} // Function that returns true if str can be// generated from any permutation of the// two strings selected from the given vectorstatic Boolean isPossible(List<String> v, String str){ // Sort the given string str = countingsort(str.ToCharArray()); // Select two strings at a time from given vector for (int i = 0; i < v.Count - 1; i++) { for (int j = i + 1; j < v.Count; j++) { // Get the concatenated string String temp = v[i] + v[j]; // Sort the resultant string temp = countingsort(temp.ToCharArray()); // If the resultant string is equal // to the given string str if (temp.Equals(str)) { return true; } } } // No valid pair found return false;} // Driver codepublic static void Main(String[] args){ String str = \"amazon\"; String []arr = { \"fds\", \"oxq\", \"zoa\", \"epw\", \"amn\" }; List<String> v = new List<String>(arr); if (isPossible(v, str)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by PrinciRaj1992", "e": 40710, "s": 38850, "text": null }, { "code": "<script> // Javascript implementation of the approach let MAX = 26; // Function to sort the given string // using counting sort function countingsort(s) { // Array to store the count of each character let count = new Array(MAX); count.fill(0); for (let i = 0; i < s.length; i++) { count[s[i].charCodeAt() - 'a'.charCodeAt()]++; } let index = 0; // Insert characters in the string // in increasing order for (let i = 0; i < MAX; i++) { let j = 0; while (j < count[i]) { s[index++] = String.fromCharCode(i + 'a'.charCodeAt()); j++; } } return s.join(\"\"); } // Function that returns true if str can be // generated from any permutation of the // two strings selected from the given vector function isPossible(v, str) { // Sort the given string str = countingsort(str.split('')); // Select two strings at a time from given vector for (let i = 0; i < v.length - 1; i++) { for (let j = i + 1; j < v.length; j++) { // Get the concatenated string let temp = v[i] + v[j]; // Sort the resultant string temp = countingsort(temp.split('')); // If the resultant string is equal // to the given string str if (temp == str) { return true; } } } // No valid pair found return false; } let str = \"amazon\"; let v = [ \"fds\", \"oxq\", \"zoa\", \"epw\", \"amn\" ]; if (isPossible(v, str)) document.write(\"Yes\"); else document.write(\"No\"); </script>", "e": 42539, "s": 40710, "text": null }, { "code": null, "e": 42543, "s": 42539, "text": "Yes" }, { "code": null, "e": 42555, "s": 42545, "text": "Rajput-Ji" }, { "code": null, "e": 42563, "s": 42555, "text": "ankthon" }, { "code": null, "e": 42580, "s": 42563, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 42593, "s": 42580, "text": "princi singh" }, { "code": null, "e": 42605, "s": 42593, "text": "29AjayKumar" }, { "code": null, "e": 42619, "s": 42605, "text": "princiraj1992" }, { "code": null, "e": 42629, "s": 42619, "text": "rutvik_56" }, { "code": null, "e": 42647, "s": 42629, "text": "divyeshrabadiya07" }, { "code": null, "e": 42661, "s": 42647, "text": "counting-sort" }, { "code": null, "e": 42668, "s": 42661, "text": "Arrays" }, { "code": null, "e": 42678, "s": 42668, "text": "Searching" }, { "code": null, "e": 42686, "s": 42678, "text": "Sorting" }, { "code": null, "e": 42694, "s": 42686, "text": "Strings" }, { "code": null, "e": 42701, "s": 42694, "text": "Arrays" }, { "code": null, "e": 42711, "s": 42701, "text": "Searching" }, { "code": null, "e": 42719, "s": 42711, "text": "Strings" }, { "code": null, "e": 42727, "s": 42719, "text": "Sorting" }, { "code": null, "e": 42825, "s": 42727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42893, "s": 42825, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 42937, "s": 42893, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 42960, "s": 42937, "text": "Introduction to Arrays" }, { "code": null, "e": 42992, "s": 42960, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 43006, "s": 42992, "text": "Linear Search" }, { "code": null, "e": 43020, "s": 43006, "text": "Binary Search" }, { "code": null, "e": 43088, "s": 43020, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 43102, "s": 43088, "text": "Linear Search" }, { "code": null, "e": 43150, "s": 43102, "text": "Search an element in a sorted and rotated array" } ]
How to Create Horizontal and Vertical Tabs using JavaScript ? - GeeksforGeeks
18 Nov, 2020 Tabs can be used for displaying large amounts of content on a single page in an organized manner. We can design single page tabs using HTML, CSS, and JavaScript. HTML elements are used to design the structure of the tabs and their content in paragraphs. The styling is performed using CSS. On the click of each tab button, the tabs display their respective content. This is done using JavaScript. Horizontal Tabs: The following code demonstrates the simple HTML structure with tabs and its contents in the form of a paragraph. On click of each tab, it calls the displayContent() method implemented in the “script.js” file given below. HTML Code: HTML <!DOCTYPE html><html> <head> <link rel="stylesheet" href="style.css"> <script src="script.js"></script></head> <body> <h2 style="color:green"> GeeksforGeeks Horizontal tabs </h2> <!-- Link to each tab with onclick event --> <div id="tabsDiv"> <button class="linkClass" onclick= "displayContent(event, 'interview')"> Interview </button> <button class="linkClass" onclick= "displayContent(event, 'practice')"> Practice </button> <button class="linkClass" onclick= "displayContent(event, 'python')"> Python </button> <button class="linkClass" onclick= "displayContent(event, 'algorithms')"> Algorithms </button> <button class="linkClass" onclick= "displayContent(event, 'machine')"> Machine Learning </button> </div> <!-- Content for each HTML tab --> <div id="interview" class="contentClass"> <h3>Interview</h3> <p> Also, in Asymptotic analysis, we always talk about input sizes larger than a constant value. It might be possible that those large inputs are never given to your software and an algorithm which is asymptotically slower, always performs better for your particular situation. So, you may end up choosing an algorithm that is Asymptotically slower but faster for your software. </p> </div> <div id="practice" class="contentClass"> <h3>Practice</h3> <p> Asymptotic Analysis is the big idea that handles above issues in analyzing algorithms. In Asymptotic Analysis, we evaluate the performance of an algorithm in terms of input size (we don’t measure the actual running time). We calculate, how does the time (or space) taken by an algorithm increases with the input size. </p> </div> <div id="python" class="contentClass"> <h3>Python</h3> <p> Python is a high-level, general-purpose and a very popular programming language. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting edge technology in Software Industry. Python Programming Language is very well suited for Beginners, also for experienced programmers with other programming languages like C++ and Java. </p> </div> <div id="algorithms" class="contentClass"> <h3>Greedy Algorithms</h3> <p> Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. So the problems where choosing locally optimal also leads to global solution are best fit for Greedy. </p> </div> <div id="machine" class="contentClass"> <h3>Machine Learning</h3> <p> Machine Learning is the field of study that gives computers the capability to learn without being explicitly programmed. ML is one of the most exciting technologies that one would have ever come across. As it is evident from the name, it gives the computer that makes it more similar to humans: The ability to learn. Machine learning is actively being used today, perhaps in many more places than one would expect. </p> </div></body> </html> CSS Code: The following code is of the “style.css” file that is used for the styling of the page and the tabs. css <style> h3 { text-align: left; } /* Button to open the content */ .linkclass { float: left; cursor: pointer; padding: 10px 15px 10px 10px; background-color: light-grey; } /* Button styling on mouse hover */ #tabsDiv a:hover { color: black; background-color: #e9e9e9; font-size: 16px; } /* Change the color of the button */ button.active { background-color: #c0c0c0; } /* Content for button tabs*/ .contentClass { display: none; padding: 10px 16px; border: 2px solid #c0c0c0; }</style> JavaScript Code: The following code contains the functionality of tabs using JavaScript. Javascript function displayContent(event, contentNameID) { let content = document.getElementsByClassName("contentClass"); let totalCount = content.length; // Loop through the content class // and hide the tabs first for (let count = 0; count < totalCount; count++) { content[count].style.display = "none"; } let links = document.getElementsByClassName("linkClass"); totalLinks = links.length; // Loop through the links and // remove the active class for (let count = 0; count < totalLinks; count++) { links[count].classList.remove("active"); } // Display the current tab document.getElementById(contentNameID) .style.display = "block"; // Add the active class to the current tab event.currentTarget.classList.add("active");} Output: Vertical Tabs: The tabs can be made vertical by changing the HTML structure and replacing the CSS stylesheet with a modified one used for the vertical tabs design. The following code demonstrates the vertical tabs. HTML code: HTML <!DOCTYPE html><html> <head> <link rel="stylesheet" href="vstyle.css"> <script src="script.js"></script></head> <body> <h2 style="color:green"> GeeksforGeeks Vertical tabs </h2> <div id="tabsDiv"> <div id="interview" class="contentClass"> <h3>Interview</h3> <p> Also, in Asymptotic analysis, we always talk about input sizes larger than a constant value. It might be possible that those large inputs are never given to your software and an algorithm which is asymptotically slower, always performs better for your particular situation. So, you may end up choosing an algorithm that is Asymptotically slower but faster for your software. </p> </div> <div id="practice" class="contentClass"> <h3>Practice</h3> <p> Asymptotic Analysis is the big idea that handles above issues in analyzing algorithms. In Asymptotic Analysis, we evaluate the performance of an algorithm in terms of input size (we don’t measure the actual running time). We calculate, how does the time (or space) taken by an algorithm increases with the input size. </p> </div> <div id="python" class="contentClass"> <h3>Python</h3> <p> Python is a high-level, general-purpose and a very popular programming language. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting edge technology in Software Industry. Python Programming Language is very well suited for Beginners, also for experienced programmers with other programming languages like C++ and Java. </p> </div> <div id="algorithms" class="contentClass"> <h3>Greedy Algorithms</h3> <p> Greedy is an algorithmic paradigm that builds up a solution piece by piece,always choosing the next piece that offers the most obvious and immediate benefit. So the problems where choosing locally optimal also leads to global solution are best fit for Greedy. </p> </div> <ul class="ulClass" style="height:300px"> <li style="list-style-type:none;"> <button class="linkClass" onclick= "displayContent(event, 'interview')"> Interview </button> </li> <li style="list-style-type:none;"> <button class="linkClass" onclick= "displayContent(event, 'practice')"> Practice </button> </li> <li style="list-style-type:none;"> <button class="linkClass" onclick= "displayContent(event, 'python')"> Python </button> </li> <li style="list-style-type:none;"> <button class="linkClass" onclick= "displayContent(event, 'algorithms')"> Algorithms </button> </li> </ul> </div></body> </html> CSS Code: The below code is the modified CSS code for the vertical tabs display. css <style> * { box-sizing: border-box; } #tabsDiv { height: 300px; border: 2px solid #c0c0c0; } #tabsDiv ul { height: 300px; padding: 0px 5px; } #tabsDiv li { width: 15%; height: 60px; } #tabsDiv button { float: left; border: 1px solid #c0c0c0; background-color: #f1f0f4; } /* Button to open the content */ #tabsDiv button { display: block; background-color: inherit; color: black; padding: 25px 15px; width: 100%; text-align: left; cursor: pointer; } /* Button styling on mouse hover */ #tabsDiv button:hover { background-color: #d1d1d1; color: lime; } #tabsDiv button.active { background-color: #c0c0c0; } /* Content for tabs*/ .contentClass { display: none; position: absolute; left: 18%; padding: 0px 15px; width: 70%; border-style: none; height: 300px; }</style> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n18 Nov, 2020" }, { "code": null, "e": 27018, "s": 26621, "text": "Tabs can be used for displaying large amounts of content on a single page in an organized manner. We can design single page tabs using HTML, CSS, and JavaScript. HTML elements are used to design the structure of the tabs and their content in paragraphs. The styling is performed using CSS. On the click of each tab button, the tabs display their respective content. This is done using JavaScript." }, { "code": null, "e": 27256, "s": 27018, "text": "Horizontal Tabs: The following code demonstrates the simple HTML structure with tabs and its contents in the form of a paragraph. On click of each tab, it calls the displayContent() method implemented in the “script.js” file given below." }, { "code": null, "e": 27268, "s": 27256, "text": "HTML Code: " }, { "code": null, "e": 27273, "s": 27268, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"style.css\"> <script src=\"script.js\"></script></head> <body> <h2 style=\"color:green\"> GeeksforGeeks Horizontal tabs </h2> <!-- Link to each tab with onclick event --> <div id=\"tabsDiv\"> <button class=\"linkClass\" onclick= \"displayContent(event, 'interview')\"> Interview </button> <button class=\"linkClass\" onclick= \"displayContent(event, 'practice')\"> Practice </button> <button class=\"linkClass\" onclick= \"displayContent(event, 'python')\"> Python </button> <button class=\"linkClass\" onclick= \"displayContent(event, 'algorithms')\"> Algorithms </button> <button class=\"linkClass\" onclick= \"displayContent(event, 'machine')\"> Machine Learning </button> </div> <!-- Content for each HTML tab --> <div id=\"interview\" class=\"contentClass\"> <h3>Interview</h3> <p> Also, in Asymptotic analysis, we always talk about input sizes larger than a constant value. It might be possible that those large inputs are never given to your software and an algorithm which is asymptotically slower, always performs better for your particular situation. So, you may end up choosing an algorithm that is Asymptotically slower but faster for your software. </p> </div> <div id=\"practice\" class=\"contentClass\"> <h3>Practice</h3> <p> Asymptotic Analysis is the big idea that handles above issues in analyzing algorithms. In Asymptotic Analysis, we evaluate the performance of an algorithm in terms of input size (we don’t measure the actual running time). We calculate, how does the time (or space) taken by an algorithm increases with the input size. </p> </div> <div id=\"python\" class=\"contentClass\"> <h3>Python</h3> <p> Python is a high-level, general-purpose and a very popular programming language. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting edge technology in Software Industry. Python Programming Language is very well suited for Beginners, also for experienced programmers with other programming languages like C++ and Java. </p> </div> <div id=\"algorithms\" class=\"contentClass\"> <h3>Greedy Algorithms</h3> <p> Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. So the problems where choosing locally optimal also leads to global solution are best fit for Greedy. </p> </div> <div id=\"machine\" class=\"contentClass\"> <h3>Machine Learning</h3> <p> Machine Learning is the field of study that gives computers the capability to learn without being explicitly programmed. ML is one of the most exciting technologies that one would have ever come across. As it is evident from the name, it gives the computer that makes it more similar to humans: The ability to learn. Machine learning is actively being used today, perhaps in many more places than one would expect. </p> </div></body> </html>", "e": 31134, "s": 27273, "text": null }, { "code": null, "e": 31245, "s": 31134, "text": "CSS Code: The following code is of the “style.css” file that is used for the styling of the page and the tabs." }, { "code": null, "e": 31249, "s": 31245, "text": "css" }, { "code": "<style> h3 { text-align: left; } /* Button to open the content */ .linkclass { float: left; cursor: pointer; padding: 10px 15px 10px 10px; background-color: light-grey; } /* Button styling on mouse hover */ #tabsDiv a:hover { color: black; background-color: #e9e9e9; font-size: 16px; } /* Change the color of the button */ button.active { background-color: #c0c0c0; } /* Content for button tabs*/ .contentClass { display: none; padding: 10px 16px; border: 2px solid #c0c0c0; }</style>", "e": 31868, "s": 31249, "text": null }, { "code": null, "e": 31957, "s": 31868, "text": "JavaScript Code: The following code contains the functionality of tabs using JavaScript." }, { "code": null, "e": 31968, "s": 31957, "text": "Javascript" }, { "code": "function displayContent(event, contentNameID) { let content = document.getElementsByClassName(\"contentClass\"); let totalCount = content.length; // Loop through the content class // and hide the tabs first for (let count = 0; count < totalCount; count++) { content[count].style.display = \"none\"; } let links = document.getElementsByClassName(\"linkClass\"); totalLinks = links.length; // Loop through the links and // remove the active class for (let count = 0; count < totalLinks; count++) { links[count].classList.remove(\"active\"); } // Display the current tab document.getElementById(contentNameID) .style.display = \"block\"; // Add the active class to the current tab event.currentTarget.classList.add(\"active\");}", "e": 32791, "s": 31968, "text": null }, { "code": null, "e": 32801, "s": 32791, "text": "Output: " }, { "code": null, "e": 33016, "s": 32801, "text": "Vertical Tabs: The tabs can be made vertical by changing the HTML structure and replacing the CSS stylesheet with a modified one used for the vertical tabs design. The following code demonstrates the vertical tabs." }, { "code": null, "e": 33028, "s": 33016, "text": "HTML code: " }, { "code": null, "e": 33033, "s": 33028, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"vstyle.css\"> <script src=\"script.js\"></script></head> <body> <h2 style=\"color:green\"> GeeksforGeeks Vertical tabs </h2> <div id=\"tabsDiv\"> <div id=\"interview\" class=\"contentClass\"> <h3>Interview</h3> <p> Also, in Asymptotic analysis, we always talk about input sizes larger than a constant value. It might be possible that those large inputs are never given to your software and an algorithm which is asymptotically slower, always performs better for your particular situation. So, you may end up choosing an algorithm that is Asymptotically slower but faster for your software. </p> </div> <div id=\"practice\" class=\"contentClass\"> <h3>Practice</h3> <p> Asymptotic Analysis is the big idea that handles above issues in analyzing algorithms. In Asymptotic Analysis, we evaluate the performance of an algorithm in terms of input size (we don’t measure the actual running time). We calculate, how does the time (or space) taken by an algorithm increases with the input size. </p> </div> <div id=\"python\" class=\"contentClass\"> <h3>Python</h3> <p> Python is a high-level, general-purpose and a very popular programming language. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting edge technology in Software Industry. Python Programming Language is very well suited for Beginners, also for experienced programmers with other programming languages like C++ and Java. </p> </div> <div id=\"algorithms\" class=\"contentClass\"> <h3>Greedy Algorithms</h3> <p> Greedy is an algorithmic paradigm that builds up a solution piece by piece,always choosing the next piece that offers the most obvious and immediate benefit. So the problems where choosing locally optimal also leads to global solution are best fit for Greedy. </p> </div> <ul class=\"ulClass\" style=\"height:300px\"> <li style=\"list-style-type:none;\"> <button class=\"linkClass\" onclick= \"displayContent(event, 'interview')\"> Interview </button> </li> <li style=\"list-style-type:none;\"> <button class=\"linkClass\" onclick= \"displayContent(event, 'practice')\"> Practice </button> </li> <li style=\"list-style-type:none;\"> <button class=\"linkClass\" onclick= \"displayContent(event, 'python')\"> Python </button> </li> <li style=\"list-style-type:none;\"> <button class=\"linkClass\" onclick= \"displayContent(event, 'algorithms')\"> Algorithms </button> </li> </ul> </div></body> </html>", "e": 36689, "s": 33033, "text": null }, { "code": null, "e": 36770, "s": 36689, "text": "CSS Code: The below code is the modified CSS code for the vertical tabs display." }, { "code": null, "e": 36774, "s": 36770, "text": "css" }, { "code": "<style> * { box-sizing: border-box; } #tabsDiv { height: 300px; border: 2px solid #c0c0c0; } #tabsDiv ul { height: 300px; padding: 0px 5px; } #tabsDiv li { width: 15%; height: 60px; } #tabsDiv button { float: left; border: 1px solid #c0c0c0; background-color: #f1f0f4; } /* Button to open the content */ #tabsDiv button { display: block; background-color: inherit; color: black; padding: 25px 15px; width: 100%; text-align: left; cursor: pointer; } /* Button styling on mouse hover */ #tabsDiv button:hover { background-color: #d1d1d1; color: lime; } #tabsDiv button.active { background-color: #c0c0c0; } /* Content for tabs*/ .contentClass { display: none; position: absolute; left: 18%; padding: 0px 15px; width: 70%; border-style: none; height: 300px; }</style>", "e": 37807, "s": 36774, "text": null }, { "code": null, "e": 37815, "s": 37807, "text": "Output:" }, { "code": null, "e": 37824, "s": 37815, "text": "CSS-Misc" }, { "code": null, "e": 37834, "s": 37824, "text": "HTML-Misc" }, { "code": null, "e": 37850, "s": 37834, "text": "JavaScript-Misc" }, { "code": null, "e": 37854, "s": 37850, "text": "CSS" }, { "code": null, "e": 37859, "s": 37854, "text": "HTML" }, { "code": null, "e": 37870, "s": 37859, "text": "JavaScript" }, { "code": null, "e": 37887, "s": 37870, "text": "Web Technologies" }, { "code": null, "e": 37914, "s": 37887, "text": "Web technologies Questions" }, { "code": null, "e": 37919, "s": 37914, "text": "HTML" }, { "code": null, "e": 38017, "s": 37919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38056, "s": 38017, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 38093, "s": 38056, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 38122, "s": 38093, "text": "Form validation using jQuery" }, { "code": null, "e": 38164, "s": 38122, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 38199, "s": 38164, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 38259, "s": 38199, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 38312, "s": 38259, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 38373, "s": 38312, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 38397, "s": 38373, "text": "REST API (Introduction)" } ]
SQLAlchemy Core - Creating Table - GeeksforGeeks
22 Nov, 2021 In this article, we are going to see how to create table in SQLAlchemy using Python. SQLAlchemy is a large SQL toolkit with lots of different components. The two largest components are SQLAlchemy Core and SQLAlchemy ORM. The major difference between them is SQLAlchemy Core is a schema-centric model that means everything is treated as a part of the database i.e., rows, columns, tables, etc while SQLAlchemy Core uses an object-centric view which encapsulates the schema with business objects. SQLAlchemy is a more pythonic implementation. In this post, we shall look at the SQLAlchemy core and how to create a table using it. SQLAlchemy is available via the pip install package. pip install sqlalchemy However, if you are using a flask you can make use of its own implementation of SQLAlchemy. It can be installed using – pip install flask-sqlalchemy We are going to make use of the sqlite3 database. Follow the below process to create a database that names users: Step 1: Open the command prompt and point to the directory to which the sqlite.exe file is present. Step 2: Create a database named users using the command sqlite3 users.db and Check the created database using the command .databases Creating database using sqlite3 First, let us look at the entire code and then jump to the explanation and the output for the same Python import sqlalchemy as db # Defining the Engineengine = db.create_engine('sqlite:///users.db', echo=True) # Create the Metadata Objectmetadata_obj = db.MetaData() # Define the profile table # database nameprofile = db.Table( 'profile', metadata_obj, db.Column('email', db.String, primary_key=True), db.Column('name', db.String), db.Column('contact', db.Integer), ) # Create the profile tablemetadata_obj.create_all(engine) Output: 2021-11-08 11:08:36,988 INFO sqlalchemy.engine.base.Engine () 2021-11-08 11:08:36,997 INFO sqlalchemy.engine.base.Engine COMMIT First, we import all the requirements from the sqlalchemy library. After that, we create the engine which is used to perform all the operations like creating tables, inserting or modifying values into a table, etc. From the engine, we can create connections on which we can run database queries on. The metadata_obj contains all the information about our database which is why we pass it in when creating the table. The metadata.create_all(engine) binds the metadata to the engine and creates the profile table if it is not existing in the users database. Output Viewed in SQLite3 terminal In order to view the tables present in the users database, use the command .tables. In the output, when the command is used for the first time we cannot see any output that is because the above code was not run at that time. After running the above code and then using the .tables command, we can see in the sqlite3 terminal that the profile table that we created using the code is present in the users database. The SELECT query is also successfully executed which indicates the table is created. However, there is no output since we did not insert any entry in the table. Picked Python SQLAlchemy-Core Python-SQLAlchemy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25611, "s": 25583, "text": "\n22 Nov, 2021" }, { "code": null, "e": 25696, "s": 25611, "text": "In this article, we are going to see how to create table in SQLAlchemy using Python." }, { "code": null, "e": 26239, "s": 25696, "text": "SQLAlchemy is a large SQL toolkit with lots of different components. The two largest components are SQLAlchemy Core and SQLAlchemy ORM. The major difference between them is SQLAlchemy Core is a schema-centric model that means everything is treated as a part of the database i.e., rows, columns, tables, etc while SQLAlchemy Core uses an object-centric view which encapsulates the schema with business objects. SQLAlchemy is a more pythonic implementation. In this post, we shall look at the SQLAlchemy core and how to create a table using it." }, { "code": null, "e": 26292, "s": 26239, "text": "SQLAlchemy is available via the pip install package." }, { "code": null, "e": 26315, "s": 26292, "text": "pip install sqlalchemy" }, { "code": null, "e": 26435, "s": 26315, "text": "However, if you are using a flask you can make use of its own implementation of SQLAlchemy. It can be installed using –" }, { "code": null, "e": 26464, "s": 26435, "text": "pip install flask-sqlalchemy" }, { "code": null, "e": 26578, "s": 26464, "text": "We are going to make use of the sqlite3 database. Follow the below process to create a database that names users:" }, { "code": null, "e": 26678, "s": 26578, "text": "Step 1: Open the command prompt and point to the directory to which the sqlite.exe file is present." }, { "code": null, "e": 26811, "s": 26678, "text": "Step 2: Create a database named users using the command sqlite3 users.db and Check the created database using the command .databases" }, { "code": null, "e": 26843, "s": 26811, "text": "Creating database using sqlite3" }, { "code": null, "e": 26942, "s": 26843, "text": "First, let us look at the entire code and then jump to the explanation and the output for the same" }, { "code": null, "e": 26949, "s": 26942, "text": "Python" }, { "code": "import sqlalchemy as db # Defining the Engineengine = db.create_engine('sqlite:///users.db', echo=True) # Create the Metadata Objectmetadata_obj = db.MetaData() # Define the profile table # database nameprofile = db.Table( 'profile', metadata_obj, db.Column('email', db.String, primary_key=True), db.Column('name', db.String), db.Column('contact', db.Integer), ) # Create the profile tablemetadata_obj.create_all(engine)", "e": 27503, "s": 26949, "text": null }, { "code": null, "e": 27511, "s": 27503, "text": "Output:" }, { "code": null, "e": 27639, "s": 27511, "text": "2021-11-08 11:08:36,988 INFO sqlalchemy.engine.base.Engine ()\n2021-11-08 11:08:36,997 INFO sqlalchemy.engine.base.Engine COMMIT" }, { "code": null, "e": 28195, "s": 27639, "text": "First, we import all the requirements from the sqlalchemy library. After that, we create the engine which is used to perform all the operations like creating tables, inserting or modifying values into a table, etc. From the engine, we can create connections on which we can run database queries on. The metadata_obj contains all the information about our database which is why we pass it in when creating the table. The metadata.create_all(engine) binds the metadata to the engine and creates the profile table if it is not existing in the users database." }, { "code": null, "e": 28229, "s": 28195, "text": "Output Viewed in SQLite3 terminal" }, { "code": null, "e": 28803, "s": 28229, "text": "In order to view the tables present in the users database, use the command .tables. In the output, when the command is used for the first time we cannot see any output that is because the above code was not run at that time. After running the above code and then using the .tables command, we can see in the sqlite3 terminal that the profile table that we created using the code is present in the users database. The SELECT query is also successfully executed which indicates the table is created. However, there is no output since we did not insert any entry in the table." }, { "code": null, "e": 28810, "s": 28803, "text": "Picked" }, { "code": null, "e": 28833, "s": 28810, "text": "Python SQLAlchemy-Core" }, { "code": null, "e": 28851, "s": 28833, "text": "Python-SQLAlchemy" }, { "code": null, "e": 28858, "s": 28851, "text": "Python" }, { "code": null, "e": 28956, "s": 28858, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28988, "s": 28956, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29030, "s": 28988, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29072, "s": 29030, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29099, "s": 29072, "text": "Python Classes and Objects" }, { "code": null, "e": 29155, "s": 29099, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29186, "s": 29155, "text": "Python | os.path.join() method" }, { "code": null, "e": 29225, "s": 29186, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29254, "s": 29225, "text": "Create a directory in Python" }, { "code": null, "e": 29276, "s": 29254, "text": "Defaultdict in Python" } ]
Introduction to Kotlin
06 Dec, 2019 Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and a new language for the JVM. Kotlin is object-oriented language, and a “better language” than Java, but still be fully interoperable with Java code. Kotlin is sponsored by Google, announced as one of the official languages for Android Development in 2017. Example of Kotlin – fun main(){ println("Hello Geeks");} Key Features of Kotlin: Statically typed – Statically typed is a programming language characteristic that means the type of every variable and expression is known at compile time. Although it is statically typed language, it does not require you to explicitly specify the type of every variable you declare.Data Classes– In Kotlin, there are Data Classes which lead to auto-generation of boilerplate like equals, hashCode, toString, getters/setters and much more.Consider the following example –/* Java Code */class Book { private String title; private Author author; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; }}But in Kotlin only one line used to define the above class –/* Kotlin Code */ data class Book(var title:String, var author:Author) Concise – It drastically reduces the extra code written in other object-oriented programming languages.Safe – It provides the safety from most annoying and irritating NullPointerExceptions by supporting nullability as part of its system.Every variable in Kotlin is non-null by default.String s = "Hello Geeks" // Non-null If we try to assign s null value then it gives compile time error.So,s = null // compile time error To assign null value to any string string it should be declared as nullable.String nullableStr? = null // compiles successfully length() function also disabled on the nullable strings.Interoperable with Java – Kotlin runs on Java Virtual Machine(JVM) so it is totally interoperable with java. We can easily access use java code from kotlin and kotlin code from java.Functional and Object Oriented Capabilities – Kotlin has rich set of many useful methods which includes higher-order functions, lambda expressions, operator overloading, lazy evaluation, operator overloading and much more.Higher order function is a function which accepts function as a parameter or returns a function or can do both.Example of higher-order function –fun myFun(company: String,product: String, fn: (String,String) -> String): Unit { val result = fn(company,product) println(result) } fun main(args: Array){ val fn:(String,String)->String={org,portal->"$org develops $portal"} myFun("JetBrains","Kotlin",fn) } Output:JetBrains develops KotlinSmart Cast – It explicitly typecasts the immutable values and inserts the value in its safe cast automatically.If we try to access a nullable type of String ( String? = “BYE”) without safe cast it will generate a compile error.fun main(args: Array){ var string: String? = "BYE" print(string.length) // compile time error } } fun main(args: Array){ var string: String? = "BYE" if(string != null) { // smart cast print(string.length) } } Compilation time – It has higher performance and fast compilation time.Tool- Friendly – It has excellent tooling support. Any of the Java IDEs – IntelliJ IDEA, Eclipse and Android Studio can be used for Kotlin. We can also be run Kotlin program from command line. Statically typed – Statically typed is a programming language characteristic that means the type of every variable and expression is known at compile time. Although it is statically typed language, it does not require you to explicitly specify the type of every variable you declare. Data Classes– In Kotlin, there are Data Classes which lead to auto-generation of boilerplate like equals, hashCode, toString, getters/setters and much more.Consider the following example –/* Java Code */class Book { private String title; private Author author; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; }}But in Kotlin only one line used to define the above class –/* Kotlin Code */ data class Book(var title:String, var author:Author) Consider the following example – /* Java Code */class Book { private String title; private Author author; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; }} But in Kotlin only one line used to define the above class – /* Kotlin Code */ data class Book(var title:String, var author:Author) Concise – It drastically reduces the extra code written in other object-oriented programming languages. Safe – It provides the safety from most annoying and irritating NullPointerExceptions by supporting nullability as part of its system.Every variable in Kotlin is non-null by default.String s = "Hello Geeks" // Non-null If we try to assign s null value then it gives compile time error.So,s = null // compile time error To assign null value to any string string it should be declared as nullable.String nullableStr? = null // compiles successfully length() function also disabled on the nullable strings. String s = "Hello Geeks" // Non-null If we try to assign s null value then it gives compile time error.So, s = null // compile time error To assign null value to any string string it should be declared as nullable. String nullableStr? = null // compiles successfully length() function also disabled on the nullable strings. Interoperable with Java – Kotlin runs on Java Virtual Machine(JVM) so it is totally interoperable with java. We can easily access use java code from kotlin and kotlin code from java. Functional and Object Oriented Capabilities – Kotlin has rich set of many useful methods which includes higher-order functions, lambda expressions, operator overloading, lazy evaluation, operator overloading and much more.Higher order function is a function which accepts function as a parameter or returns a function or can do both.Example of higher-order function –fun myFun(company: String,product: String, fn: (String,String) -> String): Unit { val result = fn(company,product) println(result) } fun main(args: Array){ val fn:(String,String)->String={org,portal->"$org develops $portal"} myFun("JetBrains","Kotlin",fn) } Output:JetBrains develops Kotlin Example of higher-order function – fun myFun(company: String,product: String, fn: (String,String) -> String): Unit { val result = fn(company,product) println(result) } fun main(args: Array){ val fn:(String,String)->String={org,portal->"$org develops $portal"} myFun("JetBrains","Kotlin",fn) } Output: JetBrains develops Kotlin Smart Cast – It explicitly typecasts the immutable values and inserts the value in its safe cast automatically.If we try to access a nullable type of String ( String? = “BYE”) without safe cast it will generate a compile error.fun main(args: Array){ var string: String? = "BYE" print(string.length) // compile time error } } fun main(args: Array){ var string: String? = "BYE" if(string != null) { // smart cast print(string.length) } } fun main(args: Array){ var string: String? = "BYE" print(string.length) // compile time error } } fun main(args: Array){ var string: String? = "BYE" if(string != null) { // smart cast print(string.length) } } Compilation time – It has higher performance and fast compilation time. Tool- Friendly – It has excellent tooling support. Any of the Java IDEs – IntelliJ IDEA, Eclipse and Android Studio can be used for Kotlin. We can also be run Kotlin program from command line. Advantages of Kotlin language: Easy to learn – Basic is almost similar to java.If anybody worked in java then easily understand in no time. Kotlin is multi-platform – Kotlin is supported by all IDEs of java so you can write your program and execute them on any machine which supports JVM. It’s much safer than Java. It allows using the Java frameworks and libraries in your new Kotlin projects by using advanced frameworks without any need to change the whole project in Java. Kotlin programming language, including the compiler, libraries and all the tooling is completely free and open source and available on github. Here is the link for Github https://github.com/JetBrains/kotlin Applications of Kotlin language: You can use Kotlin to build Android Application. Kotlin can also compile to JavaScript, and making it available for the frontend. It is also designed to work well for web development and server-side development. nidhi_biet Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Dec, 2019" }, { "code": null, "e": 416, "s": 52, "text": "Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and a new language for the JVM. Kotlin is object-oriented language, and a “better language” than Java, but still be fully interoperable with Java code." }, { "code": null, "e": 523, "s": 416, "text": "Kotlin is sponsored by Google, announced as one of the official languages for Android Development in 2017." }, { "code": null, "e": 543, "s": 523, "text": "Example of Kotlin –" }, { "code": "fun main(){ println(\"Hello Geeks\");}", "e": 583, "s": 543, "text": null }, { "code": null, "e": 607, "s": 583, "text": "Key Features of Kotlin:" }, { "code": null, "e": 3823, "s": 607, "text": "Statically typed – Statically typed is a programming language characteristic that means the type of every variable and expression is known at compile time. Although it is statically typed language, it does not require you to explicitly specify the type of every variable you declare.Data Classes– In Kotlin, there are Data Classes which lead to auto-generation of boilerplate like equals, hashCode, toString, getters/setters and much more.Consider the following example –/* Java Code */class Book { private String title; private Author author; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; }}But in Kotlin only one line used to define the above class –/* Kotlin Code */\ndata class Book(var title:String, var author:Author)\nConcise – It drastically reduces the extra code written in other object-oriented programming languages.Safe – It provides the safety from most annoying and irritating NullPointerExceptions by supporting nullability as part of its system.Every variable in Kotlin is non-null by default.String s = \"Hello Geeks\" // Non-null \nIf we try to assign s null value then it gives compile time error.So,s = null // compile time error\nTo assign null value to any string string it should be declared as nullable.String nullableStr? = null // compiles successfully\nlength() function also disabled on the nullable strings.Interoperable with Java – Kotlin runs on Java Virtual Machine(JVM) so it is totally interoperable with java. We can easily access use java code from kotlin and kotlin code from java.Functional and Object Oriented Capabilities – Kotlin has rich set of many useful methods which includes higher-order functions, lambda expressions, operator overloading, lazy evaluation, operator overloading and much more.Higher order function is a function which accepts function as a parameter or returns a function or can do both.Example of higher-order function –fun myFun(company: String,product: String, fn: (String,String) -> String): Unit {\n val result = fn(company,product)\n println(result)\n}\n\nfun main(args: Array){\n val fn:(String,String)->String={org,portal->\"$org develops $portal\"}\n myFun(\"JetBrains\",\"Kotlin\",fn)\n}\nOutput:JetBrains develops KotlinSmart Cast – It explicitly typecasts the immutable values and inserts the value in its safe cast automatically.If we try to access a nullable type of String ( String? = “BYE”) without safe cast it will generate a compile error.fun main(args: Array){\n var string: String? = \"BYE\" \n print(string.length) // compile time error\n }\n}\nfun main(args: Array){\n var string: String? = \"BYE\"\n if(string != null) { // smart cast\n print(string.length) \n }\n}\nCompilation time – It has higher performance and fast compilation time.Tool- Friendly – It has excellent tooling support. Any of the Java IDEs – IntelliJ IDEA, Eclipse and Android Studio can be used for Kotlin. We can also be run Kotlin program from command line." }, { "code": null, "e": 4107, "s": 3823, "text": "Statically typed – Statically typed is a programming language characteristic that means the type of every variable and expression is known at compile time. Although it is statically typed language, it does not require you to explicitly specify the type of every variable you declare." }, { "code": null, "e": 4788, "s": 4107, "text": "Data Classes– In Kotlin, there are Data Classes which lead to auto-generation of boilerplate like equals, hashCode, toString, getters/setters and much more.Consider the following example –/* Java Code */class Book { private String title; private Author author; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; }}But in Kotlin only one line used to define the above class –/* Kotlin Code */\ndata class Book(var title:String, var author:Author)\n" }, { "code": null, "e": 4821, "s": 4788, "text": "Consider the following example –" }, { "code": "/* Java Code */class Book { private String title; private Author author; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; }}", "e": 5183, "s": 4821, "text": null }, { "code": null, "e": 5244, "s": 5183, "text": "But in Kotlin only one line used to define the above class –" }, { "code": null, "e": 5316, "s": 5244, "text": "/* Kotlin Code */\ndata class Book(var title:String, var author:Author)\n" }, { "code": null, "e": 5420, "s": 5316, "text": "Concise – It drastically reduces the extra code written in other object-oriented programming languages." }, { "code": null, "e": 5948, "s": 5420, "text": "Safe – It provides the safety from most annoying and irritating NullPointerExceptions by supporting nullability as part of its system.Every variable in Kotlin is non-null by default.String s = \"Hello Geeks\" // Non-null \nIf we try to assign s null value then it gives compile time error.So,s = null // compile time error\nTo assign null value to any string string it should be declared as nullable.String nullableStr? = null // compiles successfully\nlength() function also disabled on the nullable strings." }, { "code": null, "e": 5990, "s": 5948, "text": "String s = \"Hello Geeks\" // Non-null \n" }, { "code": null, "e": 6060, "s": 5990, "text": "If we try to assign s null value then it gives compile time error.So," }, { "code": null, "e": 6111, "s": 6060, "text": "s = null // compile time error\n" }, { "code": null, "e": 6188, "s": 6111, "text": "To assign null value to any string string it should be declared as nullable." }, { "code": null, "e": 6242, "s": 6188, "text": "String nullableStr? = null // compiles successfully\n" }, { "code": null, "e": 6299, "s": 6242, "text": "length() function also disabled on the nullable strings." }, { "code": null, "e": 6482, "s": 6299, "text": "Interoperable with Java – Kotlin runs on Java Virtual Machine(JVM) so it is totally interoperable with java. We can easily access use java code from kotlin and kotlin code from java." }, { "code": null, "e": 7157, "s": 6482, "text": "Functional and Object Oriented Capabilities – Kotlin has rich set of many useful methods which includes higher-order functions, lambda expressions, operator overloading, lazy evaluation, operator overloading and much more.Higher order function is a function which accepts function as a parameter or returns a function or can do both.Example of higher-order function –fun myFun(company: String,product: String, fn: (String,String) -> String): Unit {\n val result = fn(company,product)\n println(result)\n}\n\nfun main(args: Array){\n val fn:(String,String)->String={org,portal->\"$org develops $portal\"}\n myFun(\"JetBrains\",\"Kotlin\",fn)\n}\nOutput:JetBrains develops Kotlin" }, { "code": null, "e": 7192, "s": 7157, "text": "Example of higher-order function –" }, { "code": null, "e": 7468, "s": 7192, "text": "fun myFun(company: String,product: String, fn: (String,String) -> String): Unit {\n val result = fn(company,product)\n println(result)\n}\n\nfun main(args: Array){\n val fn:(String,String)->String={org,portal->\"$org develops $portal\"}\n myFun(\"JetBrains\",\"Kotlin\",fn)\n}\n" }, { "code": null, "e": 7476, "s": 7468, "text": "Output:" }, { "code": null, "e": 7502, "s": 7476, "text": "JetBrains develops Kotlin" }, { "code": null, "e": 8006, "s": 7502, "text": "Smart Cast – It explicitly typecasts the immutable values and inserts the value in its safe cast automatically.If we try to access a nullable type of String ( String? = “BYE”) without safe cast it will generate a compile error.fun main(args: Array){\n var string: String? = \"BYE\" \n print(string.length) // compile time error\n }\n}\nfun main(args: Array){\n var string: String? = \"BYE\"\n if(string != null) { // smart cast\n print(string.length) \n }\n}\n" }, { "code": null, "e": 8137, "s": 8006, "text": "fun main(args: Array){\n var string: String? = \"BYE\" \n print(string.length) // compile time error\n }\n}\n" }, { "code": null, "e": 8284, "s": 8137, "text": "fun main(args: Array){\n var string: String? = \"BYE\"\n if(string != null) { // smart cast\n print(string.length) \n }\n}\n" }, { "code": null, "e": 8356, "s": 8284, "text": "Compilation time – It has higher performance and fast compilation time." }, { "code": null, "e": 8549, "s": 8356, "text": "Tool- Friendly – It has excellent tooling support. Any of the Java IDEs – IntelliJ IDEA, Eclipse and Android Studio can be used for Kotlin. We can also be run Kotlin program from command line." }, { "code": null, "e": 8580, "s": 8549, "text": "Advantages of Kotlin language:" }, { "code": null, "e": 8689, "s": 8580, "text": "Easy to learn – Basic is almost similar to java.If anybody worked in java then easily understand in no time." }, { "code": null, "e": 8838, "s": 8689, "text": "Kotlin is multi-platform – Kotlin is supported by all IDEs of java so you can write your program and execute them on any machine which supports JVM." }, { "code": null, "e": 8865, "s": 8838, "text": "It’s much safer than Java." }, { "code": null, "e": 9026, "s": 8865, "text": "It allows using the Java frameworks and libraries in your new Kotlin projects by using advanced frameworks without any need to change the whole project in Java." }, { "code": null, "e": 9233, "s": 9026, "text": "Kotlin programming language, including the compiler, libraries and all the tooling is completely free and open source and available on github. Here is the link for Github https://github.com/JetBrains/kotlin" }, { "code": null, "e": 9266, "s": 9233, "text": "Applications of Kotlin language:" }, { "code": null, "e": 9315, "s": 9266, "text": "You can use Kotlin to build Android Application." }, { "code": null, "e": 9396, "s": 9315, "text": "Kotlin can also compile to JavaScript, and making it available for the frontend." }, { "code": null, "e": 9478, "s": 9396, "text": "It is also designed to work well for web development and server-side development." }, { "code": null, "e": 9489, "s": 9478, "text": "nidhi_biet" }, { "code": null, "e": 9496, "s": 9489, "text": "Kotlin" } ]
Counting pairs when a person can form pair with at most one
06 Jul, 2022 Consider a coding competition on geeksforgeeks practice. Now there are n distinct participants taking part in the competition. A single participant can make pair with at most one other participant. We need count the number of ways in which n participants participating in the coding competition.Examples : Input : n = 2 Output : 2 2 shows that either both participant can pair themselves in one way or both of them can remain single. Input : n = 3 Output : 4 One way : Three participants remain single Three More Ways : [(1, 2)(3)], [(1), (2,3)] and [(1,3)(2)] 1) Every participant can either pair with another participant or can remain single. 2) Let us consider X-th participant, he can either remain single or he can pair up with someone from [1, x-1]. C++ Java Python3 C# PHP Javascript // Number of ways in which participant can take part.#include<iostream>using namespace std; int numberOfWays(int x){ // Base condition if (x==0 || x==1) return 1; // A participant can choose to consider // (1) Remains single. Number of people // reduce to (x-1) // (2) Pairs with one of the (x-1) others. // For every pairing, number of people // reduce to (x-2). else return numberOfWays(x-1) + (x-1)*numberOfWays(x-2);} // Driver codeint main(){ int x = 3; cout << numberOfWays(x) << endl; return 0;} // Number of ways in which// participant can take part.import java.io.*; class GFG { static int numberOfWays(int x){ // Base condition if (x==0 || x==1) return 1; // A participant can choose to consider // (1) Remains single. Number of people // reduce to (x-1) // (2) Pairs with one of the (x-1) others. // For every pairing, number of people // reduce to (x-2). else return numberOfWays(x-1) + (x-1)*numberOfWays(x-2);} // Driver codepublic static void main (String[] args) {int x = 3;System.out.println( numberOfWays(x)); }} // This code is contributed by vt_m. # Python program to find Number of ways# in which participant can take part. # Function to calculate number of ways.def numberOfWays (x): # Base condition if x == 0 or x == 1: return 1 # A participant can choose to consider # (1) Remains single. Number of people # reduce to (x-1) # (2) Pairs with one of the (x-1) others. # For every pairing, number of people # reduce to (x-2). else: return (numberOfWays(x-1) + (x-1) * numberOfWays(x-2)) # Driver codex = 3print (numberOfWays(x)) # This code is contributed by "Sharad_Bhardwaj" // Number of ways in which// participant can take part.using System; class GFG { static int numberOfWays(int x) { // Base condition if (x == 0 || x == 1) return 1; // A participant can choose to // consider (1) Remains single. // Number of people reduce to // (x-1) (2) Pairs with one of // the (x-1) others. For every // pairing, number of people // reduce to (x-2). else return numberOfWays(x - 1) + (x - 1) * numberOfWays(x - 2); } // Driver code public static void Main () { int x = 3; Console.WriteLine(numberOfWays(x)); }} // This code is contributed by vt_m. <?php// Number of ways in which// participant can take part. function numberOfWays($x){ // Base condition if ($x == 0 || $x == 1) return 1; // A participant can choose // to consider (1) Remains single. // Number of people reduce to (x-1) // (2) Pairs with one of the (x-1) // others. For every pairing, number // of peopl reduce to (x-2). else return numberOfWays($x - 1) + ($x - 1) * numberOfWays($x - 2);} // Driver code$x = 3;echo numberOfWays($x); // This code is contributed by Sam007?> <script>// Number of ways in which// participant can take part. function numberOfWays(x) { // Base condition if (x == 0 || x == 1) return 1; // A participant can choose to consider // (1) Remains single. Number of people // reduce to (x-1) // (2) Pairs with one of the (x-1) others. // For every pairing, number of people // reduce to (x-2). else return numberOfWays(x - 1) + (x - 1) * numberOfWays(x - 2); } // Driver code var x = 3; document.write(numberOfWays(x)); // This code is contributed by gauravrajput1</script> Output : 4 Since there are overlapping subproblems, we can optimize it using dynamic programming. C++ Java Python3 C# PHP Javascript // Number of ways in which participant can take part.#include<iostream>using namespace std; int numberOfWays(int x){ int dp[x+1]; dp[0] = dp[1] = 1; for (int i=2; i<=x; i++) dp[i] = dp[i-1] + (i-1)*dp[i-2]; return dp[x];} // Driver codeint main(){ int x = 3; cout << numberOfWays(x) << endl; return 0;} // Number of ways in which// participant can take part.import java.io.*;class GFG { static int numberOfWays(int x){ int dp[] = new int[x+1]; dp[0] = dp[1] = 1; for (int i=2; i<=x; i++) dp[i] = dp[i-1] + (i-1)*dp[i-2]; return dp[x];} // Driver codepublic static void main (String[] args) {int x = 3;System.out.println(numberOfWays(x)); }}// This code is contributed by vipinyadav15799 # Python program to find Number of ways# in which participant can take part. # Function to calculate number of ways.def numberOfWays (x): dp=[] dp.append(1) dp.append(1) for i in range(2,x+1): dp.append(dp[i-1]+(i-1)*dp[i-2]) return(dp[x]) # Driver codex = 3print (numberOfWays(x)) # This code is contributed by "Sharad_Bhardwaj" // Number of ways in which// participant can take part.using System; class GFG { static int numberOfWays(int x) { int []dp = new int[x+1]; dp[0] = dp[1] = 1; for (int i = 2; i <= x; i++) dp[i] = dp[i - 1] + (i - 1) * dp[i - 2]; return dp[x]; } // Driver code public static void Main () { int x = 3; Console.WriteLine(numberOfWays(x)); }} // This code is contributed by vt_m. <?php// PHP program for Number of ways// in which participant can take part. function numberOfWays($x){ $dp[0] = 1; $dp[1] = 1; for ($i = 2; $i <= $x; $i++) $dp[$i] = $dp[$i - 1] + ($i - 1) * $dp[$i - 2]; return $dp[$x];} // Driver code $x = 3; echo numberOfWays($x) ; // This code is contributed by Sam007?> <script>// Number of ways in which// participant can take part. function numberOfWays( x) { let dp = Array(x + 1).fill(0); dp[0] = dp[1] = 1; for ( i = 2; i <= x; i++) dp[i] = dp[i - 1] + (i - 1) * dp[i - 2]; return dp[x]; } // Driver code let x = 3; document.write(numberOfWays(x)); // This code is contributed by gauravrajput1</script> Output: 4 This article is contributed by nikunj_agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Sam007 vipinyadav15799 GauravRajput1 mitalibhola94 Combinatorial Dynamic Programming Dynamic Programming Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 360, "s": 52, "text": "Consider a coding competition on geeksforgeeks practice. Now there are n distinct participants taking part in the competition. A single participant can make pair with at most one other participant. We need count the number of ways in which n participants participating in the coding competition.Examples : " }, { "code": null, "e": 619, "s": 360, "text": "Input : n = 2\nOutput : 2\n2 shows that either both participant \ncan pair themselves in one way or both \nof them can remain single.\n\nInput : n = 3 \nOutput : 4\nOne way : Three participants remain single\nThree More Ways : [(1, 2)(3)], [(1), (2,3)]\nand [(1,3)(2)]" }, { "code": null, "e": 817, "s": 621, "text": "1) Every participant can either pair with another participant or can remain single. 2) Let us consider X-th participant, he can either remain single or he can pair up with someone from [1, x-1]. " }, { "code": null, "e": 821, "s": 817, "text": "C++" }, { "code": null, "e": 826, "s": 821, "text": "Java" }, { "code": null, "e": 834, "s": 826, "text": "Python3" }, { "code": null, "e": 837, "s": 834, "text": "C#" }, { "code": null, "e": 841, "s": 837, "text": "PHP" }, { "code": null, "e": 852, "s": 841, "text": "Javascript" }, { "code": "// Number of ways in which participant can take part.#include<iostream>using namespace std; int numberOfWays(int x){ // Base condition if (x==0 || x==1) return 1; // A participant can choose to consider // (1) Remains single. Number of people // reduce to (x-1) // (2) Pairs with one of the (x-1) others. // For every pairing, number of people // reduce to (x-2). else return numberOfWays(x-1) + (x-1)*numberOfWays(x-2);} // Driver codeint main(){ int x = 3; cout << numberOfWays(x) << endl; return 0;}", "e": 1436, "s": 852, "text": null }, { "code": "// Number of ways in which// participant can take part.import java.io.*; class GFG { static int numberOfWays(int x){ // Base condition if (x==0 || x==1) return 1; // A participant can choose to consider // (1) Remains single. Number of people // reduce to (x-1) // (2) Pairs with one of the (x-1) others. // For every pairing, number of people // reduce to (x-2). else return numberOfWays(x-1) + (x-1)*numberOfWays(x-2);} // Driver codepublic static void main (String[] args) {int x = 3;System.out.println( numberOfWays(x)); }} // This code is contributed by vt_m.", "e": 2078, "s": 1436, "text": null }, { "code": "# Python program to find Number of ways# in which participant can take part. # Function to calculate number of ways.def numberOfWays (x): # Base condition if x == 0 or x == 1: return 1 # A participant can choose to consider # (1) Remains single. Number of people # reduce to (x-1) # (2) Pairs with one of the (x-1) others. # For every pairing, number of people # reduce to (x-2). else: return (numberOfWays(x-1) + (x-1) * numberOfWays(x-2)) # Driver codex = 3print (numberOfWays(x)) # This code is contributed by \"Sharad_Bhardwaj\"", "e": 2673, "s": 2078, "text": null }, { "code": "// Number of ways in which// participant can take part.using System; class GFG { static int numberOfWays(int x) { // Base condition if (x == 0 || x == 1) return 1; // A participant can choose to // consider (1) Remains single. // Number of people reduce to // (x-1) (2) Pairs with one of // the (x-1) others. For every // pairing, number of people // reduce to (x-2). else return numberOfWays(x - 1) + (x - 1) * numberOfWays(x - 2); } // Driver code public static void Main () { int x = 3; Console.WriteLine(numberOfWays(x)); }} // This code is contributed by vt_m.", "e": 3406, "s": 2673, "text": null }, { "code": "<?php// Number of ways in which// participant can take part. function numberOfWays($x){ // Base condition if ($x == 0 || $x == 1) return 1; // A participant can choose // to consider (1) Remains single. // Number of people reduce to (x-1) // (2) Pairs with one of the (x-1) // others. For every pairing, number // of peopl reduce to (x-2). else return numberOfWays($x - 1) + ($x - 1) * numberOfWays($x - 2);} // Driver code$x = 3;echo numberOfWays($x); // This code is contributed by Sam007?>", "e": 3956, "s": 3406, "text": null }, { "code": "<script>// Number of ways in which// participant can take part. function numberOfWays(x) { // Base condition if (x == 0 || x == 1) return 1; // A participant can choose to consider // (1) Remains single. Number of people // reduce to (x-1) // (2) Pairs with one of the (x-1) others. // For every pairing, number of people // reduce to (x-2). else return numberOfWays(x - 1) + (x - 1) * numberOfWays(x - 2); } // Driver code var x = 3; document.write(numberOfWays(x)); // This code is contributed by gauravrajput1</script>", "e": 4589, "s": 3956, "text": null }, { "code": null, "e": 4600, "s": 4589, "text": "Output : " }, { "code": null, "e": 4602, "s": 4600, "text": "4" }, { "code": null, "e": 4691, "s": 4602, "text": "Since there are overlapping subproblems, we can optimize it using dynamic programming. " }, { "code": null, "e": 4695, "s": 4691, "text": "C++" }, { "code": null, "e": 4700, "s": 4695, "text": "Java" }, { "code": null, "e": 4708, "s": 4700, "text": "Python3" }, { "code": null, "e": 4711, "s": 4708, "text": "C#" }, { "code": null, "e": 4715, "s": 4711, "text": "PHP" }, { "code": null, "e": 4726, "s": 4715, "text": "Javascript" }, { "code": "// Number of ways in which participant can take part.#include<iostream>using namespace std; int numberOfWays(int x){ int dp[x+1]; dp[0] = dp[1] = 1; for (int i=2; i<=x; i++) dp[i] = dp[i-1] + (i-1)*dp[i-2]; return dp[x];} // Driver codeint main(){ int x = 3; cout << numberOfWays(x) << endl; return 0;}", "e": 5058, "s": 4726, "text": null }, { "code": "// Number of ways in which// participant can take part.import java.io.*;class GFG { static int numberOfWays(int x){ int dp[] = new int[x+1]; dp[0] = dp[1] = 1; for (int i=2; i<=x; i++) dp[i] = dp[i-1] + (i-1)*dp[i-2]; return dp[x];} // Driver codepublic static void main (String[] args) {int x = 3;System.out.println(numberOfWays(x)); }}// This code is contributed by vipinyadav15799", "e": 5467, "s": 5058, "text": null }, { "code": "# Python program to find Number of ways# in which participant can take part. # Function to calculate number of ways.def numberOfWays (x): dp=[] dp.append(1) dp.append(1) for i in range(2,x+1): dp.append(dp[i-1]+(i-1)*dp[i-2]) return(dp[x]) # Driver codex = 3print (numberOfWays(x)) # This code is contributed by \"Sharad_Bhardwaj\"", "e": 5825, "s": 5467, "text": null }, { "code": "// Number of ways in which// participant can take part.using System; class GFG { static int numberOfWays(int x) { int []dp = new int[x+1]; dp[0] = dp[1] = 1; for (int i = 2; i <= x; i++) dp[i] = dp[i - 1] + (i - 1) * dp[i - 2]; return dp[x]; } // Driver code public static void Main () { int x = 3; Console.WriteLine(numberOfWays(x)); }} // This code is contributed by vt_m. ", "e": 6316, "s": 5825, "text": null }, { "code": "<?php// PHP program for Number of ways// in which participant can take part. function numberOfWays($x){ $dp[0] = 1; $dp[1] = 1; for ($i = 2; $i <= $x; $i++) $dp[$i] = $dp[$i - 1] + ($i - 1) * $dp[$i - 2]; return $dp[$x];} // Driver code $x = 3; echo numberOfWays($x) ; // This code is contributed by Sam007?>", "e": 6684, "s": 6316, "text": null }, { "code": "<script>// Number of ways in which// participant can take part. function numberOfWays( x) { let dp = Array(x + 1).fill(0); dp[0] = dp[1] = 1; for ( i = 2; i <= x; i++) dp[i] = dp[i - 1] + (i - 1) * dp[i - 2]; return dp[x]; } // Driver code let x = 3; document.write(numberOfWays(x)); // This code is contributed by gauravrajput1</script>", "e": 7083, "s": 6684, "text": null }, { "code": null, "e": 7093, "s": 7083, "text": "Output: " }, { "code": null, "e": 7095, "s": 7093, "text": "4" }, { "code": null, "e": 7518, "s": 7095, "text": "This article is contributed by nikunj_agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7523, "s": 7518, "text": "vt_m" }, { "code": null, "e": 7530, "s": 7523, "text": "Sam007" }, { "code": null, "e": 7546, "s": 7530, "text": "vipinyadav15799" }, { "code": null, "e": 7560, "s": 7546, "text": "GauravRajput1" }, { "code": null, "e": 7574, "s": 7560, "text": "mitalibhola94" }, { "code": null, "e": 7588, "s": 7574, "text": "Combinatorial" }, { "code": null, "e": 7608, "s": 7588, "text": "Dynamic Programming" }, { "code": null, "e": 7628, "s": 7608, "text": "Dynamic Programming" }, { "code": null, "e": 7642, "s": 7628, "text": "Combinatorial" } ]
JavaFX | Canvas Class
04 Sep, 2018 Canvas class is a part of JavaFX. Canvas class basically creates an image that can be drawn on using a set of graphics commands provided by a GraphicsContext. Canvas has a specified height and width and all the drawing operations are clipped to the bounds of the canvas. Constructors of the class: Canvas(): Creates a new canvas object.Canvas(double w, double h): Creates a new canvas object with specified width and height. Canvas(): Creates a new canvas object. Canvas(double w, double h): Creates a new canvas object with specified width and height. Commonly Used Methods: Below programs illustrate the use of Canvas class: Java Program to create a canvas with specified width and height(as arguments of constructor), add it to the stage and also add a circle and rectangle on it: In this program we will create a Canvas named canvas with specified width and height. We will extract the GraphicsContext using the getGraphicsContext2D() function and draw a rectangle and a oval of different color. Now we will create a Group named group and add the canvas to the group. Now create a scene and add the group to the scene and then attach the scene to the stage and call the show() function to display the results.// Java Program to create a canvas with specified// width and height(as arguments of constructor),// add it to the stage and also add a circle and// rectangle on itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.paint.Color;import javafx.scene.Group; public class canvas extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating canvas"); // create a canvas Canvas canvas = new Canvas(100.0f, 100.0f); // graphics context GraphicsContext graphics_context = canvas.getGraphicsContext2D(); // set fill for rectangle graphics_context.setFill(Color.RED); graphics_context.fillRect(20, 20, 70, 70); // set fill for oval graphics_context.setFill(Color.BLUE); graphics_context.fillOval(30, 30, 70, 70); // create a Group Group group = new Group(canvas); // create a scene Scene scene = new Scene(group, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a canvas and use setHeight() and setWidth() function to set canvas size and add it to the stage and also add a circle and rectangle on it: In this program we will create a Canvas named canvas and set the width and height using the setWidth() and setHeight() function. We will extract the GraphicsContext using the getGraphicsContext2D() function and draw two rectangles and a oval of different color. We will create a Group named group and add the canvas to the group. We will create a scene and add the group to the scene and then attach the scene to the stage. Finally, call the show() function to display the results.// Java Program to create a canvas and use // setHeight() and setWidth() function to// set canvas size and add it to the stage// and also add a circle and rectangle on itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.paint.Color;import javafx.scene.Group; public class canvas1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating canvas"); // create a canvas Canvas canvas = new Canvas(); // set height and width canvas.setHeight(400); canvas.setWidth(400); // graphics context GraphicsContext graphics_context = canvas.getGraphicsContext2D(); // set fill for rectangle graphics_context.setFill(Color.PINK); graphics_context.fillRect(40, 40, 100, 100); // set fill for rectangle graphics_context.setFill(Color.RED); graphics_context.fillRect(20, 20, 70, 70); // set fill for oval graphics_context.setFill(Color.BLUE); graphics_context.fillOval(30, 30, 70, 70); // create a Group Group group = new Group(canvas); // create a scene Scene scene = new Scene(group, 400, 400); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE. Please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/canvas/Canvas.htmlMy Personal Notes arrow_drop_upSave Java Program to create a canvas with specified width and height(as arguments of constructor), add it to the stage and also add a circle and rectangle on it: In this program we will create a Canvas named canvas with specified width and height. We will extract the GraphicsContext using the getGraphicsContext2D() function and draw a rectangle and a oval of different color. Now we will create a Group named group and add the canvas to the group. Now create a scene and add the group to the scene and then attach the scene to the stage and call the show() function to display the results.// Java Program to create a canvas with specified// width and height(as arguments of constructor),// add it to the stage and also add a circle and// rectangle on itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.paint.Color;import javafx.scene.Group; public class canvas extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating canvas"); // create a canvas Canvas canvas = new Canvas(100.0f, 100.0f); // graphics context GraphicsContext graphics_context = canvas.getGraphicsContext2D(); // set fill for rectangle graphics_context.setFill(Color.RED); graphics_context.fillRect(20, 20, 70, 70); // set fill for oval graphics_context.setFill(Color.BLUE); graphics_context.fillOval(30, 30, 70, 70); // create a Group Group group = new Group(canvas); // create a scene Scene scene = new Scene(group, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output: // Java Program to create a canvas with specified// width and height(as arguments of constructor),// add it to the stage and also add a circle and// rectangle on itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.paint.Color;import javafx.scene.Group; public class canvas extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating canvas"); // create a canvas Canvas canvas = new Canvas(100.0f, 100.0f); // graphics context GraphicsContext graphics_context = canvas.getGraphicsContext2D(); // set fill for rectangle graphics_context.setFill(Color.RED); graphics_context.fillRect(20, 20, 70, 70); // set fill for oval graphics_context.setFill(Color.BLUE); graphics_context.fillOval(30, 30, 70, 70); // create a Group Group group = new Group(canvas); // create a scene Scene scene = new Scene(group, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }} Output: Java Program to create a canvas and use setHeight() and setWidth() function to set canvas size and add it to the stage and also add a circle and rectangle on it: In this program we will create a Canvas named canvas and set the width and height using the setWidth() and setHeight() function. We will extract the GraphicsContext using the getGraphicsContext2D() function and draw two rectangles and a oval of different color. We will create a Group named group and add the canvas to the group. We will create a scene and add the group to the scene and then attach the scene to the stage. Finally, call the show() function to display the results.// Java Program to create a canvas and use // setHeight() and setWidth() function to// set canvas size and add it to the stage// and also add a circle and rectangle on itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.paint.Color;import javafx.scene.Group; public class canvas1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating canvas"); // create a canvas Canvas canvas = new Canvas(); // set height and width canvas.setHeight(400); canvas.setWidth(400); // graphics context GraphicsContext graphics_context = canvas.getGraphicsContext2D(); // set fill for rectangle graphics_context.setFill(Color.PINK); graphics_context.fillRect(40, 40, 100, 100); // set fill for rectangle graphics_context.setFill(Color.RED); graphics_context.fillRect(20, 20, 70, 70); // set fill for oval graphics_context.setFill(Color.BLUE); graphics_context.fillOval(30, 30, 70, 70); // create a Group Group group = new Group(canvas); // create a scene Scene scene = new Scene(group, 400, 400); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output: // Java Program to create a canvas and use // setHeight() and setWidth() function to// set canvas size and add it to the stage// and also add a circle and rectangle on itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.paint.Color;import javafx.scene.Group; public class canvas1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating canvas"); // create a canvas Canvas canvas = new Canvas(); // set height and width canvas.setHeight(400); canvas.setWidth(400); // graphics context GraphicsContext graphics_context = canvas.getGraphicsContext2D(); // set fill for rectangle graphics_context.setFill(Color.PINK); graphics_context.fillRect(40, 40, 100, 100); // set fill for rectangle graphics_context.setFill(Color.RED); graphics_context.fillRect(20, 20, 70, 70); // set fill for oval graphics_context.setFill(Color.BLUE); graphics_context.fillOval(30, 30, 70, 70); // create a Group Group group = new Group(canvas); // create a scene Scene scene = new Scene(group, 400, 400); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }} Output: Note: The above programs might not run in an online IDE. Please use an offline compiler. Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/canvas/Canvas.html JavaFX Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Sep, 2018" }, { "code": null, "e": 299, "s": 28, "text": "Canvas class is a part of JavaFX. Canvas class basically creates an image that can be drawn on using a set of graphics commands provided by a GraphicsContext. Canvas has a specified height and width and all the drawing operations are clipped to the bounds of the canvas." }, { "code": null, "e": 326, "s": 299, "text": "Constructors of the class:" }, { "code": null, "e": 453, "s": 326, "text": "Canvas(): Creates a new canvas object.Canvas(double w, double h): Creates a new canvas object with specified width and height." }, { "code": null, "e": 492, "s": 453, "text": "Canvas(): Creates a new canvas object." }, { "code": null, "e": 581, "s": 492, "text": "Canvas(double w, double h): Creates a new canvas object with specified width and height." }, { "code": null, "e": 604, "s": 581, "text": "Commonly Used Methods:" }, { "code": null, "e": 655, "s": 604, "text": "Below programs illustrate the use of Canvas class:" }, { "code": null, "e": 5244, "s": 655, "text": "Java Program to create a canvas with specified width and height(as arguments of constructor), add it to the stage and also add a circle and rectangle on it: In this program we will create a Canvas named canvas with specified width and height. We will extract the GraphicsContext using the getGraphicsContext2D() function and draw a rectangle and a oval of different color. Now we will create a Group named group and add the canvas to the group. Now create a scene and add the group to the scene and then attach the scene to the stage and call the show() function to display the results.// Java Program to create a canvas with specified// width and height(as arguments of constructor),// add it to the stage and also add a circle and// rectangle on itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.paint.Color;import javafx.scene.Group; public class canvas extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating canvas\"); // create a canvas Canvas canvas = new Canvas(100.0f, 100.0f); // graphics context GraphicsContext graphics_context = canvas.getGraphicsContext2D(); // set fill for rectangle graphics_context.setFill(Color.RED); graphics_context.fillRect(20, 20, 70, 70); // set fill for oval graphics_context.setFill(Color.BLUE); graphics_context.fillOval(30, 30, 70, 70); // create a Group Group group = new Group(canvas); // create a scene Scene scene = new Scene(group, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a canvas and use setHeight() and setWidth() function to set canvas size and add it to the stage and also add a circle and rectangle on it: In this program we will create a Canvas named canvas and set the width and height using the setWidth() and setHeight() function. We will extract the GraphicsContext using the getGraphicsContext2D() function and draw two rectangles and a oval of different color. We will create a Group named group and add the canvas to the group. We will create a scene and add the group to the scene and then attach the scene to the stage. Finally, call the show() function to display the results.// Java Program to create a canvas and use // setHeight() and setWidth() function to// set canvas size and add it to the stage// and also add a circle and rectangle on itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.paint.Color;import javafx.scene.Group; public class canvas1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating canvas\"); // create a canvas Canvas canvas = new Canvas(); // set height and width canvas.setHeight(400); canvas.setWidth(400); // graphics context GraphicsContext graphics_context = canvas.getGraphicsContext2D(); // set fill for rectangle graphics_context.setFill(Color.PINK); graphics_context.fillRect(40, 40, 100, 100); // set fill for rectangle graphics_context.setFill(Color.RED); graphics_context.fillRect(20, 20, 70, 70); // set fill for oval graphics_context.setFill(Color.BLUE); graphics_context.fillOval(30, 30, 70, 70); // create a Group Group group = new Group(canvas); // create a scene Scene scene = new Scene(group, 400, 400); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE. Please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/canvas/Canvas.htmlMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 7298, "s": 5244, "text": "Java Program to create a canvas with specified width and height(as arguments of constructor), add it to the stage and also add a circle and rectangle on it: In this program we will create a Canvas named canvas with specified width and height. We will extract the GraphicsContext using the getGraphicsContext2D() function and draw a rectangle and a oval of different color. Now we will create a Group named group and add the canvas to the group. Now create a scene and add the group to the scene and then attach the scene to the stage and call the show() function to display the results.// Java Program to create a canvas with specified// width and height(as arguments of constructor),// add it to the stage and also add a circle and// rectangle on itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.paint.Color;import javafx.scene.Group; public class canvas extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating canvas\"); // create a canvas Canvas canvas = new Canvas(100.0f, 100.0f); // graphics context GraphicsContext graphics_context = canvas.getGraphicsContext2D(); // set fill for rectangle graphics_context.setFill(Color.RED); graphics_context.fillRect(20, 20, 70, 70); // set fill for oval graphics_context.setFill(Color.BLUE); graphics_context.fillOval(30, 30, 70, 70); // create a Group Group group = new Group(canvas); // create a scene Scene scene = new Scene(group, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:" }, { "code": "// Java Program to create a canvas with specified// width and height(as arguments of constructor),// add it to the stage and also add a circle and// rectangle on itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.paint.Color;import javafx.scene.Group; public class canvas extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating canvas\"); // create a canvas Canvas canvas = new Canvas(100.0f, 100.0f); // graphics context GraphicsContext graphics_context = canvas.getGraphicsContext2D(); // set fill for rectangle graphics_context.setFill(Color.RED); graphics_context.fillRect(20, 20, 70, 70); // set fill for oval graphics_context.setFill(Color.BLUE); graphics_context.fillOval(30, 30, 70, 70); // create a Group Group group = new Group(canvas); // create a scene Scene scene = new Scene(group, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}", "e": 8759, "s": 7298, "text": null }, { "code": null, "e": 8767, "s": 8759, "text": "Output:" }, { "code": null, "e": 11094, "s": 8767, "text": "Java Program to create a canvas and use setHeight() and setWidth() function to set canvas size and add it to the stage and also add a circle and rectangle on it: In this program we will create a Canvas named canvas and set the width and height using the setWidth() and setHeight() function. We will extract the GraphicsContext using the getGraphicsContext2D() function and draw two rectangles and a oval of different color. We will create a Group named group and add the canvas to the group. We will create a scene and add the group to the scene and then attach the scene to the stage. Finally, call the show() function to display the results.// Java Program to create a canvas and use // setHeight() and setWidth() function to// set canvas size and add it to the stage// and also add a circle and rectangle on itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.paint.Color;import javafx.scene.Group; public class canvas1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating canvas\"); // create a canvas Canvas canvas = new Canvas(); // set height and width canvas.setHeight(400); canvas.setWidth(400); // graphics context GraphicsContext graphics_context = canvas.getGraphicsContext2D(); // set fill for rectangle graphics_context.setFill(Color.PINK); graphics_context.fillRect(40, 40, 100, 100); // set fill for rectangle graphics_context.setFill(Color.RED); graphics_context.fillRect(20, 20, 70, 70); // set fill for oval graphics_context.setFill(Color.BLUE); graphics_context.fillOval(30, 30, 70, 70); // create a Group Group group = new Group(canvas); // create a scene Scene scene = new Scene(group, 400, 400); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:" }, { "code": "// Java Program to create a canvas and use // setHeight() and setWidth() function to// set canvas size and add it to the stage// and also add a circle and rectangle on itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.paint.Color;import javafx.scene.Group; public class canvas1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating canvas\"); // create a canvas Canvas canvas = new Canvas(); // set height and width canvas.setHeight(400); canvas.setWidth(400); // graphics context GraphicsContext graphics_context = canvas.getGraphicsContext2D(); // set fill for rectangle graphics_context.setFill(Color.PINK); graphics_context.fillRect(40, 40, 100, 100); // set fill for rectangle graphics_context.setFill(Color.RED); graphics_context.fillRect(20, 20, 70, 70); // set fill for oval graphics_context.setFill(Color.BLUE); graphics_context.fillOval(30, 30, 70, 70); // create a Group Group group = new Group(canvas); // create a scene Scene scene = new Scene(group, 400, 400); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}", "e": 12771, "s": 11094, "text": null }, { "code": null, "e": 12779, "s": 12771, "text": "Output:" }, { "code": null, "e": 12868, "s": 12779, "text": "Note: The above programs might not run in an online IDE. Please use an offline compiler." }, { "code": null, "e": 12955, "s": 12868, "text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/canvas/Canvas.html" }, { "code": null, "e": 12962, "s": 12955, "text": "JavaFX" }, { "code": null, "e": 12967, "s": 12962, "text": "Java" }, { "code": null, "e": 12972, "s": 12967, "text": "Java" } ]
How to display Current Date/Time in the DateTimePicker in C#?
02 Aug, 2019 In Windows Forms, the DateTimePicker control is used to select and display date/time with a specific format in your form. In DateTimePicker control, you can set the current Date/Time using the Value Property. or in other words, we can say that Value property is used to assign a Date/Time value to the DateTimePicker control. The default value of this property is the current date/time. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the value for the DateTimePicker as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Next, drag and drop the DateTimePicker control from the toolbox to the form as shown in the below image: Step 3: After drag and drop you will go to the properties of the DateTimePicker and set the value for the DateTimePicker as shown in the below image:Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set a date and time value for the DateTimePicker control programmatically with the help of given syntax: public DateTime Value { get; set; } It will throw an ArgumentOutOfRangeException if the value of this property is less than MinDate or more than MaxDate. The following steps show how to set the value for the DateTimePicker dynamically: Step 1: Create a DateTimePicker using the DateTimePicker() constructor is provided by the DateTimePicker class.// Creating a DateTimePicker DateTimePicker dt = new DateTimePicker(); // Creating a DateTimePicker DateTimePicker dt = new DateTimePicker(); Step 2: After creating DateTimePicker, set the Value property of the DateTimePicker provided by the DateTimePicker class.// Setting the value dt.Value = DateTime.Today; // Setting the value dt.Value = DateTime.Today; Step 3: And last add this DateTimePicker control to the form using the following statement:// Adding this control to the form this.Controls.Add(dt); // Adding this control to the form this.Controls.Add(dt); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp48 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label lab = new Label(); lab.Location = new Point(183, 162); lab.Size = new Size(172, 20); lab.Text = "Select Date and Time"; lab.Font = new Font("Comic Sans MS", 12); // Adding this control to the form this.Controls.Add(lab); // Creating and setting the // properties of the DateTimePicker DateTimePicker dt = new DateTimePicker(); dt.Location = new Point(360, 162); dt.Size = new Size(292, 26); dt.MaxDate = new DateTime(2500, 12, 20); dt.MinDate = new DateTime(1753, 1, 1); dt.Format = DateTimePickerFormat.Long; dt.Name = "MyPicker"; dt.Font = new Font("Comic Sans MS", 12); dt.Visible = true; dt.Value = DateTime.Today; // Adding this control // to the form this.Controls.Add(dt); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Aug, 2019" }, { "code": null, "e": 490, "s": 54, "text": "In Windows Forms, the DateTimePicker control is used to select and display date/time with a specific format in your form. In DateTimePicker control, you can set the current Date/Time using the Value Property. or in other words, we can say that Value property is used to assign a Date/Time value to the DateTimePicker control. The default value of this property is the current date/time. You can set this property in two different ways:" }, { "code": null, "e": 601, "s": 490, "text": "1. Design-Time: It is the easiest way to set the value for the DateTimePicker as shown in the following steps:" }, { "code": null, "e": 717, "s": 601, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 830, "s": 717, "text": "Step 2: Next, drag and drop the DateTimePicker control from the toolbox to the form as shown in the below image:" }, { "code": null, "e": 987, "s": 830, "text": "Step 3: After drag and drop you will go to the properties of the DateTimePicker and set the value for the DateTimePicker as shown in the below image:Output:" }, { "code": null, "e": 995, "s": 987, "text": "Output:" }, { "code": null, "e": 1188, "s": 995, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set a date and time value for the DateTimePicker control programmatically with the help of given syntax:" }, { "code": null, "e": 1224, "s": 1188, "text": "public DateTime Value { get; set; }" }, { "code": null, "e": 1424, "s": 1224, "text": "It will throw an ArgumentOutOfRangeException if the value of this property is less than MinDate or more than MaxDate. The following steps show how to set the value for the DateTimePicker dynamically:" }, { "code": null, "e": 1607, "s": 1424, "text": "Step 1: Create a DateTimePicker using the DateTimePicker() constructor is provided by the DateTimePicker class.// Creating a DateTimePicker\nDateTimePicker dt = new DateTimePicker();\n" }, { "code": null, "e": 1679, "s": 1607, "text": "// Creating a DateTimePicker\nDateTimePicker dt = new DateTimePicker();\n" }, { "code": null, "e": 1849, "s": 1679, "text": "Step 2: After creating DateTimePicker, set the Value property of the DateTimePicker provided by the DateTimePicker class.// Setting the value\ndt.Value = DateTime.Today;\n" }, { "code": null, "e": 1898, "s": 1849, "text": "// Setting the value\ndt.Value = DateTime.Today;\n" }, { "code": null, "e": 2048, "s": 1898, "text": "Step 3: And last add this DateTimePicker control to the form using the following statement:// Adding this control to the form\nthis.Controls.Add(dt);\n" }, { "code": null, "e": 2107, "s": 2048, "text": "// Adding this control to the form\nthis.Controls.Add(dt);\n" }, { "code": null, "e": 2116, "s": 2107, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp48 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label lab = new Label(); lab.Location = new Point(183, 162); lab.Size = new Size(172, 20); lab.Text = \"Select Date and Time\"; lab.Font = new Font(\"Comic Sans MS\", 12); // Adding this control to the form this.Controls.Add(lab); // Creating and setting the // properties of the DateTimePicker DateTimePicker dt = new DateTimePicker(); dt.Location = new Point(360, 162); dt.Size = new Size(292, 26); dt.MaxDate = new DateTime(2500, 12, 20); dt.MinDate = new DateTime(1753, 1, 1); dt.Format = DateTimePickerFormat.Long; dt.Name = \"MyPicker\"; dt.Font = new Font(\"Comic Sans MS\", 12); dt.Visible = true; dt.Value = DateTime.Today; // Adding this control // to the form this.Controls.Add(dt); }}}", "e": 3436, "s": 2116, "text": null }, { "code": null, "e": 3444, "s": 3436, "text": "Output:" }, { "code": null, "e": 3475, "s": 3444, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 3478, "s": 3475, "text": "C#" } ]