title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
HTML - <doctype> Tag
|
The HTML <doctype> tag is used for specifying which version of HTML the document is using. This is referred to as the document type declaration (DTD).
NOTE − The <!DOCTYPE> tag does not have an end tag!.
<!DOCTYPE html>
<html>
<head>
<title>HTML doctype Tag</title>
</head>
<body>
<p>doctype declaration <doctype> is mentioned at the starting of
every HTML document.</p>
</body>
</html>
This will produce the following result −
doctype declaration is mentioned at the starting of every HTML document.
HTML 4.01 has 3 possible doctypes − HTML 4 Strict, HTML 4 Transitional, and HTML 4 Frameset. Every HTML document you create should have one of these three DTDs.
This document type includes all HTML elements except those that have been deprecated, and those that appear in frameset documents.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
This document type includes all HTML elements including those that have been deprecated.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">;
This document type includes all HTML elements in the transitional DTD as well as those in framed document.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
"http://www.w3.org/TR/html4/frameset.dtd">
In HTML5 there is only one declaration i.e.
|
[
{
"code": null,
"e": 2659,
"s": 2508,
"text": "The HTML <doctype> tag is used for specifying which version of HTML the document is using. This is referred to as the document type declaration (DTD)."
},
{
"code": null,
"e": 2712,
"s": 2659,
"text": "NOTE − The <!DOCTYPE> tag does not have an end tag!."
},
{
"code": null,
"e": 2930,
"s": 2712,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML doctype Tag</title>\n </head>\n\n <body>\n <p>doctype declaration <doctype> is mentioned at the starting of\n every HTML document.</p>\n </body>\n</html>"
},
{
"code": null,
"e": 2971,
"s": 2930,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3045,
"s": 2971,
"text": "doctype declaration is mentioned at the starting of every HTML document."
},
{
"code": null,
"e": 3206,
"s": 3045,
"text": "HTML 4.01 has 3 possible doctypes − HTML 4 Strict, HTML 4 Transitional, and HTML 4 Frameset. Every HTML document you create should have one of these three DTDs."
},
{
"code": null,
"e": 3337,
"s": 3206,
"text": "This document type includes all HTML elements except those that have been deprecated, and those that appear in frameset documents."
},
{
"code": null,
"e": 3431,
"s": 3337,
"text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\">"
},
{
"code": null,
"e": 3520,
"s": 3431,
"text": "This document type includes all HTML elements including those that have been deprecated."
},
{
"code": null,
"e": 3627,
"s": 3520,
"text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n \"http://www.w3.org/TR/html4/loose.dtd\">;"
},
{
"code": null,
"e": 3734,
"s": 3627,
"text": "This document type includes all HTML elements in the transitional DTD as well as those in framed document."
},
{
"code": null,
"e": 3839,
"s": 3734,
"text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\"\n \"http://www.w3.org/TR/html4/frameset.dtd\">"
}
] |
TypeScript | Array every() Method
|
18 Jun, 2020
The Array.every() is an inbuilt TypeScript function which is used to check for all the elements in an array passes the test implemented by the provided function. Syntax:
array.every(callback[, thisObject])
Parameter: This method accepts two parameter as mentioned above and described below:
callback : This parameter is the Function to test for each element.
thisObject : This parameter is the Object to use as this when executing callback.
Return Value: This method returns true if every element in this array satisfies the provided testing function. Below examples illustrate Array every() method in TypeScript
Example 1:
JavaScript
<script> // Check for positive number function ispositive(element, index, array) { return element > 0; } // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // Check for positive number var value = arr.every(ispositive); console.log( value );</script>
Output:
true
Example 2:
JavaScript
<script> // Check for odd number function isodd(element, index, array) { return (element % 2 == 1); } // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // Check for positive number var value = arr.every(isodd); console.log( value );</script>
Output:
false
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
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": "\n18 Jun, 2020"
},
{
"code": null,
"e": 198,
"s": 28,
"text": "The Array.every() is an inbuilt TypeScript function which is used to check for all the elements in an array passes the test implemented by the provided function. Syntax:"
},
{
"code": null,
"e": 234,
"s": 198,
"text": "array.every(callback[, thisObject])"
},
{
"code": null,
"e": 319,
"s": 234,
"text": "Parameter: This method accepts two parameter as mentioned above and described below:"
},
{
"code": null,
"e": 387,
"s": 319,
"text": "callback : This parameter is the Function to test for each element."
},
{
"code": null,
"e": 469,
"s": 387,
"text": "thisObject : This parameter is the Object to use as this when executing callback."
},
{
"code": null,
"e": 641,
"s": 469,
"text": "Return Value: This method returns true if every element in this array satisfies the provided testing function. Below examples illustrate Array every() method in TypeScript"
},
{
"code": null,
"e": 653,
"s": 641,
"text": "Example 1: "
},
{
"code": null,
"e": 664,
"s": 653,
"text": "JavaScript"
},
{
"code": "<script> // Check for positive number function ispositive(element, index, array) { return element > 0; } // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // Check for positive number var value = arr.every(ispositive); console.log( value );</script>",
"e": 961,
"s": 664,
"text": null
},
{
"code": null,
"e": 970,
"s": 961,
"text": "Output: "
},
{
"code": null,
"e": 975,
"s": 970,
"text": "true"
},
{
"code": null,
"e": 987,
"s": 975,
"text": "Example 2: "
},
{
"code": null,
"e": 998,
"s": 987,
"text": "JavaScript"
},
{
"code": "<script> // Check for odd number function isodd(element, index, array) { return (element % 2 == 1); } // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // Check for positive number var value = arr.every(isodd); console.log( value );</script>",
"e": 1289,
"s": 998,
"text": null
},
{
"code": null,
"e": 1298,
"s": 1289,
"text": "Output: "
},
{
"code": null,
"e": 1304,
"s": 1298,
"text": "false"
},
{
"code": null,
"e": 1315,
"s": 1304,
"text": "TypeScript"
},
{
"code": null,
"e": 1326,
"s": 1315,
"text": "JavaScript"
},
{
"code": null,
"e": 1343,
"s": 1326,
"text": "Web Technologies"
},
{
"code": null,
"e": 1441,
"s": 1343,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1502,
"s": 1441,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1574,
"s": 1502,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1614,
"s": 1574,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1655,
"s": 1614,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1707,
"s": 1655,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 1740,
"s": 1707,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1802,
"s": 1740,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1863,
"s": 1802,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1913,
"s": 1863,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Select Rows With Multiple Filters in Pandas
|
24 Jan, 2021
In this article, we are going to select rows using multiple filters in pandas. We will select multiple rows in pandas using multiple conditions, logical operators and using loc() function.
Selecting rows with logical operators i.e. AND and OR can be achieved easily with a combination of >, <, <=, >= and == to extract rows with multiple filters. loc() is primarily label based, but may also be used with a boolean array to access a group of rows and columns by label or a boolean array.
Dataset Used:
Creating a dataframe with columns Name, Class, Marks in English, Marks in Maths, and Marks in History. We are going to use the below dataset for all operations:
Python
import pandas as pd # initialize list of listsdata = [['John', 8, 7, 6, 5], ['Paul', 8, 3, 6, 4], ['Juli', 9, 10, 9, 9], ['Geeta', 9, 5, 4, 4]] # Create the pandas DataFramedf = pd.DataFrame( data, columns=['Name', 'Class', 'English', 'Maths', 'History']) # print dataframe.print(df)
Output
Below are various operations which implement the selection of rows with multiple filters:
Selecting row with students having marks is English greater than 6 and marks is maths greater than 8.
Python
df1 = df[(df.English>6) & (df.Maths>8)]print(df1)
Output:
Selecting rows with students having marks in English greater than equal to 5 or marks is history greater than 7.
Python
df1 = df[(df.English>=5) | (df.History>7)]print(df1)
Output
Selecting rows with students of class 9 having marks in English greater than equal to 5 or marks is history greater than 7.
Python
df1 = df[(df.Class == 9) & ((df.English>=5) | (df.History>7))]print(df1)
Output:
Selecting row with students having marks in English less than equal to 5 and marks is maths less than equal to 5 and marks is history less than equal to 5.
Python
df1 = df[(df.English<=5) & (df.Maths<=5) & (df.History<=5)]print(df1)
Output:
Selecting rows with students of class 8 having marks in English less than equal to 5 or marks is maths greater than 5 or marks is history less than equal to 5.
Python
df1 = df[(df.Class == 8) & ((df.English<=5) | (df.Maths>5) | (df.History<=5))]print(df1)
Output:
Selecting rows with loc() having marks in English greater than 6 and marks in maths greater than 6.
Python
df1 = df.loc[(df['English']>6) & (df['Maths']>6)]print(df1)
Output:
Selecting rows with loc() having students marks in English greater than 6 or marks in maths greater than 4. We only display columns with Name and Class.
Python
df1 = df.loc[((df['English']>6) | (df['Maths']>4)),['Name','Class']]print(df1)
Output:
Picked
Python Pandas-exercise
Python-pandas
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": "\n24 Jan, 2021"
},
{
"code": null,
"e": 217,
"s": 28,
"text": "In this article, we are going to select rows using multiple filters in pandas. We will select multiple rows in pandas using multiple conditions, logical operators and using loc() function."
},
{
"code": null,
"e": 516,
"s": 217,
"text": "Selecting rows with logical operators i.e. AND and OR can be achieved easily with a combination of >, <, <=, >= and == to extract rows with multiple filters. loc() is primarily label based, but may also be used with a boolean array to access a group of rows and columns by label or a boolean array."
},
{
"code": null,
"e": 530,
"s": 516,
"text": "Dataset Used:"
},
{
"code": null,
"e": 694,
"s": 530,
"text": "Creating a dataframe with columns Name, Class, Marks in English, Marks in Maths, and Marks in History. We are going to use the below dataset for all operations: "
},
{
"code": null,
"e": 701,
"s": 694,
"text": "Python"
},
{
"code": "import pandas as pd # initialize list of listsdata = [['John', 8, 7, 6, 5], ['Paul', 8, 3, 6, 4], ['Juli', 9, 10, 9, 9], ['Geeta', 9, 5, 4, 4]] # Create the pandas DataFramedf = pd.DataFrame( data, columns=['Name', 'Class', 'English', 'Maths', 'History']) # print dataframe.print(df)",
"e": 1017,
"s": 701,
"text": null
},
{
"code": null,
"e": 1024,
"s": 1017,
"text": "Output"
},
{
"code": null,
"e": 1114,
"s": 1024,
"text": "Below are various operations which implement the selection of rows with multiple filters:"
},
{
"code": null,
"e": 1216,
"s": 1114,
"text": "Selecting row with students having marks is English greater than 6 and marks is maths greater than 8."
},
{
"code": null,
"e": 1223,
"s": 1216,
"text": "Python"
},
{
"code": "df1 = df[(df.English>6) & (df.Maths>8)]print(df1)",
"e": 1273,
"s": 1223,
"text": null
},
{
"code": null,
"e": 1281,
"s": 1273,
"text": "Output:"
},
{
"code": null,
"e": 1394,
"s": 1281,
"text": "Selecting rows with students having marks in English greater than equal to 5 or marks is history greater than 7."
},
{
"code": null,
"e": 1401,
"s": 1394,
"text": "Python"
},
{
"code": "df1 = df[(df.English>=5) | (df.History>7)]print(df1)",
"e": 1454,
"s": 1401,
"text": null
},
{
"code": null,
"e": 1461,
"s": 1454,
"text": "Output"
},
{
"code": null,
"e": 1585,
"s": 1461,
"text": "Selecting rows with students of class 9 having marks in English greater than equal to 5 or marks is history greater than 7."
},
{
"code": null,
"e": 1592,
"s": 1585,
"text": "Python"
},
{
"code": "df1 = df[(df.Class == 9) & ((df.English>=5) | (df.History>7))]print(df1)",
"e": 1665,
"s": 1592,
"text": null
},
{
"code": null,
"e": 1673,
"s": 1665,
"text": "Output:"
},
{
"code": null,
"e": 1829,
"s": 1673,
"text": "Selecting row with students having marks in English less than equal to 5 and marks is maths less than equal to 5 and marks is history less than equal to 5."
},
{
"code": null,
"e": 1836,
"s": 1829,
"text": "Python"
},
{
"code": "df1 = df[(df.English<=5) & (df.Maths<=5) & (df.History<=5)]print(df1)",
"e": 1906,
"s": 1836,
"text": null
},
{
"code": null,
"e": 1914,
"s": 1906,
"text": "Output:"
},
{
"code": null,
"e": 2074,
"s": 1914,
"text": "Selecting rows with students of class 8 having marks in English less than equal to 5 or marks is maths greater than 5 or marks is history less than equal to 5."
},
{
"code": null,
"e": 2081,
"s": 2074,
"text": "Python"
},
{
"code": "df1 = df[(df.Class == 8) & ((df.English<=5) | (df.Maths>5) | (df.History<=5))]print(df1)",
"e": 2170,
"s": 2081,
"text": null
},
{
"code": null,
"e": 2178,
"s": 2170,
"text": "Output:"
},
{
"code": null,
"e": 2278,
"s": 2178,
"text": "Selecting rows with loc() having marks in English greater than 6 and marks in maths greater than 6."
},
{
"code": null,
"e": 2285,
"s": 2278,
"text": "Python"
},
{
"code": "df1 = df.loc[(df['English']>6) & (df['Maths']>6)]print(df1)",
"e": 2345,
"s": 2285,
"text": null
},
{
"code": null,
"e": 2353,
"s": 2345,
"text": "Output:"
},
{
"code": null,
"e": 2506,
"s": 2353,
"text": "Selecting rows with loc() having students marks in English greater than 6 or marks in maths greater than 4. We only display columns with Name and Class."
},
{
"code": null,
"e": 2513,
"s": 2506,
"text": "Python"
},
{
"code": "df1 = df.loc[((df['English']>6) | (df['Maths']>4)),['Name','Class']]print(df1)",
"e": 2592,
"s": 2513,
"text": null
},
{
"code": null,
"e": 2600,
"s": 2592,
"text": "Output:"
},
{
"code": null,
"e": 2607,
"s": 2600,
"text": "Picked"
},
{
"code": null,
"e": 2630,
"s": 2607,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 2644,
"s": 2630,
"text": "Python-pandas"
},
{
"code": null,
"e": 2651,
"s": 2644,
"text": "Python"
},
{
"code": null,
"e": 2749,
"s": 2651,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2781,
"s": 2749,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2808,
"s": 2781,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2829,
"s": 2808,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2852,
"s": 2829,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2908,
"s": 2852,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2939,
"s": 2908,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2981,
"s": 2939,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3023,
"s": 2981,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3062,
"s": 3023,
"text": "Python | Get unique values from a list"
}
] |
Recursive Relationships in ER diagrams
|
10 Jun, 2021
Prerequisite – ER Model A relationship between two entities of a similar entity type is called a recursive relationship. Here the same entity type participates more than once in a relationship type with a different role for each instance. In other words, a relationship has always been between occurrences in two different entities. However, the same entity can participate in the relationship. This is termed a recursive relationship.
Example – Let us suppose that we have an employee table. A manager supervises a subordinate. Every employee can have a supervisor except the CEO and there can be at most one boss for each employee. One employee may be the boss of more than one employee. Let’s suppose that REPORTS_TO is a recursive relationship on the Employee entity type where each Employee plays two roles.
SupervisorSubordinate
Supervisor
Subordinate
Supervisors and subordinates are called “Role Names”. Here the degree of the REPORTS_TO relationship is 1 i.e. a unary relationship.
The minimum cardinality of the Supervisor entity is ZERO since the lowest level employee may not be a manager for anyone.
The maximum cardinality of the Supervisor entity is N since an employee can manage many employees.
Similarly, the Subordinate entity has a minimum cardinality of ZERO to account for the case where CEO can never be a subordinate.
Its maximum cardinality is ONE since a subordinate employee can have at most one supervisor.
Note – Here none of the participants have total participation since both minimum cardinalities are Zero. Hence, the relationships are connected by a single line instead of a double line in the ER diagram.
To implement a recursive relationship, a foreign key of the employee’s manager number would be held in each employee record. A Sample table would look something like this:-
Emp_entity( Emp_no,Emp_Fname, Emp_Lname, Emp_DOB, Emp_NI_Number, Manager_no);
Manager no - (this is the employee no of the employee's manager)
This article is contributed by Siddhant Bajaj 2. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
magbene
vaibhavsinghtanwar
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
SQL query to find second highest salary?
CTE in SQL
Difference between Clustered and Non-clustered index
Layers of OSI Model
TCP/IP Model
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Introduction of Operating System - Set 1
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 491,
"s": 54,
"text": "Prerequisite – ER Model A relationship between two entities of a similar entity type is called a recursive relationship. Here the same entity type participates more than once in a relationship type with a different role for each instance. In other words, a relationship has always been between occurrences in two different entities. However, the same entity can participate in the relationship. This is termed a recursive relationship. "
},
{
"code": null,
"e": 870,
"s": 493,
"text": "Example – Let us suppose that we have an employee table. A manager supervises a subordinate. Every employee can have a supervisor except the CEO and there can be at most one boss for each employee. One employee may be the boss of more than one employee. Let’s suppose that REPORTS_TO is a recursive relationship on the Employee entity type where each Employee plays two roles."
},
{
"code": null,
"e": 893,
"s": 870,
"text": "SupervisorSubordinate "
},
{
"code": null,
"e": 904,
"s": 893,
"text": "Supervisor"
},
{
"code": null,
"e": 917,
"s": 904,
"text": "Subordinate "
},
{
"code": null,
"e": 1054,
"s": 919,
"text": "Supervisors and subordinates are called “Role Names”. Here the degree of the REPORTS_TO relationship is 1 i.e. a unary relationship. "
},
{
"code": null,
"e": 1176,
"s": 1054,
"text": "The minimum cardinality of the Supervisor entity is ZERO since the lowest level employee may not be a manager for anyone."
},
{
"code": null,
"e": 1275,
"s": 1176,
"text": "The maximum cardinality of the Supervisor entity is N since an employee can manage many employees."
},
{
"code": null,
"e": 1405,
"s": 1275,
"text": "Similarly, the Subordinate entity has a minimum cardinality of ZERO to account for the case where CEO can never be a subordinate."
},
{
"code": null,
"e": 1498,
"s": 1405,
"text": "Its maximum cardinality is ONE since a subordinate employee can have at most one supervisor."
},
{
"code": null,
"e": 1704,
"s": 1498,
"text": "Note – Here none of the participants have total participation since both minimum cardinalities are Zero. Hence, the relationships are connected by a single line instead of a double line in the ER diagram. "
},
{
"code": null,
"e": 1878,
"s": 1704,
"text": "To implement a recursive relationship, a foreign key of the employee’s manager number would be held in each employee record. A Sample table would look something like this:- "
},
{
"code": null,
"e": 2022,
"s": 1878,
"text": "Emp_entity( Emp_no,Emp_Fname, Emp_Lname, Emp_DOB, Emp_NI_Number, Manager_no);\n\nManager no - (this is the employee no of the employee's manager)"
},
{
"code": null,
"e": 2323,
"s": 2022,
"text": "This article is contributed by Siddhant Bajaj 2. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 2449,
"s": 2323,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 2457,
"s": 2449,
"text": "magbene"
},
{
"code": null,
"e": 2476,
"s": 2457,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 2481,
"s": 2476,
"text": "DBMS"
},
{
"code": null,
"e": 2489,
"s": 2481,
"text": "GATE CS"
},
{
"code": null,
"e": 2494,
"s": 2489,
"text": "DBMS"
},
{
"code": null,
"e": 2592,
"s": 2494,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2639,
"s": 2592,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 2657,
"s": 2639,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 2698,
"s": 2657,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 2709,
"s": 2698,
"text": "CTE in SQL"
},
{
"code": null,
"e": 2762,
"s": 2709,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 2782,
"s": 2762,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 2795,
"s": 2782,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 2822,
"s": 2795,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 2871,
"s": 2822,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
How to convert a string into kebab case using JavaScript ?
|
01 Apr, 2021
Given a string with space-separated or camel case or snake case letters, the task is to find the kebab case of the following string.
For examples :
Input: Geeks For Geeks
Output: geeks-for-geeks
Input: GeeksForGeeks
Output: geeks-for-geeks
Input: Geeks_for_geeks
Output: geeks-for-geeks
This can be achieved by following ways:
Approach 1: By using the replace method
Here we have a function named kebabCase which takes a string and returns a string after converting the kebab case. Here we are using replace method two times because the first replace method is to get all the letters that are near to the uppercase letters and replacing them with a hyphen. And the second replace function is used for getting the spaces and underscores and replacing them with a hyphen.
Javascript
<script> const kebabCase = string => string .replace(/([a-z])([A-Z])/g, "$1-$2") .replace(/[\s_]+/g, '-') .toLowerCase(); console.log(kebabCase('Geeks For Geeks')); console.log(kebabCase('GeeksForGeeks')); console.log(kebabCase('Geeks_For_Geeks'));</script>
Output:
geeks-for-geeks
geeks-for-geeks
geeks-for-geeks
Approach 2: By using the match method
Here, we use the map method that checks for space, capital letters, and underscores. It creates an array and pushes the words that separate the strings. Now join the array with the hyphen using the join(). After that convert the whole string into a lower case.
Javascript
<script> const kebabCase = str => str .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) .join('-') .toLowerCase(); console.log(kebabCase('Geeks For Geeks')); console.log(kebabCase('GeeksForGeeks')); console.log(kebabCase('Geeks_For_Geeks'));</script>
Output:
geeks-for-geeks
geeks-for-geeks
geeks-for-geeks
JavaScript-Methods
JavaScript-Questions
regular-expression
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
JavaScript String includes() Method
Implementation of LinkedList in Javascript
DOM (Document Object Model)
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 162,
"s": 28,
"text": "Given a string with space-separated or camel case or snake case letters, the task is to find the kebab case of the following string. "
},
{
"code": null,
"e": 177,
"s": 162,
"text": "For examples :"
},
{
"code": null,
"e": 323,
"s": 177,
"text": "Input: Geeks For Geeks\nOutput: geeks-for-geeks\n\nInput: GeeksForGeeks\nOutput: geeks-for-geeks\n\nInput: Geeks_for_geeks\nOutput: geeks-for-geeks"
},
{
"code": null,
"e": 363,
"s": 323,
"text": "This can be achieved by following ways:"
},
{
"code": null,
"e": 403,
"s": 363,
"text": "Approach 1: By using the replace method"
},
{
"code": null,
"e": 807,
"s": 403,
"text": "Here we have a function named kebabCase which takes a string and returns a string after converting the kebab case. Here we are using replace method two times because the first replace method is to get all the letters that are near to the uppercase letters and replacing them with a hyphen. And the second replace function is used for getting the spaces and underscores and replacing them with a hyphen. "
},
{
"code": null,
"e": 818,
"s": 807,
"text": "Javascript"
},
{
"code": "<script> const kebabCase = string => string .replace(/([a-z])([A-Z])/g, \"$1-$2\") .replace(/[\\s_]+/g, '-') .toLowerCase(); console.log(kebabCase('Geeks For Geeks')); console.log(kebabCase('GeeksForGeeks')); console.log(kebabCase('Geeks_For_Geeks'));</script>",
"e": 1111,
"s": 818,
"text": null
},
{
"code": null,
"e": 1119,
"s": 1111,
"text": "Output:"
},
{
"code": null,
"e": 1167,
"s": 1119,
"text": "geeks-for-geeks\ngeeks-for-geeks\ngeeks-for-geeks"
},
{
"code": null,
"e": 1205,
"s": 1167,
"text": "Approach 2: By using the match method"
},
{
"code": null,
"e": 1466,
"s": 1205,
"text": "Here, we use the map method that checks for space, capital letters, and underscores. It creates an array and pushes the words that separate the strings. Now join the array with the hyphen using the join(). After that convert the whole string into a lower case."
},
{
"code": null,
"e": 1477,
"s": 1466,
"text": "Javascript"
},
{
"code": "<script> const kebabCase = str => str .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) .join('-') .toLowerCase(); console.log(kebabCase('Geeks For Geeks')); console.log(kebabCase('GeeksForGeeks')); console.log(kebabCase('Geeks_For_Geeks'));</script>",
"e": 1790,
"s": 1477,
"text": null
},
{
"code": null,
"e": 1798,
"s": 1790,
"text": "Output:"
},
{
"code": null,
"e": 1846,
"s": 1798,
"text": "geeks-for-geeks\ngeeks-for-geeks\ngeeks-for-geeks"
},
{
"code": null,
"e": 1865,
"s": 1846,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 1886,
"s": 1865,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 1905,
"s": 1886,
"text": "regular-expression"
},
{
"code": null,
"e": 1916,
"s": 1905,
"text": "JavaScript"
},
{
"code": null,
"e": 1933,
"s": 1916,
"text": "Web Technologies"
},
{
"code": null,
"e": 2031,
"s": 1933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2092,
"s": 2031,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2132,
"s": 2092,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2168,
"s": 2132,
"text": "JavaScript String includes() Method"
},
{
"code": null,
"e": 2211,
"s": 2168,
"text": "Implementation of LinkedList in Javascript"
},
{
"code": null,
"e": 2239,
"s": 2211,
"text": "DOM (Document Object Model)"
},
{
"code": null,
"e": 2272,
"s": 2239,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2322,
"s": 2272,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2384,
"s": 2322,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2442,
"s": 2384,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
Top 50 Blockchain Interview Questions and Answers
|
11 Nov, 2021
Blockchain is one of the most trending technologies out there in the tech world. It is basically concerned with a distributed database that maintains the records of all transactions that have been executed and shared across the network of computer systems globally. From payment processing to healthcare to supply chain and logistics monitoring – Blockchain has a wide range of uses and applications. Also, there are numerous prominent benefits associated with Blockchain technology including time-saving, cost-saving, decentralized structure, improved security, and privacy, etc. In a nutshell, if you’re looking forward to building a career in the Blockchain domain, then it would be a worthwhile and rewarding career decision for you.
Companies like Samsung, Microsoft, Capgemini, etc. provide remarkable career opportunities for Blockchain Professionals. Further on, to make things a bit more hassle-free for you – here, we’re providing you with an extensive list of 50 Interview Questions for Blockchain that are often asked by the recruiters. Do check out all these questions from below:
1. What is the underlying principle of Blockchain Technology?
Blockchain is a P2P network where no single user controls the transaction. Blockchain principles are as follows:
Decentralization: The power is distributed among all the users in the network, this means no single user can hack, manipulate, or close the chain of blocks or can shut it down. Due to the decentralized mechanism, the blockchain is free from hacks.
Integrity: In the blockchain, all the users have got the right to make the decision, and the trust in the system is not forced but is guided by the user intuition.
Cryptography: Blockchain uses cryptography to ensure security and data integrity. Blockchain enables the information to be transmitted without being copied.
Security: Blockchain uses Public Key Encryption Mechanism, due to this the transactions over the network are highly secure unless the public key is shared, in that case, there exists no solution for the protection or security.
2. Why Blockchain is a trusted approach?
Blockchain Technology is a trusted approach due to the following reasons:
Due to its open-source nature, blockchain technology is compatible with many business applications.It provides secure transactions by using the Public Key Encryption mechanism.It provides equal opportunities to every person without any discrimination in the global economy.It is a decentralized network due to which the power is distributed among all the participants in the network. There is no single authority in the network.
Due to its open-source nature, blockchain technology is compatible with many business applications.
It provides secure transactions by using the Public Key Encryption mechanism.
It provides equal opportunities to every person without any discrimination in the global economy.
It is a decentralized network due to which the power is distributed among all the participants in the network. There is no single authority in the network.
3. Name two types of records in the blockchain databases?
The two records are block records and transactional records. These records can be easily accessed and can be integrated easily without following any complex algorithm.
4. Differentiate between Blockchain and Hyperledger.
S.No.
Blockchain
Hyperledger
There are many projects which utilize blockchain:
Bitcoin
Ethereum
Hyperledger, etc.
Hyperledger has several implementations from different vendors:
Fabric from IBM
Sawtooth Lake from Intel.
Corda from R3 consortium.
5. How can you identify a block?
Every block in blockchain consists of these four fields:
Hash value: The hash value of the previous block, and this acts as a pointer to the previous block.
Transactional data: The block consists of details of the transactions.
Nonce: It is a random value that is used to vary the value of the hash in order to generate a hash value less than the target.
Hash of the block: This is the digital signature of the block and an alphanumeric value that is used to identify a block.
6. What is a Genesis Block?
In 2009, a developer named Santoshi Nakamoto created the genesis block. The genesis block is the first block in the blockchain and is also referred to as block 0. Some features of this block are as follows:
It is the only block that does not refer to any previous block.
It defines parameters of blockchain such as level of difficulty, consensus mechanism, etc to mine the blocks.
The genesis block forms the foundation of the Bitcoin trading system, and it is the prototype for all other blocks in the blockchain.
7. List some cryptographic algorithms used in blockchain.
Here are some extensively used cryptographic algorithms
SHA-256
Ethash
Triple DES
RSABlowfish
8. How hash value is generated in blockchain?
The steps involved in generating the hash value or block signature is as follows:
Transaction details are passed through the one-way hash function SHA-256.
The output value is then passed through the signature algorithm like ECDSA with the user’s private key.
The encrypted hash along with other information is called the digital signature.
9. Is it possible to modify the data written in the block?
No, it is not possible to modify the data in one particular block. If the need arises, the organization has to erase data from all the other blocks. Due to this reason, it is very important to deal with data with utmost care in the blockchain.
10. What is a method to recognize a block in the blockchain approach?
Every block has a hash pointer that acts as a link to the previous block, transaction data, and a stamp of time.
11. What do you mean by blocks in Blockchain?
A blockchain consists of a list of records that are stored in the blocks. Each time a block gets completed a new block is generated and that block is linked to the previous block. The blocks linked to each other are known as Blockchain i.e. the chain of blocks. It is not possible to delete or reverse any block from the blockchain.
12. A block in a blockchain consists of which elements?
A block in a blockchain consists of these elements-
A hash pointer to the previous block.
A list of transactions.
Timestamp.
13. What is the difference between public and private keys?
S. No.
Public key
Private Key
14. Is it possible to remove a complete block from a blockchain network?
Yes, it is possible to remove a complete block from the network. There are some default options and filters that can be helpful in scenarios where only a specific portion of the online ledger is to be considered.
15. List some applications of smart contracts.
Smart Contracts are lines of code in blockchain that are executed automatically. They define the rules of how a transaction has to be processed between the parties under specific conditions. Some applications are:
Insurance: Smart contracts can be useful in preventing forgeries and identifying false claims.
Employee contract: They can be useful in helping with wage payments.
Transportation: Smart contracts can be used to track down the shipment of goods.
16. Where do nodes run a smart contract?
Nodes run the smart contract on an Ethereum Virtual Machine (EVM). EVM operates in a sandboxed environment that is a perfect environment for Ethereum-based smart contracts.
17. What is the first thing specified in the Solidity file?
The first line specifies the version number of Solidity as it eliminates incompatibility issues that can arise while comparing with another version. It is important to mention the correct version number for the code.
18. What do you mean by Nonce? How it is used in Mining?
Mining is a process to solve a mathematical puzzle called proof of work. Proof of work is the process to determine the number Nonce. It is a random value that is used to vary the value of the hash so that the final hash value meets the hash conditions.
19. List the steps in Blockchain project implementation.
Requirement Identification.
Planning.
Development of project.
Feasibility study on the security of the project.
Implementation.
Controlling and Monitoring the project.
20. Are there any network-specific conditions for using Blockchain technology in an organization?
There is no specific network condition, but the network must be a peer-to-peer network under the concerned protocols.
21. List some differences between Blockchain and Baking Ledgers.
One of the most striking differences between Blockchain and Banking Ledgers is that blockchain is decentralized, distributed, and open-source. This means that the people don’t have to rely on the central bank to keep track of all the transactions. In a peer-to-peer network in blockchain technology, it is possible to keep track of all the transactions without having the fear of having them lost or erased.
Due to the open-source nature of blockchain, it is more versatile and easy to program. The programmers can easily add new functionality on top of already existing software through consensus.
22. What do you mean by executive accounting? Does blockchain support the same?
Executive accounting typically focuses on corporate accounting rather than public accounting. This means that executive accounting oversees finances for a business rather than focusing on individuals. Blockchain Technology has some algorithms that are specially designed to handle executive accounting.
23. What do you mean by secret sharing? Does it have any benefit in Blockchain technology?
Secret sharing is the method of distributing the secret among a group of participants in the blockchain network. All participants are allocated a share of the secret. The individual shares have no meaning of their own. The secret can be reconstructed only when a sufficient number of different types of shares are combined. There are many security-related benefits that secret sharing offers in blockchain technology.
24. What is an off-chain transaction?
Off-chain transactions are the transactions occurring on the cryptocurrency network that moves value outside the network. Due to the low cost/ zero cost of these transactions, off-chain transactions are becoming popular among a large set of participants. These transactions have the following features:
Off-chain transactions may eventually have to be recorded on-chain.
These transactions can entail lower fees, immediate settlement, and greater anonymity than on-chain transactions.
These transactions work by swapping the private keys to an existing wallet instead of transferring funds.
25. List and explain the parts of EVM Memory.
The EVM memory can be divided into three parts:
Storage: It is extremely expensive and the storage values are stored permanently on the blockchain network.
Memory: It is temporary modifiable storage that can be accessed only during the contract execution. Once the contract execution is finished, all the data is lost.
Stack: It is temporary non-modifiable storage and the content is lost once the execution completes.
26. What happens if the cost of execution of the smart contract is more than the specified gas?
Initially, the transaction will get executed but if the execution of the smart contract costs more than the specified gas, then the miners will stop validating the contract and the blockchain will record the transaction as failed. The user will also not get a refund in this case.
27. What are function modifiers in Solidity and mention the most widely used modifiers.
Function modifiers are used to modify the behavior of the smart contract functions. The most commonly used function modifiers in solidity are:
View: These are read-only functions. They cannot modify the state of a smart contract.
Pure: These functions neither read nor write the state of the smart contract.
28. What do you mean by forks? What are the different types of forking?
Forking is the updating of cryptocurrency protocol or code. It happens when the participants of the network cannot agree with regard to the consensus algorithm and new rules to validate the transactions. Thus, blockchain splits into two branches. There are three types of forking:
Soft Fork: When the blockchain protocol is altered in a backward-compatible way.
Hard Fork: When the blockchain protocol is altered in a non-backward-compatible way.
Temporary Fork: When two miners mine a new block at the same time.
29. On what factors does the gas usage in a transaction depends upon? How is the transaction fee calculated?
Gas usage in a transaction depends on the following criteria:
Amount of storage.
Set of instructions used in the smart contract.
The transaction fee is calculated in Ether using the formula:
Ether = Tx Fees = Gas Limit * Gas Price
30. In what order are the blocks linked in the blockchain?
In the blockchain, each block is linked with the previous block as each block consists of a pointer to the previous block. This means that the blocks are linked in the backward order.
31. Which cryptographic algorithm is used in blockchain?
Blockchain uses SHS-256 cryptographic algorithm. This hashing algorithm was developed by National Security Agency (NSA) in 2001.
32. What type of records can be kept in the blockchain?
Blockchain can be used to store any form of data. Industries can make use of this feature and can use blockchain to their advantage. The most common types of records that can be stored in the blockchain are as follows:
Medical records.
Management activities.
Transaction processing.
Business transactions, etc.
33. How is DApp different from a Normal App?
DApp runs on a decentralized network whereas apps are not generally designed to run in a decentralized ecosystem. DApps are the next-generation applications that are designed to take advantage of Blockchain Technology. Popular blockchain solutions that support DApp are Ethereum, NEO.
S. No.
DApp
Normal App
It includes:
Front-end
Smart contract
Blockchain
It includes:
Front-end
API
Database
34. Is it possible to hack a blockchain network?
Blockchain is a fairly secure network, but it is not completely secure. There are many types of hacks that can be carried out by hackers in a blockchain network. These include:
Sybil attack.
Direct denial of service.
Routing attack.
51% attack.
35. What is MetaMask?
MetaMask is a type of Ethereum wallet that bridges the gap between the user interfaces for Ethereum (For Example, Mist browsers, DApps, etc.) and the regular web (For Example, Google Chrome, Mozilla Firefox, Websites, etc.). Its function is to inject a JavaScript library called web3.js into the namespace of each page the browser loads. It is mainly used as a plugin in the regular web (For Example, Google Chrome, Mozilla Firefox, etc.)
36. What is the Lightning Network?
Lightning Network is an off-chain layer 2 payment protocol designed to be layered on top of blockchain-based cryptocurrencies such as litecoin or bitcoin. The lightning network is in the active development phase and is already being used by many vendors.
37. What is Atomic Swap?
Atomic swap is a revolutionary smart contract technology that allows exchanging one cryptocurrency to another without any intermediary exchange. It is done between two blockchains and off-chain.
38. How blockchain is useful to Digital Protection?
Blockchain is a solution that can help data-sensitive information to be protected. This means that blockchain can be useful to cybersecurity and digital protection. Other features of blockchain that will be helpful in these areas will be transparency, integrity, decentralized approach ad the use of cryptography in the blockchain technology also protects data.
39. How to check if a block is a valid block?
When a new block is announced on the network, every node that receives it does a list of checks. The two most important checks are:
Proof of work: To check if a block provides enough work to be included in the chain.
Validity of all the transactions: Each transaction must be a valid transaction.
40. How are the blocks and transactions encrypted in a bitcoin implementation?
Every block in a bitcoin implementation is a public block, so the blocks are not encrypted in any way. Block content is processed using a special hash function, SHA-256 to prevent modification and guarantee data integrity. This block hash value is included in the blockchain.
41. Why a blockchain needs a token to operate?
Coins/ tokens are used to implement changes between the states. When a transaction is done, there is a change of state and the coins are moved from one address to another. Technically, a blockchain does not need coins for its essential operations but without them, there is a need to introduce some other way to manage the states of the chain and to verify the transactions.
42. What is the function, and why is it needed in the blockchain?
Trapdoor functions are essential for public-key encryption. These are the functions that are easy to compute in one direction but difficult to compute in the opposite direction unless there is special information available to conduct the opposite process. These are commonly used in the blockchain to represent the ideas of addresses and private keys.
43. List a few types of Ethereum Networks?
There are three types of networks in Ethereum:
Live Network: This is the main network. Smart contracts are deployed on the main network.
Test Network: Some examples of the Test Network are Rinkeby, Kovan, Ropsten. These networks allow users to run their smart contracts with no fees before deploying on the main network.
Private Network: They run within the premises of the organization, but they carry the features of the Ethereum network. These are not connected to the main network.
44. What are the limitations of the blockchain?
There are some limitations of the blockchain:
Scalability is an Issue in the blockchain. This means the more people or nodes join the network, the more chances of slowing down are more.
Blockchain is not a distributed computing system where the network does not depend on the involvement and participation of the nodes.
Some blockchain solutions consume too much energy. Every time a ledger is updated with a new transaction, the miners need to solve the problems which means spending a lot of energy. The high energy consumption makes these mathematical problems not so ideal for the real world.
Data is immutable in the blockchain. Once data is written, it cannot be removed
Blockchains are sometimes inefficient. Even if the blockchain technology used in bitcoin is picked, you will find a lot of inefficiencies in the system.
45. What do businesses get from using the blockchain?
Businesses/Corporate Sectors can make a lot of benefits from the use of blockchain. They are:
Audibility.
Transparency.
Feedback.
Traceability.
Security.
Efficiency.
46. What is a block identifier?
Every block in a blockchain network has a hash value and this hash value acts as a unique identifier. This means that no two blocks will have the same identifier i.e. no two blocks will have the same hash value.
47. How can you stop double-spending?
Double spending is prevented using the consensus algorithm. The consensus algorithm ensures that the requested transaction is genuine and records it in the block. It is thus verified by the multiple nodes thus making double-spending not possible.
48. What do you mean by fungible tokens?
Any fungible entity refers to its capability for interchangeability with another asset or good of the same value. The most common examples are currency and money.
49. What do you mean by Non-fungible tokens?
Non-fungible tokens are different from cryptocurrencies as they do not have any inherent value. NFT derives its values from the assets or goods represented by them.
50. What is DeFi technology?
Decentralized Finance can be defined as financial services using smart contracts that use decentralized, distributed ledger technology. Thus, it doesn’t need any central authority and blockchain.
Blockchain
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect ReactJS with MetaMask ?
Solidity - While, Do-While, and For Loop
Solidity - Libraries
Solidity - Functions
Blockchain - Hyperledger vs Ethereum
Difference between Public and Private blockchain
Solidity - Variables
What are Events in Solidity?
Solidity - Error Handling
Hyperledger Fabric in Blockchain
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Nov, 2021"
},
{
"code": null,
"e": 766,
"s": 28,
"text": "Blockchain is one of the most trending technologies out there in the tech world. It is basically concerned with a distributed database that maintains the records of all transactions that have been executed and shared across the network of computer systems globally. From payment processing to healthcare to supply chain and logistics monitoring – Blockchain has a wide range of uses and applications. Also, there are numerous prominent benefits associated with Blockchain technology including time-saving, cost-saving, decentralized structure, improved security, and privacy, etc. In a nutshell, if you’re looking forward to building a career in the Blockchain domain, then it would be a worthwhile and rewarding career decision for you."
},
{
"code": null,
"e": 1122,
"s": 766,
"text": "Companies like Samsung, Microsoft, Capgemini, etc. provide remarkable career opportunities for Blockchain Professionals. Further on, to make things a bit more hassle-free for you – here, we’re providing you with an extensive list of 50 Interview Questions for Blockchain that are often asked by the recruiters. Do check out all these questions from below:"
},
{
"code": null,
"e": 1184,
"s": 1122,
"text": "1. What is the underlying principle of Blockchain Technology?"
},
{
"code": null,
"e": 1297,
"s": 1184,
"text": "Blockchain is a P2P network where no single user controls the transaction. Blockchain principles are as follows:"
},
{
"code": null,
"e": 1545,
"s": 1297,
"text": "Decentralization: The power is distributed among all the users in the network, this means no single user can hack, manipulate, or close the chain of blocks or can shut it down. Due to the decentralized mechanism, the blockchain is free from hacks."
},
{
"code": null,
"e": 1709,
"s": 1545,
"text": "Integrity: In the blockchain, all the users have got the right to make the decision, and the trust in the system is not forced but is guided by the user intuition."
},
{
"code": null,
"e": 1866,
"s": 1709,
"text": "Cryptography: Blockchain uses cryptography to ensure security and data integrity. Blockchain enables the information to be transmitted without being copied."
},
{
"code": null,
"e": 2093,
"s": 1866,
"text": "Security: Blockchain uses Public Key Encryption Mechanism, due to this the transactions over the network are highly secure unless the public key is shared, in that case, there exists no solution for the protection or security."
},
{
"code": null,
"e": 2134,
"s": 2093,
"text": "2. Why Blockchain is a trusted approach?"
},
{
"code": null,
"e": 2208,
"s": 2134,
"text": "Blockchain Technology is a trusted approach due to the following reasons:"
},
{
"code": null,
"e": 2637,
"s": 2208,
"text": "Due to its open-source nature, blockchain technology is compatible with many business applications.It provides secure transactions by using the Public Key Encryption mechanism.It provides equal opportunities to every person without any discrimination in the global economy.It is a decentralized network due to which the power is distributed among all the participants in the network. There is no single authority in the network."
},
{
"code": null,
"e": 2737,
"s": 2637,
"text": "Due to its open-source nature, blockchain technology is compatible with many business applications."
},
{
"code": null,
"e": 2815,
"s": 2737,
"text": "It provides secure transactions by using the Public Key Encryption mechanism."
},
{
"code": null,
"e": 2913,
"s": 2815,
"text": "It provides equal opportunities to every person without any discrimination in the global economy."
},
{
"code": null,
"e": 3069,
"s": 2913,
"text": "It is a decentralized network due to which the power is distributed among all the participants in the network. There is no single authority in the network."
},
{
"code": null,
"e": 3127,
"s": 3069,
"text": "3. Name two types of records in the blockchain databases?"
},
{
"code": null,
"e": 3295,
"s": 3127,
"text": "The two records are block records and transactional records. These records can be easily accessed and can be integrated easily without following any complex algorithm."
},
{
"code": null,
"e": 3348,
"s": 3295,
"text": "4. Differentiate between Blockchain and Hyperledger."
},
{
"code": null,
"e": 3354,
"s": 3348,
"text": "S.No."
},
{
"code": null,
"e": 3365,
"s": 3354,
"text": "Blockchain"
},
{
"code": null,
"e": 3377,
"s": 3365,
"text": "Hyperledger"
},
{
"code": null,
"e": 3427,
"s": 3377,
"text": "There are many projects which utilize blockchain:"
},
{
"code": null,
"e": 3435,
"s": 3427,
"text": "Bitcoin"
},
{
"code": null,
"e": 3444,
"s": 3435,
"text": "Ethereum"
},
{
"code": null,
"e": 3462,
"s": 3444,
"text": "Hyperledger, etc."
},
{
"code": null,
"e": 3526,
"s": 3462,
"text": "Hyperledger has several implementations from different vendors:"
},
{
"code": null,
"e": 3542,
"s": 3526,
"text": "Fabric from IBM"
},
{
"code": null,
"e": 3568,
"s": 3542,
"text": "Sawtooth Lake from Intel."
},
{
"code": null,
"e": 3594,
"s": 3568,
"text": "Corda from R3 consortium."
},
{
"code": null,
"e": 3627,
"s": 3594,
"text": "5. How can you identify a block?"
},
{
"code": null,
"e": 3684,
"s": 3627,
"text": "Every block in blockchain consists of these four fields:"
},
{
"code": null,
"e": 3784,
"s": 3684,
"text": "Hash value: The hash value of the previous block, and this acts as a pointer to the previous block."
},
{
"code": null,
"e": 3855,
"s": 3784,
"text": "Transactional data: The block consists of details of the transactions."
},
{
"code": null,
"e": 3982,
"s": 3855,
"text": "Nonce: It is a random value that is used to vary the value of the hash in order to generate a hash value less than the target."
},
{
"code": null,
"e": 4104,
"s": 3982,
"text": "Hash of the block: This is the digital signature of the block and an alphanumeric value that is used to identify a block."
},
{
"code": null,
"e": 4132,
"s": 4104,
"text": "6. What is a Genesis Block?"
},
{
"code": null,
"e": 4339,
"s": 4132,
"text": "In 2009, a developer named Santoshi Nakamoto created the genesis block. The genesis block is the first block in the blockchain and is also referred to as block 0. Some features of this block are as follows:"
},
{
"code": null,
"e": 4403,
"s": 4339,
"text": "It is the only block that does not refer to any previous block."
},
{
"code": null,
"e": 4513,
"s": 4403,
"text": "It defines parameters of blockchain such as level of difficulty, consensus mechanism, etc to mine the blocks."
},
{
"code": null,
"e": 4647,
"s": 4513,
"text": "The genesis block forms the foundation of the Bitcoin trading system, and it is the prototype for all other blocks in the blockchain."
},
{
"code": null,
"e": 4705,
"s": 4647,
"text": "7. List some cryptographic algorithms used in blockchain."
},
{
"code": null,
"e": 4761,
"s": 4705,
"text": "Here are some extensively used cryptographic algorithms"
},
{
"code": null,
"e": 4769,
"s": 4761,
"text": "SHA-256"
},
{
"code": null,
"e": 4776,
"s": 4769,
"text": "Ethash"
},
{
"code": null,
"e": 4787,
"s": 4776,
"text": "Triple DES"
},
{
"code": null,
"e": 4799,
"s": 4787,
"text": "RSABlowfish"
},
{
"code": null,
"e": 4845,
"s": 4799,
"text": "8. How hash value is generated in blockchain?"
},
{
"code": null,
"e": 4927,
"s": 4845,
"text": "The steps involved in generating the hash value or block signature is as follows:"
},
{
"code": null,
"e": 5001,
"s": 4927,
"text": "Transaction details are passed through the one-way hash function SHA-256."
},
{
"code": null,
"e": 5105,
"s": 5001,
"text": "The output value is then passed through the signature algorithm like ECDSA with the user’s private key."
},
{
"code": null,
"e": 5186,
"s": 5105,
"text": "The encrypted hash along with other information is called the digital signature."
},
{
"code": null,
"e": 5245,
"s": 5186,
"text": "9. Is it possible to modify the data written in the block?"
},
{
"code": null,
"e": 5489,
"s": 5245,
"text": "No, it is not possible to modify the data in one particular block. If the need arises, the organization has to erase data from all the other blocks. Due to this reason, it is very important to deal with data with utmost care in the blockchain."
},
{
"code": null,
"e": 5559,
"s": 5489,
"text": "10. What is a method to recognize a block in the blockchain approach?"
},
{
"code": null,
"e": 5672,
"s": 5559,
"text": "Every block has a hash pointer that acts as a link to the previous block, transaction data, and a stamp of time."
},
{
"code": null,
"e": 5718,
"s": 5672,
"text": "11. What do you mean by blocks in Blockchain?"
},
{
"code": null,
"e": 6051,
"s": 5718,
"text": "A blockchain consists of a list of records that are stored in the blocks. Each time a block gets completed a new block is generated and that block is linked to the previous block. The blocks linked to each other are known as Blockchain i.e. the chain of blocks. It is not possible to delete or reverse any block from the blockchain."
},
{
"code": null,
"e": 6107,
"s": 6051,
"text": "12. A block in a blockchain consists of which elements?"
},
{
"code": null,
"e": 6159,
"s": 6107,
"text": "A block in a blockchain consists of these elements-"
},
{
"code": null,
"e": 6197,
"s": 6159,
"text": "A hash pointer to the previous block."
},
{
"code": null,
"e": 6221,
"s": 6197,
"text": "A list of transactions."
},
{
"code": null,
"e": 6232,
"s": 6221,
"text": "Timestamp."
},
{
"code": null,
"e": 6292,
"s": 6232,
"text": "13. What is the difference between public and private keys?"
},
{
"code": null,
"e": 6299,
"s": 6292,
"text": "S. No."
},
{
"code": null,
"e": 6310,
"s": 6299,
"text": "Public key"
},
{
"code": null,
"e": 6322,
"s": 6310,
"text": "Private Key"
},
{
"code": null,
"e": 6395,
"s": 6322,
"text": "14. Is it possible to remove a complete block from a blockchain network?"
},
{
"code": null,
"e": 6608,
"s": 6395,
"text": "Yes, it is possible to remove a complete block from the network. There are some default options and filters that can be helpful in scenarios where only a specific portion of the online ledger is to be considered."
},
{
"code": null,
"e": 6655,
"s": 6608,
"text": "15. List some applications of smart contracts."
},
{
"code": null,
"e": 6869,
"s": 6655,
"text": "Smart Contracts are lines of code in blockchain that are executed automatically. They define the rules of how a transaction has to be processed between the parties under specific conditions. Some applications are:"
},
{
"code": null,
"e": 6964,
"s": 6869,
"text": "Insurance: Smart contracts can be useful in preventing forgeries and identifying false claims."
},
{
"code": null,
"e": 7033,
"s": 6964,
"text": "Employee contract: They can be useful in helping with wage payments."
},
{
"code": null,
"e": 7114,
"s": 7033,
"text": "Transportation: Smart contracts can be used to track down the shipment of goods."
},
{
"code": null,
"e": 7155,
"s": 7114,
"text": "16. Where do nodes run a smart contract?"
},
{
"code": null,
"e": 7328,
"s": 7155,
"text": "Nodes run the smart contract on an Ethereum Virtual Machine (EVM). EVM operates in a sandboxed environment that is a perfect environment for Ethereum-based smart contracts."
},
{
"code": null,
"e": 7388,
"s": 7328,
"text": "17. What is the first thing specified in the Solidity file?"
},
{
"code": null,
"e": 7605,
"s": 7388,
"text": "The first line specifies the version number of Solidity as it eliminates incompatibility issues that can arise while comparing with another version. It is important to mention the correct version number for the code."
},
{
"code": null,
"e": 7662,
"s": 7605,
"text": "18. What do you mean by Nonce? How it is used in Mining?"
},
{
"code": null,
"e": 7915,
"s": 7662,
"text": "Mining is a process to solve a mathematical puzzle called proof of work. Proof of work is the process to determine the number Nonce. It is a random value that is used to vary the value of the hash so that the final hash value meets the hash conditions."
},
{
"code": null,
"e": 7972,
"s": 7915,
"text": "19. List the steps in Blockchain project implementation."
},
{
"code": null,
"e": 8000,
"s": 7972,
"text": "Requirement Identification."
},
{
"code": null,
"e": 8010,
"s": 8000,
"text": "Planning."
},
{
"code": null,
"e": 8034,
"s": 8010,
"text": "Development of project."
},
{
"code": null,
"e": 8084,
"s": 8034,
"text": "Feasibility study on the security of the project."
},
{
"code": null,
"e": 8100,
"s": 8084,
"text": "Implementation."
},
{
"code": null,
"e": 8140,
"s": 8100,
"text": "Controlling and Monitoring the project."
},
{
"code": null,
"e": 8238,
"s": 8140,
"text": "20. Are there any network-specific conditions for using Blockchain technology in an organization?"
},
{
"code": null,
"e": 8357,
"s": 8238,
"text": " There is no specific network condition, but the network must be a peer-to-peer network under the concerned protocols."
},
{
"code": null,
"e": 8422,
"s": 8357,
"text": "21. List some differences between Blockchain and Baking Ledgers."
},
{
"code": null,
"e": 8830,
"s": 8422,
"text": "One of the most striking differences between Blockchain and Banking Ledgers is that blockchain is decentralized, distributed, and open-source. This means that the people don’t have to rely on the central bank to keep track of all the transactions. In a peer-to-peer network in blockchain technology, it is possible to keep track of all the transactions without having the fear of having them lost or erased."
},
{
"code": null,
"e": 9021,
"s": 8830,
"text": "Due to the open-source nature of blockchain, it is more versatile and easy to program. The programmers can easily add new functionality on top of already existing software through consensus."
},
{
"code": null,
"e": 9101,
"s": 9021,
"text": "22. What do you mean by executive accounting? Does blockchain support the same?"
},
{
"code": null,
"e": 9404,
"s": 9101,
"text": "Executive accounting typically focuses on corporate accounting rather than public accounting. This means that executive accounting oversees finances for a business rather than focusing on individuals. Blockchain Technology has some algorithms that are specially designed to handle executive accounting."
},
{
"code": null,
"e": 9495,
"s": 9404,
"text": "23. What do you mean by secret sharing? Does it have any benefit in Blockchain technology?"
},
{
"code": null,
"e": 9913,
"s": 9495,
"text": "Secret sharing is the method of distributing the secret among a group of participants in the blockchain network. All participants are allocated a share of the secret. The individual shares have no meaning of their own. The secret can be reconstructed only when a sufficient number of different types of shares are combined. There are many security-related benefits that secret sharing offers in blockchain technology."
},
{
"code": null,
"e": 9951,
"s": 9913,
"text": "24. What is an off-chain transaction?"
},
{
"code": null,
"e": 10254,
"s": 9951,
"text": "Off-chain transactions are the transactions occurring on the cryptocurrency network that moves value outside the network. Due to the low cost/ zero cost of these transactions, off-chain transactions are becoming popular among a large set of participants. These transactions have the following features:"
},
{
"code": null,
"e": 10322,
"s": 10254,
"text": "Off-chain transactions may eventually have to be recorded on-chain."
},
{
"code": null,
"e": 10436,
"s": 10322,
"text": "These transactions can entail lower fees, immediate settlement, and greater anonymity than on-chain transactions."
},
{
"code": null,
"e": 10542,
"s": 10436,
"text": "These transactions work by swapping the private keys to an existing wallet instead of transferring funds."
},
{
"code": null,
"e": 10588,
"s": 10542,
"text": "25. List and explain the parts of EVM Memory."
},
{
"code": null,
"e": 10636,
"s": 10588,
"text": "The EVM memory can be divided into three parts:"
},
{
"code": null,
"e": 10744,
"s": 10636,
"text": "Storage: It is extremely expensive and the storage values are stored permanently on the blockchain network."
},
{
"code": null,
"e": 10907,
"s": 10744,
"text": "Memory: It is temporary modifiable storage that can be accessed only during the contract execution. Once the contract execution is finished, all the data is lost."
},
{
"code": null,
"e": 11007,
"s": 10907,
"text": "Stack: It is temporary non-modifiable storage and the content is lost once the execution completes."
},
{
"code": null,
"e": 11103,
"s": 11007,
"text": "26. What happens if the cost of execution of the smart contract is more than the specified gas?"
},
{
"code": null,
"e": 11384,
"s": 11103,
"text": "Initially, the transaction will get executed but if the execution of the smart contract costs more than the specified gas, then the miners will stop validating the contract and the blockchain will record the transaction as failed. The user will also not get a refund in this case."
},
{
"code": null,
"e": 11472,
"s": 11384,
"text": "27. What are function modifiers in Solidity and mention the most widely used modifiers."
},
{
"code": null,
"e": 11615,
"s": 11472,
"text": "Function modifiers are used to modify the behavior of the smart contract functions. The most commonly used function modifiers in solidity are:"
},
{
"code": null,
"e": 11702,
"s": 11615,
"text": "View: These are read-only functions. They cannot modify the state of a smart contract."
},
{
"code": null,
"e": 11781,
"s": 11702,
"text": "Pure: These functions neither read nor write the state of the smart contract. "
},
{
"code": null,
"e": 11853,
"s": 11781,
"text": "28. What do you mean by forks? What are the different types of forking?"
},
{
"code": null,
"e": 12134,
"s": 11853,
"text": "Forking is the updating of cryptocurrency protocol or code. It happens when the participants of the network cannot agree with regard to the consensus algorithm and new rules to validate the transactions. Thus, blockchain splits into two branches. There are three types of forking:"
},
{
"code": null,
"e": 12215,
"s": 12134,
"text": "Soft Fork: When the blockchain protocol is altered in a backward-compatible way."
},
{
"code": null,
"e": 12300,
"s": 12215,
"text": "Hard Fork: When the blockchain protocol is altered in a non-backward-compatible way."
},
{
"code": null,
"e": 12367,
"s": 12300,
"text": "Temporary Fork: When two miners mine a new block at the same time."
},
{
"code": null,
"e": 12476,
"s": 12367,
"text": "29. On what factors does the gas usage in a transaction depends upon? How is the transaction fee calculated?"
},
{
"code": null,
"e": 12538,
"s": 12476,
"text": "Gas usage in a transaction depends on the following criteria:"
},
{
"code": null,
"e": 12557,
"s": 12538,
"text": "Amount of storage."
},
{
"code": null,
"e": 12605,
"s": 12557,
"text": "Set of instructions used in the smart contract."
},
{
"code": null,
"e": 12667,
"s": 12605,
"text": "The transaction fee is calculated in Ether using the formula:"
},
{
"code": null,
"e": 12707,
"s": 12667,
"text": "Ether = Tx Fees = Gas Limit * Gas Price"
},
{
"code": null,
"e": 12766,
"s": 12707,
"text": "30. In what order are the blocks linked in the blockchain?"
},
{
"code": null,
"e": 12950,
"s": 12766,
"text": "In the blockchain, each block is linked with the previous block as each block consists of a pointer to the previous block. This means that the blocks are linked in the backward order."
},
{
"code": null,
"e": 13007,
"s": 12950,
"text": "31. Which cryptographic algorithm is used in blockchain?"
},
{
"code": null,
"e": 13136,
"s": 13007,
"text": "Blockchain uses SHS-256 cryptographic algorithm. This hashing algorithm was developed by National Security Agency (NSA) in 2001."
},
{
"code": null,
"e": 13192,
"s": 13136,
"text": "32. What type of records can be kept in the blockchain?"
},
{
"code": null,
"e": 13411,
"s": 13192,
"text": "Blockchain can be used to store any form of data. Industries can make use of this feature and can use blockchain to their advantage. The most common types of records that can be stored in the blockchain are as follows:"
},
{
"code": null,
"e": 13428,
"s": 13411,
"text": "Medical records."
},
{
"code": null,
"e": 13451,
"s": 13428,
"text": "Management activities."
},
{
"code": null,
"e": 13475,
"s": 13451,
"text": "Transaction processing."
},
{
"code": null,
"e": 13503,
"s": 13475,
"text": "Business transactions, etc."
},
{
"code": null,
"e": 13548,
"s": 13503,
"text": "33. How is DApp different from a Normal App?"
},
{
"code": null,
"e": 13833,
"s": 13548,
"text": "DApp runs on a decentralized network whereas apps are not generally designed to run in a decentralized ecosystem. DApps are the next-generation applications that are designed to take advantage of Blockchain Technology. Popular blockchain solutions that support DApp are Ethereum, NEO."
},
{
"code": null,
"e": 13840,
"s": 13833,
"text": "S. No."
},
{
"code": null,
"e": 13845,
"s": 13840,
"text": "DApp"
},
{
"code": null,
"e": 13856,
"s": 13845,
"text": "Normal App"
},
{
"code": null,
"e": 13869,
"s": 13856,
"text": "It includes:"
},
{
"code": null,
"e": 13879,
"s": 13869,
"text": "Front-end"
},
{
"code": null,
"e": 13894,
"s": 13879,
"text": "Smart contract"
},
{
"code": null,
"e": 13905,
"s": 13894,
"text": "Blockchain"
},
{
"code": null,
"e": 13918,
"s": 13905,
"text": "It includes:"
},
{
"code": null,
"e": 13928,
"s": 13918,
"text": "Front-end"
},
{
"code": null,
"e": 13932,
"s": 13928,
"text": "API"
},
{
"code": null,
"e": 13941,
"s": 13932,
"text": "Database"
},
{
"code": null,
"e": 13990,
"s": 13941,
"text": "34. Is it possible to hack a blockchain network?"
},
{
"code": null,
"e": 14167,
"s": 13990,
"text": "Blockchain is a fairly secure network, but it is not completely secure. There are many types of hacks that can be carried out by hackers in a blockchain network. These include:"
},
{
"code": null,
"e": 14181,
"s": 14167,
"text": "Sybil attack."
},
{
"code": null,
"e": 14207,
"s": 14181,
"text": "Direct denial of service."
},
{
"code": null,
"e": 14223,
"s": 14207,
"text": "Routing attack."
},
{
"code": null,
"e": 14235,
"s": 14223,
"text": "51% attack."
},
{
"code": null,
"e": 14257,
"s": 14235,
"text": "35. What is MetaMask?"
},
{
"code": null,
"e": 14696,
"s": 14257,
"text": "MetaMask is a type of Ethereum wallet that bridges the gap between the user interfaces for Ethereum (For Example, Mist browsers, DApps, etc.) and the regular web (For Example, Google Chrome, Mozilla Firefox, Websites, etc.). Its function is to inject a JavaScript library called web3.js into the namespace of each page the browser loads. It is mainly used as a plugin in the regular web (For Example, Google Chrome, Mozilla Firefox, etc.)"
},
{
"code": null,
"e": 14731,
"s": 14696,
"text": "36. What is the Lightning Network?"
},
{
"code": null,
"e": 14986,
"s": 14731,
"text": "Lightning Network is an off-chain layer 2 payment protocol designed to be layered on top of blockchain-based cryptocurrencies such as litecoin or bitcoin. The lightning network is in the active development phase and is already being used by many vendors."
},
{
"code": null,
"e": 15011,
"s": 14986,
"text": "37. What is Atomic Swap?"
},
{
"code": null,
"e": 15206,
"s": 15011,
"text": "Atomic swap is a revolutionary smart contract technology that allows exchanging one cryptocurrency to another without any intermediary exchange. It is done between two blockchains and off-chain."
},
{
"code": null,
"e": 15258,
"s": 15206,
"text": "38. How blockchain is useful to Digital Protection?"
},
{
"code": null,
"e": 15620,
"s": 15258,
"text": "Blockchain is a solution that can help data-sensitive information to be protected. This means that blockchain can be useful to cybersecurity and digital protection. Other features of blockchain that will be helpful in these areas will be transparency, integrity, decentralized approach ad the use of cryptography in the blockchain technology also protects data."
},
{
"code": null,
"e": 15666,
"s": 15620,
"text": "39. How to check if a block is a valid block?"
},
{
"code": null,
"e": 15798,
"s": 15666,
"text": "When a new block is announced on the network, every node that receives it does a list of checks. The two most important checks are:"
},
{
"code": null,
"e": 15883,
"s": 15798,
"text": "Proof of work: To check if a block provides enough work to be included in the chain."
},
{
"code": null,
"e": 15963,
"s": 15883,
"text": "Validity of all the transactions: Each transaction must be a valid transaction."
},
{
"code": null,
"e": 16042,
"s": 15963,
"text": "40. How are the blocks and transactions encrypted in a bitcoin implementation?"
},
{
"code": null,
"e": 16318,
"s": 16042,
"text": "Every block in a bitcoin implementation is a public block, so the blocks are not encrypted in any way. Block content is processed using a special hash function, SHA-256 to prevent modification and guarantee data integrity. This block hash value is included in the blockchain."
},
{
"code": null,
"e": 16365,
"s": 16318,
"text": "41. Why a blockchain needs a token to operate?"
},
{
"code": null,
"e": 16740,
"s": 16365,
"text": "Coins/ tokens are used to implement changes between the states. When a transaction is done, there is a change of state and the coins are moved from one address to another. Technically, a blockchain does not need coins for its essential operations but without them, there is a need to introduce some other way to manage the states of the chain and to verify the transactions."
},
{
"code": null,
"e": 16806,
"s": 16740,
"text": "42. What is the function, and why is it needed in the blockchain?"
},
{
"code": null,
"e": 17158,
"s": 16806,
"text": "Trapdoor functions are essential for public-key encryption. These are the functions that are easy to compute in one direction but difficult to compute in the opposite direction unless there is special information available to conduct the opposite process. These are commonly used in the blockchain to represent the ideas of addresses and private keys."
},
{
"code": null,
"e": 17201,
"s": 17158,
"text": "43. List a few types of Ethereum Networks?"
},
{
"code": null,
"e": 17248,
"s": 17201,
"text": "There are three types of networks in Ethereum:"
},
{
"code": null,
"e": 17338,
"s": 17248,
"text": "Live Network: This is the main network. Smart contracts are deployed on the main network."
},
{
"code": null,
"e": 17522,
"s": 17338,
"text": "Test Network: Some examples of the Test Network are Rinkeby, Kovan, Ropsten. These networks allow users to run their smart contracts with no fees before deploying on the main network."
},
{
"code": null,
"e": 17687,
"s": 17522,
"text": "Private Network: They run within the premises of the organization, but they carry the features of the Ethereum network. These are not connected to the main network."
},
{
"code": null,
"e": 17736,
"s": 17687,
"text": "44. What are the limitations of the blockchain?"
},
{
"code": null,
"e": 17782,
"s": 17736,
"text": "There are some limitations of the blockchain:"
},
{
"code": null,
"e": 17922,
"s": 17782,
"text": "Scalability is an Issue in the blockchain. This means the more people or nodes join the network, the more chances of slowing down are more."
},
{
"code": null,
"e": 18056,
"s": 17922,
"text": "Blockchain is not a distributed computing system where the network does not depend on the involvement and participation of the nodes."
},
{
"code": null,
"e": 18333,
"s": 18056,
"text": "Some blockchain solutions consume too much energy. Every time a ledger is updated with a new transaction, the miners need to solve the problems which means spending a lot of energy. The high energy consumption makes these mathematical problems not so ideal for the real world."
},
{
"code": null,
"e": 18414,
"s": 18333,
"text": "Data is immutable in the blockchain. Once data is written, it cannot be removed "
},
{
"code": null,
"e": 18567,
"s": 18414,
"text": "Blockchains are sometimes inefficient. Even if the blockchain technology used in bitcoin is picked, you will find a lot of inefficiencies in the system."
},
{
"code": null,
"e": 18621,
"s": 18567,
"text": "45. What do businesses get from using the blockchain?"
},
{
"code": null,
"e": 18715,
"s": 18621,
"text": "Businesses/Corporate Sectors can make a lot of benefits from the use of blockchain. They are:"
},
{
"code": null,
"e": 18727,
"s": 18715,
"text": "Audibility."
},
{
"code": null,
"e": 18741,
"s": 18727,
"text": "Transparency."
},
{
"code": null,
"e": 18751,
"s": 18741,
"text": "Feedback."
},
{
"code": null,
"e": 18765,
"s": 18751,
"text": "Traceability."
},
{
"code": null,
"e": 18775,
"s": 18765,
"text": "Security."
},
{
"code": null,
"e": 18787,
"s": 18775,
"text": "Efficiency."
},
{
"code": null,
"e": 18819,
"s": 18787,
"text": "46. What is a block identifier?"
},
{
"code": null,
"e": 19031,
"s": 18819,
"text": "Every block in a blockchain network has a hash value and this hash value acts as a unique identifier. This means that no two blocks will have the same identifier i.e. no two blocks will have the same hash value."
},
{
"code": null,
"e": 19069,
"s": 19031,
"text": "47. How can you stop double-spending?"
},
{
"code": null,
"e": 19316,
"s": 19069,
"text": "Double spending is prevented using the consensus algorithm. The consensus algorithm ensures that the requested transaction is genuine and records it in the block. It is thus verified by the multiple nodes thus making double-spending not possible."
},
{
"code": null,
"e": 19357,
"s": 19316,
"text": "48. What do you mean by fungible tokens?"
},
{
"code": null,
"e": 19521,
"s": 19357,
"text": "Any fungible entity refers to its capability for interchangeability with another asset or good of the same value. The most common examples are currency and money. "
},
{
"code": null,
"e": 19566,
"s": 19521,
"text": "49. What do you mean by Non-fungible tokens?"
},
{
"code": null,
"e": 19731,
"s": 19566,
"text": "Non-fungible tokens are different from cryptocurrencies as they do not have any inherent value. NFT derives its values from the assets or goods represented by them."
},
{
"code": null,
"e": 19760,
"s": 19731,
"text": "50. What is DeFi technology?"
},
{
"code": null,
"e": 19957,
"s": 19760,
"text": "Decentralized Finance can be defined as financial services using smart contracts that use decentralized, distributed ledger technology. Thus, it doesn’t need any central authority and blockchain. "
},
{
"code": null,
"e": 19968,
"s": 19957,
"text": "Blockchain"
},
{
"code": null,
"e": 20066,
"s": 19968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 20105,
"s": 20066,
"text": "How to connect ReactJS with MetaMask ?"
},
{
"code": null,
"e": 20146,
"s": 20105,
"text": "Solidity - While, Do-While, and For Loop"
},
{
"code": null,
"e": 20167,
"s": 20146,
"text": "Solidity - Libraries"
},
{
"code": null,
"e": 20188,
"s": 20167,
"text": "Solidity - Functions"
},
{
"code": null,
"e": 20225,
"s": 20188,
"text": "Blockchain - Hyperledger vs Ethereum"
},
{
"code": null,
"e": 20274,
"s": 20225,
"text": "Difference between Public and Private blockchain"
},
{
"code": null,
"e": 20295,
"s": 20274,
"text": "Solidity - Variables"
},
{
"code": null,
"e": 20324,
"s": 20295,
"text": "What are Events in Solidity?"
},
{
"code": null,
"e": 20350,
"s": 20324,
"text": "Solidity - Error Handling"
}
] |
SAS - Correlation Analysis
|
Correlation analysis deals with relationships among variables. The correlation coefficient is a measure of linear association between two variables.Values of the correlation coefficient are always between -1 and +1. SAS provides the procedure PROC CORR to find the correlation coefficients between a pair of variables in a dataset.
The basic syntax for applying PROC CORR in SAS is −
PROC CORR DATA = dataset options;
VAR variable;
Following is the description of the parameters used −
Dataset is the name of the dataset.
Dataset is the name of the dataset.
Options is the additional option with procedure like plotting a matrix etc.
Options is the additional option with procedure like plotting a matrix etc.
Variable is the variable name of the dataset used in finding the correlation.
Variable is the variable name of the dataset used in finding the correlation.
Correlation coefficients between a pair of variables available in a dataset can be obtained by use their names in the VAR statement.In the below example we use the dataset CARS1 and get the result showing the correlation coefficients between horsepower and weight.
PROC SQL;
create table CARS1 as
SELECT invoice, horsepower, length, weight
FROM
SASHELP.CARS
WHERE make in ('Audi','BMW')
;
RUN;
proc corr data = cars1 ;
VAR horsepower weight ;
BY make;
run;
When the above code is executed, we get the following result −
Correlation coefficients between all the variables available in a dataset can be obtained by simply applying the procedure with the dataset name.
In the below example we use the dataset CARS1 and get the result showing the correlation coefficients between each pair of the variables.
proc corr data = cars1 ;
run;
When the above code is executed, we get the following result −
We can obtain a scatterplot matrix between the variables by choosing the option to plot matrix in the PROC statement.
In below example we get the matrix between horsepower and weight.
proc corr data = cars1 plots = matrix ;
VAR horsepower weight ;
run;
When the above code is executed, we get the following result −
50 Lectures
5.5 hours
Code And Create
124 Lectures
30 hours
Juan Galvan
162 Lectures
31.5 hours
Yossef Ayman Zedan
35 Lectures
2.5 hours
Ermin Dedic
167 Lectures
45.5 hours
Muslim Helalee
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2915,
"s": 2583,
"text": "Correlation analysis deals with relationships among variables. The correlation coefficient is a measure of linear association between two variables.Values of the correlation coefficient are always between -1 and +1. SAS provides the procedure PROC CORR to find the correlation coefficients between a pair of variables in a dataset."
},
{
"code": null,
"e": 2967,
"s": 2915,
"text": "The basic syntax for applying PROC CORR in SAS is −"
},
{
"code": null,
"e": 3016,
"s": 2967,
"text": "PROC CORR DATA = dataset options;\nVAR variable;\n"
},
{
"code": null,
"e": 3070,
"s": 3016,
"text": "Following is the description of the parameters used −"
},
{
"code": null,
"e": 3106,
"s": 3070,
"text": "Dataset is the name of the dataset."
},
{
"code": null,
"e": 3142,
"s": 3106,
"text": "Dataset is the name of the dataset."
},
{
"code": null,
"e": 3218,
"s": 3142,
"text": "Options is the additional option with procedure like plotting a matrix etc."
},
{
"code": null,
"e": 3294,
"s": 3218,
"text": "Options is the additional option with procedure like plotting a matrix etc."
},
{
"code": null,
"e": 3372,
"s": 3294,
"text": "Variable is the variable name of the dataset used in finding the correlation."
},
{
"code": null,
"e": 3450,
"s": 3372,
"text": "Variable is the variable name of the dataset used in finding the correlation."
},
{
"code": null,
"e": 3715,
"s": 3450,
"text": "Correlation coefficients between a pair of variables available in a dataset can be obtained by use their names in the VAR statement.In the below example we use the dataset CARS1 and get the result showing the correlation coefficients between horsepower and weight."
},
{
"code": null,
"e": 3919,
"s": 3715,
"text": "PROC SQL;\ncreate table CARS1 as\nSELECT invoice, horsepower, length, weight\n FROM \n SASHELP.CARS\n WHERE make in ('Audi','BMW')\n;\nRUN;\n\nproc corr data = cars1 ;\nVAR horsepower weight ;\nBY make;\nrun;\n"
},
{
"code": null,
"e": 3982,
"s": 3919,
"text": "When the above code is executed, we get the following result −"
},
{
"code": null,
"e": 4128,
"s": 3982,
"text": "Correlation coefficients between all the variables available in a dataset can be obtained by simply applying the procedure with the dataset name."
},
{
"code": null,
"e": 4266,
"s": 4128,
"text": "In the below example we use the dataset CARS1 and get the result showing the correlation coefficients between each pair of the variables."
},
{
"code": null,
"e": 4297,
"s": 4266,
"text": "proc corr data = cars1 ;\nrun;\n"
},
{
"code": null,
"e": 4360,
"s": 4297,
"text": "When the above code is executed, we get the following result −"
},
{
"code": null,
"e": 4478,
"s": 4360,
"text": "We can obtain a scatterplot matrix between the variables by choosing the option to plot matrix in the PROC statement."
},
{
"code": null,
"e": 4544,
"s": 4478,
"text": "In below example we get the matrix between horsepower and weight."
},
{
"code": null,
"e": 4614,
"s": 4544,
"text": "proc corr data = cars1 plots = matrix ;\nVAR horsepower weight ;\nrun;\n"
},
{
"code": null,
"e": 4677,
"s": 4614,
"text": "When the above code is executed, we get the following result −"
},
{
"code": null,
"e": 4712,
"s": 4677,
"text": "\n 50 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4729,
"s": 4712,
"text": " Code And Create"
},
{
"code": null,
"e": 4764,
"s": 4729,
"text": "\n 124 Lectures \n 30 hours \n"
},
{
"code": null,
"e": 4777,
"s": 4764,
"text": " Juan Galvan"
},
{
"code": null,
"e": 4814,
"s": 4777,
"text": "\n 162 Lectures \n 31.5 hours \n"
},
{
"code": null,
"e": 4834,
"s": 4814,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 4869,
"s": 4834,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4882,
"s": 4869,
"text": " Ermin Dedic"
},
{
"code": null,
"e": 4919,
"s": 4882,
"text": "\n 167 Lectures \n 45.5 hours \n"
},
{
"code": null,
"e": 4935,
"s": 4919,
"text": " Muslim Helalee"
},
{
"code": null,
"e": 4942,
"s": 4935,
"text": " Print"
},
{
"code": null,
"e": 4953,
"s": 4942,
"text": " Add Notes"
}
] |
Interactive Visualization with Dash and Plotly | by Alper Aydın | Towards Data Science
|
Interactive data visualization has an important impact on exploratory data analysis. Before applying any descriptive or predictive algorithm to a dataset we must first understand how the features are related with each other and how they are distributed inside. It is obvious that many visualization libraries provide numerous types of charts that satisfy this requirement. But another obvious thing is that it is a hard job to do the same plotting work for each feature and scroll over each chart to compare findings for each feature.
For the last couple of weeks, I had to do this job so much that I had to find a shortcut for this. Yes, it is true that I am a lazy man, and yes it is true that laziness is a key to creativity. That is how I met dash and plotly as a solution to my problem. In this post you will find how this couple would be a good solution for exploratory data analysis.
Let me first explain what dash and plotly are for whom did not hear before. Plotly is a data analytics and visualization company. In this writing, we are interested with the two python libraries of this company; plotly.py and dash. Plotly.py library provides interactive visualization for python applications. As indicated on their website, you can “Create interactive, D3 and WebGL charts in Python. All the chart types of matplotlib and more.”
Dash is also another product of the same company, providing a framework for building web based applications for Python. If you are working with a team or just want share your work with others, a web application is the simplest way, eliminating the library version or interface issues. We will see how convenient sharing our findings over the web is, during the rest of this writing.
So, let’s start coding...
Below is a simple dash web application consisting of six lines of code. Just write it down into a .py file and call the file and your app is up and running, that’s all.
#this is the dash_test.py fileimport dashimport dash_html_components as htmlapp = dash.Dash(__name__)app.layout = html.H1('hello dash')if __name__ == '__main__': app.run_server(debug=True, port=8080)
Call the file from command prompt as follows, with the exact path of your file. You will see a console windows that tells the server is running.
python "c:\users\alper\documents\dash_test.py"
We can now open a web browser and navigate to the localhost url with the given port number: 127.0.0.1:8080.
In the first two lines of the code, we simply import the required dash libraries. The third line initializes the dash app, fourth line prepares the page layout with a header tag which we will be displaying on the page, and the last two lines run the server with debug and port options. (See the detailed explanation on stackoverflow for the “if __name__ ... ” line)
Yes, we are far from both interactivity and visuality but be patient, we are on the way. First, we place the required elements. For this, we will modify app.layout and insert a button and a label element into a div. Note that the two elements are placed in a list as the children of the div element. Dash stores html elements in dash_html_components library, you can find the whole list on their website and github repo.
app.layout = html.Div( [ html.Button('create random number', id='button1'), html.Label('...', id='label1') ])
When we save the file, we will see a new line on the console window with a new debugger pin. If there is a problem in the code, then we will see the error message instead. In this case, we need to call the file again and refresh the browser.
Now, lets add some styling to the elements we had insert. I can’t say I am good at styling, but I’m sure you can do better. We can add style to an element with style attribute accepting a dictionary of css tags.
html.Button('create random number', id='button1', style={'display':'block', 'background-color':'#aabbcc'} ), html.Label('...', id='label1', style={'display':'inline-block', 'margin':'10'} )
And it’s time to go a step further and add some responsiveness. First we import the required libraries
from dash.dependencies import Input, Outputimport random
Then we add the callback decorator and the function we want to execute on callback.
@app.callback( Output(component_id=’label1', component_property=’children’), [Input(component_id=’button1', component_property=’n_clicks’)])def update_output(input_value): return random.random()
update_output function simply generates a random number and returns it as result.
@app.callback decorator binds the button click event to the update_output function, and the result of the function to the label1 element. This is the core part of the responsiveness. There will be another post on callbacks and state parameters.
Since we covered the interactivity enough for introduction, it is time to add some charts. First, we will keep it simple and put a bar chart with random values on each button click. So, we need to add a graph object to our layout:
app.layout = html.Div( [ html.Button(‘create random number’, id=’button1', style={‘display’:’block’, ‘padding’:’5', ‘background-color’:’#aabbcc’}), html.Label(‘...’, id=’label1', style={‘display’:’inline-block’, ‘margin’:’10'} ), dcc.Graph(id=’graph1') # this is the graph we add ])
And we need to modify our callback function to produce the chart:
@app.callback( Output(component_id='graph1', component_property='figure'), [Input(component_id='button1', component_property='n_clicks')])def update_output(input_value): random_x = [i for i in range(5)] random_y = [random.random() for _ in range(5)] figure = { 'data': [ {'x':random_x, 'y':random_y, 'type':'bar', 'name': 'Series1'} ], 'layout': { 'title': 'Dash Data Visualization' } } return figure
In the callback decorator, we first replace the label in our Output statement with the graph object we recently added to our layout. Then inside the function we crate x and y values for the chart, and the figure object. That is all. The result is an interactive bar chart inside your browser.
If the above chart is not fancy enough for you, don’t worry, here is another example for you. Let’s get some deeper.
Was it too fast? Ok, let’s look at the code then.
# coding=utf8import randomimport pandas as pdimport dashfrom dash.dependencies import Input, Outputimport dash_html_components as htmlimport dash_core_components as dccimport plotly.graph_objs as goapp = dash.Dash(__name__)names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', names=names)app.layout = html.Div( [ html.Div([ dcc.Dropdown( id='ddl_x', options=[{'label': i, 'value': i} for i in names], value='sepal-width', style={'width':'50%'} ), dcc.Dropdown( id='ddl_y', options=[{'label': i, 'value': i} for i in names], value='petal-width', style={'width':'50%'} ), ],style={'width':'100%','display':'inline-block'}), html.Div([ dcc.Graph(id='graph1') ],style={'width':'100%','display':'inline-block'}) ])@app.callback( Output(component_id='graph1', component_property='figure'), [ Input(component_id='ddl_x', component_property='value'), Input(component_id='ddl_y', component_property='value') ])def update_output(ddl_x_value, ddl_y_value): figure={ 'data': [ go.Scatter( x=data[data['class'] == cls][ddl_x_value], y=data[data['class'] == cls][ddl_y_value], mode='markers', marker={ 'size': 15 }, name=cls ) for cls in data['class'].unique() ], 'layout': go.Layout( height= 350, hovermode= 'closest', title=go.layout.Title(text='Dash Interactive Data Visualization',xref='paper', x=0) ) } return figureif __name__ == '__main__': app.run_server(debug=True, port=8080)
The code structure is exactly the same as the previous. After initializing the app,
we added two lines for data reading.
in the app.layout section, we added two dropdown lists, and fill the options with a loop of data columns.
in the @app.callback decorator, we added these two dropdowns as input components
and in the update_output function, we draw a scatter plot graph with the data and the columns selected by the dropdown lists. Here, there is a tricky part. We draw the scatter plot for each class. You see, there is a for loop at the end of the go.Scatter() function and inside the ‘data’ list. And this for loop, also called as list comprehension, returns Scatter() objects n times, where n is the number of unique records in the ‘class’ column of the data. And following line is for the layout properties of the chart.
The code is ready to run. Just;
save it into a file with .py extension, -> “c:\...\dash_test.py”
call it via command prompt using python -> python “c:\...\dash_test.py”
open a browser and navigate to the app -> http://localhost:8080
Your interactive data visualization application is ready in 60 lines of code.
That is all for my first writing on Medium. I will keep on writing what I’ve learned. Please share your feelings, so I may improve myself.
https://dash.plot.ly/
Edit:
go.Layout value was passed inside an array in figure object under update_output function. This caused javascript error in some versions. Removing the array and passing the go.Layout object directly solved the problem. 2019/06/20
|
[
{
"code": null,
"e": 706,
"s": 171,
"text": "Interactive data visualization has an important impact on exploratory data analysis. Before applying any descriptive or predictive algorithm to a dataset we must first understand how the features are related with each other and how they are distributed inside. It is obvious that many visualization libraries provide numerous types of charts that satisfy this requirement. But another obvious thing is that it is a hard job to do the same plotting work for each feature and scroll over each chart to compare findings for each feature."
},
{
"code": null,
"e": 1062,
"s": 706,
"text": "For the last couple of weeks, I had to do this job so much that I had to find a shortcut for this. Yes, it is true that I am a lazy man, and yes it is true that laziness is a key to creativity. That is how I met dash and plotly as a solution to my problem. In this post you will find how this couple would be a good solution for exploratory data analysis."
},
{
"code": null,
"e": 1508,
"s": 1062,
"text": "Let me first explain what dash and plotly are for whom did not hear before. Plotly is a data analytics and visualization company. In this writing, we are interested with the two python libraries of this company; plotly.py and dash. Plotly.py library provides interactive visualization for python applications. As indicated on their website, you can “Create interactive, D3 and WebGL charts in Python. All the chart types of matplotlib and more.”"
},
{
"code": null,
"e": 1891,
"s": 1508,
"text": "Dash is also another product of the same company, providing a framework for building web based applications for Python. If you are working with a team or just want share your work with others, a web application is the simplest way, eliminating the library version or interface issues. We will see how convenient sharing our findings over the web is, during the rest of this writing."
},
{
"code": null,
"e": 1917,
"s": 1891,
"text": "So, let’s start coding..."
},
{
"code": null,
"e": 2086,
"s": 1917,
"text": "Below is a simple dash web application consisting of six lines of code. Just write it down into a .py file and call the file and your app is up and running, that’s all."
},
{
"code": null,
"e": 2289,
"s": 2086,
"text": "#this is the dash_test.py fileimport dashimport dash_html_components as htmlapp = dash.Dash(__name__)app.layout = html.H1('hello dash')if __name__ == '__main__': app.run_server(debug=True, port=8080)"
},
{
"code": null,
"e": 2434,
"s": 2289,
"text": "Call the file from command prompt as follows, with the exact path of your file. You will see a console windows that tells the server is running."
},
{
"code": null,
"e": 2481,
"s": 2434,
"text": "python \"c:\\users\\alper\\documents\\dash_test.py\""
},
{
"code": null,
"e": 2589,
"s": 2481,
"text": "We can now open a web browser and navigate to the localhost url with the given port number: 127.0.0.1:8080."
},
{
"code": null,
"e": 2955,
"s": 2589,
"text": "In the first two lines of the code, we simply import the required dash libraries. The third line initializes the dash app, fourth line prepares the page layout with a header tag which we will be displaying on the page, and the last two lines run the server with debug and port options. (See the detailed explanation on stackoverflow for the “if __name__ ... ” line)"
},
{
"code": null,
"e": 3376,
"s": 2955,
"text": "Yes, we are far from both interactivity and visuality but be patient, we are on the way. First, we place the required elements. For this, we will modify app.layout and insert a button and a label element into a div. Note that the two elements are placed in a list as the children of the div element. Dash stores html elements in dash_html_components library, you can find the whole list on their website and github repo."
},
{
"code": null,
"e": 3488,
"s": 3376,
"text": "app.layout = html.Div( [ html.Button('create random number', id='button1'), html.Label('...', id='label1') ])"
},
{
"code": null,
"e": 3730,
"s": 3488,
"text": "When we save the file, we will see a new line on the console window with a new debugger pin. If there is a problem in the code, then we will see the error message instead. In this case, we need to call the file again and refresh the browser."
},
{
"code": null,
"e": 3942,
"s": 3730,
"text": "Now, lets add some styling to the elements we had insert. I can’t say I am good at styling, but I’m sure you can do better. We can add style to an element with style attribute accepting a dictionary of css tags."
},
{
"code": null,
"e": 4149,
"s": 3942,
"text": " html.Button('create random number', id='button1', style={'display':'block', 'background-color':'#aabbcc'} ), html.Label('...', id='label1', style={'display':'inline-block', 'margin':'10'} )"
},
{
"code": null,
"e": 4252,
"s": 4149,
"text": "And it’s time to go a step further and add some responsiveness. First we import the required libraries"
},
{
"code": null,
"e": 4309,
"s": 4252,
"text": "from dash.dependencies import Input, Outputimport random"
},
{
"code": null,
"e": 4393,
"s": 4309,
"text": "Then we add the callback decorator and the function we want to execute on callback."
},
{
"code": null,
"e": 4588,
"s": 4393,
"text": "@app.callback( Output(component_id=’label1', component_property=’children’), [Input(component_id=’button1', component_property=’n_clicks’)])def update_output(input_value): return random.random()"
},
{
"code": null,
"e": 4670,
"s": 4588,
"text": "update_output function simply generates a random number and returns it as result."
},
{
"code": null,
"e": 4915,
"s": 4670,
"text": "@app.callback decorator binds the button click event to the update_output function, and the result of the function to the label1 element. This is the core part of the responsiveness. There will be another post on callbacks and state parameters."
},
{
"code": null,
"e": 5146,
"s": 4915,
"text": "Since we covered the interactivity enough for introduction, it is time to add some charts. First, we will keep it simple and put a bar chart with random values on each button click. So, we need to add a graph object to our layout:"
},
{
"code": null,
"e": 5503,
"s": 5146,
"text": "app.layout = html.Div( [ html.Button(‘create random number’, id=’button1', style={‘display’:’block’, ‘padding’:’5', ‘background-color’:’#aabbcc’}), html.Label(‘...’, id=’label1', style={‘display’:’inline-block’, ‘margin’:’10'} ), dcc.Graph(id=’graph1') # this is the graph we add ])"
},
{
"code": null,
"e": 5569,
"s": 5503,
"text": "And we need to modify our callback function to produce the chart:"
},
{
"code": null,
"e": 6041,
"s": 5569,
"text": "@app.callback( Output(component_id='graph1', component_property='figure'), [Input(component_id='button1', component_property='n_clicks')])def update_output(input_value): random_x = [i for i in range(5)] random_y = [random.random() for _ in range(5)] figure = { 'data': [ {'x':random_x, 'y':random_y, 'type':'bar', 'name': 'Series1'} ], 'layout': { 'title': 'Dash Data Visualization' } } return figure"
},
{
"code": null,
"e": 6334,
"s": 6041,
"text": "In the callback decorator, we first replace the label in our Output statement with the graph object we recently added to our layout. Then inside the function we crate x and y values for the chart, and the figure object. That is all. The result is an interactive bar chart inside your browser."
},
{
"code": null,
"e": 6451,
"s": 6334,
"text": "If the above chart is not fancy enough for you, don’t worry, here is another example for you. Let’s get some deeper."
},
{
"code": null,
"e": 6501,
"s": 6451,
"text": "Was it too fast? Ok, let’s look at the code then."
},
{
"code": null,
"e": 8433,
"s": 6501,
"text": "# coding=utf8import randomimport pandas as pdimport dashfrom dash.dependencies import Input, Outputimport dash_html_components as htmlimport dash_core_components as dccimport plotly.graph_objs as goapp = dash.Dash(__name__)names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', names=names)app.layout = html.Div( [ html.Div([ dcc.Dropdown( id='ddl_x', options=[{'label': i, 'value': i} for i in names], value='sepal-width', style={'width':'50%'} ), dcc.Dropdown( id='ddl_y', options=[{'label': i, 'value': i} for i in names], value='petal-width', style={'width':'50%'} ), ],style={'width':'100%','display':'inline-block'}), html.Div([ dcc.Graph(id='graph1') ],style={'width':'100%','display':'inline-block'}) ])@app.callback( Output(component_id='graph1', component_property='figure'), [ Input(component_id='ddl_x', component_property='value'), Input(component_id='ddl_y', component_property='value') ])def update_output(ddl_x_value, ddl_y_value): figure={ 'data': [ go.Scatter( x=data[data['class'] == cls][ddl_x_value], y=data[data['class'] == cls][ddl_y_value], mode='markers', marker={ 'size': 15 }, name=cls ) for cls in data['class'].unique() ], 'layout': go.Layout( height= 350, hovermode= 'closest', title=go.layout.Title(text='Dash Interactive Data Visualization',xref='paper', x=0) ) } return figureif __name__ == '__main__': app.run_server(debug=True, port=8080)"
},
{
"code": null,
"e": 8517,
"s": 8433,
"text": "The code structure is exactly the same as the previous. After initializing the app,"
},
{
"code": null,
"e": 8554,
"s": 8517,
"text": "we added two lines for data reading."
},
{
"code": null,
"e": 8660,
"s": 8554,
"text": "in the app.layout section, we added two dropdown lists, and fill the options with a loop of data columns."
},
{
"code": null,
"e": 8741,
"s": 8660,
"text": "in the @app.callback decorator, we added these two dropdowns as input components"
},
{
"code": null,
"e": 9261,
"s": 8741,
"text": "and in the update_output function, we draw a scatter plot graph with the data and the columns selected by the dropdown lists. Here, there is a tricky part. We draw the scatter plot for each class. You see, there is a for loop at the end of the go.Scatter() function and inside the ‘data’ list. And this for loop, also called as list comprehension, returns Scatter() objects n times, where n is the number of unique records in the ‘class’ column of the data. And following line is for the layout properties of the chart."
},
{
"code": null,
"e": 9293,
"s": 9261,
"text": "The code is ready to run. Just;"
},
{
"code": null,
"e": 9358,
"s": 9293,
"text": "save it into a file with .py extension, -> “c:\\...\\dash_test.py”"
},
{
"code": null,
"e": 9430,
"s": 9358,
"text": "call it via command prompt using python -> python “c:\\...\\dash_test.py”"
},
{
"code": null,
"e": 9494,
"s": 9430,
"text": "open a browser and navigate to the app -> http://localhost:8080"
},
{
"code": null,
"e": 9572,
"s": 9494,
"text": "Your interactive data visualization application is ready in 60 lines of code."
},
{
"code": null,
"e": 9711,
"s": 9572,
"text": "That is all for my first writing on Medium. I will keep on writing what I’ve learned. Please share your feelings, so I may improve myself."
},
{
"code": null,
"e": 9733,
"s": 9711,
"text": "https://dash.plot.ly/"
},
{
"code": null,
"e": 9739,
"s": 9733,
"text": "Edit:"
}
] |
Sort a String in Java (2 different ways) - GeeksforGeeks
|
14 Sep, 2021
String class doesn’t have any method that directly sorts a string, but we can sort a string by applying other methods one after other. String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created.
Creating a String
There are two ways to create a string in Java:
String literal
String s = “GeeksforGeeks”;
Using new keyword
String s = new String (“GeeksforGeeks”);
Note: As we know that String is immutable in java, hence in third step we have to create a new string.
Methods:
There exist two methods with which we can sort any string in java alphabetically
Without using the sort() methodWith using sort() method
Without using the sort() method
With using sort() method
Illustration:
Input string : "geeksforgeeks"
Output string : "eeeefggkkorss"
Now let us discuss methods and implement the same.
Method 1: Without using the sort() method
Here we will be laying an approach t sort a string without using any predefined logic. So, it also does becomes an important approach from an interview perceptive view.
Procedure:
Convert string to array with the help of the toCharArray() method of String classNow use nested loops to check for swapping elements of an array.Print these character array elements.
Convert string to array with the help of the toCharArray() method of String class
Now use nested loops to check for swapping elements of an array.
Print these character array elements.
Example
Java
// Java program to Sort a String Alphabetically// Using toCharArray() method// Without using sort() method // Importing required classesimport java.io.*;import java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Custom string input String str = "geeksforgeeks"; // Converting string into an array for computation char arr[] = str.toCharArray(); // Nested loops for comparison of characters // in above character array char temp; int i = 0; while (i <= arr.length) { int j = i + 1; while (j <= arr.length) { if (arr[j] < arr[i]) { // Comparing the characters one by one temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } j += 1; } i += 1; } // By now loop is done means we have // iterated the whole array System.out.println(arr); }}
Output:
eeeefggkkorss
Method 2: With using sort() method
2A With using sort() method- natural sorting
Procedure:
The main logic is to toCharArray() method of String class over the input string to create a character array for the input string.Now use Arrays.sort(char c[]) method to sort character array.Use String class constructor to create a sorted string from char array.
The main logic is to toCharArray() method of String class over the input string to create a character array for the input string.
Now use Arrays.sort(char c[]) method to sort character array.
Use String class constructor to create a sorted string from char array.
Example 1
Java
// Java program to Sort a String Alphabetically// Using toCharArray() method// With using the sort() method // Importing Arrays class from java.util packageimport java.util.Arrays; // Main classpublic class GFG { // Method 1 // To sort a string alphabetically public static String sortString(String inputString) { // Converting input string to character array char tempArray[] = inputString.toCharArray(); // Sorting temp array using Arrays.sort(tempArray); // Returning new sorted string return new String(tempArray); } // Method 2 // Main driver method public static void main(String[] args) { // Custom string as input String inputString = "geeksforgeeks"; String outputString = sortString(inputString); // Print and display commands // Input string System.out.println("Input String : " + inputString); // Output string System.out.println("Output String : " + outputString); }}
Input String : geeksforgeeks
Output String : eeeefggkkorss
2B With using sort() method- Custom sorting
Arrays.sort(char c[]) method sort characters based on their ASCII value, we can define our custom Comparator to sort a string.
Illustration:
Input String : GeeksforGeeks
Output String : eeeefGGkkorss
Procedure:
Convert input string to Character array. There is no direct method to do it. We will use for loop to fill the array.Use Arrays.sort(T [ ], Comparator c) method to sort Character array. For this, we must have to implement compare() method based on our custom sorting behavior.Now we can use StringBuilder to convert the Character array to String.
Convert input string to Character array. There is no direct method to do it. We will use for loop to fill the array.
Use Arrays.sort(T [ ], Comparator c) method to sort Character array. For this, we must have to implement compare() method based on our custom sorting behavior.
Now we can use StringBuilder to convert the Character array to String.
Example 2
Java
// Java Program to Sort a Mixed String Containing// Uppercase and Lowercase Characters // Importing required classesimport java.util.Arrays;import java.util.Comparator; // Main classclass GFG { // Method 1 // To sort a mixed string public static String sortString(String inputString) { // Converting input string to Character array Character tempArray[] = new Character[inputString.length()]; for (int i = 0; i < inputString.length(); i++) { tempArray[i] = inputString.charAt(i); } // Sort, ignoring case during sorting Arrays.sort(tempArray, new Comparator<Character>() { // Method 2 // To compare characters @Override public int compare(Character c1, Character c2) { // Ignoring case return Character.compare( Character.toLowerCase(c1), Character.toLowerCase(c2)); } }); // Using StringBuilder to convert Character array to // String StringBuilder sb = new StringBuilder(tempArray.length); for (Character c : tempArray) sb.append(c.charValue()); return sb.toString(); } // Method 3 // MAin driver method public static void main(String[] args) { // Custom input string String inputString = "GeeksforGeeks"; // Calling method 1 to sort input string // and storing in a string String outputString = sortString(inputString); // Print and display the input and output strings System.out.println("Input String : " + inputString); System.out.println("Output String : " + outputString); }}
Input String : GeeksforGeeks
Output String : eeeefGGkkorss
Note:
public int compare(Object o1, Object o2) {}
have to return -ve if o1 has to come before o2
have to return +ve if o1 has to come after o2
have to return 0 if o1 is equal to o2
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
wurocpengpeng
ruhelaa48
simmytarika5
Java-String-Programs
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Overriding in Java
Collections in Java
Singleton Class in Java
Multithreading in Java
|
[
{
"code": null,
"e": 24444,
"s": 24416,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 24715,
"s": 24444,
"text": "String class doesn’t have any method that directly sorts a string, but we can sort a string by applying other methods one after other. String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created."
},
{
"code": null,
"e": 24733,
"s": 24715,
"text": "Creating a String"
},
{
"code": null,
"e": 24780,
"s": 24733,
"text": "There are two ways to create a string in Java:"
},
{
"code": null,
"e": 24795,
"s": 24780,
"text": "String literal"
},
{
"code": null,
"e": 24823,
"s": 24795,
"text": "String s = “GeeksforGeeks”;"
},
{
"code": null,
"e": 24841,
"s": 24823,
"text": "Using new keyword"
},
{
"code": null,
"e": 24882,
"s": 24841,
"text": "String s = new String (“GeeksforGeeks”);"
},
{
"code": null,
"e": 24985,
"s": 24882,
"text": "Note: As we know that String is immutable in java, hence in third step we have to create a new string."
},
{
"code": null,
"e": 24994,
"s": 24985,
"text": "Methods:"
},
{
"code": null,
"e": 25075,
"s": 24994,
"text": "There exist two methods with which we can sort any string in java alphabetically"
},
{
"code": null,
"e": 25131,
"s": 25075,
"text": "Without using the sort() methodWith using sort() method"
},
{
"code": null,
"e": 25163,
"s": 25131,
"text": "Without using the sort() method"
},
{
"code": null,
"e": 25188,
"s": 25163,
"text": "With using sort() method"
},
{
"code": null,
"e": 25202,
"s": 25188,
"text": "Illustration:"
},
{
"code": null,
"e": 25265,
"s": 25202,
"text": "Input string : \"geeksforgeeks\"\nOutput string : \"eeeefggkkorss\""
},
{
"code": null,
"e": 25317,
"s": 25265,
"text": "Now let us discuss methods and implement the same. "
},
{
"code": null,
"e": 25359,
"s": 25317,
"text": "Method 1: Without using the sort() method"
},
{
"code": null,
"e": 25528,
"s": 25359,
"text": "Here we will be laying an approach t sort a string without using any predefined logic. So, it also does becomes an important approach from an interview perceptive view."
},
{
"code": null,
"e": 25539,
"s": 25528,
"text": "Procedure:"
},
{
"code": null,
"e": 25722,
"s": 25539,
"text": "Convert string to array with the help of the toCharArray() method of String classNow use nested loops to check for swapping elements of an array.Print these character array elements."
},
{
"code": null,
"e": 25804,
"s": 25722,
"text": "Convert string to array with the help of the toCharArray() method of String class"
},
{
"code": null,
"e": 25869,
"s": 25804,
"text": "Now use nested loops to check for swapping elements of an array."
},
{
"code": null,
"e": 25907,
"s": 25869,
"text": "Print these character array elements."
},
{
"code": null,
"e": 25915,
"s": 25907,
"text": "Example"
},
{
"code": null,
"e": 25920,
"s": 25915,
"text": "Java"
},
{
"code": "// Java program to Sort a String Alphabetically// Using toCharArray() method// Without using sort() method // Importing required classesimport java.io.*;import java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Custom string input String str = \"geeksforgeeks\"; // Converting string into an array for computation char arr[] = str.toCharArray(); // Nested loops for comparison of characters // in above character array char temp; int i = 0; while (i <= arr.length) { int j = i + 1; while (j <= arr.length) { if (arr[j] < arr[i]) { // Comparing the characters one by one temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } j += 1; } i += 1; } // By now loop is done means we have // iterated the whole array System.out.println(arr); }}",
"e": 27030,
"s": 25920,
"text": null
},
{
"code": null,
"e": 27038,
"s": 27030,
"text": "Output:"
},
{
"code": null,
"e": 27052,
"s": 27038,
"text": "eeeefggkkorss"
},
{
"code": null,
"e": 27087,
"s": 27052,
"text": "Method 2: With using sort() method"
},
{
"code": null,
"e": 27132,
"s": 27087,
"text": "2A With using sort() method- natural sorting"
},
{
"code": null,
"e": 27143,
"s": 27132,
"text": "Procedure:"
},
{
"code": null,
"e": 27405,
"s": 27143,
"text": "The main logic is to toCharArray() method of String class over the input string to create a character array for the input string.Now use Arrays.sort(char c[]) method to sort character array.Use String class constructor to create a sorted string from char array."
},
{
"code": null,
"e": 27535,
"s": 27405,
"text": "The main logic is to toCharArray() method of String class over the input string to create a character array for the input string."
},
{
"code": null,
"e": 27597,
"s": 27535,
"text": "Now use Arrays.sort(char c[]) method to sort character array."
},
{
"code": null,
"e": 27669,
"s": 27597,
"text": "Use String class constructor to create a sorted string from char array."
},
{
"code": null,
"e": 27679,
"s": 27669,
"text": "Example 1"
},
{
"code": null,
"e": 27684,
"s": 27679,
"text": "Java"
},
{
"code": "// Java program to Sort a String Alphabetically// Using toCharArray() method// With using the sort() method // Importing Arrays class from java.util packageimport java.util.Arrays; // Main classpublic class GFG { // Method 1 // To sort a string alphabetically public static String sortString(String inputString) { // Converting input string to character array char tempArray[] = inputString.toCharArray(); // Sorting temp array using Arrays.sort(tempArray); // Returning new sorted string return new String(tempArray); } // Method 2 // Main driver method public static void main(String[] args) { // Custom string as input String inputString = \"geeksforgeeks\"; String outputString = sortString(inputString); // Print and display commands // Input string System.out.println(\"Input String : \" + inputString); // Output string System.out.println(\"Output String : \" + outputString); }}",
"e": 28724,
"s": 27684,
"text": null
},
{
"code": null,
"e": 28783,
"s": 28724,
"text": "Input String : geeksforgeeks\nOutput String : eeeefggkkorss"
},
{
"code": null,
"e": 28827,
"s": 28783,
"text": "2B With using sort() method- Custom sorting"
},
{
"code": null,
"e": 28955,
"s": 28827,
"text": "Arrays.sort(char c[]) method sort characters based on their ASCII value, we can define our custom Comparator to sort a string. "
},
{
"code": null,
"e": 28969,
"s": 28955,
"text": "Illustration:"
},
{
"code": null,
"e": 29028,
"s": 28969,
"text": "Input String : GeeksforGeeks\nOutput String : eeeefGGkkorss"
},
{
"code": null,
"e": 29040,
"s": 29028,
"text": "Procedure: "
},
{
"code": null,
"e": 29386,
"s": 29040,
"text": "Convert input string to Character array. There is no direct method to do it. We will use for loop to fill the array.Use Arrays.sort(T [ ], Comparator c) method to sort Character array. For this, we must have to implement compare() method based on our custom sorting behavior.Now we can use StringBuilder to convert the Character array to String."
},
{
"code": null,
"e": 29503,
"s": 29386,
"text": "Convert input string to Character array. There is no direct method to do it. We will use for loop to fill the array."
},
{
"code": null,
"e": 29663,
"s": 29503,
"text": "Use Arrays.sort(T [ ], Comparator c) method to sort Character array. For this, we must have to implement compare() method based on our custom sorting behavior."
},
{
"code": null,
"e": 29734,
"s": 29663,
"text": "Now we can use StringBuilder to convert the Character array to String."
},
{
"code": null,
"e": 29744,
"s": 29734,
"text": "Example 2"
},
{
"code": null,
"e": 29749,
"s": 29744,
"text": "Java"
},
{
"code": "// Java Program to Sort a Mixed String Containing// Uppercase and Lowercase Characters // Importing required classesimport java.util.Arrays;import java.util.Comparator; // Main classclass GFG { // Method 1 // To sort a mixed string public static String sortString(String inputString) { // Converting input string to Character array Character tempArray[] = new Character[inputString.length()]; for (int i = 0; i < inputString.length(); i++) { tempArray[i] = inputString.charAt(i); } // Sort, ignoring case during sorting Arrays.sort(tempArray, new Comparator<Character>() { // Method 2 // To compare characters @Override public int compare(Character c1, Character c2) { // Ignoring case return Character.compare( Character.toLowerCase(c1), Character.toLowerCase(c2)); } }); // Using StringBuilder to convert Character array to // String StringBuilder sb = new StringBuilder(tempArray.length); for (Character c : tempArray) sb.append(c.charValue()); return sb.toString(); } // Method 3 // MAin driver method public static void main(String[] args) { // Custom input string String inputString = \"GeeksforGeeks\"; // Calling method 1 to sort input string // and storing in a string String outputString = sortString(inputString); // Print and display the input and output strings System.out.println(\"Input String : \" + inputString); System.out.println(\"Output String : \" + outputString); }}",
"e": 31526,
"s": 29749,
"text": null
},
{
"code": null,
"e": 31585,
"s": 31526,
"text": "Input String : GeeksforGeeks\nOutput String : eeeefGGkkorss"
},
{
"code": null,
"e": 31591,
"s": 31585,
"text": "Note:"
},
{
"code": null,
"e": 31636,
"s": 31591,
"text": "public int compare(Object o1, Object o2) {} "
},
{
"code": null,
"e": 31683,
"s": 31636,
"text": "have to return -ve if o1 has to come before o2"
},
{
"code": null,
"e": 31729,
"s": 31683,
"text": "have to return +ve if o1 has to come after o2"
},
{
"code": null,
"e": 31767,
"s": 31729,
"text": "have to return 0 if o1 is equal to o2"
},
{
"code": null,
"e": 32189,
"s": 31767,
"text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 32203,
"s": 32189,
"text": "wurocpengpeng"
},
{
"code": null,
"e": 32213,
"s": 32203,
"text": "ruhelaa48"
},
{
"code": null,
"e": 32226,
"s": 32213,
"text": "simmytarika5"
},
{
"code": null,
"e": 32247,
"s": 32226,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 32260,
"s": 32247,
"text": "Java-Strings"
},
{
"code": null,
"e": 32265,
"s": 32260,
"text": "Java"
},
{
"code": null,
"e": 32278,
"s": 32265,
"text": "Java-Strings"
},
{
"code": null,
"e": 32283,
"s": 32278,
"text": "Java"
},
{
"code": null,
"e": 32381,
"s": 32283,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32390,
"s": 32381,
"text": "Comments"
},
{
"code": null,
"e": 32403,
"s": 32390,
"text": "Old Comments"
},
{
"code": null,
"e": 32433,
"s": 32403,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 32452,
"s": 32433,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 32503,
"s": 32452,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 32521,
"s": 32503,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 32552,
"s": 32521,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 32584,
"s": 32552,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 32603,
"s": 32584,
"text": "Overriding in Java"
},
{
"code": null,
"e": 32623,
"s": 32603,
"text": "Collections in Java"
},
{
"code": null,
"e": 32647,
"s": 32623,
"text": "Singleton Class in Java"
}
] |
Find the position of the last removed element from the array - GeeksforGeeks
|
03 May, 2021
Given an array of size and an integer . Perform the following operations on the given array:
If a[i] > M then push a[i] – M to end of the array, otherwise remove it from the array.Perform the first operation while the array is non-empty.
If a[i] > M then push a[i] – M to end of the array, otherwise remove it from the array.
Perform the first operation while the array is non-empty.
The task is to find the original position of the element which gets removed last.
Examples:
Input: arr[] = {4, 3}, M = 2 Output: 2 Remove 4 from the array and the array becomes {3, 2} with original positions {2, 1} Remove 3 from the array and the array becomes {2, 1} with original positions {1, 2} Remove 2 from the array and the array becomes {1} with original positions {2} So, 2nd positioned element is the last to be removed from the array.
Input: arr[] = {2, 5, 4}, M = 2 Output: 2
The idea is to observe the last element which will be removed from the array. It can by easily said that the element to be removed last will be the element which can be subtracted max number of times by among all elements of the array. That is, the element with maximum value of ceil(a[i] / M).
So, the task now reduces to find the index of the element in the array with maximum value of ceil(a[i] / M).
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the position of the// last removed element from the array#include <bits/stdc++.h>using namespace std; // Function to find the original position// of the element which will be// removed lastint getPosition(int a[], int n, int m){ // take ceil of every number for (int i = 0; i < n; i++) { a[i] = (a[i] / m + (a[i] % m != 0)); } int ans = -1, max = -1; for (int i = n - 1; i >= 0; i--) { if (max < a[i]) { max = a[i]; ans = i; } } // Since position is index+1 return ans + 1;} // Driver codeint main(){ int a[] = { 2, 5, 4 }; int n = sizeof(a) / sizeof(a[0]); int m = 2; cout << getPosition(a, n, m); return 0;}
// Java program to find the position of the// last removed element from the arrayimport java.util.*; class solution{ // Function to find the original position// of the element which will be// removed last static int getPosition(int a[], int n, int m){ // take ceil of every number for (int i = 0; i < n; i++) { a[i] = (a[i] / m + (a[i] % m)); } int ans = -1, max = -1; for (int i = n - 1; i >= 0; i--) { if (max < a[i]) { max = a[i]; ans = i; } } // Since position is index+1 return ans + 1;} // Driver codepublic static void main(String args[]){ int a[] = { 2, 5, 4 }; int n = a.length; int m = 2; System.out.println(getPosition(a, n, m)); } }//This code is contributed by// Surendra_Gangwar
# Python3 program to find the position of# the last removed element from the arrayimport math as mt # Function to find the original# position of the element which# will be removed lastdef getPosition(a, n, m): # take ceil of every number for i in range(n): a[i] = (a[i] // m + (a[i] % m != 0)) ans, maxx = -1,-1 for i in range(n - 1, -1, -1): if (maxx < a[i]): maxx = a[i] ans = i # Since position is index+1 return ans + 1 # Driver codea = [2, 5, 4] n = len(a) m = 2 print(getPosition(a, n, m)) # This is contributed by Mohit kumar 29
// C# program to find the position of the// last removed element from the arrayusing System; class GFG{ // Function to find the original// position of the element which// will be removed laststatic int getPosition(int []a, int n, int m){ // take ceil of every number for (int i = 0; i < n; i++) { a[i] = (a[i] / m + (a[i] % m)); } int ans = -1, max = -1; for (int i = n - 1; i >= 0; i--) { if (max < a[i]) { max = a[i]; ans = i; } } // Since position is index+1 return ans + 1;} // Driver codestatic public void Main (){ int []a = { 2, 5, 4 }; int n = a.Length; int m = 2; Console.WriteLine(getPosition(a, n, m));}} // This code is contributed by ajit
<?php// PHP program to find the position of the// last removed element from the array // Function to find the original// position of the element which// will be removed lastfunction getPosition($a, $n, $m){ // take ceil of every number for ( $i = 0; $i < $n; $i++) { $a[$i] = ($a[$i] / $m + ($a[$i] % $m != 0)); } $ans = -1; $max = -1; for ($i = $n - 1; $i >= 0; $i--) { if ($max < $a[$i]) { $max = $a[$i]; $ans = $i; } } // Since position is index+1 return $ans + 1;} // Driver code$a = array( 2, 5, 4 );$n = sizeof($a);$m = 2; echo getPosition($a, $n, $m); // This code is contributed by jit_t?>
<script> // Javascript program to find the position// of the last removed element from the array // Function to find the original// position of the element which// will be removed lastfunction getPosition(a, n, m){ // Take ceil of every number for(let i = 0; i < n; i++) { a[i] = (a[i] / m + (a[i] % m)); } let ans = -1, max = -1; for(let i = n - 1; i >= 0; i--) { if (max < a[i]) { max = a[i]; ans = i; } } // Since position is index+1 return ans + 1;} // Driver codelet a = [ 2, 5, 4 ];let n = a.length;let m = 2; document.write(getPosition(a, n, m)); // This code is contributed by rameshtravel07 </script>
2
SURENDRA_GANGWAR
jit_t
mohit kumar 29
rameshtravel07
number-theory
Arrays
Competitive Programming
Mathematical
Arrays
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Trapping Rain Water
Find duplicates in O(n) time and O(1) extra space | Set 1
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Competitive Programming - A Complete Guide
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
|
[
{
"code": null,
"e": 24740,
"s": 24712,
"text": "\n03 May, 2021"
},
{
"code": null,
"e": 24834,
"s": 24740,
"text": "Given an array of size and an integer . Perform the following operations on the given array: "
},
{
"code": null,
"e": 24979,
"s": 24834,
"text": "If a[i] > M then push a[i] – M to end of the array, otherwise remove it from the array.Perform the first operation while the array is non-empty."
},
{
"code": null,
"e": 25067,
"s": 24979,
"text": "If a[i] > M then push a[i] – M to end of the array, otherwise remove it from the array."
},
{
"code": null,
"e": 25125,
"s": 25067,
"text": "Perform the first operation while the array is non-empty."
},
{
"code": null,
"e": 25208,
"s": 25125,
"text": "The task is to find the original position of the element which gets removed last. "
},
{
"code": null,
"e": 25220,
"s": 25208,
"text": "Examples: "
},
{
"code": null,
"e": 25574,
"s": 25220,
"text": "Input: arr[] = {4, 3}, M = 2 Output: 2 Remove 4 from the array and the array becomes {3, 2} with original positions {2, 1} Remove 3 from the array and the array becomes {2, 1} with original positions {1, 2} Remove 2 from the array and the array becomes {1} with original positions {2} So, 2nd positioned element is the last to be removed from the array."
},
{
"code": null,
"e": 25618,
"s": 25574,
"text": "Input: arr[] = {2, 5, 4}, M = 2 Output: 2 "
},
{
"code": null,
"e": 25913,
"s": 25618,
"text": "The idea is to observe the last element which will be removed from the array. It can by easily said that the element to be removed last will be the element which can be subtracted max number of times by among all elements of the array. That is, the element with maximum value of ceil(a[i] / M)."
},
{
"code": null,
"e": 26022,
"s": 25913,
"text": "So, the task now reduces to find the index of the element in the array with maximum value of ceil(a[i] / M)."
},
{
"code": null,
"e": 26075,
"s": 26022,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26079,
"s": 26075,
"text": "C++"
},
{
"code": null,
"e": 26084,
"s": 26079,
"text": "Java"
},
{
"code": null,
"e": 26092,
"s": 26084,
"text": "Python3"
},
{
"code": null,
"e": 26095,
"s": 26092,
"text": "C#"
},
{
"code": null,
"e": 26099,
"s": 26095,
"text": "PHP"
},
{
"code": null,
"e": 26110,
"s": 26099,
"text": "Javascript"
},
{
"code": "// C++ program to find the position of the// last removed element from the array#include <bits/stdc++.h>using namespace std; // Function to find the original position// of the element which will be// removed lastint getPosition(int a[], int n, int m){ // take ceil of every number for (int i = 0; i < n; i++) { a[i] = (a[i] / m + (a[i] % m != 0)); } int ans = -1, max = -1; for (int i = n - 1; i >= 0; i--) { if (max < a[i]) { max = a[i]; ans = i; } } // Since position is index+1 return ans + 1;} // Driver codeint main(){ int a[] = { 2, 5, 4 }; int n = sizeof(a) / sizeof(a[0]); int m = 2; cout << getPosition(a, n, m); return 0;}",
"e": 26831,
"s": 26110,
"text": null
},
{
"code": "// Java program to find the position of the// last removed element from the arrayimport java.util.*; class solution{ // Function to find the original position// of the element which will be// removed last static int getPosition(int a[], int n, int m){ // take ceil of every number for (int i = 0; i < n; i++) { a[i] = (a[i] / m + (a[i] % m)); } int ans = -1, max = -1; for (int i = n - 1; i >= 0; i--) { if (max < a[i]) { max = a[i]; ans = i; } } // Since position is index+1 return ans + 1;} // Driver codepublic static void main(String args[]){ int a[] = { 2, 5, 4 }; int n = a.length; int m = 2; System.out.println(getPosition(a, n, m)); } }//This code is contributed by// Surendra_Gangwar",
"e": 27604,
"s": 26831,
"text": null
},
{
"code": "# Python3 program to find the position of# the last removed element from the arrayimport math as mt # Function to find the original# position of the element which# will be removed lastdef getPosition(a, n, m): # take ceil of every number for i in range(n): a[i] = (a[i] // m + (a[i] % m != 0)) ans, maxx = -1,-1 for i in range(n - 1, -1, -1): if (maxx < a[i]): maxx = a[i] ans = i # Since position is index+1 return ans + 1 # Driver codea = [2, 5, 4] n = len(a) m = 2 print(getPosition(a, n, m)) # This is contributed by Mohit kumar 29",
"e": 28227,
"s": 27604,
"text": null
},
{
"code": "// C# program to find the position of the// last removed element from the arrayusing System; class GFG{ // Function to find the original// position of the element which// will be removed laststatic int getPosition(int []a, int n, int m){ // take ceil of every number for (int i = 0; i < n; i++) { a[i] = (a[i] / m + (a[i] % m)); } int ans = -1, max = -1; for (int i = n - 1; i >= 0; i--) { if (max < a[i]) { max = a[i]; ans = i; } } // Since position is index+1 return ans + 1;} // Driver codestatic public void Main (){ int []a = { 2, 5, 4 }; int n = a.Length; int m = 2; Console.WriteLine(getPosition(a, n, m));}} // This code is contributed by ajit",
"e": 28999,
"s": 28227,
"text": null
},
{
"code": "<?php// PHP program to find the position of the// last removed element from the array // Function to find the original// position of the element which// will be removed lastfunction getPosition($a, $n, $m){ // take ceil of every number for ( $i = 0; $i < $n; $i++) { $a[$i] = ($a[$i] / $m + ($a[$i] % $m != 0)); } $ans = -1; $max = -1; for ($i = $n - 1; $i >= 0; $i--) { if ($max < $a[$i]) { $max = $a[$i]; $ans = $i; } } // Since position is index+1 return $ans + 1;} // Driver code$a = array( 2, 5, 4 );$n = sizeof($a);$m = 2; echo getPosition($a, $n, $m); // This code is contributed by jit_t?>",
"e": 29698,
"s": 28999,
"text": null
},
{
"code": "<script> // Javascript program to find the position// of the last removed element from the array // Function to find the original// position of the element which// will be removed lastfunction getPosition(a, n, m){ // Take ceil of every number for(let i = 0; i < n; i++) { a[i] = (a[i] / m + (a[i] % m)); } let ans = -1, max = -1; for(let i = n - 1; i >= 0; i--) { if (max < a[i]) { max = a[i]; ans = i; } } // Since position is index+1 return ans + 1;} // Driver codelet a = [ 2, 5, 4 ];let n = a.length;let m = 2; document.write(getPosition(a, n, m)); // This code is contributed by rameshtravel07 </script>",
"e": 30395,
"s": 29698,
"text": null
},
{
"code": null,
"e": 30397,
"s": 30395,
"text": "2"
},
{
"code": null,
"e": 30416,
"s": 30399,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 30422,
"s": 30416,
"text": "jit_t"
},
{
"code": null,
"e": 30437,
"s": 30422,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 30452,
"s": 30437,
"text": "rameshtravel07"
},
{
"code": null,
"e": 30466,
"s": 30452,
"text": "number-theory"
},
{
"code": null,
"e": 30473,
"s": 30466,
"text": "Arrays"
},
{
"code": null,
"e": 30497,
"s": 30473,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30510,
"s": 30497,
"text": "Mathematical"
},
{
"code": null,
"e": 30517,
"s": 30510,
"text": "Arrays"
},
{
"code": null,
"e": 30531,
"s": 30517,
"text": "number-theory"
},
{
"code": null,
"e": 30544,
"s": 30531,
"text": "Mathematical"
},
{
"code": null,
"e": 30642,
"s": 30544,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30651,
"s": 30642,
"text": "Comments"
},
{
"code": null,
"e": 30664,
"s": 30651,
"text": "Old Comments"
},
{
"code": null,
"e": 30689,
"s": 30664,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 30738,
"s": 30689,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30776,
"s": 30738,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 30796,
"s": 30776,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 30854,
"s": 30796,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 30897,
"s": 30854,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 30938,
"s": 30897,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 30981,
"s": 30938,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 31008,
"s": 30981,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
How to use IF-THEN-ELSE in Python the way you do it in SAS | by Valentin Nordstroem | Towards Data Science
|
I think I’ve used IF-THEN-ELSE Statement or conditional coding in almost every analysis or program I have developed in the last 30 years. It is very useful in both preparing and cleaning data.
IF-THEN-ELSE is an integrated part of the data step in SAS. We don’t have an object for a data step in Python, but can step through the data frame in a similar way and use IF-ELIF-ELSE as it is called in Python.
So in this article, We will look at what we do in SAS and see how we can do the same kind of conditional coding in Python. I’ll also show you alternative ways of running IF-ELIF-ELSE statements.
IF-END-ELSE It’s a straightforward concept. In pseudocode it looks something like this:
IF something is true, THEN return the first value,ELSE IF some other thing is true THEN return the second value,ELSE return the third value.
The most commonly used if-the-else coding on earth is putting people into different age groups.
First I will create a SAS data set with a random generated age around a mean of 50 and a variace of 100.
%%SAS%LET mu = 50; %let s2 = 100;DATA dd1.age; DO id = 1000 TO 2000; age = INT(&mu + sqrt(&s2) * rannor(1066)); OUTPUT; END; RUN;PROC PRINT DATA = dd1.age(OBS=5);RUN;
I want to use the same data in both SAS and Python so I can compare the results. Since you can not generate the same sequence of random numbers in both SAS and Python, I want to use the SAS data set in Python too.
For this article, I have used an environment where I can run both SAS and Python in the same Jupyter notebook.
You can find a description on how to do this guide at:
How to set up SAS and Python on Amazon Web Services Free Tier.
I import the SAS data set with pd.read_sas() in Python. Since SAS only have floating-point numbers, Python will import age as a float and not an integer, so I’ll convert age to an integer.
df = pd.read_sas('/age.sas7bdat')df.id = df.id.astype('int')df.age = df.age.astype('int')df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 1001 entries, 0 to 1000Data columns (total 2 columns):id 1001 non-null int64age 1001 non-null int64dtypes: int64(2)memory usage: 15.7 KB
We will create three groups: Young, Middle and Old age. Let’s define young age as people younger than 35 years. middle age for people between 35 and 60 and old age for people over 60 years old.
%%SASDATA age_group; SET dd1.age;IF age < 35 THEN age_group = 'young age ';ELSE IF age >= 35 AND age < 60 THEN age_group = 'middle age';ELSE IF age >= 60 THEN age_group = 'old age ';RUN; proc print DATA = age_group(obs=10);run;
We can do this with a simple IF-THEN statement for each condition, though, it is much better to use an ELSE IF after the first IF statement.
The reason is that this gives you more control over what is happening.
Notice the blank space I have added to the text in the age_group. That’s because I haven’t defined the length of the character variable. Therefore, I have to make sure it will capture all three values with the full text.
There are many different ways you can code conditional programming in Python. It is called IF-ELIF-ELSE. Python does not use the word THEN but uses a colon instead.
We will look at the following different ways:
Using a user-defined function
Using a lambda function
Using a for loop
Using a list comprehension
def age_grp_if(x): if (x < 35) : return 'young age' elif (x < 60): return 'middle age' else: return 'old age'age_group = df.copy()age_group['age_grp_if'] = age_group['age'].apply(age_grp_if)age_group.head()
First, you define the function with the argument you want in your condition and end it with a colon. The indented lines are telling Python to read them as part of the function definition.
You write the condition in brackets with a colon. In the next line, if the condition is true, you write the result you want to return and so forth... The last statement is an else: which will return if none of the above conditions are true.
To use the function in a DataFrame, you use the .apply(func) method on the column you want to use in the condition.
This method of defining your if-else coding in a function is very popular in Python and very easy to read. It’s different from what we are used to doing in SAS. But you can think about functions in SAS as a macro function.
You can use a lambda function instead of defining the function first and then applying it in your data step. The only problem with using lambda functions is that they are slightly difficult to read. This is because they do things in an opposing way.
The syntax for a lambda function using if-else is:
lambda args : return Value1 if condition1 else ( return value2 if condition2 else return value3)
The good thing about lambda functions is that you only need to write them on the fly when you need them.
age_group['age_grp_lambda'] = age_group['age'].apply( lambda x : 'young age' if (x < 35) else ( 'middle age' if (x < 60) else 'old age'))age_group.head()
In case you have more than three conditions, the syntax will look like this:
lambda x : return Value1 if condition1 ( return value2 if condition2 ( return value3 if condition3 else return value4))age_group['age_grp_lambda4grp'] = age_group['age'].apply( lambda x : 'young age' if (x < 35) else ( 'middle age' if (x < 60) else ( 'senior age' if (x < 75) else 'old age')))age_group.head(10)
It is also possible to use a loop to construct an if-elif condition.
As we saw in the lecture regarding loops, you first build the loop in basic Python syntax and run it through the list of values in the age_group['age'] column.
age=[]for x in age_group['age']: if (x < 35): age.append('young age') elif (x < 60): age.append('middle age') elif (x < 65): age.append('senior age') else : age.append('old age') age_group['age_grp_forloop'] = ageage_group.head()
You append the results to the list, age and then assign this list to a new column in the DataFrame.
Compare to the function method, the loop message is very easy to read, plus you type less.
The last method for coding if-elif statement is using list comprehension. A method that is sufficiently fast and even easier sometimes.
([return Value1 if condition1 else ( return value2 if condition2 else ( return value3 if condition3 else return value4)) for x in df['col']] )
The outer brackets of the list are only necessary when codes span over multiple lines.
age_group['age_grp_forxin'] = ([ 'young age' if (x < 35) else ( 'middle age' if (x < 60) else ( 'senior age' if (x < 65) else 'old age')) for x in age_group['age'] ])age_group.head(10)
There are other ways you can do it in Python. Here I will show you how to use some functionalities from NumPy and Pandas to make conditional coding.
From Numpy you can use np.where and np.select.
From Pandas, you can use .loc[]
First, let’s look at how to use the np.where() function
np.where(contidion1, return Value1, return Value2)
Where you can substitute return Value2 with a new np.where()u001b for each condition
In the age group examples, the code will look like the following:
age_group['age_grp_whr'] = np.where(age_group['age'] < 35, 'young age', np.where(age_group['age'] < 60, 'middle age', np.where(age_group['age'] < 65, 'senior age', 'old age')))age_group.head(10)
Let’s look at how to use the np.select() function. This is very different from the other examples because you should first list all the conditions and then list all the return Values:
np.select([(condition1),(condition2),(condition3)], [return Value1,return Value2,return Value3]
In the age group example, the code will look like this:
age_group['age_select'] = np.select([(age_group['age']<35), (age_group['age']<60), (age_group['age']>=60)], ['young age', 'middle age', 'old age']) age_group.head(10)
The last way I’ll show you is to use the .loc method in Pandas. It’s quite handy as it’s got a straightforward syntax.
Remember, if you are not consistent in the coding of the conditions, you are more likely to make a mistake with your groupings. Also, if you’ve missed something, you won’t get any warnings.
With .loc you test if a condition is True, If it is True you assign a value and save the result in a new column.
The syntax is:
df.loc[condition, 'new var'] = return value
In our age group example, the code will look like this:
age_group.loc[age_group['age'] < 30, 'age_grp_loc'] = 'young age' age_group.loc[(age_group['age'] >= 30) & (age_group['age'] < 60), 'age_grp_loc'] = 'middle age' age_group.loc[age_group['age'] >= 60, 'age_grp_loc'] = 'old age' age_group.head(10)
In this article, we have seen how you can use conditional coding in Python in a similar way as you do in SAS. There are many different ways to do it in Python and you should choose the one you are most familiar with.
That been said, the different methods are not the same when it comes to speed and if you are working with a huge amount of data and have a lot of conditional coding, you should choose with care.
You can find out more about learning Python the way you work in SAS at my website: www.nordstroem.uk
|
[
{
"code": null,
"e": 365,
"s": 172,
"text": "I think I’ve used IF-THEN-ELSE Statement or conditional coding in almost every analysis or program I have developed in the last 30 years. It is very useful in both preparing and cleaning data."
},
{
"code": null,
"e": 577,
"s": 365,
"text": "IF-THEN-ELSE is an integrated part of the data step in SAS. We don’t have an object for a data step in Python, but can step through the data frame in a similar way and use IF-ELIF-ELSE as it is called in Python."
},
{
"code": null,
"e": 772,
"s": 577,
"text": "So in this article, We will look at what we do in SAS and see how we can do the same kind of conditional coding in Python. I’ll also show you alternative ways of running IF-ELIF-ELSE statements."
},
{
"code": null,
"e": 860,
"s": 772,
"text": "IF-END-ELSE It’s a straightforward concept. In pseudocode it looks something like this:"
},
{
"code": null,
"e": 1001,
"s": 860,
"text": "IF something is true, THEN return the first value,ELSE IF some other thing is true THEN return the second value,ELSE return the third value."
},
{
"code": null,
"e": 1097,
"s": 1001,
"text": "The most commonly used if-the-else coding on earth is putting people into different age groups."
},
{
"code": null,
"e": 1202,
"s": 1097,
"text": "First I will create a SAS data set with a random generated age around a mean of 50 and a variace of 100."
},
{
"code": null,
"e": 1378,
"s": 1202,
"text": "%%SAS%LET mu = 50; %let s2 = 100;DATA dd1.age; DO id = 1000 TO 2000; age = INT(&mu + sqrt(&s2) * rannor(1066)); OUTPUT; END; RUN;PROC PRINT DATA = dd1.age(OBS=5);RUN;"
},
{
"code": null,
"e": 1592,
"s": 1378,
"text": "I want to use the same data in both SAS and Python so I can compare the results. Since you can not generate the same sequence of random numbers in both SAS and Python, I want to use the SAS data set in Python too."
},
{
"code": null,
"e": 1703,
"s": 1592,
"text": "For this article, I have used an environment where I can run both SAS and Python in the same Jupyter notebook."
},
{
"code": null,
"e": 1758,
"s": 1703,
"text": "You can find a description on how to do this guide at:"
},
{
"code": null,
"e": 1821,
"s": 1758,
"text": "How to set up SAS and Python on Amazon Web Services Free Tier."
},
{
"code": null,
"e": 2010,
"s": 1821,
"text": "I import the SAS data set with pd.read_sas() in Python. Since SAS only have floating-point numbers, Python will import age as a float and not an integer, so I’ll convert age to an integer."
},
{
"code": null,
"e": 2301,
"s": 2010,
"text": "df = pd.read_sas('/age.sas7bdat')df.id = df.id.astype('int')df.age = df.age.astype('int')df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 1001 entries, 0 to 1000Data columns (total 2 columns):id 1001 non-null int64age 1001 non-null int64dtypes: int64(2)memory usage: 15.7 KB"
},
{
"code": null,
"e": 2495,
"s": 2301,
"text": "We will create three groups: Young, Middle and Old age. Let’s define young age as people younger than 35 years. middle age for people between 35 and 60 and old age for people over 60 years old."
},
{
"code": null,
"e": 2727,
"s": 2495,
"text": "%%SASDATA age_group;\tSET dd1.age;IF age < 35 THEN age_group = 'young age ';ELSE IF age >= 35 AND age < 60 THEN age_group = 'middle age';ELSE IF age >= 60 THEN age_group = 'old age ';RUN; proc print DATA = age_group(obs=10);run;"
},
{
"code": null,
"e": 2868,
"s": 2727,
"text": "We can do this with a simple IF-THEN statement for each condition, though, it is much better to use an ELSE IF after the first IF statement."
},
{
"code": null,
"e": 2939,
"s": 2868,
"text": "The reason is that this gives you more control over what is happening."
},
{
"code": null,
"e": 3160,
"s": 2939,
"text": "Notice the blank space I have added to the text in the age_group. That’s because I haven’t defined the length of the character variable. Therefore, I have to make sure it will capture all three values with the full text."
},
{
"code": null,
"e": 3325,
"s": 3160,
"text": "There are many different ways you can code conditional programming in Python. It is called IF-ELIF-ELSE. Python does not use the word THEN but uses a colon instead."
},
{
"code": null,
"e": 3371,
"s": 3325,
"text": "We will look at the following different ways:"
},
{
"code": null,
"e": 3401,
"s": 3371,
"text": "Using a user-defined function"
},
{
"code": null,
"e": 3425,
"s": 3401,
"text": "Using a lambda function"
},
{
"code": null,
"e": 3442,
"s": 3425,
"text": "Using a for loop"
},
{
"code": null,
"e": 3469,
"s": 3442,
"text": "Using a list comprehension"
},
{
"code": null,
"e": 3707,
"s": 3469,
"text": "def age_grp_if(x): if (x < 35) : return 'young age' elif (x < 60): return 'middle age' else: return 'old age'age_group = df.copy()age_group['age_grp_if'] = age_group['age'].apply(age_grp_if)age_group.head()"
},
{
"code": null,
"e": 3895,
"s": 3707,
"text": "First, you define the function with the argument you want in your condition and end it with a colon. The indented lines are telling Python to read them as part of the function definition."
},
{
"code": null,
"e": 4136,
"s": 3895,
"text": "You write the condition in brackets with a colon. In the next line, if the condition is true, you write the result you want to return and so forth... The last statement is an else: which will return if none of the above conditions are true."
},
{
"code": null,
"e": 4252,
"s": 4136,
"text": "To use the function in a DataFrame, you use the .apply(func) method on the column you want to use in the condition."
},
{
"code": null,
"e": 4475,
"s": 4252,
"text": "This method of defining your if-else coding in a function is very popular in Python and very easy to read. It’s different from what we are used to doing in SAS. But you can think about functions in SAS as a macro function."
},
{
"code": null,
"e": 4725,
"s": 4475,
"text": "You can use a lambda function instead of defining the function first and then applying it in your data step. The only problem with using lambda functions is that they are slightly difficult to read. This is because they do things in an opposing way."
},
{
"code": null,
"e": 4776,
"s": 4725,
"text": "The syntax for a lambda function using if-else is:"
},
{
"code": null,
"e": 4873,
"s": 4776,
"text": "lambda args : return Value1 if condition1 else ( return value2 if condition2 else return value3)"
},
{
"code": null,
"e": 4978,
"s": 4873,
"text": "The good thing about lambda functions is that you only need to write them on the fly when you need them."
},
{
"code": null,
"e": 5150,
"s": 4978,
"text": "age_group['age_grp_lambda'] = age_group['age'].apply( lambda x : 'young age' if (x < 35) else ( 'middle age' if (x < 60) else 'old age'))age_group.head()"
},
{
"code": null,
"e": 5227,
"s": 5150,
"text": "In case you have more than three conditions, the syntax will look like this:"
},
{
"code": null,
"e": 5582,
"s": 5227,
"text": "lambda x : return Value1 if condition1 ( return value2 if condition2 ( return value3 if condition3 else return value4))age_group['age_grp_lambda4grp'] = age_group['age'].apply( lambda x : 'young age' if (x < 35) else ( 'middle age' if (x < 60) else ( 'senior age' if (x < 75) else 'old age')))age_group.head(10)"
},
{
"code": null,
"e": 5651,
"s": 5582,
"text": "It is also possible to use a loop to construct an if-elif condition."
},
{
"code": null,
"e": 5811,
"s": 5651,
"text": "As we saw in the lecture regarding loops, you first build the loop in basic Python syntax and run it through the list of values in the age_group['age'] column."
},
{
"code": null,
"e": 6088,
"s": 5811,
"text": "age=[]for x in age_group['age']: if (x < 35): age.append('young age') elif (x < 60): age.append('middle age') elif (x < 65): age.append('senior age') else : age.append('old age') age_group['age_grp_forloop'] = ageage_group.head()"
},
{
"code": null,
"e": 6188,
"s": 6088,
"text": "You append the results to the list, age and then assign this list to a new column in the DataFrame."
},
{
"code": null,
"e": 6279,
"s": 6188,
"text": "Compare to the function method, the loop message is very easy to read, plus you type less."
},
{
"code": null,
"e": 6415,
"s": 6279,
"text": "The last method for coding if-elif statement is using list comprehension. A method that is sufficiently fast and even easier sometimes."
},
{
"code": null,
"e": 6560,
"s": 6415,
"text": "([return Value1 if condition1 else ( return value2 if condition2 else ( return value3 if condition3 else return value4)) for x in df['col']] )"
},
{
"code": null,
"e": 6647,
"s": 6560,
"text": "The outer brackets of the list are only necessary when codes span over multiple lines."
},
{
"code": null,
"e": 6906,
"s": 6647,
"text": "age_group['age_grp_forxin'] = ([ 'young age' if (x < 35) else ( 'middle age' if (x < 60) else ( 'senior age' if (x < 65) else 'old age')) for x in age_group['age'] ])age_group.head(10)"
},
{
"code": null,
"e": 7055,
"s": 6906,
"text": "There are other ways you can do it in Python. Here I will show you how to use some functionalities from NumPy and Pandas to make conditional coding."
},
{
"code": null,
"e": 7102,
"s": 7055,
"text": "From Numpy you can use np.where and np.select."
},
{
"code": null,
"e": 7134,
"s": 7102,
"text": "From Pandas, you can use .loc[]"
},
{
"code": null,
"e": 7190,
"s": 7134,
"text": "First, let’s look at how to use the np.where() function"
},
{
"code": null,
"e": 7241,
"s": 7190,
"text": "np.where(contidion1, return Value1, return Value2)"
},
{
"code": null,
"e": 7326,
"s": 7241,
"text": "Where you can substitute return Value2 with a new np.where()u001b for each condition"
},
{
"code": null,
"e": 7392,
"s": 7326,
"text": "In the age group examples, the code will look like the following:"
},
{
"code": null,
"e": 7674,
"s": 7392,
"text": "age_group['age_grp_whr'] = np.where(age_group['age'] < 35, 'young age', np.where(age_group['age'] < 60, 'middle age', np.where(age_group['age'] < 65, 'senior age', 'old age')))age_group.head(10)"
},
{
"code": null,
"e": 7858,
"s": 7674,
"text": "Let’s look at how to use the np.select() function. This is very different from the other examples because you should first list all the conditions and then list all the return Values:"
},
{
"code": null,
"e": 7963,
"s": 7858,
"text": "np.select([(condition1),(condition2),(condition3)], [return Value1,return Value2,return Value3]"
},
{
"code": null,
"e": 8019,
"s": 7963,
"text": "In the age group example, the code will look like this:"
},
{
"code": null,
"e": 8365,
"s": 8019,
"text": "age_group['age_select'] = np.select([(age_group['age']<35), (age_group['age']<60), (age_group['age']>=60)], ['young age', 'middle age', 'old age']) age_group.head(10)"
},
{
"code": null,
"e": 8484,
"s": 8365,
"text": "The last way I’ll show you is to use the .loc method in Pandas. It’s quite handy as it’s got a straightforward syntax."
},
{
"code": null,
"e": 8674,
"s": 8484,
"text": "Remember, if you are not consistent in the coding of the conditions, you are more likely to make a mistake with your groupings. Also, if you’ve missed something, you won’t get any warnings."
},
{
"code": null,
"e": 8787,
"s": 8674,
"text": "With .loc you test if a condition is True, If it is True you assign a value and save the result in a new column."
},
{
"code": null,
"e": 8802,
"s": 8787,
"text": "The syntax is:"
},
{
"code": null,
"e": 8846,
"s": 8802,
"text": "df.loc[condition, 'new var'] = return value"
},
{
"code": null,
"e": 8902,
"s": 8846,
"text": "In our age group example, the code will look like this:"
},
{
"code": null,
"e": 9148,
"s": 8902,
"text": "age_group.loc[age_group['age'] < 30, 'age_grp_loc'] = 'young age' age_group.loc[(age_group['age'] >= 30) & (age_group['age'] < 60), 'age_grp_loc'] = 'middle age' age_group.loc[age_group['age'] >= 60, 'age_grp_loc'] = 'old age' age_group.head(10)"
},
{
"code": null,
"e": 9365,
"s": 9148,
"text": "In this article, we have seen how you can use conditional coding in Python in a similar way as you do in SAS. There are many different ways to do it in Python and you should choose the one you are most familiar with."
},
{
"code": null,
"e": 9560,
"s": 9365,
"text": "That been said, the different methods are not the same when it comes to speed and if you are working with a huge amount of data and have a lot of conditional coding, you should choose with care."
}
] |
IntegerField - Django Models - GeeksforGeeks
|
12 Feb, 2020
IntegerField is a integer number represented in Python by a int instance. This field is generally used to store integer numbers in the database. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise. It supports values from -2147483648 to 2147483647 are safe in all databases supported by Django.It uses MinValueValidator and MaxValueValidator to validate the input based on the values that the default database supports.
Syntax:
field_name = models.IntegerField(**options)
Illustration of IntegerField using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app.
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.IntegerField()
Add the geeks app to INSTALLED_APPS
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]
Now when we run makemigrations command from the terminal,
Python manage.py makemigrations
A new folder named migrations would be created in geeks directory with a file named 0001_initial.py
# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.IntegerField()), ], ), ]
Now run,
Python manage.py migrate
Thus, an geeks_field IntegerField is created when you run migrations on the project. It is a field to store a integer numbers.
IntegerField is used for storing a integer number represented in Python by a int instance. To know more about int, visit Python | int() function. Let’s try to save a flating number in FlatField.
# importing the model# from geeks appfrom geeks.models import GeeksModel # creating an instance of# intd = int(2189) # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()
Now let’s check it in admin server. We have created an instance of GeeksModel.
Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to IntegerField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an IntegerField can use.
NaveenArora
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Box Plot in Python using Matplotlib
Python Dictionary
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Graph Plotting in Python | Set 1
Python - Call function from another file
loops in python
|
[
{
"code": null,
"e": 23939,
"s": 23911,
"text": "\n12 Feb, 2020"
},
{
"code": null,
"e": 24409,
"s": 23939,
"text": "IntegerField is a integer number represented in Python by a int instance. This field is generally used to store integer numbers in the database. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise. It supports values from -2147483648 to 2147483647 are safe in all databases supported by Django.It uses MinValueValidator and MaxValueValidator to validate the input based on the values that the default database supports."
},
{
"code": null,
"e": 24417,
"s": 24409,
"text": "Syntax:"
},
{
"code": null,
"e": 24461,
"s": 24417,
"text": "field_name = models.IntegerField(**options)"
},
{
"code": null,
"e": 24574,
"s": 24461,
"text": "Illustration of IntegerField using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 24661,
"s": 24574,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 24712,
"s": 24661,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 24745,
"s": 24712,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 24804,
"s": 24745,
"text": "Enter the following code into models.py file of geeks app."
},
{
"code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.IntegerField()",
"e": 24958,
"s": 24804,
"text": null
},
{
"code": null,
"e": 24994,
"s": 24958,
"text": "Add the geeks app to INSTALLED_APPS"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]",
"e": 25232,
"s": 24994,
"text": null
},
{
"code": null,
"e": 25290,
"s": 25232,
"text": "Now when we run makemigrations command from the terminal,"
},
{
"code": null,
"e": 25322,
"s": 25290,
"text": "Python manage.py makemigrations"
},
{
"code": null,
"e": 25422,
"s": 25322,
"text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py"
},
{
"code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.IntegerField()), ], ), ]",
"e": 26029,
"s": 25422,
"text": null
},
{
"code": null,
"e": 26038,
"s": 26029,
"text": "Now run,"
},
{
"code": null,
"e": 26063,
"s": 26038,
"text": "Python manage.py migrate"
},
{
"code": null,
"e": 26190,
"s": 26063,
"text": "Thus, an geeks_field IntegerField is created when you run migrations on the project. It is a field to store a integer numbers."
},
{
"code": null,
"e": 26385,
"s": 26190,
"text": "IntegerField is used for storing a integer number represented in Python by a int instance. To know more about int, visit Python | int() function. Let’s try to save a flating number in FlatField."
},
{
"code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # creating an instance of# intd = int(2189) # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()",
"e": 26616,
"s": 26385,
"text": null
},
{
"code": null,
"e": 26695,
"s": 26616,
"text": "Now let’s check it in admin server. We have created an instance of GeeksModel."
},
{
"code": null,
"e": 27047,
"s": 26695,
"text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to IntegerField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an IntegerField can use."
},
{
"code": null,
"e": 27059,
"s": 27047,
"text": "NaveenArora"
},
{
"code": null,
"e": 27073,
"s": 27059,
"text": "Django-models"
},
{
"code": null,
"e": 27087,
"s": 27073,
"text": "Python Django"
},
{
"code": null,
"e": 27094,
"s": 27087,
"text": "Python"
},
{
"code": null,
"e": 27192,
"s": 27094,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27201,
"s": 27192,
"text": "Comments"
},
{
"code": null,
"e": 27214,
"s": 27201,
"text": "Old Comments"
},
{
"code": null,
"e": 27251,
"s": 27214,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27287,
"s": 27251,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 27305,
"s": 27287,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27328,
"s": 27305,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 27367,
"s": 27328,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27400,
"s": 27367,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 27449,
"s": 27400,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 27482,
"s": 27449,
"text": "Graph Plotting in Python | Set 1"
},
{
"code": null,
"e": 27523,
"s": 27482,
"text": "Python - Call function from another file"
}
] |
Embedded Systems - I/O Programming
|
In 8051, I/O operations are done using four ports and 40 pins. The following pin diagram shows the details of the 40 pins. I/O operation port reserves 32 pins where each port has 8 pins. The other 8 pins are designated as Vcc, GND, XTAL1, XTAL2, RST, EA (bar), ALE/PROG (bar), and PSEN (bar).
It is a 40 Pin PDIP (Plastic Dual Inline Package)
Note − In a DIP package, you can recognize the first pin and the last pin by the cut at the middle of the IC. The first pin is on the left of this cut mark and the last pin (i.e. the 40th pin in this case) is to the right of the cut mark.
The four ports P0, P1, P2, and P3, each use 8 pins, making them 8-bit ports. Upon RESET, all the ports are configured as inputs, ready to be used as input ports. When the first 0 is written to a port, it becomes an output. To reconfigure it as an input, a 1 must be sent to a port.
It has 8 pins (32 to 39). It can be used for input or output. Unlike P1, P2, and P3 ports, we normally connect P0 to 10K-ohm pull-up resistors to use it as an input or output port being an open drain.
It is also designated as AD0-AD7, allowing it to be used as both address and data. In case of 8031 (i.e. ROMless Chip), when we need to access the external ROM, then P0 will be used for both Address and Data Bus. ALE (Pin no 31) indicates if P0 has address or data. When ALE = 0, it provides data D0-D7, but when ALE = 1, it has address A0-A7. In case no external memory connection is available, P0 must be connected externally to a 10K-ohm pull-up resistor.
MOV A,#0FFH ;(comments: A=FFH(Hexadecimal i.e. A=1111 1111)
MOV P0,A ;(Port0 have 1's on every pin so that it works as Input)
It is an 8-bit port (pin 1 through 8) and can be used either as input or output. It doesn't require pull-up resistors because they are already connected internally. Upon reset, Port 1 is configured as an input port. The following code can be used to send alternating values of 55H and AAH to Port 1.
;Toggle all bits of continuously
MOV A,#55
BACK:
MOV P2,A
ACALL DELAY
CPL A ;complement(invert) reg. A
SJMP BACK
If Port 1 is configured to be used as an output port, then to use it as an input port again, program it by writing 1 to all of its bits as in the following code.
;Toggle all bits of continuously
MOV A ,#0FFH ;A = FF hex
MOV P1,A ;Make P1 an input port
MOV A,P1 ;get data from P1
MOV R7,A ;save it in Reg R7
ACALL DELAY ;wait
MOV A,P1 ;get another data from P1
MOV R6,A ;save it in R6
ACALL DELAY ;wait
MOV A,P1 ;get another data from P1
MOV R5,A ;save it in R5
Port 2 occupies a total of 8 pins (pins 21 through 28) and can be used for both input and output operations. Just as P1 (Port 1), P2 also doesn't require external Pull-up resistors because they are already connected internally. It must be used along with P0 to provide the 16-bit address for the external memory. So it is also designated as (A0–A7), as shown in the pin diagram. When the 8051 is connected to an external memory, it provides path for upper 8-bits of 16-bits address, and it cannot be used as I/O. Upon reset, Port 2 is configured as an input port. The following code can be used to send alternating values of 55H and AAH to port 2.
;Toggle all bits of continuously
MOV A,#55
BACK:
MOV P2,A
ACALL DELAY
CPL A ; complement(invert) reg. A
SJMP BACK
If Port 2 is configured to be used as an output port, then to use it as an input port again, program it by writing 1 to all of its bits as in the following code.
;Get a byte from P2 and send it to P1
MOV A,#0FFH ;A = FF hex
MOV P2,A ;make P2 an input port
BACK:
MOV A,P2 ;get data from P2
MOV P1,A ;send it to Port 1
SJMP BACK ;keep doing that
It is also of 8 bits and can be used as Input/Output. This port provides some extremely important signals. P3.0 and P3.1 are RxD (Receiver) and TxD (Transmitter) respectively and are collectively used for Serial Communication. P3.2 and P3.3 pins are used for external interrupts. P3.4 and P3.5 are used for timers T0 and T1 respectively. P3.6 and P3.7 are Write (WR) and Read (RD) pins. These are active low pins, means they will be active when 0 is given to them and these are used to provide Read and Write operations to External ROM in 8031 based systems.
Dual role of Port 0 − Port 0 is also designated as AD0–AD7, as it can be used for both data and address handling. While connecting an 8051 to external memory, Port 0 can provide both address and data. The 8051 microcontroller then multiplexes the input as address or data in order to save pins.
Dual role of Port 0 − Port 0 is also designated as AD0–AD7, as it can be used for both data and address handling. While connecting an 8051 to external memory, Port 0 can provide both address and data. The 8051 microcontroller then multiplexes the input as address or data in order to save pins.
Dual role of Port 2 − Besides working as I/O, Port P2 is also used to provide 16-bit address bus for external memory along with Port 0. Port P2 is also designated as (A8– A15), while Port 0 provides the lower 8-bits via A0–A7. In other words, we can say that when an 8051 is connected to an external memory (ROM) which can be maximum up to 64KB and this is possible by 16 bit address bus because we know 216 = 64KB. Port2 is used for the upper 8-bit of the 16 bits address, and it cannot be used for I/O and this is the way any Program code of external ROM is addressed.
Dual role of Port 2 − Besides working as I/O, Port P2 is also used to provide 16-bit address bus for external memory along with Port 0. Port P2 is also designated as (A8– A15), while Port 0 provides the lower 8-bits via A0–A7. In other words, we can say that when an 8051 is connected to an external memory (ROM) which can be maximum up to 64KB and this is possible by 16 bit address bus because we know 216 = 64KB. Port2 is used for the upper 8-bit of the 16 bits address, and it cannot be used for I/O and this is the way any Program code of external ROM is addressed.
Vcc − Pin 40 provides supply to the Chip and it is +5 V.
Vcc − Pin 40 provides supply to the Chip and it is +5 V.
Gnd − Pin 20 provides ground for the Reference.
Gnd − Pin 20 provides ground for the Reference.
XTAL1, XTAL2 (Pin no 18 & Pin no 19) − 8051 has on-chip oscillator but requires external clock to run it. A quartz crystal is connected between the XTAL1 & XTAL2 pin of the chip. This crystal also needs two capacitors of 30pF for generating a signal of desired frequency. One side of each capacitor is connected to ground. 8051 IC is available in various speeds and it all depends on this Quartz crystal, for example, a 20 MHz microcontroller requires a crystal with a frequency no more than 20 MHz.
XTAL1, XTAL2 (Pin no 18 & Pin no 19) − 8051 has on-chip oscillator but requires external clock to run it. A quartz crystal is connected between the XTAL1 & XTAL2 pin of the chip. This crystal also needs two capacitors of 30pF for generating a signal of desired frequency. One side of each capacitor is connected to ground. 8051 IC is available in various speeds and it all depends on this Quartz crystal, for example, a 20 MHz microcontroller requires a crystal with a frequency no more than 20 MHz.
RST (Pin No. 9) − It is an Input pin and active High pin. Upon applying a high pulse on this pin, that is 1, the microcontroller will reset and terminate all activities. This process is known as Power-On Reset. Activating a power-on reset will cause all values in the register to be lost. It will set a program counter to all 0's. To ensure a valid input of Reset, the high pulse must be high for a minimum of two machine cycles before it is allowed to go low, which depends on the capacitor value and the rate at which it charges. (Machine Cycle is the minimum amount of frequency a single instruction requires in execution).
RST (Pin No. 9) − It is an Input pin and active High pin. Upon applying a high pulse on this pin, that is 1, the microcontroller will reset and terminate all activities. This process is known as Power-On Reset. Activating a power-on reset will cause all values in the register to be lost. It will set a program counter to all 0's. To ensure a valid input of Reset, the high pulse must be high for a minimum of two machine cycles before it is allowed to go low, which depends on the capacitor value and the rate at which it charges. (Machine Cycle is the minimum amount of frequency a single instruction requires in execution).
EA or External Access (Pin No. 31) − It is an input pin. This pin is an active low pin; upon applying a low pulse, it gets activated. In case of microcontroller (8051/52) having on-chip ROM, the EA (bar) pin is connected to Vcc. But in an 8031 microcontroller which does not have an on-chip ROM, the code is stored in an external ROM and then fetched by the microcontroller. In this case, we must connect the (pin no 31) EA to Gnd to indicate that the program code is stored externally.
EA or External Access (Pin No. 31) − It is an input pin. This pin is an active low pin; upon applying a low pulse, it gets activated. In case of microcontroller (8051/52) having on-chip ROM, the EA (bar) pin is connected to Vcc. But in an 8031 microcontroller which does not have an on-chip ROM, the code is stored in an external ROM and then fetched by the microcontroller. In this case, we must connect the (pin no 31) EA to Gnd to indicate that the program code is stored externally.
PSEN or Program store Enable (Pin No 29) − This is also an active low pin, i.e., it gets activated after applying a low pulse. It is an output pin and used along with the EA pin in 8031 based (i.e. ROMLESS) Systems to allow storage of program code in external ROM.
PSEN or Program store Enable (Pin No 29) − This is also an active low pin, i.e., it gets activated after applying a low pulse. It is an output pin and used along with the EA pin in 8031 based (i.e. ROMLESS) Systems to allow storage of program code in external ROM.
ALE or (Address Latch Enable) − This is an Output Pin and is active high. It is especially used for 8031 IC to connect it to the external memory. It can be used while deciding whether P0 pins will be used as Address bus or Data bus. When ALE = 1, then the P0 pins work as Data bus and when ALE = 0, then the P0 pins act as Address bus.
ALE or (Address Latch Enable) − This is an Output Pin and is active high. It is especially used for 8031 IC to connect it to the external memory. It can be used while deciding whether P0 pins will be used as Address bus or Data bus. When ALE = 1, then the P0 pins work as Data bus and when ALE = 0, then the P0 pins act as Address bus.
It is a most widely used feature of 8051 while writing code for 8051. Sometimes we need to access only 1 or 2 bits of the port instead of the entire 8-bits. 8051 provides the capability to access individual bits of the ports.
While accessing a port in a single-bit manner, we use the syntax "SETB X. Y" where X is the port number (0 to 3), and Y is a bit number (0 to 7) for data bits D0-D7 where D0 is the LSB and D7 is the MSB. For example, "SETB P1.5" sets high bit 5 of port 1.
The following code shows how we can toggle the bit P1.2 continuously.
AGAIN:
SETB P1.2
ACALL DELAY
CLR P1.2
ACALL DELAY
SJMP AGAIN
65 Lectures
6.5 hours
Amit Rana
36 Lectures
4.5 hours
Amit Rana
33 Lectures
3 hours
Ashraf Said
23 Lectures
2 hours
Smart Logic Academy
66 Lectures
5.5 hours
NerdyElectronics
49 Lectures
8.5 hours
Rahul Shrivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2176,
"s": 1883,
"text": "In 8051, I/O operations are done using four ports and 40 pins. The following pin diagram shows the details of the 40 pins. I/O operation port reserves 32 pins where each port has 8 pins. The other 8 pins are designated as Vcc, GND, XTAL1, XTAL2, RST, EA (bar), ALE/PROG (bar), and PSEN (bar)."
},
{
"code": null,
"e": 2226,
"s": 2176,
"text": "It is a 40 Pin PDIP (Plastic Dual Inline Package)"
},
{
"code": null,
"e": 2465,
"s": 2226,
"text": "Note − In a DIP package, you can recognize the first pin and the last pin by the cut at the middle of the IC. The first pin is on the left of this cut mark and the last pin (i.e. the 40th pin in this case) is to the right of the cut mark."
},
{
"code": null,
"e": 2747,
"s": 2465,
"text": "The four ports P0, P1, P2, and P3, each use 8 pins, making them 8-bit ports. Upon RESET, all the ports are configured as inputs, ready to be used as input ports. When the first 0 is written to a port, it becomes an output. To reconfigure it as an input, a 1 must be sent to a port."
},
{
"code": null,
"e": 2948,
"s": 2747,
"text": "It has 8 pins (32 to 39). It can be used for input or output. Unlike P1, P2, and P3 ports, we normally connect P0 to 10K-ohm pull-up resistors to use it as an input or output port being an open drain."
},
{
"code": null,
"e": 3407,
"s": 2948,
"text": "It is also designated as AD0-AD7, allowing it to be used as both address and data. In case of 8031 (i.e. ROMless Chip), when we need to access the external ROM, then P0 will be used for both Address and Data Bus. ALE (Pin no 31) indicates if P0 has address or data. When ALE = 0, it provides data D0-D7, but when ALE = 1, it has address A0-A7. In case no external memory connection is available, P0 must be connected externally to a 10K-ohm pull-up resistor."
},
{
"code": null,
"e": 3543,
"s": 3407,
"text": "MOV A,#0FFH ;(comments: A=FFH(Hexadecimal i.e. A=1111 1111) \n\nMOV P0,A ;(Port0 have 1's on every pin so that it works as Input)\n"
},
{
"code": null,
"e": 3843,
"s": 3543,
"text": "It is an 8-bit port (pin 1 through 8) and can be used either as input or output. It doesn't require pull-up resistors because they are already connected internally. Upon reset, Port 1 is configured as an input port. The following code can be used to send alternating values of 55H and AAH to Port 1."
},
{
"code": null,
"e": 3989,
"s": 3843,
"text": ";Toggle all bits of continuously \nMOV A,#55 \nBACK: \n\nMOV P2,A \nACALL DELAY \nCPL A ;complement(invert) reg. A \nSJMP BACK\n"
},
{
"code": null,
"e": 4151,
"s": 3989,
"text": "If Port 1 is configured to be used as an output port, then to use it as an input port again, program it by writing 1 to all of its bits as in the following code."
},
{
"code": null,
"e": 4584,
"s": 4151,
"text": ";Toggle all bits of continuously \n\nMOV A ,#0FFH ;A = FF hex \nMOV P1,A ;Make P1 an input port \nMOV A,P1 ;get data from P1 \nMOV R7,A ;save it in Reg R7 \nACALL DELAY ;wait \n\nMOV A,P1 ;get another data from P1 \nMOV R6,A ;save it in R6 \nACALL DELAY ;wait \n\nMOV A,P1 ;get another data from P1 \nMOV R5,A ;save it in R5\n"
},
{
"code": null,
"e": 5232,
"s": 4584,
"text": "Port 2 occupies a total of 8 pins (pins 21 through 28) and can be used for both input and output operations. Just as P1 (Port 1), P2 also doesn't require external Pull-up resistors because they are already connected internally. It must be used along with P0 to provide the 16-bit address for the external memory. So it is also designated as (A0–A7), as shown in the pin diagram. When the 8051 is connected to an external memory, it provides path for upper 8-bits of 16-bits address, and it cannot be used as I/O. Upon reset, Port 2 is configured as an input port. The following code can be used to send alternating values of 55H and AAH to port 2."
},
{
"code": null,
"e": 5378,
"s": 5232,
"text": ";Toggle all bits of continuously \nMOV A,#55 \nBACK: \nMOV P2,A \nACALL DELAY \nCPL A ; complement(invert) reg. A \nSJMP BACK\n"
},
{
"code": null,
"e": 5540,
"s": 5378,
"text": "If Port 2 is configured to be used as an output port, then to use it as an input port again, program it by writing 1 to all of its bits as in the following code."
},
{
"code": null,
"e": 5769,
"s": 5540,
"text": ";Get a byte from P2 and send it to P1 \nMOV A,#0FFH ;A = FF hex \nMOV P2,A ;make P2 an input port \nBACK: \nMOV A,P2 ;get data from P2 \nMOV P1,A ;send it to Port 1\nSJMP BACK ;keep doing that\n"
},
{
"code": null,
"e": 6328,
"s": 5769,
"text": "It is also of 8 bits and can be used as Input/Output. This port provides some extremely important signals. P3.0 and P3.1 are RxD (Receiver) and TxD (Transmitter) respectively and are collectively used for Serial Communication. P3.2 and P3.3 pins are used for external interrupts. P3.4 and P3.5 are used for timers T0 and T1 respectively. P3.6 and P3.7 are Write (WR) and Read (RD) pins. These are active low pins, means they will be active when 0 is given to them and these are used to provide Read and Write operations to External ROM in 8031 based systems."
},
{
"code": null,
"e": 6623,
"s": 6328,
"text": "Dual role of Port 0 − Port 0 is also designated as AD0–AD7, as it can be used for both data and address handling. While connecting an 8051 to external memory, Port 0 can provide both address and data. The 8051 microcontroller then multiplexes the input as address or data in order to save pins."
},
{
"code": null,
"e": 6918,
"s": 6623,
"text": "Dual role of Port 0 − Port 0 is also designated as AD0–AD7, as it can be used for both data and address handling. While connecting an 8051 to external memory, Port 0 can provide both address and data. The 8051 microcontroller then multiplexes the input as address or data in order to save pins."
},
{
"code": null,
"e": 7489,
"s": 6918,
"text": "Dual role of Port 2 − Besides working as I/O, Port P2 is also used to provide 16-bit address bus for external memory along with Port 0. Port P2 is also designated as (A8– A15), while Port 0 provides the lower 8-bits via A0–A7. In other words, we can say that when an 8051 is connected to an external memory (ROM) which can be maximum up to 64KB and this is possible by 16 bit address bus because we know 216 = 64KB. Port2 is used for the upper 8-bit of the 16 bits address, and it cannot be used for I/O and this is the way any Program code of external ROM is addressed."
},
{
"code": null,
"e": 8060,
"s": 7489,
"text": "Dual role of Port 2 − Besides working as I/O, Port P2 is also used to provide 16-bit address bus for external memory along with Port 0. Port P2 is also designated as (A8– A15), while Port 0 provides the lower 8-bits via A0–A7. In other words, we can say that when an 8051 is connected to an external memory (ROM) which can be maximum up to 64KB and this is possible by 16 bit address bus because we know 216 = 64KB. Port2 is used for the upper 8-bit of the 16 bits address, and it cannot be used for I/O and this is the way any Program code of external ROM is addressed."
},
{
"code": null,
"e": 8117,
"s": 8060,
"text": "Vcc − Pin 40 provides supply to the Chip and it is +5 V."
},
{
"code": null,
"e": 8174,
"s": 8117,
"text": "Vcc − Pin 40 provides supply to the Chip and it is +5 V."
},
{
"code": null,
"e": 8222,
"s": 8174,
"text": "Gnd − Pin 20 provides ground for the Reference."
},
{
"code": null,
"e": 8270,
"s": 8222,
"text": "Gnd − Pin 20 provides ground for the Reference."
},
{
"code": null,
"e": 8770,
"s": 8270,
"text": "XTAL1, XTAL2 (Pin no 18 & Pin no 19) − 8051 has on-chip oscillator but requires external clock to run it. A quartz crystal is connected between the XTAL1 & XTAL2 pin of the chip. This crystal also needs two capacitors of 30pF for generating a signal of desired frequency. One side of each capacitor is connected to ground. 8051 IC is available in various speeds and it all depends on this Quartz crystal, for example, a 20 MHz microcontroller requires a crystal with a frequency no more than 20 MHz."
},
{
"code": null,
"e": 9270,
"s": 8770,
"text": "XTAL1, XTAL2 (Pin no 18 & Pin no 19) − 8051 has on-chip oscillator but requires external clock to run it. A quartz crystal is connected between the XTAL1 & XTAL2 pin of the chip. This crystal also needs two capacitors of 30pF for generating a signal of desired frequency. One side of each capacitor is connected to ground. 8051 IC is available in various speeds and it all depends on this Quartz crystal, for example, a 20 MHz microcontroller requires a crystal with a frequency no more than 20 MHz."
},
{
"code": null,
"e": 9897,
"s": 9270,
"text": "RST (Pin No. 9) − It is an Input pin and active High pin. Upon applying a high pulse on this pin, that is 1, the microcontroller will reset and terminate all activities. This process is known as Power-On Reset. Activating a power-on reset will cause all values in the register to be lost. It will set a program counter to all 0's. To ensure a valid input of Reset, the high pulse must be high for a minimum of two machine cycles before it is allowed to go low, which depends on the capacitor value and the rate at which it charges. (Machine Cycle is the minimum amount of frequency a single instruction requires in execution)."
},
{
"code": null,
"e": 10524,
"s": 9897,
"text": "RST (Pin No. 9) − It is an Input pin and active High pin. Upon applying a high pulse on this pin, that is 1, the microcontroller will reset and terminate all activities. This process is known as Power-On Reset. Activating a power-on reset will cause all values in the register to be lost. It will set a program counter to all 0's. To ensure a valid input of Reset, the high pulse must be high for a minimum of two machine cycles before it is allowed to go low, which depends on the capacitor value and the rate at which it charges. (Machine Cycle is the minimum amount of frequency a single instruction requires in execution)."
},
{
"code": null,
"e": 11011,
"s": 10524,
"text": "EA or External Access (Pin No. 31) − It is an input pin. This pin is an active low pin; upon applying a low pulse, it gets activated. In case of microcontroller (8051/52) having on-chip ROM, the EA (bar) pin is connected to Vcc. But in an 8031 microcontroller which does not have an on-chip ROM, the code is stored in an external ROM and then fetched by the microcontroller. In this case, we must connect the (pin no 31) EA to Gnd to indicate that the program code is stored externally."
},
{
"code": null,
"e": 11498,
"s": 11011,
"text": "EA or External Access (Pin No. 31) − It is an input pin. This pin is an active low pin; upon applying a low pulse, it gets activated. In case of microcontroller (8051/52) having on-chip ROM, the EA (bar) pin is connected to Vcc. But in an 8031 microcontroller which does not have an on-chip ROM, the code is stored in an external ROM and then fetched by the microcontroller. In this case, we must connect the (pin no 31) EA to Gnd to indicate that the program code is stored externally."
},
{
"code": null,
"e": 11763,
"s": 11498,
"text": "PSEN or Program store Enable (Pin No 29) − This is also an active low pin, i.e., it gets activated after applying a low pulse. It is an output pin and used along with the EA pin in 8031 based (i.e. ROMLESS) Systems to allow storage of program code in external ROM."
},
{
"code": null,
"e": 12028,
"s": 11763,
"text": "PSEN or Program store Enable (Pin No 29) − This is also an active low pin, i.e., it gets activated after applying a low pulse. It is an output pin and used along with the EA pin in 8031 based (i.e. ROMLESS) Systems to allow storage of program code in external ROM."
},
{
"code": null,
"e": 12364,
"s": 12028,
"text": "ALE or (Address Latch Enable) − This is an Output Pin and is active high. It is especially used for 8031 IC to connect it to the external memory. It can be used while deciding whether P0 pins will be used as Address bus or Data bus. When ALE = 1, then the P0 pins work as Data bus and when ALE = 0, then the P0 pins act as Address bus."
},
{
"code": null,
"e": 12700,
"s": 12364,
"text": "ALE or (Address Latch Enable) − This is an Output Pin and is active high. It is especially used for 8031 IC to connect it to the external memory. It can be used while deciding whether P0 pins will be used as Address bus or Data bus. When ALE = 1, then the P0 pins work as Data bus and when ALE = 0, then the P0 pins act as Address bus."
},
{
"code": null,
"e": 12926,
"s": 12700,
"text": "It is a most widely used feature of 8051 while writing code for 8051. Sometimes we need to access only 1 or 2 bits of the port instead of the entire 8-bits. 8051 provides the capability to access individual bits of the ports."
},
{
"code": null,
"e": 13182,
"s": 12926,
"text": "While accessing a port in a single-bit manner, we use the syntax \"SETB X. Y\" where X is the port number (0 to 3), and Y is a bit number (0 to 7) for data bits D0-D7 where D0 is the LSB and D7 is the MSB. For example, \"SETB P1.5\" sets high bit 5 of port 1."
},
{
"code": null,
"e": 13252,
"s": 13182,
"text": "The following code shows how we can toggle the bit P1.2 continuously."
},
{
"code": null,
"e": 13340,
"s": 13252,
"text": "AGAIN: \nSETB P1.2\nACALL DELAY \nCLR P1.2 \nACALL DELAY \nSJMP AGAIN\n"
},
{
"code": null,
"e": 13375,
"s": 13340,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 13386,
"s": 13375,
"text": " Amit Rana"
},
{
"code": null,
"e": 13421,
"s": 13386,
"text": "\n 36 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 13432,
"s": 13421,
"text": " Amit Rana"
},
{
"code": null,
"e": 13465,
"s": 13432,
"text": "\n 33 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 13478,
"s": 13465,
"text": " Ashraf Said"
},
{
"code": null,
"e": 13511,
"s": 13478,
"text": "\n 23 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 13532,
"s": 13511,
"text": " Smart Logic Academy"
},
{
"code": null,
"e": 13567,
"s": 13532,
"text": "\n 66 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 13585,
"s": 13567,
"text": " NerdyElectronics"
},
{
"code": null,
"e": 13620,
"s": 13585,
"text": "\n 49 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 13639,
"s": 13620,
"text": " Rahul Shrivastava"
},
{
"code": null,
"e": 13646,
"s": 13639,
"text": " Print"
},
{
"code": null,
"e": 13657,
"s": 13646,
"text": " Add Notes"
}
] |
Python | Get Kth Column of Matrix - GeeksforGeeks
|
30 Dec, 2020
Sometimes, while working with Python Matrix, one can have a problem in which one needs to find the Kth column of Matrix. This is a very popular problem in Machine Learning Domain and having solution to this is useful. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehensionThis problem can be solved using list comprehension in which we can iterate through all the rows and selectively gather all the elements occurring at Kth index.
# Python3 code to demonstrate working of# Get Kth Column of Matrix# using list comprehension # initialize listtest_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]] # printing original listprint("The original list is : " + str(test_list)) # initialize KK = 2 # Get Kth Column of Matrix# using list comprehensionres = [sub[K] for sub in test_list] # printing resultprint("The Kth column of matrix is : " + str(res))
The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
The Kth column of matrix is : [6, 10, 5]
Method #2 : Using zip()This task can also be performed using zip(). This does the similar task of gathering elements like is done by above list comprehension and offers compact but slower execution. Works with Python2 only.
# Python code to demonstrate working of# Get Kth Column of Matrix# using zip() # initialize listtest_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]] # printing original listprint("The original list is : " + str(test_list)) # initialize KK = 2 # Get Kth Column of Matrix# using zip()res = list(zip(*test_list)[K]) # printing resultprint("The Kth column of matrix is : " + str(res))
The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
The Kth column of matrix is : [6, 10, 5]
Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 25843,
"s": 25561,
"text": "Sometimes, while working with Python Matrix, one can have a problem in which one needs to find the Kth column of Matrix. This is a very popular problem in Machine Learning Domain and having solution to this is useful. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 26040,
"s": 25843,
"text": "Method #1 : Using list comprehensionThis problem can be solved using list comprehension in which we can iterate through all the rows and selectively gather all the elements occurring at Kth index."
},
{
"code": "# Python3 code to demonstrate working of# Get Kth Column of Matrix# using list comprehension # initialize listtest_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]] # printing original listprint(\"The original list is : \" + str(test_list)) # initialize KK = 2 # Get Kth Column of Matrix# using list comprehensionres = [sub[K] for sub in test_list] # printing resultprint(\"The Kth column of matrix is : \" + str(res))",
"e": 26453,
"s": 26040,
"text": null
},
{
"code": null,
"e": 26554,
"s": 26453,
"text": "The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]\nThe Kth column of matrix is : [6, 10, 5]\n"
},
{
"code": null,
"e": 26780,
"s": 26556,
"text": "Method #2 : Using zip()This task can also be performed using zip(). This does the similar task of gathering elements like is done by above list comprehension and offers compact but slower execution. Works with Python2 only."
},
{
"code": "# Python code to demonstrate working of# Get Kth Column of Matrix# using zip() # initialize listtest_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]] # printing original listprint(\"The original list is : \" + str(test_list)) # initialize KK = 2 # Get Kth Column of Matrix# using zip()res = list(zip(*test_list)[K]) # printing resultprint(\"The Kth column of matrix is : \" + str(res))",
"e": 27161,
"s": 26780,
"text": null
},
{
"code": null,
"e": 27262,
"s": 27161,
"text": "The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]\nThe Kth column of matrix is : [6, 10, 5]\n"
},
{
"code": null,
"e": 27283,
"s": 27262,
"text": "Python list-programs"
},
{
"code": null,
"e": 27305,
"s": 27283,
"text": "Python matrix-program"
},
{
"code": null,
"e": 27312,
"s": 27305,
"text": "Python"
},
{
"code": null,
"e": 27328,
"s": 27312,
"text": "Python Programs"
},
{
"code": null,
"e": 27426,
"s": 27328,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27458,
"s": 27426,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27500,
"s": 27458,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27542,
"s": 27500,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27598,
"s": 27542,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27625,
"s": 27598,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27647,
"s": 27625,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27686,
"s": 27647,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27732,
"s": 27686,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27770,
"s": 27732,
"text": "Python | Convert a list to dictionary"
}
] |
PHP | mt_rand( ) Function - GeeksforGeeks
|
07 Mar, 2018
While working with algorithms we often come across situations when we need to generate random integers. The most common way to generate random numbers is using Mersenne Twister.The Mersenne Twister is a pseudorandom number generator which got its name derived from the fact that its period length is chosen to be a Mersenne prime. It was the first pseudorandom number generator to provide fast generation of high-quality pseudorandom integers. It was designed specifically to rectify most of the flaws found in older pseudorandom number generators.So in PHP, there is an inbuilt function mt_rand() which is based on Mersenne Twister which helps in generating random numbers.
The mt_rand() function generates a random integer between the specified minimum and maximum values. It produces a better random value and is faster than the rand() function. You may also refer to the article on PHP | rand() Function which is another inbuilt function in PHP to generate random numbers.
Syntax:
int mt_rand($min, $max)
Parameters: This function accepts two parameter which are described below:
$min : It is an optional parameter. It specifies the lowest number to be returned.The default value is 0.$max : It is an optional parameter. It specifies the highest number to be returned.
$min : It is an optional parameter. It specifies the lowest number to be returned.The default value is 0.
$max : It is an optional parameter. It specifies the highest number to be returned.
Return Value: It returns a random number between min (or 0) and max and the return type is integer.
Examples:
Input : mt_rand()
Output : 34567
Input : mt_rand(15, 50)
Output : 49
Below programs illustrate the working of mt_rand() in PHP:
Program 1:
<?php echo mt_rand(); ?>
Output:
34567
Program 2:
<?php echo mt_rand(15, 50); ?>
Output:
49
Important points to note :
mt_rand() function generates a random integer using the Mersenne Twister algorithm.
It produces a better random value and is faster than the rand() function.
Reference:http://php.net/manual/en/function.mt-rand.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to 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": 26113,
"s": 26085,
"text": "\n07 Mar, 2018"
},
{
"code": null,
"e": 26788,
"s": 26113,
"text": "While working with algorithms we often come across situations when we need to generate random integers. The most common way to generate random numbers is using Mersenne Twister.The Mersenne Twister is a pseudorandom number generator which got its name derived from the fact that its period length is chosen to be a Mersenne prime. It was the first pseudorandom number generator to provide fast generation of high-quality pseudorandom integers. It was designed specifically to rectify most of the flaws found in older pseudorandom number generators.So in PHP, there is an inbuilt function mt_rand() which is based on Mersenne Twister which helps in generating random numbers."
},
{
"code": null,
"e": 27090,
"s": 26788,
"text": "The mt_rand() function generates a random integer between the specified minimum and maximum values. It produces a better random value and is faster than the rand() function. You may also refer to the article on PHP | rand() Function which is another inbuilt function in PHP to generate random numbers."
},
{
"code": null,
"e": 27098,
"s": 27090,
"text": "Syntax:"
},
{
"code": null,
"e": 27122,
"s": 27098,
"text": "int mt_rand($min, $max)"
},
{
"code": null,
"e": 27197,
"s": 27122,
"text": "Parameters: This function accepts two parameter which are described below:"
},
{
"code": null,
"e": 27386,
"s": 27197,
"text": "$min : It is an optional parameter. It specifies the lowest number to be returned.The default value is 0.$max : It is an optional parameter. It specifies the highest number to be returned."
},
{
"code": null,
"e": 27492,
"s": 27386,
"text": "$min : It is an optional parameter. It specifies the lowest number to be returned.The default value is 0."
},
{
"code": null,
"e": 27576,
"s": 27492,
"text": "$max : It is an optional parameter. It specifies the highest number to be returned."
},
{
"code": null,
"e": 27676,
"s": 27576,
"text": "Return Value: It returns a random number between min (or 0) and max and the return type is integer."
},
{
"code": null,
"e": 27686,
"s": 27676,
"text": "Examples:"
},
{
"code": null,
"e": 27757,
"s": 27686,
"text": "Input : mt_rand()\nOutput : 34567\n\nInput : mt_rand(15, 50)\nOutput : 49\n"
},
{
"code": null,
"e": 27816,
"s": 27757,
"text": "Below programs illustrate the working of mt_rand() in PHP:"
},
{
"code": null,
"e": 27827,
"s": 27816,
"text": "Program 1:"
},
{
"code": "<?php echo mt_rand(); ?>",
"e": 27854,
"s": 27827,
"text": null
},
{
"code": null,
"e": 27862,
"s": 27854,
"text": "Output:"
},
{
"code": null,
"e": 27868,
"s": 27862,
"text": "34567"
},
{
"code": null,
"e": 27879,
"s": 27868,
"text": "Program 2:"
},
{
"code": "<?php echo mt_rand(15, 50); ?>",
"e": 27912,
"s": 27879,
"text": null
},
{
"code": null,
"e": 27920,
"s": 27912,
"text": "Output:"
},
{
"code": null,
"e": 27923,
"s": 27920,
"text": "49"
},
{
"code": null,
"e": 27950,
"s": 27923,
"text": "Important points to note :"
},
{
"code": null,
"e": 28034,
"s": 27950,
"text": "mt_rand() function generates a random integer using the Mersenne Twister algorithm."
},
{
"code": null,
"e": 28108,
"s": 28034,
"text": "It produces a better random value and is faster than the rand() function."
},
{
"code": null,
"e": 28164,
"s": 28108,
"text": "Reference:http://php.net/manual/en/function.mt-rand.php"
},
{
"code": null,
"e": 28177,
"s": 28164,
"text": "PHP-function"
},
{
"code": null,
"e": 28181,
"s": 28177,
"text": "PHP"
},
{
"code": null,
"e": 28198,
"s": 28181,
"text": "Web Technologies"
},
{
"code": null,
"e": 28202,
"s": 28198,
"text": "PHP"
},
{
"code": null,
"e": 28300,
"s": 28202,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28350,
"s": 28300,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28390,
"s": 28350,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28451,
"s": 28390,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 28501,
"s": 28451,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 28546,
"s": 28501,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 28586,
"s": 28546,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28619,
"s": 28586,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28664,
"s": 28619,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28707,
"s": 28664,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Convert a String to ArrayList in Java? - GeeksforGeeks
|
19 Jan, 2021
Converting String to ArrayList means each character of the string is added as a separator character element in the ArrayList.
Example:
Input: 0001
Output: 0
0
0
1
Input: Geeks
Output: G
e
e
k
s
We can easily convert String to ArrayList in Java using the split() method and regular expression.
Parameters:
regex – a delimiting regular expression
Limit – the resulting threshold
Returns: An array of strings computed by splitting the given string.
Throws: PatternSyntaxException – if the provided regular expression’s syntax is invalid.
Approach:
Splitting the string by using the Java split() method and storing the substrings into an array.
Creating an ArrayList while passing the substring reference to it using Arrays.asList() method.
Java
// Java program to convert String to ArrayList import java.util.ArrayList;import java.util.Arrays; public class Main { public static void main(String[] args) { String str = "Geeks"; // split string by no space String[] strSplit = str.split(""); // Now convert string into ArrayList ArrayList<String> strList = new ArrayList<String>( Arrays.asList(strSplit)); // Now print the ArrayList for (String s : strList) System.out.println(s); }}
G
e
e
k
s
Java-ArrayList
Java-Strings
Java
Java Programs
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
|
[
{
"code": null,
"e": 25249,
"s": 25221,
"text": "\n19 Jan, 2021"
},
{
"code": null,
"e": 25375,
"s": 25249,
"text": "Converting String to ArrayList means each character of the string is added as a separator character element in the ArrayList."
},
{
"code": null,
"e": 25384,
"s": 25375,
"text": "Example:"
},
{
"code": null,
"e": 25508,
"s": 25384,
"text": "Input: 0001\nOutput: 0\n 0\n 0\n 1\n \nInput: Geeks\nOutput: G\n e\n e\n k\n s"
},
{
"code": null,
"e": 25607,
"s": 25508,
"text": "We can easily convert String to ArrayList in Java using the split() method and regular expression."
},
{
"code": null,
"e": 25619,
"s": 25607,
"text": "Parameters:"
},
{
"code": null,
"e": 25659,
"s": 25619,
"text": "regex – a delimiting regular expression"
},
{
"code": null,
"e": 25691,
"s": 25659,
"text": "Limit – the resulting threshold"
},
{
"code": null,
"e": 25760,
"s": 25691,
"text": "Returns: An array of strings computed by splitting the given string."
},
{
"code": null,
"e": 25851,
"s": 25760,
"text": "Throws: PatternSyntaxException – if the provided regular expression’s syntax is invalid. "
},
{
"code": null,
"e": 25861,
"s": 25851,
"text": "Approach:"
},
{
"code": null,
"e": 25957,
"s": 25861,
"text": "Splitting the string by using the Java split() method and storing the substrings into an array."
},
{
"code": null,
"e": 26053,
"s": 25957,
"text": "Creating an ArrayList while passing the substring reference to it using Arrays.asList() method."
},
{
"code": null,
"e": 26058,
"s": 26053,
"text": "Java"
},
{
"code": "// Java program to convert String to ArrayList import java.util.ArrayList;import java.util.Arrays; public class Main { public static void main(String[] args) { String str = \"Geeks\"; // split string by no space String[] strSplit = str.split(\"\"); // Now convert string into ArrayList ArrayList<String> strList = new ArrayList<String>( Arrays.asList(strSplit)); // Now print the ArrayList for (String s : strList) System.out.println(s); }}",
"e": 26587,
"s": 26058,
"text": null
},
{
"code": null,
"e": 26597,
"s": 26587,
"text": "G\ne\ne\nk\ns"
},
{
"code": null,
"e": 26612,
"s": 26597,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 26625,
"s": 26612,
"text": "Java-Strings"
},
{
"code": null,
"e": 26630,
"s": 26625,
"text": "Java"
},
{
"code": null,
"e": 26644,
"s": 26630,
"text": "Java Programs"
},
{
"code": null,
"e": 26657,
"s": 26644,
"text": "Java-Strings"
},
{
"code": null,
"e": 26662,
"s": 26657,
"text": "Java"
},
{
"code": null,
"e": 26760,
"s": 26662,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26775,
"s": 26760,
"text": "Stream In Java"
},
{
"code": null,
"e": 26796,
"s": 26775,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26815,
"s": 26796,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26845,
"s": 26815,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26891,
"s": 26845,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26917,
"s": 26891,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 26951,
"s": 26917,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 26998,
"s": 26951,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 27030,
"s": 26998,
"text": "How to Iterate HashMap in Java?"
}
] |
Python | sympy.Pow() method - GeeksforGeeks
|
28 Aug, 2019
With the help of sympy.Pow() method, we can find a raised to the power of b where a and b are parameters to the method.
Syntax: Pow(a, b)Parameter:a – It denotes an integer.b – It denotes an integer.
Returns: Returns an integer which is equal to a raised to the power of b, i. e., a^b.
Example #1:
# import Pow() method from sympyfrom sympy import Pow a = 3b = 3 # Use Pow() method pow_a_b = Pow(a, b) print("{}^{} = {}".format(a, b, pow_a_b))
Output:
3^3 = 27
Example #2:
# import Pow() method from sympyfrom sympy import Pow a = 5b = 4 # Use Pow() method pow_a_b = Pow(a, b) print("{}^{} = {}".format(a, b, pow_a_b))
Output:
5^4 = 625
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
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
Convert integer to string in Python
|
[
{
"code": null,
"e": 26031,
"s": 26003,
"text": "\n28 Aug, 2019"
},
{
"code": null,
"e": 26151,
"s": 26031,
"text": "With the help of sympy.Pow() method, we can find a raised to the power of b where a and b are parameters to the method."
},
{
"code": null,
"e": 26231,
"s": 26151,
"text": "Syntax: Pow(a, b)Parameter:a – It denotes an integer.b – It denotes an integer."
},
{
"code": null,
"e": 26317,
"s": 26231,
"text": "Returns: Returns an integer which is equal to a raised to the power of b, i. e., a^b."
},
{
"code": null,
"e": 26329,
"s": 26317,
"text": "Example #1:"
},
{
"code": "# import Pow() method from sympyfrom sympy import Pow a = 3b = 3 # Use Pow() method pow_a_b = Pow(a, b) print(\"{}^{} = {}\".format(a, b, pow_a_b))",
"e": 26483,
"s": 26329,
"text": null
},
{
"code": null,
"e": 26491,
"s": 26483,
"text": "Output:"
},
{
"code": null,
"e": 26501,
"s": 26491,
"text": "3^3 = 27\n"
},
{
"code": null,
"e": 26513,
"s": 26501,
"text": "Example #2:"
},
{
"code": "# import Pow() method from sympyfrom sympy import Pow a = 5b = 4 # Use Pow() method pow_a_b = Pow(a, b) print(\"{}^{} = {}\".format(a, b, pow_a_b))",
"e": 26667,
"s": 26513,
"text": null
},
{
"code": null,
"e": 26675,
"s": 26667,
"text": "Output:"
},
{
"code": null,
"e": 26686,
"s": 26675,
"text": "5^4 = 625\n"
},
{
"code": null,
"e": 26692,
"s": 26686,
"text": "SymPy"
},
{
"code": null,
"e": 26699,
"s": 26692,
"text": "Python"
},
{
"code": null,
"e": 26797,
"s": 26699,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26815,
"s": 26797,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26850,
"s": 26815,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26872,
"s": 26850,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26914,
"s": 26872,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26944,
"s": 26914,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26970,
"s": 26944,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26999,
"s": 26970,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27043,
"s": 26999,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27080,
"s": 27043,
"text": "Create a Pandas DataFrame from Lists"
}
] |
quit driver method - Selenium Python - GeeksforGeeks
|
15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around quit driver method in Selenium. quit method quits the driver and closes every associated window.
Syntax –
driver.quit()
Example –Now one can use quit method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.quit()
To demonstrate, quit method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s quit window,
Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # quit window positiondriver.quit()
Output –Screenshot added –
Python-selenium
selenium
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 | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 26276,
"s": 25537,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc."
},
{
"code": null,
"e": 26402,
"s": 26276,
"text": "This article revolves around quit driver method in Selenium. quit method quits the driver and closes every associated window."
},
{
"code": null,
"e": 26411,
"s": 26402,
"text": "Syntax –"
},
{
"code": null,
"e": 26425,
"s": 26411,
"text": "driver.quit()"
},
{
"code": null,
"e": 26492,
"s": 26425,
"text": "Example –Now one can use quit method as a driver method as below –"
},
{
"code": null,
"e": 26551,
"s": 26492,
"text": "diver.get(\"https://www.geeksforgeeks.org/\")\ndriver.quit()\n"
},
{
"code": null,
"e": 26705,
"s": 26551,
"text": "To demonstrate, quit method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s quit window,"
},
{
"code": null,
"e": 26715,
"s": 26705,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # quit window positiondriver.quit()",
"e": 26927,
"s": 26715,
"text": null
},
{
"code": null,
"e": 26954,
"s": 26927,
"text": "Output –Screenshot added –"
},
{
"code": null,
"e": 26970,
"s": 26954,
"text": "Python-selenium"
},
{
"code": null,
"e": 26979,
"s": 26970,
"text": "selenium"
},
{
"code": null,
"e": 26986,
"s": 26979,
"text": "Python"
},
{
"code": null,
"e": 27084,
"s": 26986,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27116,
"s": 27084,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27158,
"s": 27116,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27200,
"s": 27158,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27227,
"s": 27200,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27283,
"s": 27227,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27322,
"s": 27283,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27344,
"s": 27322,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27375,
"s": 27344,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27404,
"s": 27375,
"text": "Create a directory in Python"
}
] |
How to Install Cockpit on Linux CentOS 7? - GeeksforGeeks
|
01 Feb, 2021
The cockpit is a free, open-source Linux Server Management Tool which provides you the facility to control your server using the mouse on the web-interface. The cockpit can be used to perform any server related task such as start containers, storage administration, and network configuration and much more. It has a very beautiful user interface along with its light-weight application.
Fedora Server comes with Cockpit pre-installed but in CentOS we have to install it separately. In this article, we will discuss the ways in which we can install Cockpit in CentOS 7.
Cockpit is already included in CentOS 7.x official base repository, so we can install directly from ‘yum‘ command.
Installation Steps:
Open your terminal app in CentOSDownload and install cockpit using yum command.Enable the cockpit.Open the firewall for cockpit and reloading the firewall.Logging In Cockpit Admin Panel.
Open your terminal app in CentOS
Download and install cockpit using yum command.
Enable the cockpit.
Open the firewall for cockpit and reloading the firewall.
Logging In Cockpit Admin Panel.
Step-wise implementation of installations:
Step 1: Open your Terminal
You can launch the terminal app using ‘ctrl+shift+T’ or from application menu.
Step 2: Download and install Cockpit
Use the command below to download and install the cockpit.
sudo yum install cockpit
We will need admin rights in order to install new applications in our system, that’s why we are using sudo command. You may need to enter your root password because of security reasons.
Installing Cockpit using ‘yum’ Command
It may ask you to confirm again whether you are sure to install cockpit. In that case, you just need to type ‘y’ and press enter for the confirmation.
Confirming the cockpit Installation.
Once the package is installed successfully without any errors, your screen will show a ‘Complete’ message, just like in the picture below. At this stage, you are ready to proceed with the next steps.
Cockpit Successfully Installed
Step 3: Enable the Cockpit
Use the command below to enable the cockpit in our system.
sudo systemctl enable --now cockpit.socket
Enabling the Cockpit in System
Step 4: Open the firewall for Cockpit
Use the command below to open the firewall for cockpit.
sudo firewall-cmd --permanent --zone=public --add-service=cockpit
We will need to reload the firewall in order to reflect the changes. This can be easily done by using the command below.
sudo firewall-cmd --reload
Opening Firewall for Cockpit and Reloading the Firewall
Step 5: Loading the Cockpit Web Interface
Now we are ready to use Cockpit. Open any browser of your preference and type the URL as: https://SERVER_IP:9090. Where server IP should be replaced with the actual IP of your server. You can also use https://localhost:9090 to login into Cockpit.
Cockpit Web Interface
Use your admin username and root password which you use for CentOS to login into the admin panel. After the successful login, you will see the admin Console of Cockpit web interface.
Cockpit Application Interface
In this way, you can easily install and use cockpit in CentOS 7.x or any other later version.
Picked
Technical Scripter 2020
How To
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Install Jupyter Notebook on MacOS?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
|
[
{
"code": null,
"e": 26197,
"s": 26169,
"text": "\n01 Feb, 2021"
},
{
"code": null,
"e": 26584,
"s": 26197,
"text": "The cockpit is a free, open-source Linux Server Management Tool which provides you the facility to control your server using the mouse on the web-interface. The cockpit can be used to perform any server related task such as start containers, storage administration, and network configuration and much more. It has a very beautiful user interface along with its light-weight application."
},
{
"code": null,
"e": 26766,
"s": 26584,
"text": "Fedora Server comes with Cockpit pre-installed but in CentOS we have to install it separately. In this article, we will discuss the ways in which we can install Cockpit in CentOS 7."
},
{
"code": null,
"e": 26882,
"s": 26766,
"text": "Cockpit is already included in CentOS 7.x official base repository, so we can install directly from ‘yum‘ command. "
},
{
"code": null,
"e": 26902,
"s": 26882,
"text": "Installation Steps:"
},
{
"code": null,
"e": 27089,
"s": 26902,
"text": "Open your terminal app in CentOSDownload and install cockpit using yum command.Enable the cockpit.Open the firewall for cockpit and reloading the firewall.Logging In Cockpit Admin Panel."
},
{
"code": null,
"e": 27122,
"s": 27089,
"text": "Open your terminal app in CentOS"
},
{
"code": null,
"e": 27170,
"s": 27122,
"text": "Download and install cockpit using yum command."
},
{
"code": null,
"e": 27190,
"s": 27170,
"text": "Enable the cockpit."
},
{
"code": null,
"e": 27248,
"s": 27190,
"text": "Open the firewall for cockpit and reloading the firewall."
},
{
"code": null,
"e": 27280,
"s": 27248,
"text": "Logging In Cockpit Admin Panel."
},
{
"code": null,
"e": 27323,
"s": 27280,
"text": "Step-wise implementation of installations:"
},
{
"code": null,
"e": 27350,
"s": 27323,
"text": "Step 1: Open your Terminal"
},
{
"code": null,
"e": 27429,
"s": 27350,
"text": "You can launch the terminal app using ‘ctrl+shift+T’ or from application menu."
},
{
"code": null,
"e": 27466,
"s": 27429,
"text": "Step 2: Download and install Cockpit"
},
{
"code": null,
"e": 27525,
"s": 27466,
"text": "Use the command below to download and install the cockpit."
},
{
"code": null,
"e": 27551,
"s": 27525,
"text": "sudo yum install cockpit "
},
{
"code": null,
"e": 27737,
"s": 27551,
"text": "We will need admin rights in order to install new applications in our system, that’s why we are using sudo command. You may need to enter your root password because of security reasons."
},
{
"code": null,
"e": 27776,
"s": 27737,
"text": "Installing Cockpit using ‘yum’ Command"
},
{
"code": null,
"e": 27927,
"s": 27776,
"text": "It may ask you to confirm again whether you are sure to install cockpit. In that case, you just need to type ‘y’ and press enter for the confirmation."
},
{
"code": null,
"e": 27965,
"s": 27927,
"text": "Confirming the cockpit Installation. "
},
{
"code": null,
"e": 28165,
"s": 27965,
"text": "Once the package is installed successfully without any errors, your screen will show a ‘Complete’ message, just like in the picture below. At this stage, you are ready to proceed with the next steps."
},
{
"code": null,
"e": 28196,
"s": 28165,
"text": "Cockpit Successfully Installed"
},
{
"code": null,
"e": 28224,
"s": 28196,
"text": " Step 3: Enable the Cockpit"
},
{
"code": null,
"e": 28283,
"s": 28224,
"text": "Use the command below to enable the cockpit in our system."
},
{
"code": null,
"e": 28326,
"s": 28283,
"text": "sudo systemctl enable --now cockpit.socket"
},
{
"code": null,
"e": 28357,
"s": 28326,
"text": "Enabling the Cockpit in System"
},
{
"code": null,
"e": 28395,
"s": 28357,
"text": "Step 4: Open the firewall for Cockpit"
},
{
"code": null,
"e": 28451,
"s": 28395,
"text": "Use the command below to open the firewall for cockpit."
},
{
"code": null,
"e": 28517,
"s": 28451,
"text": "sudo firewall-cmd --permanent --zone=public --add-service=cockpit"
},
{
"code": null,
"e": 28638,
"s": 28517,
"text": "We will need to reload the firewall in order to reflect the changes. This can be easily done by using the command below."
},
{
"code": null,
"e": 28665,
"s": 28638,
"text": "sudo firewall-cmd --reload"
},
{
"code": null,
"e": 28721,
"s": 28665,
"text": "Opening Firewall for Cockpit and Reloading the Firewall"
},
{
"code": null,
"e": 28763,
"s": 28721,
"text": "Step 5: Loading the Cockpit Web Interface"
},
{
"code": null,
"e": 29010,
"s": 28763,
"text": "Now we are ready to use Cockpit. Open any browser of your preference and type the URL as: https://SERVER_IP:9090. Where server IP should be replaced with the actual IP of your server. You can also use https://localhost:9090 to login into Cockpit."
},
{
"code": null,
"e": 29032,
"s": 29010,
"text": "Cockpit Web Interface"
},
{
"code": null,
"e": 29215,
"s": 29032,
"text": "Use your admin username and root password which you use for CentOS to login into the admin panel. After the successful login, you will see the admin Console of Cockpit web interface."
},
{
"code": null,
"e": 29245,
"s": 29215,
"text": "Cockpit Application Interface"
},
{
"code": null,
"e": 29340,
"s": 29245,
"text": "In this way, you can easily install and use cockpit in CentOS 7.x or any other later version. "
},
{
"code": null,
"e": 29347,
"s": 29340,
"text": "Picked"
},
{
"code": null,
"e": 29371,
"s": 29347,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29378,
"s": 29371,
"text": "How To"
},
{
"code": null,
"e": 29389,
"s": 29378,
"text": "Linux-Unix"
},
{
"code": null,
"e": 29408,
"s": 29389,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29506,
"s": 29408,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29540,
"s": 29506,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 29598,
"s": 29540,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 29647,
"s": 29598,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 29694,
"s": 29647,
"text": "How to create a nested RecyclerView in Android"
},
{
"code": null,
"e": 29736,
"s": 29694,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 29776,
"s": 29736,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 29816,
"s": 29776,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 29843,
"s": 29816,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 29878,
"s": 29843,
"text": "cut command in Linux with examples"
}
] |
Minimum substring flips required to convert given binary string to another - GeeksforGeeks
|
11 Jun, 2021
Given two binary strings A and B, the task is to find the minimum number of times a substring starting from the first character of A needs to be flipped, i.e. convert 1s to 0s and 0s to 1s, to convert A to B.
Examples:
Input: A = “0010”, B = “1011”Output; 3Explanation:Step 1: Flip the entire string A. Therefore, A becomes “1101” .Step 2: Flip the substring {A[0], A[2]}. Therefore, A becomes “0011” .Step 3: Flip A[0]. Therefore, A becomes “1011” which is equal to B.Therefore, the minimum number of operations required is 3.
Input: A = “1010101”, B = “0011100”Output: 5Explanation:Step 1: Flip the entiThehrefore, A becomes “0101010′′Step 2: Flip substring {A[0], A[5]}. Therefore, A becomes “1010100′′Step 3: Flip the substring {A[0], A[3]}. Therefore, A becomes “0101100′′Step 4: Flip the substring {A[0], A[2]}. Therefore, A becomes “1011100′′Step 5: Flip A[0]. Therefore, A becomes “0011100” which is equal to B.Therefore, the minimum number of operations required is 5.
Approach: The idea is to initialize a variable that holds the last index at which character at A is different from the character at B. Then negate A from the 1st index to the last index. Repeat until both strings become equal. Follow the steps below to solve the problem:
Initialize a variable last_index that holds the last index at which characters are different in A and B.
Negate string A from the 1st index to last_index and increment the count of steps.
Repeat the above steps until string A becomes equal to string B.
Print the count of steps after both the strings are the same after performing the operations.
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 that finds the minimum// number of operations required such// that string A and B are the samevoid findMinimumOperations(string a, string b){ // Stores the count of steps int step = 0; // Stores the last index whose // bits are not same int last_index; // Iterate until both string // are unequal while (a != b) { // Check till end of string to // find rightmost unequals bit for (int i = 0; i < a.length(); i++) { // Update the last index if (a[i] != b[i]) { last_index = i; } } // Flipping characters up // to the last index for (int i = 0; i <= last_index; i++) { // Flip the bit a[i] = (a[i] == '0') ? '1' : '0'; } // Increasing steps by one step++; } // Print the count of steps cout << step;} // Driver Codeint main(){ // Given strings A and B string A = "101010", B = "110011"; // Function Call findMinimumOperations(A, B); return 0;}
// Java program for the// above approachimport java.util.*;class GFG{ // Function that finds the minimum// number of operations required such// that String A and B are the samestatic void findMinimumOperations(char[] a, char[] b){ // Stores the count of steps int step = 0; // Stores the last index whose // bits are not same int last_index = 0; // Iterate until both String // are unequal while (!Arrays.equals(a, b)) { // Check till end of String to // find rightmost unequals bit for (int i = 0; i < a.length; i++) { // Update the last index if (a[i] != b[i]) { last_index = i; } } // Flipping characters up // to the last index for (int i = 0; i <= last_index; i++) { // Flip the bit a[i] = (a[i] == '0') ? '1' : '0'; } // Increasing steps by one step++; } // Print the count of steps System.out.print(step);} // Driver Codepublic static void main(String[] args){ // Given Strings A and B String A = "101010", B = "110011"; // Function Call findMinimumOperations(A.toCharArray(), B.toCharArray());}} // This code is contributed by 29AjayKumar
# Python3 program for the above approach # Function that finds the minimum# number of operations required such# that string A and B are the samedef findMinimumOperations(a, b): # Stores the count of steps step = 0 # Stores the last index whose # bits are not same last_index = 0 # Iterate until both string # are unequal while (a != b): a = [i for i in a] # Check till end of string to # find rightmost unequals bit for i in range(len(a)): # Update the last index if (a[i] != b[i]): last_index = i # Flipping characters up # to the last index for i in range(last_index + 1): # Flip the bit if (a[i] == '0'): a[i] = '1' else: a[i] = '0' a = "".join(a) # Increasing steps by one step += 1 # Print the count of steps print(step) # Driver Codeif __name__ == '__main__': # Given strings A and B A = "101010" B = "110011" # Function Call findMinimumOperations(A, B) # This code is contributed by mohit kumar 29
// C# program for the// above approachusing System; class GFG{ // Function that finds the minimum// number of operations required such// that string A and B are the samestatic void findMinimumOperations(string a, string b){ // Stores the count of steps int step = 0; // Stores the last index whose // bits are not same int last_index = 0; // Iterate until both string // are unequal while (a.Equals(b) == false) { // Check till end of string to // find rightmost unequals bit for(int i = 0; i < a.Length; i++) { // Update the last index if (a[i] != b[i]) { last_index = i; } } // Flipping characters up // to the last index char[] ch = a.ToCharArray(); for(int i = 0; i <= last_index; i++) { // Flip the bit if (ch[i] == '0') { ch[i] = '1'; } else { ch[i] = '0'; } } a = new string(ch); // Increasing steps by one step++; } // Print the count of steps Console.WriteLine(step);} // Driver Codepublic static void Main(){ // Given strings A and B string A = "101010"; string B = "110011"; // Function Call findMinimumOperations(A,B);}} // This code is contributed by SURENDRA_GANGWAR
<script> // JavaScript program for the// above approach // Function that finds the minimum// number of operations required such// that string A and B are the samefunction findMinimumOperations(a, b){ // Stores the count of steps var step = 0; // Stores the last index whose // bits are not same var last_index = 0; // Iterate until both string // are unequal while (a !== b) { // Check till end of string to // find rightmost unequals bit for (var i = 0; i < a.length; i++) { // Update the last index if (a[i] !== b[i]) { last_index = i; } } // Flipping characters up // to the last index var ch = a.split(""); for(var i = 0; i <= last_index; i++) { // Flip the bit if (ch[i] === "0") { ch[i] = "1"; } else { ch[i] = "0"; } } a = ch.join(""); // Increasing steps by one step++; } // Print the count of steps document.write(step);} // Driver Code // Given strings A and Bvar A = "101010";var B = "110011"; // Function CallfindMinimumOperations(A, B); // This code is contributed by rdtank </script>
4
Time Complexity: O(N2)Auxiliary Space: O(1)
mohit kumar 29
29AjayKumar
SURENDRA_GANGWAR
rdtank
adnanirshad158
binary-string
substring
Greedy
Searching
Strings
Searching
Strings
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Optimal Page Replacement Algorithm
Program for Best Fit algorithm in Memory Management
Program for First Fit algorithm in Memory Management
Bin Packing Problem (Minimize number of used Bins)
Max Flow Problem Introduction
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": 26537,
"s": 26509,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 26746,
"s": 26537,
"text": "Given two binary strings A and B, the task is to find the minimum number of times a substring starting from the first character of A needs to be flipped, i.e. convert 1s to 0s and 0s to 1s, to convert A to B."
},
{
"code": null,
"e": 26756,
"s": 26746,
"text": "Examples:"
},
{
"code": null,
"e": 27065,
"s": 26756,
"text": "Input: A = “0010”, B = “1011”Output; 3Explanation:Step 1: Flip the entire string A. Therefore, A becomes “1101” .Step 2: Flip the substring {A[0], A[2]}. Therefore, A becomes “0011” .Step 3: Flip A[0]. Therefore, A becomes “1011” which is equal to B.Therefore, the minimum number of operations required is 3."
},
{
"code": null,
"e": 27515,
"s": 27065,
"text": "Input: A = “1010101”, B = “0011100”Output: 5Explanation:Step 1: Flip the entiThehrefore, A becomes “0101010′′Step 2: Flip substring {A[0], A[5]}. Therefore, A becomes “1010100′′Step 3: Flip the substring {A[0], A[3]}. Therefore, A becomes “0101100′′Step 4: Flip the substring {A[0], A[2]}. Therefore, A becomes “1011100′′Step 5: Flip A[0]. Therefore, A becomes “0011100” which is equal to B.Therefore, the minimum number of operations required is 5."
},
{
"code": null,
"e": 27787,
"s": 27515,
"text": "Approach: The idea is to initialize a variable that holds the last index at which character at A is different from the character at B. Then negate A from the 1st index to the last index. Repeat until both strings become equal. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27892,
"s": 27787,
"text": "Initialize a variable last_index that holds the last index at which characters are different in A and B."
},
{
"code": null,
"e": 27975,
"s": 27892,
"text": "Negate string A from the 1st index to last_index and increment the count of steps."
},
{
"code": null,
"e": 28040,
"s": 27975,
"text": "Repeat the above steps until string A becomes equal to string B."
},
{
"code": null,
"e": 28134,
"s": 28040,
"text": "Print the count of steps after both the strings are the same after performing the operations."
},
{
"code": null,
"e": 28185,
"s": 28134,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28189,
"s": 28185,
"text": "C++"
},
{
"code": null,
"e": 28194,
"s": 28189,
"text": "Java"
},
{
"code": null,
"e": 28202,
"s": 28194,
"text": "Python3"
},
{
"code": null,
"e": 28205,
"s": 28202,
"text": "C#"
},
{
"code": null,
"e": 28216,
"s": 28205,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function that finds the minimum// number of operations required such// that string A and B are the samevoid findMinimumOperations(string a, string b){ // Stores the count of steps int step = 0; // Stores the last index whose // bits are not same int last_index; // Iterate until both string // are unequal while (a != b) { // Check till end of string to // find rightmost unequals bit for (int i = 0; i < a.length(); i++) { // Update the last index if (a[i] != b[i]) { last_index = i; } } // Flipping characters up // to the last index for (int i = 0; i <= last_index; i++) { // Flip the bit a[i] = (a[i] == '0') ? '1' : '0'; } // Increasing steps by one step++; } // Print the count of steps cout << step;} // Driver Codeint main(){ // Given strings A and B string A = \"101010\", B = \"110011\"; // Function Call findMinimumOperations(A, B); return 0;}",
"e": 29402,
"s": 28216,
"text": null
},
{
"code": "// Java program for the// above approachimport java.util.*;class GFG{ // Function that finds the minimum// number of operations required such// that String A and B are the samestatic void findMinimumOperations(char[] a, char[] b){ // Stores the count of steps int step = 0; // Stores the last index whose // bits are not same int last_index = 0; // Iterate until both String // are unequal while (!Arrays.equals(a, b)) { // Check till end of String to // find rightmost unequals bit for (int i = 0; i < a.length; i++) { // Update the last index if (a[i] != b[i]) { last_index = i; } } // Flipping characters up // to the last index for (int i = 0; i <= last_index; i++) { // Flip the bit a[i] = (a[i] == '0') ? '1' : '0'; } // Increasing steps by one step++; } // Print the count of steps System.out.print(step);} // Driver Codepublic static void main(String[] args){ // Given Strings A and B String A = \"101010\", B = \"110011\"; // Function Call findMinimumOperations(A.toCharArray(), B.toCharArray());}} // This code is contributed by 29AjayKumar",
"e": 30657,
"s": 29402,
"text": null
},
{
"code": "# Python3 program for the above approach # Function that finds the minimum# number of operations required such# that string A and B are the samedef findMinimumOperations(a, b): # Stores the count of steps step = 0 # Stores the last index whose # bits are not same last_index = 0 # Iterate until both string # are unequal while (a != b): a = [i for i in a] # Check till end of string to # find rightmost unequals bit for i in range(len(a)): # Update the last index if (a[i] != b[i]): last_index = i # Flipping characters up # to the last index for i in range(last_index + 1): # Flip the bit if (a[i] == '0'): a[i] = '1' else: a[i] = '0' a = \"\".join(a) # Increasing steps by one step += 1 # Print the count of steps print(step) # Driver Codeif __name__ == '__main__': # Given strings A and B A = \"101010\" B = \"110011\" # Function Call findMinimumOperations(A, B) # This code is contributed by mohit kumar 29",
"e": 31852,
"s": 30657,
"text": null
},
{
"code": "// C# program for the// above approachusing System; class GFG{ // Function that finds the minimum// number of operations required such// that string A and B are the samestatic void findMinimumOperations(string a, string b){ // Stores the count of steps int step = 0; // Stores the last index whose // bits are not same int last_index = 0; // Iterate until both string // are unequal while (a.Equals(b) == false) { // Check till end of string to // find rightmost unequals bit for(int i = 0; i < a.Length; i++) { // Update the last index if (a[i] != b[i]) { last_index = i; } } // Flipping characters up // to the last index char[] ch = a.ToCharArray(); for(int i = 0; i <= last_index; i++) { // Flip the bit if (ch[i] == '0') { ch[i] = '1'; } else { ch[i] = '0'; } } a = new string(ch); // Increasing steps by one step++; } // Print the count of steps Console.WriteLine(step);} // Driver Codepublic static void Main(){ // Given strings A and B string A = \"101010\"; string B = \"110011\"; // Function Call findMinimumOperations(A,B);}} // This code is contributed by SURENDRA_GANGWAR",
"e": 33147,
"s": 31852,
"text": null
},
{
"code": "<script> // JavaScript program for the// above approach // Function that finds the minimum// number of operations required such// that string A and B are the samefunction findMinimumOperations(a, b){ // Stores the count of steps var step = 0; // Stores the last index whose // bits are not same var last_index = 0; // Iterate until both string // are unequal while (a !== b) { // Check till end of string to // find rightmost unequals bit for (var i = 0; i < a.length; i++) { // Update the last index if (a[i] !== b[i]) { last_index = i; } } // Flipping characters up // to the last index var ch = a.split(\"\"); for(var i = 0; i <= last_index; i++) { // Flip the bit if (ch[i] === \"0\") { ch[i] = \"1\"; } else { ch[i] = \"0\"; } } a = ch.join(\"\"); // Increasing steps by one step++; } // Print the count of steps document.write(step);} // Driver Code // Given strings A and Bvar A = \"101010\";var B = \"110011\"; // Function CallfindMinimumOperations(A, B); // This code is contributed by rdtank </script>",
"e": 34514,
"s": 33147,
"text": null
},
{
"code": null,
"e": 34516,
"s": 34514,
"text": "4"
},
{
"code": null,
"e": 34562,
"s": 34518,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 34577,
"s": 34562,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34589,
"s": 34577,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34606,
"s": 34589,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 34613,
"s": 34606,
"text": "rdtank"
},
{
"code": null,
"e": 34628,
"s": 34613,
"text": "adnanirshad158"
},
{
"code": null,
"e": 34642,
"s": 34628,
"text": "binary-string"
},
{
"code": null,
"e": 34652,
"s": 34642,
"text": "substring"
},
{
"code": null,
"e": 34659,
"s": 34652,
"text": "Greedy"
},
{
"code": null,
"e": 34669,
"s": 34659,
"text": "Searching"
},
{
"code": null,
"e": 34677,
"s": 34669,
"text": "Strings"
},
{
"code": null,
"e": 34687,
"s": 34677,
"text": "Searching"
},
{
"code": null,
"e": 34695,
"s": 34687,
"text": "Strings"
},
{
"code": null,
"e": 34702,
"s": 34695,
"text": "Greedy"
},
{
"code": null,
"e": 34800,
"s": 34702,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34835,
"s": 34800,
"text": "Optimal Page Replacement Algorithm"
},
{
"code": null,
"e": 34887,
"s": 34835,
"text": "Program for Best Fit algorithm in Memory Management"
},
{
"code": null,
"e": 34940,
"s": 34887,
"text": "Program for First Fit algorithm in Memory Management"
},
{
"code": null,
"e": 34991,
"s": 34940,
"text": "Bin Packing Problem (Minimize number of used Bins)"
},
{
"code": null,
"e": 35021,
"s": 34991,
"text": "Max Flow Problem Introduction"
},
{
"code": null,
"e": 35035,
"s": 35021,
"text": "Binary Search"
},
{
"code": null,
"e": 35103,
"s": 35035,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 35117,
"s": 35103,
"text": "Linear Search"
},
{
"code": null,
"e": 35165,
"s": 35117,
"text": "Search an element in a sorted and rotated array"
}
] |
Powerful Number - GeeksforGeeks
|
07 Mar, 2022
A number n is said to be Powerful Number if for every prime factor p of it, p2 also divides it. For example:- 36 is a powerful number. It is divisible by both 3 and square of 3 i.e, 9.The first few Powerful Numbers are: 1, 4, 8, 9, 16, 25, 27, 32, 36, 49, 64 ....Given a number n, our task is to check if this is powerful or not. Examples :
Input: 27
Output: YES
Input: 32
Output: YES
Input: 12
Output: NO
The idea is based on the fact that if a number n is powerful, then all prime factors of it and their squares should be divisible by n. We find all prime factors of given number. And for every prime factor, we find the highest power of it that divides n. If we find a prime factor whose highest dividing power is 1, we return false. If highest dividing power of all prime factors is more than 1, we return true. Below is implementation of above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find if a number is powerful or not.#include <bits/stdc++.h>using namespace std; // function to check if the number is powerfulbool isPowerful(int n){ // First divide the number repeatedly by 2 while (n % 2 == 0) { int power = 0; while (n % 2 == 0) { n /= 2; power++; } // If only 2^1 divides n (not higher powers), // then return false if (power == 1) return false; } // if n is not a power of 2 then this loop will execute // repeat above process for (int factor = 3; factor <= sqrt(n); factor += 2) { // Find highest power of "factor" that divides n int power = 0; while (n % factor == 0) { n = n / factor; power++; } // If only factor^1 divides n (not higher powers), // then return false if (power == 1) return false; } // n must be 1 now if it is not a prime numenr. // Since prime numbers are not powerful, we return // false if n is not 1. return (n == 1);} // Driver program to test above functionint main(){ isPowerful(20) ? cout << "YES\n" : cout << "NO\n"; isPowerful(27) ? cout << "YES\n" : cout << "NO\n"; return 0;}
// Java program to find if a// number is powerful or not. class GFG { // function to check if the // number is powerful static boolean isPowerful(int n) { // First divide the number // repeatedly by 2 while (n % 2 == 0) { int power = 0; while (n % 2 == 0) { n /= 2; power++; } // If only 2^1 divides n (not higher powers), // then return false if (power == 1) return false; } // if n is not a power of 2 then this loop will execute // repeat above process for (int factor = 3; factor <= Math.sqrt(n); factor += 2) { // Find highest power of "factor" that divides n int power = 0; while (n % factor == 0) { n = n / factor; power++; } // If only factor^1 divides n (not higher powers), // then return false if (power == 1) return false; } // n must be 1 now if it is not a prime numenr. // Since prime numbers are not powerful, we return // false if n is not 1. return (n == 1); } // Driver code public static void main(String[] args) { if (isPowerful(20)) System.out.print("YES\n"); else System.out.print("NO\n"); if (isPowerful(27)) System.out.print("YES\n"); else System.out.print("NO\n"); }} // This code is contributed by Anant Agarwal.
# Python program to find# if a number is powerful or not.import math # function to check if# the number is powerfuldef isPowerful(n): # First divide the number repeatedly by 2 while (n % 2 == 0): power = 0 while (n % 2 == 0): n = n//2 power = power + 1 # If only 2 ^ 1 divides # n (not higher powers), # then return false if (power == 1): return False # if n is not a power of 2 # then this loop will execute # repeat above process for factor in range(3, int(math.sqrt(n))+1, 2): # Find highest power of # "factor" that divides n power = 0 while (n % factor == 0): n = n//factor power = power + 1 # If only factor ^ 1 divides # n (not higher powers), # then return false if (power == 1): return false # n must be 1 now if it # is not a prime number. # Since prime numbers are # not powerful, we return # false if n is not 1. return (n == 1) # Driver code print("YES" if isPowerful(20) else "NO")print("YES" if isPowerful(27) else "NO") # This code is contributed# by Anant Agarwal.
// C# program to find if a// number is powerful or not.using System; class GFG { // function to check if the // number is powerful static bool isPowerful(int n) { // First divide the number // repeatedly by 2 while (n % 2 == 0) { int power = 0; while (n % 2 == 0) { n /= 2; power++; } // If only 2^1 divides n // (not higher powers), // then return false if (power == 1) return false; } // if n is not a power of 2 then // this loop will execute repeat // above process for (int factor = 3; factor <= Math.Sqrt(n); factor += 2) { // Find highest power of "factor" // that divides n int power = 0; while (n % factor == 0) { n = n / factor; power++; } // If only factor^1 divides n // (not higher powers), then // return false if (power == 1) return false; } // n must be 1 now if it is not // a prime numenr. // Since prime numbers are not // powerful, we return false if // n is not 1. return (n == 1); } // Driver code public static void Main() { if (isPowerful(20)) Console.WriteLine("YES"); else Console.WriteLine("NO"); if (isPowerful(27)) Console.WriteLine("YES"); else Console.WriteLine("NO"); }} // This code is contributed by vt_m.
<?php// PHP program to find if a// number is powerful or not // function to check if// the number is powerfulfunction isPowerful($n){ // First divide the // number repeatedly by 2 while ($n % 2 == 0) { $power = 0; while ($n % 2 == 0) { $n /= 2; $power++; } // If only 2^1 divides // n (not higher powers), // then return false if ($power == 1) return false; } // if n is not a power of 2 // then this loop will execute // repeat above process for ($factor = 3; $factor <= sqrt($n); $factor += 2) { // Find highest power of // "factor" that divides n $power = 0; while ($n % $factor == 0) { $n = $n / $factor; $power++; } // If only factor^1 divides // n (not higher powers), // then return false if ($power == 1) return false; } // n must be 1 now if it is // not a prime number. Since // prime numbers are not powerful, // we return false if n is not 1. return ($n == 1);} // Driver Code$d = isPowerful(20) ? "YES\n" : "NO\n"; echo $d;$d = isPowerful(27) ? "YES\n" : "NO\n"; echo $d; // This code is contributed by ajit. ?>
<script> // Javascript program to find if a// number is powerful or not. // function to check if the // number is powerful function isPowerful(n) { // First divide the number // repeatedly by 2 while (n % 2 == 0) { let power = 0; while (n % 2 == 0) { n /= 2; power++; } // If only 2^1 divides n (not higher powers), // then return false if (power == 1) return false; } // if n is not a power of 2 then this loop will execute // repeat above process for (let factor = 3; factor <= Math.sqrt(n); factor += 2) { // Find highest power of "factor" that divides n let power = 0; while (n % factor == 0) { n = n / factor; power++; } // If only factor^1 divides n (not higher powers), // then return false if (power == 1) return false; } // n must be 1 now if it is not a prime numenr. // Since prime numbers are not powerful, we return // false if n is not 1. return (n == 1); } // Driver code to test above methods if (isPowerful(20)) document.write("YES" + "<br>"); else document.write("NO" + "<br>"); if (isPowerful(27)) document.write("YES" + "<br>"); else document.write("NO" + "<br>"); // This code is contributed by avijitmondal1998.</script>
Output :
NO
YES
References: https://en.wikipedia.org/wiki/Powerful_numberThis article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
jit_t
avijitmondal1998
simmytarika5
prime-factor
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Program for Decimal to Binary Conversion
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
|
[
{
"code": null,
"e": 26268,
"s": 26240,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 26611,
"s": 26268,
"text": "A number n is said to be Powerful Number if for every prime factor p of it, p2 also divides it. For example:- 36 is a powerful number. It is divisible by both 3 and square of 3 i.e, 9.The first few Powerful Numbers are: 1, 4, 8, 9, 16, 25, 27, 32, 36, 49, 64 ....Given a number n, our task is to check if this is powerful or not. Examples : "
},
{
"code": null,
"e": 26678,
"s": 26611,
"text": "Input: 27\nOutput: YES\n\nInput: 32\nOutput: YES\n\nInput: 12\nOutput: NO"
},
{
"code": null,
"e": 27131,
"s": 26680,
"text": "The idea is based on the fact that if a number n is powerful, then all prime factors of it and their squares should be divisible by n. We find all prime factors of given number. And for every prime factor, we find the highest power of it that divides n. If we find a prime factor whose highest dividing power is 1, we return false. If highest dividing power of all prime factors is more than 1, we return true. Below is implementation of above idea. "
},
{
"code": null,
"e": 27135,
"s": 27131,
"text": "C++"
},
{
"code": null,
"e": 27140,
"s": 27135,
"text": "Java"
},
{
"code": null,
"e": 27148,
"s": 27140,
"text": "Python3"
},
{
"code": null,
"e": 27151,
"s": 27148,
"text": "C#"
},
{
"code": null,
"e": 27155,
"s": 27151,
"text": "PHP"
},
{
"code": null,
"e": 27166,
"s": 27155,
"text": "Javascript"
},
{
"code": "// C++ program to find if a number is powerful or not.#include <bits/stdc++.h>using namespace std; // function to check if the number is powerfulbool isPowerful(int n){ // First divide the number repeatedly by 2 while (n % 2 == 0) { int power = 0; while (n % 2 == 0) { n /= 2; power++; } // If only 2^1 divides n (not higher powers), // then return false if (power == 1) return false; } // if n is not a power of 2 then this loop will execute // repeat above process for (int factor = 3; factor <= sqrt(n); factor += 2) { // Find highest power of \"factor\" that divides n int power = 0; while (n % factor == 0) { n = n / factor; power++; } // If only factor^1 divides n (not higher powers), // then return false if (power == 1) return false; } // n must be 1 now if it is not a prime numenr. // Since prime numbers are not powerful, we return // false if n is not 1. return (n == 1);} // Driver program to test above functionint main(){ isPowerful(20) ? cout << \"YES\\n\" : cout << \"NO\\n\"; isPowerful(27) ? cout << \"YES\\n\" : cout << \"NO\\n\"; return 0;}",
"e": 28419,
"s": 27166,
"text": null
},
{
"code": "// Java program to find if a// number is powerful or not. class GFG { // function to check if the // number is powerful static boolean isPowerful(int n) { // First divide the number // repeatedly by 2 while (n % 2 == 0) { int power = 0; while (n % 2 == 0) { n /= 2; power++; } // If only 2^1 divides n (not higher powers), // then return false if (power == 1) return false; } // if n is not a power of 2 then this loop will execute // repeat above process for (int factor = 3; factor <= Math.sqrt(n); factor += 2) { // Find highest power of \"factor\" that divides n int power = 0; while (n % factor == 0) { n = n / factor; power++; } // If only factor^1 divides n (not higher powers), // then return false if (power == 1) return false; } // n must be 1 now if it is not a prime numenr. // Since prime numbers are not powerful, we return // false if n is not 1. return (n == 1); } // Driver code public static void main(String[] args) { if (isPowerful(20)) System.out.print(\"YES\\n\"); else System.out.print(\"NO\\n\"); if (isPowerful(27)) System.out.print(\"YES\\n\"); else System.out.print(\"NO\\n\"); }} // This code is contributed by Anant Agarwal.",
"e": 29980,
"s": 28419,
"text": null
},
{
"code": "# Python program to find# if a number is powerful or not.import math # function to check if# the number is powerfuldef isPowerful(n): # First divide the number repeatedly by 2 while (n % 2 == 0): power = 0 while (n % 2 == 0): n = n//2 power = power + 1 # If only 2 ^ 1 divides # n (not higher powers), # then return false if (power == 1): return False # if n is not a power of 2 # then this loop will execute # repeat above process for factor in range(3, int(math.sqrt(n))+1, 2): # Find highest power of # \"factor\" that divides n power = 0 while (n % factor == 0): n = n//factor power = power + 1 # If only factor ^ 1 divides # n (not higher powers), # then return false if (power == 1): return false # n must be 1 now if it # is not a prime number. # Since prime numbers are # not powerful, we return # false if n is not 1. return (n == 1) # Driver code print(\"YES\" if isPowerful(20) else \"NO\")print(\"YES\" if isPowerful(27) else \"NO\") # This code is contributed# by Anant Agarwal.",
"e": 31237,
"s": 29980,
"text": null
},
{
"code": "// C# program to find if a// number is powerful or not.using System; class GFG { // function to check if the // number is powerful static bool isPowerful(int n) { // First divide the number // repeatedly by 2 while (n % 2 == 0) { int power = 0; while (n % 2 == 0) { n /= 2; power++; } // If only 2^1 divides n // (not higher powers), // then return false if (power == 1) return false; } // if n is not a power of 2 then // this loop will execute repeat // above process for (int factor = 3; factor <= Math.Sqrt(n); factor += 2) { // Find highest power of \"factor\" // that divides n int power = 0; while (n % factor == 0) { n = n / factor; power++; } // If only factor^1 divides n // (not higher powers), then // return false if (power == 1) return false; } // n must be 1 now if it is not // a prime numenr. // Since prime numbers are not // powerful, we return false if // n is not 1. return (n == 1); } // Driver code public static void Main() { if (isPowerful(20)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\"); if (isPowerful(27)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\"); }} // This code is contributed by vt_m.",
"e": 32854,
"s": 31237,
"text": null
},
{
"code": "<?php// PHP program to find if a// number is powerful or not // function to check if// the number is powerfulfunction isPowerful($n){ // First divide the // number repeatedly by 2 while ($n % 2 == 0) { $power = 0; while ($n % 2 == 0) { $n /= 2; $power++; } // If only 2^1 divides // n (not higher powers), // then return false if ($power == 1) return false; } // if n is not a power of 2 // then this loop will execute // repeat above process for ($factor = 3; $factor <= sqrt($n); $factor += 2) { // Find highest power of // \"factor\" that divides n $power = 0; while ($n % $factor == 0) { $n = $n / $factor; $power++; } // If only factor^1 divides // n (not higher powers), // then return false if ($power == 1) return false; } // n must be 1 now if it is // not a prime number. Since // prime numbers are not powerful, // we return false if n is not 1. return ($n == 1);} // Driver Code$d = isPowerful(20) ? \"YES\\n\" : \"NO\\n\"; echo $d;$d = isPowerful(27) ? \"YES\\n\" : \"NO\\n\"; echo $d; // This code is contributed by ajit. ?>",
"e": 34196,
"s": 32854,
"text": null
},
{
"code": "<script> // Javascript program to find if a// number is powerful or not. // function to check if the // number is powerful function isPowerful(n) { // First divide the number // repeatedly by 2 while (n % 2 == 0) { let power = 0; while (n % 2 == 0) { n /= 2; power++; } // If only 2^1 divides n (not higher powers), // then return false if (power == 1) return false; } // if n is not a power of 2 then this loop will execute // repeat above process for (let factor = 3; factor <= Math.sqrt(n); factor += 2) { // Find highest power of \"factor\" that divides n let power = 0; while (n % factor == 0) { n = n / factor; power++; } // If only factor^1 divides n (not higher powers), // then return false if (power == 1) return false; } // n must be 1 now if it is not a prime numenr. // Since prime numbers are not powerful, we return // false if n is not 1. return (n == 1); } // Driver code to test above methods if (isPowerful(20)) document.write(\"YES\" + \"<br>\"); else document.write(\"NO\" + \"<br>\"); if (isPowerful(27)) document.write(\"YES\" + \"<br>\"); else document.write(\"NO\" + \"<br>\"); // This code is contributed by avijitmondal1998.</script>",
"e": 35768,
"s": 34196,
"text": null
},
{
"code": null,
"e": 35779,
"s": 35768,
"text": "Output : "
},
{
"code": null,
"e": 35786,
"s": 35779,
"text": "NO\nYES"
},
{
"code": null,
"e": 36265,
"s": 35786,
"text": "References: https://en.wikipedia.org/wiki/Powerful_numberThis article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 36271,
"s": 36265,
"text": "jit_t"
},
{
"code": null,
"e": 36288,
"s": 36271,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 36301,
"s": 36288,
"text": "simmytarika5"
},
{
"code": null,
"e": 36314,
"s": 36301,
"text": "prime-factor"
},
{
"code": null,
"e": 36321,
"s": 36314,
"text": "series"
},
{
"code": null,
"e": 36334,
"s": 36321,
"text": "Mathematical"
},
{
"code": null,
"e": 36347,
"s": 36334,
"text": "Mathematical"
},
{
"code": null,
"e": 36354,
"s": 36347,
"text": "series"
},
{
"code": null,
"e": 36452,
"s": 36354,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36476,
"s": 36452,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 36519,
"s": 36476,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 36533,
"s": 36519,
"text": "Prime Numbers"
},
{
"code": null,
"e": 36606,
"s": 36533,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 36627,
"s": 36606,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 36670,
"s": 36627,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 36704,
"s": 36670,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 36745,
"s": 36704,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 36798,
"s": 36745,
"text": "Find minimum number of coins that make a given value"
}
] |
Maximum product of an increasing subsequence - GeeksforGeeks
|
12 May, 2022
Given an array of numbers, find the maximum product formed by multiplying numbers of an increasing subsequence of that array.Note: A single number is supposed to be an increasing subsequence of size 1.Examples:
Input : arr[] = { 3, 100, 4, 5, 150, 6 }
Output : 45000
Maximum product is 45000 formed by the
increasing subsequence 3, 100, 150. Note
that the longest increasing subsequence
is different {3, 4, 5, 6}
Input : arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }
Output : 21780000
Maximum product is 21780000 formed by the
increasing subsequence 10, 22, 33, 50, 60.
Prerequisite : Longest Increasing Subsequence Approach: Use a dynamic approach to maintain a table mpis[]. The value of mpis[i] stores product maximum product increasing subsequence ending with arr[i]. Initially all the values of increasing subsequence table are initialized to arr[i]. We use recursive approach similar to LIS problem to find the result.
C++
Java
Python3
C#
PHP
Javascript
/* Dynamic programming C++ implementation of maximum product of an increasing subsequence */#include <bits/stdc++.h>#define ll long long intusing namespace std; // Returns product of maximum product increasing// subsequence.ll lis(ll arr[], ll n){ ll mpis[n]; /* Initialize MPIS values */ for (int i = 0; i < n; i++) mpis[i] = arr[i]; /* Compute optimized MPIS values considering every element as ending element of sequence */ for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (arr[i] > arr[j] && mpis[i] < (mpis[j] * arr[i])) mpis[i] = mpis[j] * arr[i]; /* Pick maximum of all product values */ return *max_element(mpis, mpis + n);} /* Driver program to test above function */int main(){ ll arr[] = { 3, 100, 4, 5, 150, 6 }; ll n = sizeof(arr) / sizeof(arr[0]); printf("%lld", lis(arr, n)); return 0;}
/* Dynamic programming Java implementationof maximum product of an increasingsubsequence */import java.util.Arrays;import java.util.Collections; class GFG { // Returns product of maximum product // increasing subsequence. static int lis(int[] arr, int n) { int[] mpis = new int[n]; int max = Integer.MIN_VALUE; /* Initialize MPIS values */ for (int i = 0; i < n; i++) mpis[i] = arr[i]; /* Compute optimized MPIS values considering every element as ending element of sequence */ for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (arr[i] > arr[j] && mpis[i] < (mpis[j] * arr[i])) mpis[i] = mpis[j] * arr[i]; /* Pick maximum of all product values using for loop*/ for (int k = 0; k < mpis.length; k++) { if (mpis[k] > max) { max = mpis[k]; } } return max; } // Driver program to test above function static public void main(String[] args) { int[] arr = { 3, 100, 4, 5, 150, 6 }; int n = arr.length; System.out.println(lis(arr, n)); }} // This code is contributed by parashar.
# Python program implementation# of maximum product of an increasing # Returns product of maximum product# increasing subsequence.import sys def lis(arr, n): mpis = [] Max = -sys.maxsize -1 # Initialize MPIS values * for i in range(n): mpis.append(arr[i]) # Compute optimized MPIS values # considering every element as ending # element of sequence for i in range(1,n): for j in range(i): if (arr[i] > arr[j] and mpis[i] < (mpis[j] * arr[i])): mpis[i] = mpis[j] * arr[i] # Pick maximum of all product values # using for loop for k in range(len(mpis)): if (mpis[k] > Max): Max = mpis[k] return Max # Driver Codearr = [ 3, 100, 4, 5, 150, 6 ]n = len(arr)print(lis(arr, n)) # This code is contributed by shinjanpatra
/* Dynamic programming C# implementationof maximum product of an increasingsubsequence */using System;using System.Linq; public class GFG { // Returns product of maximum product // increasing subsequence. static long lis(long[] arr, long n) { long[] mpis = new long[n]; /* Initialize MPIS values */ for (int i = 0; i < n; i++) mpis[i] = arr[i]; /* Compute optimized MPIS values considering every element as ending element of sequence */ for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (arr[i] > arr[j] && mpis[i] < (mpis[j] * arr[i])) mpis[i] = mpis[j] * arr[i]; /* Pick maximum of all product values */ return mpis.Max(); } /* Driver program to test above function */ static public void Main() { long[] arr = { 3, 100, 4, 5, 150, 6 }; long n = arr.Length; Console.WriteLine(lis(arr, n)); }} // This code is contributed by vt_m.
<?PHP /* Dynamic programming PHP implementation of maximum product of an increasing subsequence */ // Returns product of maximum product increasing// subsequence.function lis(&$arr, $n){ $mpis = array_fill(0,$n, NULL); /* Initialize MPIS values */ for ($i = 0; $i < $n; $i++) $mpis[$i] = $arr[$i]; /* Compute optimized MPIS values considering every element as ending element of sequence */ for ($i = 1; $i < $n; $i++) for ($j = 0; $j < $i; $j++) if ($arr[$i] > $arr[$j] && $mpis[$i] < ($mpis[$j] * $arr[$i])) $mpis[$i] = $mpis[$j] * $arr[$i]; /* Pick maximum of all product values */ return max($mpis);} /* Driver program to test above function */ $arr = array ( 3, 100, 4, 5, 150, 6 ); $n = sizeof($arr) / sizeof($arr[0]); echo lis($arr, $n); return 0;?>
<script> // JavaScript program implementationof maximum product of an increasing // Returns product of maximum product // increasing subsequence. function lis(arr, n) { let mpis = []; let max = Number.MIN_VALUE; /* Initialize MPIS values */ for (let i = 0; i < n; i++) mpis[i] = arr[i]; /* Compute optimized MPIS values considering every element as ending element of sequence */ for (let i = 1; i < n; i++) for (let j = 0; j < i; j++) if (arr[i] > arr[j] && mpis[i] < (mpis[j] * arr[i])) mpis[i] = mpis[j] * arr[i]; /* Pick maximum of all product values using for loop*/ for (let k = 0; k < mpis.length; k++) { if (mpis[k] > max) { max = mpis[k]; } } return max; } // Driver Code let arr = [ 3, 100, 4, 5, 150, 6 ]; let n = arr.length; document.write(lis(arr, n)); // This code is contributed by chinmoy1997pal.</script>
Output:
45000
Time Complexity: O(n^2) Auxiliary Space : O(n)
parashar
ukasp
chinmoy1997pal
shinjanpatra
LIS
Arrays
Dynamic Programming
Arrays
Dynamic Programming
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
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
|
[
{
"code": null,
"e": 26065,
"s": 26037,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 26278,
"s": 26065,
"text": "Given an array of numbers, find the maximum product formed by multiplying numbers of an increasing subsequence of that array.Note: A single number is supposed to be an increasing subsequence of size 1.Examples: "
},
{
"code": null,
"e": 26648,
"s": 26278,
"text": "Input : arr[] = { 3, 100, 4, 5, 150, 6 }\nOutput : 45000\nMaximum product is 45000 formed by the \nincreasing subsequence 3, 100, 150. Note\nthat the longest increasing subsequence \nis different {3, 4, 5, 6}\n\nInput : arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }\nOutput : 21780000\nMaximum product is 21780000 formed by the \nincreasing subsequence 10, 22, 33, 50, 60.\n "
},
{
"code": null,
"e": 27007,
"s": 26650,
"text": "Prerequisite : Longest Increasing Subsequence Approach: Use a dynamic approach to maintain a table mpis[]. The value of mpis[i] stores product maximum product increasing subsequence ending with arr[i]. Initially all the values of increasing subsequence table are initialized to arr[i]. We use recursive approach similar to LIS problem to find the result. "
},
{
"code": null,
"e": 27011,
"s": 27007,
"text": "C++"
},
{
"code": null,
"e": 27016,
"s": 27011,
"text": "Java"
},
{
"code": null,
"e": 27024,
"s": 27016,
"text": "Python3"
},
{
"code": null,
"e": 27027,
"s": 27024,
"text": "C#"
},
{
"code": null,
"e": 27031,
"s": 27027,
"text": "PHP"
},
{
"code": null,
"e": 27042,
"s": 27031,
"text": "Javascript"
},
{
"code": "/* Dynamic programming C++ implementation of maximum product of an increasing subsequence */#include <bits/stdc++.h>#define ll long long intusing namespace std; // Returns product of maximum product increasing// subsequence.ll lis(ll arr[], ll n){ ll mpis[n]; /* Initialize MPIS values */ for (int i = 0; i < n; i++) mpis[i] = arr[i]; /* Compute optimized MPIS values considering every element as ending element of sequence */ for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (arr[i] > arr[j] && mpis[i] < (mpis[j] * arr[i])) mpis[i] = mpis[j] * arr[i]; /* Pick maximum of all product values */ return *max_element(mpis, mpis + n);} /* Driver program to test above function */int main(){ ll arr[] = { 3, 100, 4, 5, 150, 6 }; ll n = sizeof(arr) / sizeof(arr[0]); printf(\"%lld\", lis(arr, n)); return 0;}",
"e": 27938,
"s": 27042,
"text": null
},
{
"code": "/* Dynamic programming Java implementationof maximum product of an increasingsubsequence */import java.util.Arrays;import java.util.Collections; class GFG { // Returns product of maximum product // increasing subsequence. static int lis(int[] arr, int n) { int[] mpis = new int[n]; int max = Integer.MIN_VALUE; /* Initialize MPIS values */ for (int i = 0; i < n; i++) mpis[i] = arr[i]; /* Compute optimized MPIS values considering every element as ending element of sequence */ for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (arr[i] > arr[j] && mpis[i] < (mpis[j] * arr[i])) mpis[i] = mpis[j] * arr[i]; /* Pick maximum of all product values using for loop*/ for (int k = 0; k < mpis.length; k++) { if (mpis[k] > max) { max = mpis[k]; } } return max; } // Driver program to test above function static public void main(String[] args) { int[] arr = { 3, 100, 4, 5, 150, 6 }; int n = arr.length; System.out.println(lis(arr, n)); }} // This code is contributed by parashar.",
"e": 29206,
"s": 27938,
"text": null
},
{
"code": "# Python program implementation# of maximum product of an increasing # Returns product of maximum product# increasing subsequence.import sys def lis(arr, n): mpis = [] Max = -sys.maxsize -1 # Initialize MPIS values * for i in range(n): mpis.append(arr[i]) # Compute optimized MPIS values # considering every element as ending # element of sequence for i in range(1,n): for j in range(i): if (arr[i] > arr[j] and mpis[i] < (mpis[j] * arr[i])): mpis[i] = mpis[j] * arr[i] # Pick maximum of all product values # using for loop for k in range(len(mpis)): if (mpis[k] > Max): Max = mpis[k] return Max # Driver Codearr = [ 3, 100, 4, 5, 150, 6 ]n = len(arr)print(lis(arr, n)) # This code is contributed by shinjanpatra",
"e": 30037,
"s": 29206,
"text": null
},
{
"code": "/* Dynamic programming C# implementationof maximum product of an increasingsubsequence */using System;using System.Linq; public class GFG { // Returns product of maximum product // increasing subsequence. static long lis(long[] arr, long n) { long[] mpis = new long[n]; /* Initialize MPIS values */ for (int i = 0; i < n; i++) mpis[i] = arr[i]; /* Compute optimized MPIS values considering every element as ending element of sequence */ for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (arr[i] > arr[j] && mpis[i] < (mpis[j] * arr[i])) mpis[i] = mpis[j] * arr[i]; /* Pick maximum of all product values */ return mpis.Max(); } /* Driver program to test above function */ static public void Main() { long[] arr = { 3, 100, 4, 5, 150, 6 }; long n = arr.Length; Console.WriteLine(lis(arr, n)); }} // This code is contributed by vt_m.",
"e": 31044,
"s": 30037,
"text": null
},
{
"code": "<?PHP /* Dynamic programming PHP implementation of maximum product of an increasing subsequence */ // Returns product of maximum product increasing// subsequence.function lis(&$arr, $n){ $mpis = array_fill(0,$n, NULL); /* Initialize MPIS values */ for ($i = 0; $i < $n; $i++) $mpis[$i] = $arr[$i]; /* Compute optimized MPIS values considering every element as ending element of sequence */ for ($i = 1; $i < $n; $i++) for ($j = 0; $j < $i; $j++) if ($arr[$i] > $arr[$j] && $mpis[$i] < ($mpis[$j] * $arr[$i])) $mpis[$i] = $mpis[$j] * $arr[$i]; /* Pick maximum of all product values */ return max($mpis);} /* Driver program to test above function */ $arr = array ( 3, 100, 4, 5, 150, 6 ); $n = sizeof($arr) / sizeof($arr[0]); echo lis($arr, $n); return 0;?>",
"e": 31891,
"s": 31044,
"text": null
},
{
"code": "<script> // JavaScript program implementationof maximum product of an increasing // Returns product of maximum product // increasing subsequence. function lis(arr, n) { let mpis = []; let max = Number.MIN_VALUE; /* Initialize MPIS values */ for (let i = 0; i < n; i++) mpis[i] = arr[i]; /* Compute optimized MPIS values considering every element as ending element of sequence */ for (let i = 1; i < n; i++) for (let j = 0; j < i; j++) if (arr[i] > arr[j] && mpis[i] < (mpis[j] * arr[i])) mpis[i] = mpis[j] * arr[i]; /* Pick maximum of all product values using for loop*/ for (let k = 0; k < mpis.length; k++) { if (mpis[k] > max) { max = mpis[k]; } } return max; } // Driver Code let arr = [ 3, 100, 4, 5, 150, 6 ]; let n = arr.length; document.write(lis(arr, n)); // This code is contributed by chinmoy1997pal.</script>",
"e": 32988,
"s": 31891,
"text": null
},
{
"code": null,
"e": 32998,
"s": 32988,
"text": "Output: "
},
{
"code": null,
"e": 33005,
"s": 32998,
"text": " 45000"
},
{
"code": null,
"e": 33053,
"s": 33005,
"text": "Time Complexity: O(n^2) Auxiliary Space : O(n) "
},
{
"code": null,
"e": 33062,
"s": 33053,
"text": "parashar"
},
{
"code": null,
"e": 33068,
"s": 33062,
"text": "ukasp"
},
{
"code": null,
"e": 33083,
"s": 33068,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 33096,
"s": 33083,
"text": "shinjanpatra"
},
{
"code": null,
"e": 33100,
"s": 33096,
"text": "LIS"
},
{
"code": null,
"e": 33107,
"s": 33100,
"text": "Arrays"
},
{
"code": null,
"e": 33127,
"s": 33107,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 33134,
"s": 33127,
"text": "Arrays"
},
{
"code": null,
"e": 33154,
"s": 33134,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 33252,
"s": 33154,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33279,
"s": 33252,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 33310,
"s": 33279,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 33335,
"s": 33310,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33373,
"s": 33335,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 33394,
"s": 33373,
"text": "Next Greater Element"
},
{
"code": null,
"e": 33423,
"s": 33394,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 33453,
"s": 33423,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 33487,
"s": 33453,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 33518,
"s": 33487,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
Rename Columns of a Data Frame in R Programming - rename() Function - GeeksforGeeks
|
19 Jun, 2020
rename() function in R Language is used to rename the column names of a data frame, based on the older names.
Syntax: rename(x, names)
Parameters:x: Data framenames: Old name and new name
Example 1:
# R program to rename a Data Frame # Adding Package df <- library(plyr) # Creating a Data Frame df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8) print("Original Data Frame") print(df) print("Modified Data Frame") # Renaming Data Frame rename(df, c("row1"="one", "row2"="two", "row3"="three"))
Output:
[1] "Original Data Frame"
row1 row2 row3
1 0 3 6
2 1 4 7
3 2 5 8
[1] "Modified Data Frame"
one two three
1 0 3 6
2 1 4 7
3 2 5 8
Example 2:
# R program to modify names of a data frame # Loading librarydf <- library(plyr) # Creating a data framedf = data.frame( "col1" = c("abc", "def", "ghi"), "col2" = c("R", "Python", "Java"), "col3" = c(22, 25, 45) ) df # Calling rename() functionrename(df, c("col1" = "Name", "col2" = "Language", "col3" = "Age"))
Output:
col1 col2 col3
1 abc R 22
2 def Python 25
3 ghi Java 45
Name Language Age
1 abc R 22
2 def Python 25
3 ghi Java 45
R DataFrame-Function
R Language
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
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?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to import an Excel File into R ?
Plot mean and standard deviation using ggplot2 in R
How to filter R dataframe by multiple conditions?
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n19 Jun, 2020"
},
{
"code": null,
"e": 26597,
"s": 26487,
"text": "rename() function in R Language is used to rename the column names of a data frame, based on the older names."
},
{
"code": null,
"e": 26622,
"s": 26597,
"text": "Syntax: rename(x, names)"
},
{
"code": null,
"e": 26675,
"s": 26622,
"text": "Parameters:x: Data framenames: Old name and new name"
},
{
"code": null,
"e": 26686,
"s": 26675,
"text": "Example 1:"
},
{
"code": "# R program to rename a Data Frame # Adding Package df <- library(plyr) # Creating a Data Frame df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8) print(\"Original Data Frame\") print(df) print(\"Modified Data Frame\") # Renaming Data Frame rename(df, c(\"row1\"=\"one\", \"row2\"=\"two\", \"row3\"=\"three\")) ",
"e": 26994,
"s": 26686,
"text": null
},
{
"code": null,
"e": 27002,
"s": 26994,
"text": "Output:"
},
{
"code": null,
"e": 27187,
"s": 27002,
"text": "[1] \"Original Data Frame\"\n row1 row2 row3\n1 0 3 6\n2 1 4 7\n3 2 5 8\n[1] \"Modified Data Frame\"\n one two three\n1 0 3 6\n2 1 4 7\n3 2 5 8\n"
},
{
"code": null,
"e": 27198,
"s": 27187,
"text": "Example 2:"
},
{
"code": "# R program to modify names of a data frame # Loading librarydf <- library(plyr) # Creating a data framedf = data.frame( \"col1\" = c(\"abc\", \"def\", \"ghi\"), \"col2\" = c(\"R\", \"Python\", \"Java\"), \"col3\" = c(22, 25, 45) ) df # Calling rename() functionrename(df, c(\"col1\" = \"Name\", \"col2\" = \"Language\", \"col3\" = \"Age\"))",
"e": 27519,
"s": 27198,
"text": null
},
{
"code": null,
"e": 27527,
"s": 27519,
"text": "Output:"
},
{
"code": null,
"e": 27684,
"s": 27527,
"text": " col1 col2 col3\n1 abc R 22\n2 def Python 25\n3 ghi Java 45\n Name Language Age\n1 abc R 22\n2 def Python 25\n3 ghi Java 45\n"
},
{
"code": null,
"e": 27705,
"s": 27684,
"text": "R DataFrame-Function"
},
{
"code": null,
"e": 27716,
"s": 27705,
"text": "R Language"
},
{
"code": null,
"e": 27814,
"s": 27716,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27866,
"s": 27814,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27901,
"s": 27866,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27939,
"s": 27901,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27997,
"s": 27939,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28040,
"s": 27997,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28089,
"s": 28040,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28106,
"s": 28089,
"text": "R - if statement"
},
{
"code": null,
"e": 28143,
"s": 28106,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 28195,
"s": 28143,
"text": "Plot mean and standard deviation using ggplot2 in R"
}
] |
Spatial Filters - Averaging filter and Median filter in Image Processing - GeeksforGeeks
|
09 Nov, 2021
Spatial Filtering technique is used directly on pixels of an image. Mask is usually considered to be added in size so that it has a specific center pixel. This mask is moved on the image such that the center of the mask traverses all image pixels.In this article, we are going to cover the following topics –
To write a program in Python to implement spatial domain averaging filter and to observe its blurring effect on the image without using inbuilt functions
To write a program in Python to implement spatial domain median filter to remove salt and pepper noise without using inbuilt functions
Neighborhood processing in spatial domain: Here, to modify one pixel, we consider values of the immediate neighboring pixels also. For this purpose, 3X3, 5X5, or 7X7 neighborhood mask can be considered. An example of a 3X3 mask is shown below.
f(x-1, y-1) f(x-1, y) f(x-1, y+1)
f(x, y-1) f(x, y) f(x, y+1)
f(x+1, y-1) f(x+1, y) f(x+1, y+1)
Low Pass filtering: It is also known as the smoothing filter. It removes the high-frequency content from the image. It is also used to blur an image. A low pass averaging filter mask is as shown.
1/9 1/9 1/9
1/9 1/9 1/9
1/9 1/9 1/9
High Pass Filtering: It eliminates low-frequency regions while retaining or enhancing the high-frequency components. A high pass filtering mask is as shown.
-1/9 -1/9 -1/9
-1/9 8/9 -1/9
-1/9 -1/9 -1/9
Median Filtering: It is also known as nonlinear filtering. It is used to eliminate salt and pepper noise. Here the pixel value is replaced by the median value of the neighboring pixel.
Below is the implementation.
Input Image:
Averaging Filter:
Python3
# Low Pass SPatial Domain Filtering# to observe the blurring effect import cv2import numpy as np # Read the imageimg = cv2.imread('sample.png', 0) # Obtain number of rows and columns# of the imagem, n = img.shape # Develop Averaging filter(3, 3) maskmask = np.ones([3, 3], dtype = int)mask = mask / 9 # Convolve the 3X3 mask over the imageimg_new = np.zeros([m, n]) for i in range(1, m-1): for j in range(1, n-1): temp = img[i-1, j-1]*mask[0, 0]+img[i-1, j]*mask[0, 1]+img[i-1, j + 1]*mask[0, 2]+img[i, j-1]*mask[1, 0]+ img[i, j]*mask[1, 1]+img[i, j + 1]*mask[1, 2]+img[i + 1, j-1]*mask[2, 0]+img[i + 1, j]*mask[2, 1]+img[i + 1, j + 1]*mask[2, 2] img_new[i, j]= temp img_new = img_new.astype(np.uint8)cv2.imwrite('blurred.tif', img_new)
Output:
In the above example, it is observed that the filtered image is slightly blurred. If we increase the size of the averaging mask, more blurring can be obtained.
Median Filtering:
Python3
# Median Spatial Domain Filtering import cv2import numpy as np # Read the imageimg_noisy1 = cv2.imread('sample.png', 0) # Obtain the number of rows and columns# of the imagem, n = img_noisy1.shape # Traverse the image. For every 3X3 area,# find the median of the pixels and# replace the center pixel by the medianimg_new1 = np.zeros([m, n]) for i in range(1, m-1): for j in range(1, n-1): temp = [img_noisy1[i-1, j-1], img_noisy1[i-1, j], img_noisy1[i-1, j + 1], img_noisy1[i, j-1], img_noisy1[i, j], img_noisy1[i, j + 1], img_noisy1[i + 1, j-1], img_noisy1[i + 1, j], img_noisy1[i + 1, j + 1]] temp = sorted(temp) img_new1[i, j]= temp[4] img_new1 = img_new1.astype(np.uint8)cv2.imwrite('new_median_filtered.png', img_new1)
Output:
In the above example, we can see that the median filtered image is considerably enhanced with hardly any salt and pepper noise in it.
gulshankumarar231
Image-Processing
Python-OpenCV
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": 26037,
"s": 26009,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 26347,
"s": 26037,
"text": "Spatial Filtering technique is used directly on pixels of an image. Mask is usually considered to be added in size so that it has a specific center pixel. This mask is moved on the image such that the center of the mask traverses all image pixels.In this article, we are going to cover the following topics – "
},
{
"code": null,
"e": 26502,
"s": 26347,
"text": "To write a program in Python to implement spatial domain averaging filter and to observe its blurring effect on the image without using inbuilt functions "
},
{
"code": null,
"e": 26638,
"s": 26502,
"text": "To write a program in Python to implement spatial domain median filter to remove salt and pepper noise without using inbuilt functions "
},
{
"code": null,
"e": 26882,
"s": 26638,
"text": "Neighborhood processing in spatial domain: Here, to modify one pixel, we consider values of the immediate neighboring pixels also. For this purpose, 3X3, 5X5, or 7X7 neighborhood mask can be considered. An example of a 3X3 mask is shown below."
},
{
"code": null,
"e": 26978,
"s": 26882,
"text": "f(x-1, y-1) f(x-1, y) f(x-1, y+1)\nf(x, y-1) f(x, y) f(x, y+1)\nf(x+1, y-1) f(x+1, y) f(x+1, y+1)"
},
{
"code": null,
"e": 27174,
"s": 26978,
"text": "Low Pass filtering: It is also known as the smoothing filter. It removes the high-frequency content from the image. It is also used to blur an image. A low pass averaging filter mask is as shown."
},
{
"code": null,
"e": 27210,
"s": 27174,
"text": "1/9 1/9 1/9\n1/9 1/9 1/9\n1/9 1/9 1/9"
},
{
"code": null,
"e": 27367,
"s": 27210,
"text": "High Pass Filtering: It eliminates low-frequency regions while retaining or enhancing the high-frequency components. A high pass filtering mask is as shown."
},
{
"code": null,
"e": 27411,
"s": 27367,
"text": "-1/9 -1/9 -1/9\n-1/9 8/9 -1/9\n-1/9 -1/9 -1/9"
},
{
"code": null,
"e": 27597,
"s": 27411,
"text": "Median Filtering: It is also known as nonlinear filtering. It is used to eliminate salt and pepper noise. Here the pixel value is replaced by the median value of the neighboring pixel. "
},
{
"code": null,
"e": 27626,
"s": 27597,
"text": "Below is the implementation."
},
{
"code": null,
"e": 27641,
"s": 27626,
"text": "Input Image: "
},
{
"code": null,
"e": 27660,
"s": 27641,
"text": "Averaging Filter: "
},
{
"code": null,
"e": 27668,
"s": 27660,
"text": "Python3"
},
{
"code": "# Low Pass SPatial Domain Filtering# to observe the blurring effect import cv2import numpy as np # Read the imageimg = cv2.imread('sample.png', 0) # Obtain number of rows and columns# of the imagem, n = img.shape # Develop Averaging filter(3, 3) maskmask = np.ones([3, 3], dtype = int)mask = mask / 9 # Convolve the 3X3 mask over the imageimg_new = np.zeros([m, n]) for i in range(1, m-1): for j in range(1, n-1): temp = img[i-1, j-1]*mask[0, 0]+img[i-1, j]*mask[0, 1]+img[i-1, j + 1]*mask[0, 2]+img[i, j-1]*mask[1, 0]+ img[i, j]*mask[1, 1]+img[i, j + 1]*mask[1, 2]+img[i + 1, j-1]*mask[2, 0]+img[i + 1, j]*mask[2, 1]+img[i + 1, j + 1]*mask[2, 2] img_new[i, j]= temp img_new = img_new.astype(np.uint8)cv2.imwrite('blurred.tif', img_new)",
"e": 28447,
"s": 27668,
"text": null
},
{
"code": null,
"e": 28455,
"s": 28447,
"text": "Output:"
},
{
"code": null,
"e": 28616,
"s": 28455,
"text": "In the above example, it is observed that the filtered image is slightly blurred. If we increase the size of the averaging mask, more blurring can be obtained. "
},
{
"code": null,
"e": 28635,
"s": 28616,
"text": "Median Filtering: "
},
{
"code": null,
"e": 28643,
"s": 28635,
"text": "Python3"
},
{
"code": "# Median Spatial Domain Filtering import cv2import numpy as np # Read the imageimg_noisy1 = cv2.imread('sample.png', 0) # Obtain the number of rows and columns# of the imagem, n = img_noisy1.shape # Traverse the image. For every 3X3 area,# find the median of the pixels and# replace the center pixel by the medianimg_new1 = np.zeros([m, n]) for i in range(1, m-1): for j in range(1, n-1): temp = [img_noisy1[i-1, j-1], img_noisy1[i-1, j], img_noisy1[i-1, j + 1], img_noisy1[i, j-1], img_noisy1[i, j], img_noisy1[i, j + 1], img_noisy1[i + 1, j-1], img_noisy1[i + 1, j], img_noisy1[i + 1, j + 1]] temp = sorted(temp) img_new1[i, j]= temp[4] img_new1 = img_new1.astype(np.uint8)cv2.imwrite('new_median_filtered.png', img_new1)",
"e": 29515,
"s": 28643,
"text": null
},
{
"code": null,
"e": 29523,
"s": 29515,
"text": "Output:"
},
{
"code": null,
"e": 29658,
"s": 29523,
"text": "In the above example, we can see that the median filtered image is considerably enhanced with hardly any salt and pepper noise in it. "
},
{
"code": null,
"e": 29676,
"s": 29658,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 29693,
"s": 29676,
"text": "Image-Processing"
},
{
"code": null,
"e": 29707,
"s": 29693,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 29714,
"s": 29707,
"text": "Python"
},
{
"code": null,
"e": 29812,
"s": 29714,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29830,
"s": 29812,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29865,
"s": 29830,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29897,
"s": 29865,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29919,
"s": 29897,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29961,
"s": 29919,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29991,
"s": 29961,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 30017,
"s": 29991,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30046,
"s": 30017,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30090,
"s": 30046,
"text": "Reading and Writing to text files in Python"
}
] |
How to use Rating Component in ReactJS ? - GeeksforGeeks
|
13 Apr, 2021
Rating Component helps capture the user feedback in form of rating. With the help of this feature, users can also rate the products they have purchased. Material UI for React has this component available for us, and it is very easy to integrate. We can use the following approach in ReactJS to use the Rating Component.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui module using the following command:npm install @material-ui/core
npm install @material-ui/lab
Step 3: After creating the ReactJS application, Install the material-ui module using the following command:
npm install @material-ui/core
npm install @material-ui/lab
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import Rating from '@material-ui/lab/Rating';import Typography from '@material-ui/core/Typography';import Box from '@material-ui/core/Box'; export default function App() { const [ratingValue, setRatingValue] = React.useState(0); return ( <div style={{ display: 'block', padding: 30 }}> <h4>How to use Rating Component in ReactJS?</h4> <Box component="fieldset" mb={3} borderColor="transparent"> <Typography component="legend"> Please Rate our app </Typography> <Rating name="Rating Label" value={ratingValue} onChange={(event, newValue) => { setRatingValue(newValue); }} /> </Box> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://material-ui.com/components/rating/
Material-UI
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 26391,
"s": 26071,
"text": "Rating Component helps capture the user feedback in form of rating. With the help of this feature, users can also rate the products they have purchased. Material UI for React has this component available for us, and it is very easy to integrate. We can use the following approach in ReactJS to use the Rating Component."
},
{
"code": null,
"e": 26441,
"s": 26391,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 26536,
"s": 26441,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 26600,
"s": 26536,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 26632,
"s": 26600,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 26745,
"s": 26632,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 26845,
"s": 26745,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 26859,
"s": 26845,
"text": "cd foldername"
},
{
"code": null,
"e": 27025,
"s": 26859,
"text": "Step 3: After creating the ReactJS application, Install the material-ui module using the following command:npm install @material-ui/core\nnpm install @material-ui/lab"
},
{
"code": null,
"e": 27133,
"s": 27025,
"text": "Step 3: After creating the ReactJS application, Install the material-ui module using the following command:"
},
{
"code": null,
"e": 27192,
"s": 27133,
"text": "npm install @material-ui/core\nnpm install @material-ui/lab"
},
{
"code": null,
"e": 27244,
"s": 27192,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 27262,
"s": 27244,
"text": "Project Structure"
},
{
"code": null,
"e": 27392,
"s": 27262,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 27399,
"s": 27392,
"text": "App.js"
},
{
"code": "import React from 'react';import Rating from '@material-ui/lab/Rating';import Typography from '@material-ui/core/Typography';import Box from '@material-ui/core/Box'; export default function App() { const [ratingValue, setRatingValue] = React.useState(0); return ( <div style={{ display: 'block', padding: 30 }}> <h4>How to use Rating Component in ReactJS?</h4> <Box component=\"fieldset\" mb={3} borderColor=\"transparent\"> <Typography component=\"legend\"> Please Rate our app </Typography> <Rating name=\"Rating Label\" value={ratingValue} onChange={(event, newValue) => { setRatingValue(newValue); }} /> </Box> </div> );}",
"e": 28132,
"s": 27399,
"text": null
},
{
"code": null,
"e": 28245,
"s": 28132,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28255,
"s": 28245,
"text": "npm start"
},
{
"code": null,
"e": 28354,
"s": 28255,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 28408,
"s": 28354,
"text": "Reference: https://material-ui.com/components/rating/"
},
{
"code": null,
"e": 28420,
"s": 28408,
"text": "Material-UI"
},
{
"code": null,
"e": 28428,
"s": 28420,
"text": "ReactJS"
},
{
"code": null,
"e": 28445,
"s": 28428,
"text": "Web Technologies"
},
{
"code": null,
"e": 28543,
"s": 28445,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28570,
"s": 28543,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 28612,
"s": 28570,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 28650,
"s": 28612,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 28685,
"s": 28650,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 28743,
"s": 28685,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 28783,
"s": 28743,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28816,
"s": 28783,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28861,
"s": 28816,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28911,
"s": 28861,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to disable tabs in Bootstrap ? - GeeksforGeeks
|
24 Jun, 2021
To disable a tab, we can remove the attribute : data-toggle=”tab” from the tab part enclosed under ‘a’ element. Further we can add the class .disabled to the parent list item element to make it look visually disabled. (like class=”disabled” inside list item)To show a case of disabling tabs, first, we go through an example with tabs enabled.
html
<ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#home">Algo</a></li> <li><a data-toggle="tab" href="#menu1">DS</a></li> <li><a data-toggle="tab" href="#menu2">Languages</a></li> <li><a data-toggle="tab" href="#menu3">Interview</a></li></ul>
And here is the unordered list section to demonstrate tab disabling, for a direct comparison:
html
<ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#home">Algo</a></li> <li><a href="#menu1">DS</a></li> <li class ="disabled"><a data-toggle="tab" href="#menu2">Languages</a></li> <li class="disabled"><a href="#menu3">Interview</a></li> </ul>
Considering the code for the toggle-able tabs above, below is an example of disabling one tab, making one tab visually disabled and both disabling a tab and making it look visually disabled: Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script></head> <body> <div class="container" style="color:green"> <h2>GeeksforGeeks</h2> <ul class="nav nav-tabs"> <li class="active"> <a data-toggle="tab" href="#home">Algo</a> </li> <li><a href="#menu1">DS</a></li> <li class="disabled"> <a data-toggle="tab" href="#menu2"> Languages </a> </li> <li class="disabled"> <a href="#menu3"> Interview </a> </li> </ul> <div class="tab-content"> <div id="home" class="tab-pane fade in active"> <h3>Algo</h3> <p>Here you can find all sorts of Algorithms with explanation and problems based on them! </p> </div> <div id="menu1" class="tab-pane fade"> <h3>DS</h3> <p>Here you can find all sorts of Data Structures explained and problems wherein we need to use those!</p> </div> <div id="menu2" class="tab-pane fade"> <h3>Languages</h3> <p>Here you can find all different scripting/query languages! </p> </div> <div id="menu3" class="tab-pane fade"> <h3>Interview</h3> <p>Here, you can find 'Interview Experiences' for all the companies! </p> </div> </div> </div> </body> </html>
Output:
In the code for disabling tabs, we did not alter the first list item (with text ‘Algo’), (to show a case of tabs enabled) and hence it is both clickable/toggle-able and appears without any visual hindrance.For the second list item (with text ‘DS’) we removed the ‘ data-toggle=”tab” ‘ part and hence this tab becomes non-toggle-able and nothing happens if we try to click it.For the third list item (with text ‘Languages’) we add class .disabled (class=”disabled”) to our list item so that it becomes visually disabled, i.e. shows a disabled icon when we hover our cursor over it. However, note that since ‘ data-toggle=”tab” ‘part inside ‘a’ is still there, this tab is toggle-able and can be clicked. For the fourth list item (with text ‘Interview’) we add disabled class inside list item and also remove the ‘ data-toggle=”tab” ‘ part. This makes the tab both non-toggle-able/click-disabled (when we click) and visually disabled. This would be the case of making it completely disabled.
abhishek0719kadiyan
Bootstrap-Misc
Picked
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
How to change the background color of the active nav-item?
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 25679,
"s": 25651,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 26024,
"s": 25679,
"text": "To disable a tab, we can remove the attribute : data-toggle=”tab” from the tab part enclosed under ‘a’ element. Further we can add the class .disabled to the parent list item element to make it look visually disabled. (like class=”disabled” inside list item)To show a case of disabling tabs, first, we go through an example with tabs enabled. "
},
{
"code": null,
"e": 26029,
"s": 26024,
"text": "html"
},
{
"code": "<ul class=\"nav nav-tabs\"> <li class=\"active\"><a data-toggle=\"tab\" href=\"#home\">Algo</a></li> <li><a data-toggle=\"tab\" href=\"#menu1\">DS</a></li> <li><a data-toggle=\"tab\" href=\"#menu2\">Languages</a></li> <li><a data-toggle=\"tab\" href=\"#menu3\">Interview</a></li></ul>",
"e": 26306,
"s": 26029,
"text": null
},
{
"code": null,
"e": 26402,
"s": 26306,
"text": "And here is the unordered list section to demonstrate tab disabling, for a direct comparison: "
},
{
"code": null,
"e": 26407,
"s": 26402,
"text": "html"
},
{
"code": "<ul class=\"nav nav-tabs\"> <li class=\"active\"><a data-toggle=\"tab\" href=\"#home\">Algo</a></li> <li><a href=\"#menu1\">DS</a></li> <li class =\"disabled\"><a data-toggle=\"tab\" href=\"#menu2\">Languages</a></li> <li class=\"disabled\"><a href=\"#menu3\">Interview</a></li> </ul>",
"e": 26685,
"s": 26407,
"text": null
},
{
"code": null,
"e": 26887,
"s": 26685,
"text": "Considering the code for the toggle-able tabs above, below is an example of disabling one tab, making one tab visually disabled and both disabling a tab and making it look visually disabled: Example: "
},
{
"code": null,
"e": 26892,
"s": 26887,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\" style=\"color:green\"> <h2>GeeksforGeeks</h2> <ul class=\"nav nav-tabs\"> <li class=\"active\"> <a data-toggle=\"tab\" href=\"#home\">Algo</a> </li> <li><a href=\"#menu1\">DS</a></li> <li class=\"disabled\"> <a data-toggle=\"tab\" href=\"#menu2\"> Languages </a> </li> <li class=\"disabled\"> <a href=\"#menu3\"> Interview </a> </li> </ul> <div class=\"tab-content\"> <div id=\"home\" class=\"tab-pane fade in active\"> <h3>Algo</h3> <p>Here you can find all sorts of Algorithms with explanation and problems based on them! </p> </div> <div id=\"menu1\" class=\"tab-pane fade\"> <h3>DS</h3> <p>Here you can find all sorts of Data Structures explained and problems wherein we need to use those!</p> </div> <div id=\"menu2\" class=\"tab-pane fade\"> <h3>Languages</h3> <p>Here you can find all different scripting/query languages! </p> </div> <div id=\"menu3\" class=\"tab-pane fade\"> <h3>Interview</h3> <p>Here, you can find 'Interview Experiences' for all the companies! </p> </div> </div> </div> </body> </html>",
"e": 28821,
"s": 26892,
"text": null
},
{
"code": null,
"e": 28831,
"s": 28821,
"text": "Output: "
},
{
"code": null,
"e": 29822,
"s": 28831,
"text": "In the code for disabling tabs, we did not alter the first list item (with text ‘Algo’), (to show a case of tabs enabled) and hence it is both clickable/toggle-able and appears without any visual hindrance.For the second list item (with text ‘DS’) we removed the ‘ data-toggle=”tab” ‘ part and hence this tab becomes non-toggle-able and nothing happens if we try to click it.For the third list item (with text ‘Languages’) we add class .disabled (class=”disabled”) to our list item so that it becomes visually disabled, i.e. shows a disabled icon when we hover our cursor over it. However, note that since ‘ data-toggle=”tab” ‘part inside ‘a’ is still there, this tab is toggle-able and can be clicked. For the fourth list item (with text ‘Interview’) we add disabled class inside list item and also remove the ‘ data-toggle=”tab” ‘ part. This makes the tab both non-toggle-able/click-disabled (when we click) and visually disabled. This would be the case of making it completely disabled. "
},
{
"code": null,
"e": 29842,
"s": 29822,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 29857,
"s": 29842,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 29864,
"s": 29857,
"text": "Picked"
},
{
"code": null,
"e": 29874,
"s": 29864,
"text": "Bootstrap"
},
{
"code": null,
"e": 29891,
"s": 29874,
"text": "Web Technologies"
},
{
"code": null,
"e": 29989,
"s": 29891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30030,
"s": 29989,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 30071,
"s": 30030,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 30134,
"s": 30071,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 30167,
"s": 30134,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 30226,
"s": 30167,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 30266,
"s": 30226,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30299,
"s": 30266,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30344,
"s": 30299,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30387,
"s": 30344,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
TypeScript Tuples - GeeksforGeeks
|
11 Apr, 2022
As we know array consists of values of homogeneous (same) types but sometimes when we need to store a collection of a different types values in a single variable, then we will go with Tuples. They are just like structure in C programming and can also be passed as parameters in a function call. Tuples may be one or more than one types of data (like number with string or string with number and so on).
To denote a multi-dimensional coordinate system the term used is tuple in abstract mathematics.
In JavaScript we doesn’t have tuples as data types, but in typescript Tuples facility is available.
Syntax
let tuple_name = [val1, val2, val3, ...val n];
Example:
let arrTuple = [501, "welcome", 505, "Mohan"];
console.log(arrTuple);
Output:
[501, ‘welcome’, 105, ‘Mohan’]
Declaration and initialization of a tuple separately by initially declaring the tuple as an empty tuple in Typescript. Example:
let arrTuple = [];
arrTuple[0] = 501
arrTuple[1] = 506
Accessing tuple Elements With the help of index basis we can read or access the fields of a tuples, which is the same as an array. An index starts from zero too.
Example:
var employee: [number, string] = [1, "Steve"];
employee[0]; // returns 1
employee[1]; / return Steve
Output:
1 Steve
We can declare heterogenous datatypes in tuples like: number and string simultaneously.
Example
let empTuple = ["Vivek Singh", 22, "Honesty"];
console.log("Name of the Employee is : "+empTuple [0]);
console.log("Age of the Employee is : "+empTuple [1]);
console.log(empTuple [0]+" is workinging in "+empTuple [2]);
Output:
Name of the Employee is : Vivek Singh Age of the Employee is : 22 Vivek Singh is workinging in Microsoft
Operations on Tuple A tuple has two operations:
Push()
Pop()
Push() To add an element to the tuple with push operation. Example
var employee: [number, string] = [1, "Steve"];
employee.push(2, "Bill");
console.log(employee);
Output:
[1, ‘Steve’, 2, ‘Bill’]
This type of declaration is allowed in tuples because we are adding number and string values to the tuple and they are valid for the employee tuple.
Example
let empTuple = ["Vivek Singh", 22, "Honesty"];
console.log("Items: "+empTuple); // here we print tuple elements
empTuple.push(10001); // append value to the tuple
console.log("Length of Tuple Items after push: "+empTuple.length); // After pushing elements in tuples calculate length of tuples.
console.log("Items: "+empTuple);
Output:
Items: Vivek Singh, 22, Honesty Length of Tuple Items after push: 4 Items: Vivek Singh, 22, Honesty, 10001
To add an element to the tuple with push operation.
Example
let empTuple = ["Mohit Singh", 25, "geeksforgeeks", 10001];
console.log("Items: "+empTuple); // here we print tuple elements
empTuple.pop(); // removed value to the tuple
console.log("Length of Tuple Items after pop: "+empTuple.length); After pushing elements in tuples calculate length of tuples.
console.log("Items: "+empTuple);
Output:
Items: Mohit Singh, 25, geeksforgeeks, 10001 Length of Tuple Items after pop: 3 Items: Mohit Singh, 25, geeksforgeeks
Update or Modify the Tuple Elements We need to use the index of the fields and assignment operator for modifying the fields of tuple. It can be shown in the following example. Example
let empTuple = ["Ganesh Singh", 25, "TCS"];
empTuple[1] = 60;
console.log("Name of the Employee is: "+empTuple [0]);
console.log("Age of the Employee is: "+empTuple [1]);
console.log(empTuple [0]+" is workinging in "+empTuple [2]);
Output:
Name of the Employee is: Ganesh Singh Age of the Employee is: 60 Ganesh Singh is workinging in TCS
Clear the fields of a Tuple Fields could be cleared but we cannot delete the tuple variables. To clear the fields of a tuple, assign it with an empty tuple field set as shown below:
let empTuple = ["Rohit Sharma", 25, "JavaTpoint"];
empTuple = [];
console.log(empTuple);
Output:
[]
In TypeScript, To break up the structure of an entity by destructuring.
Example
let empTuple = ["Rohit Sharma", 25, "JavaTpoint"];
let [emp, student] = empTuple;
console.log(emp);
console.log(student);
Rohit Sharma 25
Passing Tuple to Functions
//Tuple Declaration
let empTuple = ["JavaTpoint", 101, "Abhishek"];
//Passing tuples in function
function display(tuple_values:any[]) {
for(let i = 0;i<empTuple.length;i++) {
console.log(empTuple[i]);
}
}
//Calling tuple in function
display(empTuple);
JavaTpoint 101 Abhishek
Following shown is the code snippet which will help us to understand Tuple creation in TypeScript:-
Example:
Javascript
let student_details : [number, string, string] = [1 , "Aman" , "CSE"];student_details.push(2 , "Ram" , "CSE"); console.log(student_details); // This code is contributed by Aman Singla...
Output:
[ 1, 'Aman', 'CSE', 2, 'Ram', 'CSE' ]
amansingla
TypeScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
File uploading in React.js
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 25701,
"s": 25673,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 26104,
"s": 25701,
"text": "As we know array consists of values of homogeneous (same) types but sometimes when we need to store a collection of a different types values in a single variable, then we will go with Tuples. They are just like structure in C programming and can also be passed as parameters in a function call. Tuples may be one or more than one types of data (like number with string or string with number and so on)."
},
{
"code": null,
"e": 26200,
"s": 26104,
"text": "To denote a multi-dimensional coordinate system the term used is tuple in abstract mathematics."
},
{
"code": null,
"e": 26300,
"s": 26200,
"text": "In JavaScript we doesn’t have tuples as data types, but in typescript Tuples facility is available."
},
{
"code": null,
"e": 26307,
"s": 26300,
"text": "Syntax"
},
{
"code": null,
"e": 26356,
"s": 26307,
"text": "let tuple_name = [val1, val2, val3, ...val n]; "
},
{
"code": null,
"e": 26365,
"s": 26356,
"text": "Example:"
},
{
"code": null,
"e": 26437,
"s": 26365,
"text": "let arrTuple = [501, \"welcome\", 505, \"Mohan\"]; \nconsole.log(arrTuple);"
},
{
"code": null,
"e": 26445,
"s": 26437,
"text": "Output:"
},
{
"code": null,
"e": 26476,
"s": 26445,
"text": "[501, ‘welcome’, 105, ‘Mohan’]"
},
{
"code": null,
"e": 26604,
"s": 26476,
"text": "Declaration and initialization of a tuple separately by initially declaring the tuple as an empty tuple in Typescript. Example:"
},
{
"code": null,
"e": 26665,
"s": 26604,
"text": "let arrTuple = []; \narrTuple[0] = 501 \narrTuple[1] = 506 "
},
{
"code": null,
"e": 26828,
"s": 26665,
"text": "Accessing tuple Elements With the help of index basis we can read or access the fields of a tuples, which is the same as an array. An index starts from zero too. "
},
{
"code": null,
"e": 26837,
"s": 26828,
"text": "Example:"
},
{
"code": null,
"e": 26938,
"s": 26837,
"text": "var employee: [number, string] = [1, \"Steve\"];\nemployee[0]; // returns 1\nemployee[1]; / return Steve"
},
{
"code": null,
"e": 26946,
"s": 26938,
"text": "Output:"
},
{
"code": null,
"e": 26954,
"s": 26946,
"text": "1 Steve"
},
{
"code": null,
"e": 27042,
"s": 26954,
"text": "We can declare heterogenous datatypes in tuples like: number and string simultaneously."
},
{
"code": null,
"e": 27051,
"s": 27042,
"text": " Example"
},
{
"code": null,
"e": 27278,
"s": 27051,
"text": "let empTuple = [\"Vivek Singh\", 22, \"Honesty\"]; \nconsole.log(\"Name of the Employee is : \"+empTuple [0]); \nconsole.log(\"Age of the Employee is : \"+empTuple [1]); \nconsole.log(empTuple [0]+\" is workinging in \"+empTuple [2]); "
},
{
"code": null,
"e": 27286,
"s": 27278,
"text": "Output:"
},
{
"code": null,
"e": 27391,
"s": 27286,
"text": "Name of the Employee is : Vivek Singh Age of the Employee is : 22 Vivek Singh is workinging in Microsoft"
},
{
"code": null,
"e": 27439,
"s": 27391,
"text": "Operations on Tuple A tuple has two operations:"
},
{
"code": null,
"e": 27446,
"s": 27439,
"text": "Push()"
},
{
"code": null,
"e": 27452,
"s": 27446,
"text": "Pop()"
},
{
"code": null,
"e": 27519,
"s": 27452,
"text": "Push() To add an element to the tuple with push operation. Example"
},
{
"code": null,
"e": 27617,
"s": 27519,
"text": "var employee: [number, string] = [1, \"Steve\"];\nemployee.push(2, \"Bill\"); \nconsole.log(employee); "
},
{
"code": null,
"e": 27625,
"s": 27617,
"text": "Output:"
},
{
"code": null,
"e": 27649,
"s": 27625,
"text": "[1, ‘Steve’, 2, ‘Bill’]"
},
{
"code": null,
"e": 27799,
"s": 27649,
"text": "This type of declaration is allowed in tuples because we are adding number and string values to the tuple and they are valid for the employee tuple. "
},
{
"code": null,
"e": 27807,
"s": 27799,
"text": "Example"
},
{
"code": null,
"e": 28146,
"s": 27807,
"text": "let empTuple = [\"Vivek Singh\", 22, \"Honesty\"]; \nconsole.log(\"Items: \"+empTuple); // here we print tuple elements\nempTuple.push(10001); // append value to the tuple \nconsole.log(\"Length of Tuple Items after push: \"+empTuple.length); // After pushing elements in tuples calculate length of tuples.\nconsole.log(\"Items: \"+empTuple); "
},
{
"code": null,
"e": 28154,
"s": 28146,
"text": "Output:"
},
{
"code": null,
"e": 28261,
"s": 28154,
"text": "Items: Vivek Singh, 22, Honesty Length of Tuple Items after push: 4 Items: Vivek Singh, 22, Honesty, 10001"
},
{
"code": null,
"e": 28314,
"s": 28261,
"text": "To add an element to the tuple with push operation. "
},
{
"code": null,
"e": 28322,
"s": 28314,
"text": "Example"
},
{
"code": null,
"e": 28665,
"s": 28322,
"text": "let empTuple = [\"Mohit Singh\", 25, \"geeksforgeeks\", 10001]; \nconsole.log(\"Items: \"+empTuple); // here we print tuple elements\nempTuple.pop(); // removed value to the tuple \nconsole.log(\"Length of Tuple Items after pop: \"+empTuple.length); After pushing elements in tuples calculate length of tuples.\nconsole.log(\"Items: \"+empTuple); "
},
{
"code": null,
"e": 28673,
"s": 28665,
"text": "Output:"
},
{
"code": null,
"e": 28791,
"s": 28673,
"text": "Items: Mohit Singh, 25, geeksforgeeks, 10001 Length of Tuple Items after pop: 3 Items: Mohit Singh, 25, geeksforgeeks"
},
{
"code": null,
"e": 28975,
"s": 28791,
"text": "Update or Modify the Tuple Elements We need to use the index of the fields and assignment operator for modifying the fields of tuple. It can be shown in the following example. Example"
},
{
"code": null,
"e": 29216,
"s": 28975,
"text": "let empTuple = [\"Ganesh Singh\", 25, \"TCS\"]; \nempTuple[1] = 60; \nconsole.log(\"Name of the Employee is: \"+empTuple [0]); \nconsole.log(\"Age of the Employee is: \"+empTuple [1]); \nconsole.log(empTuple [0]+\" is workinging in \"+empTuple [2]); "
},
{
"code": null,
"e": 29224,
"s": 29216,
"text": "Output:"
},
{
"code": null,
"e": 29323,
"s": 29224,
"text": "Name of the Employee is: Ganesh Singh Age of the Employee is: 60 Ganesh Singh is workinging in TCS"
},
{
"code": null,
"e": 29505,
"s": 29323,
"text": "Clear the fields of a Tuple Fields could be cleared but we cannot delete the tuple variables. To clear the fields of a tuple, assign it with an empty tuple field set as shown below:"
},
{
"code": null,
"e": 29599,
"s": 29505,
"text": "let empTuple = [\"Rohit Sharma\", 25, \"JavaTpoint\"]; \nempTuple = []; \nconsole.log(empTuple); "
},
{
"code": null,
"e": 29607,
"s": 29599,
"text": "Output:"
},
{
"code": null,
"e": 29610,
"s": 29607,
"text": "[]"
},
{
"code": null,
"e": 29683,
"s": 29610,
"text": "In TypeScript, To break up the structure of an entity by destructuring. "
},
{
"code": null,
"e": 29691,
"s": 29683,
"text": "Example"
},
{
"code": null,
"e": 29821,
"s": 29691,
"text": "let empTuple = [\"Rohit Sharma\", 25, \"JavaTpoint\"]; \nlet [emp, student] = empTuple; \nconsole.log(emp); \nconsole.log(student); "
},
{
"code": null,
"e": 29837,
"s": 29821,
"text": "Rohit Sharma 25"
},
{
"code": null,
"e": 29864,
"s": 29837,
"text": "Passing Tuple to Functions"
},
{
"code": null,
"e": 30166,
"s": 29864,
"text": "//Tuple Declaration \nlet empTuple = [\"JavaTpoint\", 101, \"Abhishek\"]; \n//Passing tuples in function \nfunction display(tuple_values:any[]) { \n for(let i = 0;i<empTuple.length;i++) { \n console.log(empTuple[i]); \n } \n} \n//Calling tuple in function \ndisplay(empTuple);"
},
{
"code": null,
"e": 30190,
"s": 30166,
"text": "JavaTpoint 101 Abhishek"
},
{
"code": null,
"e": 30290,
"s": 30190,
"text": "Following shown is the code snippet which will help us to understand Tuple creation in TypeScript:-"
},
{
"code": null,
"e": 30299,
"s": 30290,
"text": "Example:"
},
{
"code": null,
"e": 30310,
"s": 30299,
"text": "Javascript"
},
{
"code": "let student_details : [number, string, string] = [1 , \"Aman\" , \"CSE\"];student_details.push(2 , \"Ram\" , \"CSE\"); console.log(student_details); // This code is contributed by Aman Singla...",
"e": 30497,
"s": 30310,
"text": null
},
{
"code": null,
"e": 30505,
"s": 30497,
"text": "Output:"
},
{
"code": null,
"e": 30543,
"s": 30505,
"text": "[ 1, 'Aman', 'CSE', 2, 'Ram', 'CSE' ]"
},
{
"code": null,
"e": 30554,
"s": 30543,
"text": "amansingla"
},
{
"code": null,
"e": 30565,
"s": 30554,
"text": "TypeScript"
},
{
"code": null,
"e": 30582,
"s": 30565,
"text": "Web Technologies"
},
{
"code": null,
"e": 30680,
"s": 30582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30720,
"s": 30680,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30765,
"s": 30720,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30808,
"s": 30765,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30869,
"s": 30808,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30927,
"s": 30869,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 30999,
"s": 30927,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 31032,
"s": 30999,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 31092,
"s": 31032,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 31119,
"s": 31092,
"text": "File uploading in React.js"
}
] |
Find maximum distance between any city and station - GeeksforGeeks
|
14 May, 2021
Given the number of cities n numbered from 0 to n-1 and the cities in which stations are located, the task is to find the maximum distance between any city and its nearest station. Note that the cities with stations can be given in any order.Examples:
Input: numOfCities = 6, stations = [1, 4]
Output: 1
Input: numOfCities = 6, stations = [3]
Output: 3
Input: numOfCities = 6, stations = [3, 1]
Output: 2
The below figure represents the first example containing 6 cities and the cities with stations highlighted with green color. In this case, the farthest cities from their nearest stations are 0, 2, 3, and 5 each at a distance of 1. Hence, the maximum distance is 1.In the second example, the farthest city from its nearest station is 0 which is at a distance of 3. Hence, the maximum distance is 3.In the third example, the farthest city from its nearest station is 5 which is at a distance of 2. Hence, the maximum distance is 2.
The below figure represents the first example containing 6 cities and the cities with stations highlighted with green color. In this case, the farthest cities from their nearest stations are 0, 2, 3, and 5 each at a distance of 1. Hence, the maximum distance is 1.
In the second example, the farthest city from its nearest station is 0 which is at a distance of 3. Hence, the maximum distance is 3.
In the third example, the farthest city from its nearest station is 5 which is at a distance of 2. Hence, the maximum distance is 2.
Approach: There are three possible cases in this problem:
When the farthest city is between two stations.When the farthest city is on the left side of the first station.When the farthest city is on the right side of the last station.
When the farthest city is between two stations.
When the farthest city is on the left side of the first station.
When the farthest city is on the right side of the last station.
Below is the algorithm to solve the above problem:
Initialize a boolean array of size n (number of cities) with False. Then mark the values of cities with stations as True
Initialize a variable dist with 0. Initialize another variable maxDist with a value that is equal to the first city with the station (used for case 2).
Start looping through all the cities one by one.
If the current city has a station, then assign the maximum of (dist+1)//2 and maxDist to maxDist (used for case 1). Also, assign 0 to dist.
Else, increment dist.
In the end, return the maximum of dist and maxDist (used for case 3).
Below is the implementation of the above approach:
C++
Java
Python
C#
PHP
Javascript
// C++ program to calculate the maximum // distance between any city// and its nearest station#include<bits/stdc++.h> using namespace std; // Function to calculate the maximum // distance between any city and its nearest stationint findMaxDistance(int numOfCities,int station[],int n){ // Initialize boolean list bool hasStation[numOfCities + 1] = {false}; // Assign True to cities containing station for (int city = 0; city < n; city++) { hasStation[station[city]] = true; } int dist = 0; int maxDist = INT_MAX; for(int i = 0; i < n; i++) { maxDist = min(station[i],maxDist); } for (int city = 0; city < numOfCities; city++) { if (hasStation[city] == true) { maxDist = max((dist + 1) / 2, maxDist); dist = 0; } else dist += 1; } return max(maxDist, dist);} //Driver codeint main(){ int numOfCities = 6; int station[] = {3, 1}; int n = sizeof(station)/sizeof(station[0]); cout << "Max Distance:" << findMaxDistance(numOfCities, station, n);} //This code is contributed by Mohit Kumar 29
// Java program to calculate the maximum // distance between any city// and its nearest stationimport java.util.*; class GFG{ // Function to calculate the maximum // distance between any city and its nearest stationstatic int findMaxDistance(int numOfCities, int station[],int n){ // Initialize boolean list boolean hasStation[] = new boolean[numOfCities + 1]; // Assign True to cities containing station for (int city = 0; city < n; city++) { hasStation[station[city]] = true; } int dist = 0; int maxDist = Integer.MAX_VALUE; for(int i = 0; i < n; i++) { maxDist = Math.min(station[i],maxDist); } for (int city = 0; city < numOfCities; city++) { if (hasStation[city] == true) { maxDist = Math.max((dist + 1) / 2, maxDist); dist = 0; } else dist += 1; } return Math.max(maxDist, dist);} //Driver codepublic static void main(String args[]){ int numOfCities = 6; int station[] = {3, 1}; int n = station.length; System.out.println("Max Distance:"+ findMaxDistance(numOfCities,station, n));}} // This code is contributed by// Surendra_Gnagwar
# Python3 code to calculate the maximum # distance between any city and its nearest station # Function to calculate the maximum # distance between any city and its nearest stationdef findMaxDistance(numOfCities, station): # Initialize boolean list hasStation = [False] * numOfCities # Assign True to cities containing station for city in station: hasStation[city] = True dist, maxDist = 0, min(station) for city in range(numOfCities): if hasStation[city] == True: maxDist = max((dist + 1) // 2, maxDist) dist = 0 else: dist += 1 return max(maxDist, dist) numOfCities = 6station = [3, 1]print("Max Distance:", findMaxDistance(numOfCities, station))
// C# program to calculate the maximum // distance between any city // and its nearest station using System; class GFG { // Function to calculate the maximum // distance between any city and its nearest station static int findMaxDistance(int numOfCities, int []station,int n) { // Initialize boolean list bool []hasStation = new bool[numOfCities + 1]; // Assign True to cities containing station for (int city = 0; city < n; city++) { hasStation[station[city]] = true; } int dist = 0; int maxDist = int.MaxValue; for(int i = 0; i < n; i++) { maxDist = Math.Min(station[i],maxDist); } for (int city = 0; city < numOfCities; city++) { if (hasStation[city] == true) { maxDist = Math.Max((dist + 1) / 2, maxDist); dist = 0; } else dist += 1; } return Math.Max(maxDist, dist); } // Driver code public static void Main(String []args) { int numOfCities = 6; int []station = {3, 1}; int n = station.Length; Console.WriteLine("Max Distance:"+ findMaxDistance(numOfCities,station, n)); } } // This code has been contributed by 29AjayKumar
<?php// PHP program to calculate the maximum // distance between any city// and its nearest station // Function to calculate the maximum // distance between any city and // its nearest stationfunction findMaxDistance($numOfCities, $station, $n){ // Initialize boolean list $hasStation = array_fill(0, $numOfCities + 1, false); // Assign True to cities containing station for ($city = 0; $city < $n; $city++) { $hasStation[$station[$city]] = true; } $dist = 0; $maxDist = PHP_INT_MAX; for($i = 0; $i < $n; $i++) { $maxDist = min($station[$i], $maxDist); } for ($city = 0; $city < $numOfCities; $city++) { if ($hasStation[$city] == true) { $maxDist = max((int)(($dist + 1) / 2), $maxDist); $dist = 0; } else $dist += 1; } return max($maxDist, $dist);} // Driver code$numOfCities = 6;$station = array(3, 1);$n = count($station); echo "Max Distance: ".findMaxDistance($numOfCities, $station, $n); // This code is contributed by mits?>
<script> // Javascript program to calculate the maximum // distance between any city// and its nearest station // Function to calculate the maximum // distance between any city and its nearest stationfunction findMaxDistance(numOfCities,station,n){ // Initialize boolean list var hasStation = Array(numOfCities+1).fill(false); // Assign True to cities containing station for (var city = 0; city < n; city++) { hasStation[station[city]] = true; } var dist = 0; var maxDist = 1000000000; for(var i = 0; i < n; i++) { maxDist = Math.min(station[i],maxDist); } for (var city = 0; city < numOfCities; city++) { if (hasStation[city] == true) { maxDist = Math.max((dist + 1) / 2, maxDist); dist = 0; } else dist += 1; } return Math.max(maxDist, dist);} //Driver codevar numOfCities = 6;var station = [3, 1];var n = station.length;document.write( "Max Distance: " + findMaxDistance(numOfCities, station, n)); </script>
Max Distance: 2
Time Complexity: O(n) Space Complexity: O(n)
mohit kumar 29
SURENDRA_GANGWAR
29AjayKumar
Mithun Kumar
rutvik_56
Technical Scripter 2018
Competitive Programming
Greedy
Hash
Mathematical
Technical Scripter
Hash
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Prefix Sum Array - Implementation and Applications in Competitive Programming
Ordered Set and GNU C++ PBDS
Bits manipulation (Important tactics)
What is Competitive Programming and How to Prepare for It?
7 Best Coding Challenge Websites in 2020
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Program for array rotation
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 26279,
"s": 26251,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 26533,
"s": 26279,
"text": "Given the number of cities n numbered from 0 to n-1 and the cities in which stations are located, the task is to find the maximum distance between any city and its nearest station. Note that the cities with stations can be given in any order.Examples: "
},
{
"code": null,
"e": 26688,
"s": 26533,
"text": "Input: numOfCities = 6, stations = [1, 4]\nOutput: 1\n\nInput: numOfCities = 6, stations = [3]\nOutput: 3\n\nInput: numOfCities = 6, stations = [3, 1]\nOutput: 2"
},
{
"code": null,
"e": 27220,
"s": 26690,
"text": "The below figure represents the first example containing 6 cities and the cities with stations highlighted with green color. In this case, the farthest cities from their nearest stations are 0, 2, 3, and 5 each at a distance of 1. Hence, the maximum distance is 1.In the second example, the farthest city from its nearest station is 0 which is at a distance of 3. Hence, the maximum distance is 3.In the third example, the farthest city from its nearest station is 5 which is at a distance of 2. Hence, the maximum distance is 2."
},
{
"code": null,
"e": 27485,
"s": 27220,
"text": "The below figure represents the first example containing 6 cities and the cities with stations highlighted with green color. In this case, the farthest cities from their nearest stations are 0, 2, 3, and 5 each at a distance of 1. Hence, the maximum distance is 1."
},
{
"code": null,
"e": 27619,
"s": 27485,
"text": "In the second example, the farthest city from its nearest station is 0 which is at a distance of 3. Hence, the maximum distance is 3."
},
{
"code": null,
"e": 27752,
"s": 27619,
"text": "In the third example, the farthest city from its nearest station is 5 which is at a distance of 2. Hence, the maximum distance is 2."
},
{
"code": null,
"e": 27811,
"s": 27752,
"text": "Approach: There are three possible cases in this problem: "
},
{
"code": null,
"e": 27987,
"s": 27811,
"text": "When the farthest city is between two stations.When the farthest city is on the left side of the first station.When the farthest city is on the right side of the last station."
},
{
"code": null,
"e": 28035,
"s": 27987,
"text": "When the farthest city is between two stations."
},
{
"code": null,
"e": 28100,
"s": 28035,
"text": "When the farthest city is on the left side of the first station."
},
{
"code": null,
"e": 28165,
"s": 28100,
"text": "When the farthest city is on the right side of the last station."
},
{
"code": null,
"e": 28217,
"s": 28165,
"text": "Below is the algorithm to solve the above problem: "
},
{
"code": null,
"e": 28338,
"s": 28217,
"text": "Initialize a boolean array of size n (number of cities) with False. Then mark the values of cities with stations as True"
},
{
"code": null,
"e": 28490,
"s": 28338,
"text": "Initialize a variable dist with 0. Initialize another variable maxDist with a value that is equal to the first city with the station (used for case 2)."
},
{
"code": null,
"e": 28539,
"s": 28490,
"text": "Start looping through all the cities one by one."
},
{
"code": null,
"e": 28679,
"s": 28539,
"text": "If the current city has a station, then assign the maximum of (dist+1)//2 and maxDist to maxDist (used for case 1). Also, assign 0 to dist."
},
{
"code": null,
"e": 28701,
"s": 28679,
"text": "Else, increment dist."
},
{
"code": null,
"e": 28771,
"s": 28701,
"text": "In the end, return the maximum of dist and maxDist (used for case 3)."
},
{
"code": null,
"e": 28824,
"s": 28771,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28828,
"s": 28824,
"text": "C++"
},
{
"code": null,
"e": 28833,
"s": 28828,
"text": "Java"
},
{
"code": null,
"e": 28840,
"s": 28833,
"text": "Python"
},
{
"code": null,
"e": 28843,
"s": 28840,
"text": "C#"
},
{
"code": null,
"e": 28847,
"s": 28843,
"text": "PHP"
},
{
"code": null,
"e": 28858,
"s": 28847,
"text": "Javascript"
},
{
"code": "// C++ program to calculate the maximum // distance between any city// and its nearest station#include<bits/stdc++.h> using namespace std; // Function to calculate the maximum // distance between any city and its nearest stationint findMaxDistance(int numOfCities,int station[],int n){ // Initialize boolean list bool hasStation[numOfCities + 1] = {false}; // Assign True to cities containing station for (int city = 0; city < n; city++) { hasStation[station[city]] = true; } int dist = 0; int maxDist = INT_MAX; for(int i = 0; i < n; i++) { maxDist = min(station[i],maxDist); } for (int city = 0; city < numOfCities; city++) { if (hasStation[city] == true) { maxDist = max((dist + 1) / 2, maxDist); dist = 0; } else dist += 1; } return max(maxDist, dist);} //Driver codeint main(){ int numOfCities = 6; int station[] = {3, 1}; int n = sizeof(station)/sizeof(station[0]); cout << \"Max Distance:\" << findMaxDistance(numOfCities, station, n);} //This code is contributed by Mohit Kumar 29",
"e": 30053,
"s": 28858,
"text": null
},
{
"code": "// Java program to calculate the maximum // distance between any city// and its nearest stationimport java.util.*; class GFG{ // Function to calculate the maximum // distance between any city and its nearest stationstatic int findMaxDistance(int numOfCities, int station[],int n){ // Initialize boolean list boolean hasStation[] = new boolean[numOfCities + 1]; // Assign True to cities containing station for (int city = 0; city < n; city++) { hasStation[station[city]] = true; } int dist = 0; int maxDist = Integer.MAX_VALUE; for(int i = 0; i < n; i++) { maxDist = Math.min(station[i],maxDist); } for (int city = 0; city < numOfCities; city++) { if (hasStation[city] == true) { maxDist = Math.max((dist + 1) / 2, maxDist); dist = 0; } else dist += 1; } return Math.max(maxDist, dist);} //Driver codepublic static void main(String args[]){ int numOfCities = 6; int station[] = {3, 1}; int n = station.length; System.out.println(\"Max Distance:\"+ findMaxDistance(numOfCities,station, n));}} // This code is contributed by// Surendra_Gnagwar",
"e": 31283,
"s": 30053,
"text": null
},
{
"code": "# Python3 code to calculate the maximum # distance between any city and its nearest station # Function to calculate the maximum # distance between any city and its nearest stationdef findMaxDistance(numOfCities, station): # Initialize boolean list hasStation = [False] * numOfCities # Assign True to cities containing station for city in station: hasStation[city] = True dist, maxDist = 0, min(station) for city in range(numOfCities): if hasStation[city] == True: maxDist = max((dist + 1) // 2, maxDist) dist = 0 else: dist += 1 return max(maxDist, dist) numOfCities = 6station = [3, 1]print(\"Max Distance:\", findMaxDistance(numOfCities, station))",
"e": 32058,
"s": 31283,
"text": null
},
{
"code": "// C# program to calculate the maximum // distance between any city // and its nearest station using System; class GFG { // Function to calculate the maximum // distance between any city and its nearest station static int findMaxDistance(int numOfCities, int []station,int n) { // Initialize boolean list bool []hasStation = new bool[numOfCities + 1]; // Assign True to cities containing station for (int city = 0; city < n; city++) { hasStation[station[city]] = true; } int dist = 0; int maxDist = int.MaxValue; for(int i = 0; i < n; i++) { maxDist = Math.Min(station[i],maxDist); } for (int city = 0; city < numOfCities; city++) { if (hasStation[city] == true) { maxDist = Math.Max((dist + 1) / 2, maxDist); dist = 0; } else dist += 1; } return Math.Max(maxDist, dist); } // Driver code public static void Main(String []args) { int numOfCities = 6; int []station = {3, 1}; int n = station.Length; Console.WriteLine(\"Max Distance:\"+ findMaxDistance(numOfCities,station, n)); } } // This code has been contributed by 29AjayKumar",
"e": 33311,
"s": 32058,
"text": null
},
{
"code": "<?php// PHP program to calculate the maximum // distance between any city// and its nearest station // Function to calculate the maximum // distance between any city and // its nearest stationfunction findMaxDistance($numOfCities, $station, $n){ // Initialize boolean list $hasStation = array_fill(0, $numOfCities + 1, false); // Assign True to cities containing station for ($city = 0; $city < $n; $city++) { $hasStation[$station[$city]] = true; } $dist = 0; $maxDist = PHP_INT_MAX; for($i = 0; $i < $n; $i++) { $maxDist = min($station[$i], $maxDist); } for ($city = 0; $city < $numOfCities; $city++) { if ($hasStation[$city] == true) { $maxDist = max((int)(($dist + 1) / 2), $maxDist); $dist = 0; } else $dist += 1; } return max($maxDist, $dist);} // Driver code$numOfCities = 6;$station = array(3, 1);$n = count($station); echo \"Max Distance: \".findMaxDistance($numOfCities, $station, $n); // This code is contributed by mits?>",
"e": 34541,
"s": 33311,
"text": null
},
{
"code": "<script> // Javascript program to calculate the maximum // distance between any city// and its nearest station // Function to calculate the maximum // distance between any city and its nearest stationfunction findMaxDistance(numOfCities,station,n){ // Initialize boolean list var hasStation = Array(numOfCities+1).fill(false); // Assign True to cities containing station for (var city = 0; city < n; city++) { hasStation[station[city]] = true; } var dist = 0; var maxDist = 1000000000; for(var i = 0; i < n; i++) { maxDist = Math.min(station[i],maxDist); } for (var city = 0; city < numOfCities; city++) { if (hasStation[city] == true) { maxDist = Math.max((dist + 1) / 2, maxDist); dist = 0; } else dist += 1; } return Math.max(maxDist, dist);} //Driver codevar numOfCities = 6;var station = [3, 1];var n = station.length;document.write( \"Max Distance: \" + findMaxDistance(numOfCities, station, n)); </script> ",
"e": 35647,
"s": 34541,
"text": null
},
{
"code": null,
"e": 35663,
"s": 35647,
"text": "Max Distance: 2"
},
{
"code": null,
"e": 35711,
"s": 35665,
"text": "Time Complexity: O(n) Space Complexity: O(n) "
},
{
"code": null,
"e": 35726,
"s": 35711,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 35743,
"s": 35726,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 35755,
"s": 35743,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35768,
"s": 35755,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 35778,
"s": 35768,
"text": "rutvik_56"
},
{
"code": null,
"e": 35802,
"s": 35778,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 35826,
"s": 35802,
"text": "Competitive Programming"
},
{
"code": null,
"e": 35833,
"s": 35826,
"text": "Greedy"
},
{
"code": null,
"e": 35838,
"s": 35833,
"text": "Hash"
},
{
"code": null,
"e": 35851,
"s": 35838,
"text": "Mathematical"
},
{
"code": null,
"e": 35870,
"s": 35851,
"text": "Technical Scripter"
},
{
"code": null,
"e": 35875,
"s": 35870,
"text": "Hash"
},
{
"code": null,
"e": 35882,
"s": 35875,
"text": "Greedy"
},
{
"code": null,
"e": 35895,
"s": 35882,
"text": "Mathematical"
},
{
"code": null,
"e": 35993,
"s": 35895,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36071,
"s": 35993,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 36100,
"s": 36071,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 36138,
"s": 36100,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 36197,
"s": 36138,
"text": "What is Competitive Programming and How to Prepare for It?"
},
{
"code": null,
"e": 36238,
"s": 36197,
"text": "7 Best Coding Challenge Websites in 2020"
},
{
"code": null,
"e": 36289,
"s": 36238,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 36347,
"s": 36289,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 36398,
"s": 36347,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 36425,
"s": 36398,
"text": "Program for array rotation"
}
] |
Program to multiply two Matrix by taking data from user - GeeksforGeeks
|
11 Aug, 2021
Given two matrices, the task is to multiply them. The size and number of elements of matrices are to be read from the keyboard.
Examples:
Input: row1 = 2, col1 = 2,
mat1[][] = {{1, 2},
{3, 4}},
row2 = 2, col2 = 2,
mat2[][] = {{1, 1},
{1, 1}}
Output: {{3, 3},
{7, 7}}
Input: row1 = 2, col1 = 2,
mat1[][] = {{2, 4},
{3, 4}}
row1 = 2, col1 = 2,
mat2[][] = {{1, 2},
{1, 3}}
Output: {{6, 16},
{7, 18}}
Program:
C
Java
Python3
// C program to multiply two matrices. #include <stdio.h> const int MAX = 100; // Function to print Matrixvoid printMatrix(int M[][MAX], int rowSize, int colSize){ for (int i = 0; i < rowSize; i++) { for (int j = 0; j < colSize; j++) printf("%d ", M[i][j]); printf("\n"); }} // Function to multiply two matrices A[][] and B[][]void multiplyMatrix(int row1, int col1, int A[][MAX], int row2, int col2, int B[][MAX]){ int i, j, k; // Matrix to store the result int C[MAX][MAX]; // Check if multiplication is Possible if (row2 != col1) { printf("Not Possible\n"); return; } // Multiply the two for (i = 0; i < row1; i++) { for (j = 0; j < col2; j++) { C[i][j] = 0; for (k = 0; k < row2; k++) C[i][j] += A[i][k] * B[k][j]; } } // Print the result printf("\nResultant Matrix: \n"); printMatrix(C, row1, col2);} // Driven Programint main(){ int row1, col1, row2, col2, i, j; int A[MAX][MAX], B[MAX][MAX]; // Read size of Matrix A from user printf("Enter the number of rows of First Matrix: "); scanf("%d", &row1); printf("%d", row1); printf("\nEnter the number of columns of First Matrix: "); scanf("%d", &col1); printf("%d", col1); // Read the elements of Matrix A from user printf("\nEnter the elements of First Matrix: "); for (i = 0; i < row1; i++) { for (j = 0; j < col1; j++) { printf("\nA[%d][%d]: ", i, j); scanf("%d", &A[i][j]); printf("%d", A[i][j]); } } // Read size of Matrix B from user printf("\nEnter the number of rows of Second Matrix: "); scanf("%d", &row2); printf("%d", row2); printf("\nEnter the number of columns of Second Matrix: "); scanf("%d", &col2); printf("%d", col2); // Read the elements of Matrix B from user printf("\nEnter the elements of First Matrix: "); for (i = 0; i < row2; i++) { for (j = 0; j < col2; j++) { printf("\nB[%d][%d]: ", i, j); scanf("%d", &B[i][j]); printf("%d", B[i][j]); } } // Print the Matrix A printf("\n\nFirst Matrix: \n"); printMatrix(A, row1, col1); // Print the Matrix B printf("\nSecond Matrix: \n"); printMatrix(B, row2, col2); // Find the product of the 2 matrices multiplyMatrix(row1, col1, A, row2, col2, B); return 0;}
// Java program to multiply two matrices.import java.io.*;import java.util.*; class GFG{ static int MAX = 100; // Function to print Matrixstatic void printMatrix(int M[][], int rowSize, int colSize){ for(int i = 0; i < rowSize; i++) { for(int j = 0; j < colSize; j++) System.out.print(M[i][j] + " "); System.out.println(); }} // Function to multiply two matrices A[][] and B[][]static void multiplyMatrix(int row1, int col1, int A[][], int row2, int col2, int B[][]){ int i, j, k; // Matrix to store the result int C[][] = new int[MAX][MAX]; // Check if multiplication is Possible if (row2 != col1) { System.out.println("Not Possible"); return; } // Multiply the two for(i = 0; i < row1; i++) { for(j = 0; j < col2; j++) { C[i][j] = 0; for(k = 0; k < row2; k++) C[i][j] += A[i][k] * B[k][j]; } } // Print the result System.out.println(); System.out.println("Resultant Matrix: "); printMatrix(C, row1, col2);} // Driver codepublic static void main(String[] args){ Scanner read = new Scanner(System.in); int row1, col1, row2, col2, i, j; int A[][] = new int[MAX][MAX]; int B[][] = new int[MAX][MAX]; // Read size of Matrix A from user System.out.print("Enter the number of " + "rows of First Matrix: "); row1 = read.nextInt(); System.out.println(row1); System.out.print("Enter the number of " + "columns of First Matrix: "); col1 = read.nextInt(); System.out.println(col1); // Read the elements of Matrix A from user System.out.println("Enter the elements " + "of First Matrix: "); for(i = 0; i < row1; i++) { for(j = 0; j < col1; j++) { System.out.print("A[" + i + "][" + j + "]: "); A[i][j] = read.nextInt(); System.out.println(A[i][j]); } } // Read size of Matrix B from user System.out.print("Enter the number of " + "rows of Second Matrix: "); row2 = read.nextInt(); System.out.println(row2); System.out.print("Enter the number of " + "columns of Second Matrix: "); col2 = read.nextInt(); System.out.println(col2); // Read the elements of Matrix B from user System.out.println("Enter the elements " + "of First Matrix: "); for(i = 0; i < row2; i++) { for(j = 0; j < col2; j++) { System.out.print("A[" + i + "][" + j + "]: "); B[i][j] = read.nextInt(); System.out.println(B[i][j]); } } // Print the Matrix A System.out.println(); System.out.println("First Matrix: "); printMatrix(A, row1, col1); // Print the Matrix B System.out.println(); System.out.println("Second Matrix: "); printMatrix(B, row2, col2); // Find the product of the 2 matrices multiplyMatrix(row1, col1, A, row2, col2, B);}} // This code is contributed by Dharanendra L V.
# Python3 program to multiply two matrices.MAX = 100 # Function to print Matrixdef printMatrix(M, rowSize, colSize) : for i in range(rowSize) : for j in range(colSize) : print(M[i][j], end = " ") print() # Function to multiply two matrices# A[][] and B[][]def multiplyMatrix(row1, col1, A, row2, col2, B) : # Matrix to store the result C = [[0 for i in range(MAX)] for j in range(MAX)] # Check if multiplication is Possible if (row2 != col1) : print("Not Possible") return # Multiply the two for i in range(row1) : for j in range(col2) : C[i][j] = 0 for k in range(row2) : C[i][j] += A[i][k] * B[k][j]; # Print the result print("Resultant Matrix: ") printMatrix(C, row1, col2) # Driver Codeif __name__ == "__main__" : A = [[0 for i in range(MAX)] for j in range(MAX)] B = [[0 for i in range(MAX)] for j in range(MAX)] # Read size of Matrix A from user row1 = int(input("Enter the number of rows of First Matrix: ")) col1 = int(input("Enter the number of columns of First Matrix: ")) # Read the elements of Matrix A from user print("Enter the elements of First Matrix: "); for i in range(row1) : for j in range(col1) : A[i][j] = int(input("A[" + str(i) + "][" + str(j) + "]: ")) # Read size of Matrix B from user row2 = int(input("Enter the number of rows of Second Matrix: ")) col2 = int(input("Enter the number of columns of Second Matrix: ")) # Read the elements of Matrix B from user print("Enter the elements of Second Matrix: "); for i in range(row2) : for j in range(col2) : B[i][j] = int(input("B[" + str(i) + "][" + str(j) + "]: ")) # Print the Matrix A print("First Matrix: ") printMatrix(A, row1, col1) # Print the Matrix B print("Second Matrix: ") printMatrix(B, row2, col2) # Find the product of the 2 matrices multiplyMatrix(row1, col1, A, row2, col2, B) # This code is contributed by Ryuga
Enter the number of rows of First Matrix: 2
Enter the number of columns of First Matrix: 3
Enter the elements of First Matrix:
A[0][0]: 1
A[0][1]: 2
A[0][2]: 3
A[1][0]: 4
A[1][1]: 5
A[1][2]: 6
Enter the number of rows of Second Matrix: 3
Enter the number of columns of Second Matrix: 2
Enter the elements of First Matrix:
B[0][0]: 1
B[0][1]: 2
B[1][0]: 3
B[1][1]: 4
B[2][0]: 5
B[2][1]: 6
First Matrix:
1 2 3
4 5 6
Second Matrix:
1 2
3 4
5 6
Resultant Matrix:
22 28
49 64
Time Complexity: O(row1 * col2 * row2)Auxiliary Space: O(row1 * col2)
ankthon
dharanendralv23
pankajsharmagfg
Algorithms
Matrix
School Programming
Matrix
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Difference between Algorithm, Pseudocode and Program
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
|
[
{
"code": null,
"e": 25917,
"s": 25889,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 26045,
"s": 25917,
"text": "Given two matrices, the task is to multiply them. The size and number of elements of matrices are to be read from the keyboard."
},
{
"code": null,
"e": 26057,
"s": 26045,
"text": "Examples: "
},
{
"code": null,
"e": 26465,
"s": 26057,
"text": "Input: row1 = 2, col1 = 2,\n mat1[][] = {{1, 2}, \n {3, 4}},\n row2 = 2, col2 = 2,\n mat2[][] = {{1, 1}, \n {1, 1}}\nOutput: {{3, 3}, \n {7, 7}}\nInput: row1 = 2, col1 = 2,\n mat1[][] = {{2, 4}, \n {3, 4}}\n row1 = 2, col1 = 2,\n mat2[][] = {{1, 2}, \n {1, 3}} \nOutput: {{6, 16}, \n {7, 18}}"
},
{
"code": null,
"e": 26478,
"s": 26467,
"text": "Program: "
},
{
"code": null,
"e": 26480,
"s": 26478,
"text": "C"
},
{
"code": null,
"e": 26485,
"s": 26480,
"text": "Java"
},
{
"code": null,
"e": 26493,
"s": 26485,
"text": "Python3"
},
{
"code": "// C program to multiply two matrices. #include <stdio.h> const int MAX = 100; // Function to print Matrixvoid printMatrix(int M[][MAX], int rowSize, int colSize){ for (int i = 0; i < rowSize; i++) { for (int j = 0; j < colSize; j++) printf(\"%d \", M[i][j]); printf(\"\\n\"); }} // Function to multiply two matrices A[][] and B[][]void multiplyMatrix(int row1, int col1, int A[][MAX], int row2, int col2, int B[][MAX]){ int i, j, k; // Matrix to store the result int C[MAX][MAX]; // Check if multiplication is Possible if (row2 != col1) { printf(\"Not Possible\\n\"); return; } // Multiply the two for (i = 0; i < row1; i++) { for (j = 0; j < col2; j++) { C[i][j] = 0; for (k = 0; k < row2; k++) C[i][j] += A[i][k] * B[k][j]; } } // Print the result printf(\"\\nResultant Matrix: \\n\"); printMatrix(C, row1, col2);} // Driven Programint main(){ int row1, col1, row2, col2, i, j; int A[MAX][MAX], B[MAX][MAX]; // Read size of Matrix A from user printf(\"Enter the number of rows of First Matrix: \"); scanf(\"%d\", &row1); printf(\"%d\", row1); printf(\"\\nEnter the number of columns of First Matrix: \"); scanf(\"%d\", &col1); printf(\"%d\", col1); // Read the elements of Matrix A from user printf(\"\\nEnter the elements of First Matrix: \"); for (i = 0; i < row1; i++) { for (j = 0; j < col1; j++) { printf(\"\\nA[%d][%d]: \", i, j); scanf(\"%d\", &A[i][j]); printf(\"%d\", A[i][j]); } } // Read size of Matrix B from user printf(\"\\nEnter the number of rows of Second Matrix: \"); scanf(\"%d\", &row2); printf(\"%d\", row2); printf(\"\\nEnter the number of columns of Second Matrix: \"); scanf(\"%d\", &col2); printf(\"%d\", col2); // Read the elements of Matrix B from user printf(\"\\nEnter the elements of First Matrix: \"); for (i = 0; i < row2; i++) { for (j = 0; j < col2; j++) { printf(\"\\nB[%d][%d]: \", i, j); scanf(\"%d\", &B[i][j]); printf(\"%d\", B[i][j]); } } // Print the Matrix A printf(\"\\n\\nFirst Matrix: \\n\"); printMatrix(A, row1, col1); // Print the Matrix B printf(\"\\nSecond Matrix: \\n\"); printMatrix(B, row2, col2); // Find the product of the 2 matrices multiplyMatrix(row1, col1, A, row2, col2, B); return 0;}",
"e": 28931,
"s": 26493,
"text": null
},
{
"code": "// Java program to multiply two matrices.import java.io.*;import java.util.*; class GFG{ static int MAX = 100; // Function to print Matrixstatic void printMatrix(int M[][], int rowSize, int colSize){ for(int i = 0; i < rowSize; i++) { for(int j = 0; j < colSize; j++) System.out.print(M[i][j] + \" \"); System.out.println(); }} // Function to multiply two matrices A[][] and B[][]static void multiplyMatrix(int row1, int col1, int A[][], int row2, int col2, int B[][]){ int i, j, k; // Matrix to store the result int C[][] = new int[MAX][MAX]; // Check if multiplication is Possible if (row2 != col1) { System.out.println(\"Not Possible\"); return; } // Multiply the two for(i = 0; i < row1; i++) { for(j = 0; j < col2; j++) { C[i][j] = 0; for(k = 0; k < row2; k++) C[i][j] += A[i][k] * B[k][j]; } } // Print the result System.out.println(); System.out.println(\"Resultant Matrix: \"); printMatrix(C, row1, col2);} // Driver codepublic static void main(String[] args){ Scanner read = new Scanner(System.in); int row1, col1, row2, col2, i, j; int A[][] = new int[MAX][MAX]; int B[][] = new int[MAX][MAX]; // Read size of Matrix A from user System.out.print(\"Enter the number of \" + \"rows of First Matrix: \"); row1 = read.nextInt(); System.out.println(row1); System.out.print(\"Enter the number of \" + \"columns of First Matrix: \"); col1 = read.nextInt(); System.out.println(col1); // Read the elements of Matrix A from user System.out.println(\"Enter the elements \" + \"of First Matrix: \"); for(i = 0; i < row1; i++) { for(j = 0; j < col1; j++) { System.out.print(\"A[\" + i + \"][\" + j + \"]: \"); A[i][j] = read.nextInt(); System.out.println(A[i][j]); } } // Read size of Matrix B from user System.out.print(\"Enter the number of \" + \"rows of Second Matrix: \"); row2 = read.nextInt(); System.out.println(row2); System.out.print(\"Enter the number of \" + \"columns of Second Matrix: \"); col2 = read.nextInt(); System.out.println(col2); // Read the elements of Matrix B from user System.out.println(\"Enter the elements \" + \"of First Matrix: \"); for(i = 0; i < row2; i++) { for(j = 0; j < col2; j++) { System.out.print(\"A[\" + i + \"][\" + j + \"]: \"); B[i][j] = read.nextInt(); System.out.println(B[i][j]); } } // Print the Matrix A System.out.println(); System.out.println(\"First Matrix: \"); printMatrix(A, row1, col1); // Print the Matrix B System.out.println(); System.out.println(\"Second Matrix: \"); printMatrix(B, row2, col2); // Find the product of the 2 matrices multiplyMatrix(row1, col1, A, row2, col2, B);}} // This code is contributed by Dharanendra L V.",
"e": 32140,
"s": 28931,
"text": null
},
{
"code": "# Python3 program to multiply two matrices.MAX = 100 # Function to print Matrixdef printMatrix(M, rowSize, colSize) : for i in range(rowSize) : for j in range(colSize) : print(M[i][j], end = \" \") print() # Function to multiply two matrices# A[][] and B[][]def multiplyMatrix(row1, col1, A, row2, col2, B) : # Matrix to store the result C = [[0 for i in range(MAX)] for j in range(MAX)] # Check if multiplication is Possible if (row2 != col1) : print(\"Not Possible\") return # Multiply the two for i in range(row1) : for j in range(col2) : C[i][j] = 0 for k in range(row2) : C[i][j] += A[i][k] * B[k][j]; # Print the result print(\"Resultant Matrix: \") printMatrix(C, row1, col2) # Driver Codeif __name__ == \"__main__\" : A = [[0 for i in range(MAX)] for j in range(MAX)] B = [[0 for i in range(MAX)] for j in range(MAX)] # Read size of Matrix A from user row1 = int(input(\"Enter the number of rows of First Matrix: \")) col1 = int(input(\"Enter the number of columns of First Matrix: \")) # Read the elements of Matrix A from user print(\"Enter the elements of First Matrix: \"); for i in range(row1) : for j in range(col1) : A[i][j] = int(input(\"A[\" + str(i) + \"][\" + str(j) + \"]: \")) # Read size of Matrix B from user row2 = int(input(\"Enter the number of rows of Second Matrix: \")) col2 = int(input(\"Enter the number of columns of Second Matrix: \")) # Read the elements of Matrix B from user print(\"Enter the elements of Second Matrix: \"); for i in range(row2) : for j in range(col2) : B[i][j] = int(input(\"B[\" + str(i) + \"][\" + str(j) + \"]: \")) # Print the Matrix A print(\"First Matrix: \") printMatrix(A, row1, col1) # Print the Matrix B print(\"Second Matrix: \") printMatrix(B, row2, col2) # Find the product of the 2 matrices multiplyMatrix(row1, col1, A, row2, col2, B) # This code is contributed by Ryuga",
"e": 34318,
"s": 32140,
"text": null
},
{
"code": null,
"e": 34804,
"s": 34318,
"text": "Enter the number of rows of First Matrix: 2\nEnter the number of columns of First Matrix: 3\nEnter the elements of First Matrix: \nA[0][0]: 1\nA[0][1]: 2\nA[0][2]: 3\nA[1][0]: 4\nA[1][1]: 5\nA[1][2]: 6\nEnter the number of rows of Second Matrix: 3\nEnter the number of columns of Second Matrix: 2\nEnter the elements of First Matrix: \nB[0][0]: 1\nB[0][1]: 2\nB[1][0]: 3\nB[1][1]: 4\nB[2][0]: 5\nB[2][1]: 6\n\nFirst Matrix: \n1 2 3 \n4 5 6 \n\nSecond Matrix: \n1 2 \n3 4 \n5 6 \n\nResultant Matrix: \n22 28 \n49 64 "
},
{
"code": null,
"e": 34876,
"s": 34806,
"text": "Time Complexity: O(row1 * col2 * row2)Auxiliary Space: O(row1 * col2)"
},
{
"code": null,
"e": 34884,
"s": 34876,
"text": "ankthon"
},
{
"code": null,
"e": 34900,
"s": 34884,
"text": "dharanendralv23"
},
{
"code": null,
"e": 34916,
"s": 34900,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 34927,
"s": 34916,
"text": "Algorithms"
},
{
"code": null,
"e": 34934,
"s": 34927,
"text": "Matrix"
},
{
"code": null,
"e": 34953,
"s": 34934,
"text": "School Programming"
},
{
"code": null,
"e": 34960,
"s": 34953,
"text": "Matrix"
},
{
"code": null,
"e": 34971,
"s": 34960,
"text": "Algorithms"
},
{
"code": null,
"e": 35069,
"s": 34971,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35094,
"s": 35069,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 35121,
"s": 35094,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 35174,
"s": 35121,
"text": "Difference between Algorithm, Pseudocode and Program"
},
{
"code": null,
"e": 35208,
"s": 35174,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 35275,
"s": 35208,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 35310,
"s": 35275,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 35354,
"s": 35310,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 35390,
"s": 35354,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 35421,
"s": 35390,
"text": "Rat in a Maze | Backtracking-2"
}
] |
What does $$ (dollar dollar or double dollar) means in PHP ? - GeeksforGeeks
|
22 Feb, 2019
The $x (single dollar) is the normal variable with the name x that stores any value like string, integer, float, etc. The $$x (double dollar) is a reference variable that stores the value which can be accessed by using $ symbol before $x value.From the given figure below, it can be easily understood that:
$x stores the value “Geeks” of String type.
Now reference variable $$x stores the value “for Geeks” in it of String type.
So, the value of “for geeks” can be accessed by two ways which are listed below:
By using Reference variable directly. Example: echo $$x;
By using the value stored at variable $x as a variable name for accessing the “for Geeks” value. Example: echo $Geeks; which will give output as “for Geeks” (without quote marks).
Examples:
Input : $x = "Geeks";
$$x = for Geeks;
echo "$x ";
echo "$$x;";
echo $Geeks;
Output : Geeks
for Geeks
for Geeks
Input : $x = "Rajnish";
$$x = "Noida";
echo "$x lives in " . $Rajnish;
Output : Rajnish lives in Noida
Below examples illustrate the use of $ and $$ in PHP:
Example-1:
<?php // Declare variable and initialize it$x = "Geeks"; // Reference variable$$x = "GeeksforGeeks"; // Display value of xecho $x . "\n"; // Display value of $$x ($Geeks)echo $$x . "\n"; // Display value of $Geeksecho "$Geeks"; ?>
Geeks
GeeksforGeeks
GeeksforGeeks
Example-2:
<?php // Declare variable and initialize it$var = "Geeks"; // Reference variable${$var}="GeeksforGeeks"; // Use double reference variable${${$var}}="computer science"; // Display the value of variableecho $var . "\n"; echo $Geeks . "\n"; echo $GeeksforGeeks . "\n"; // Double referenceecho ${${$var}}. "\n"; ?>
Geeks
GeeksforGeeks
computer science
computer science
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Different ways for passing data to view in Laravel
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
How to pass form variables from one page to other page in PHP ?
PHP | Ternary Operator
|
[
{
"code": null,
"e": 26217,
"s": 26189,
"text": "\n22 Feb, 2019"
},
{
"code": null,
"e": 26524,
"s": 26217,
"text": "The $x (single dollar) is the normal variable with the name x that stores any value like string, integer, float, etc. The $$x (double dollar) is a reference variable that stores the value which can be accessed by using $ symbol before $x value.From the given figure below, it can be easily understood that:"
},
{
"code": null,
"e": 26568,
"s": 26524,
"text": "$x stores the value “Geeks” of String type."
},
{
"code": null,
"e": 26646,
"s": 26568,
"text": "Now reference variable $$x stores the value “for Geeks” in it of String type."
},
{
"code": null,
"e": 26727,
"s": 26646,
"text": "So, the value of “for geeks” can be accessed by two ways which are listed below:"
},
{
"code": null,
"e": 26784,
"s": 26727,
"text": "By using Reference variable directly. Example: echo $$x;"
},
{
"code": null,
"e": 26964,
"s": 26784,
"text": "By using the value stored at variable $x as a variable name for accessing the “for Geeks” value. Example: echo $Geeks; which will give output as “for Geeks” (without quote marks)."
},
{
"code": null,
"e": 26974,
"s": 26964,
"text": "Examples:"
},
{
"code": null,
"e": 27271,
"s": 26974,
"text": "Input : $x = \"Geeks\"; \n $$x = for Geeks; \n echo \"$x \"; \n echo \"$$x;\"; \n echo $Geeks;\nOutput : Geeks \n for Geeks\n for Geeks\n\nInput : $x = \"Rajnish\"; \n $$x = \"Noida\"; \n echo \"$x lives in \" . $Rajnish;\nOutput : Rajnish lives in Noida\n"
},
{
"code": null,
"e": 27325,
"s": 27271,
"text": "Below examples illustrate the use of $ and $$ in PHP:"
},
{
"code": null,
"e": 27336,
"s": 27325,
"text": "Example-1:"
},
{
"code": "<?php // Declare variable and initialize it$x = \"Geeks\"; // Reference variable$$x = \"GeeksforGeeks\"; // Display value of xecho $x . \"\\n\"; // Display value of $$x ($Geeks)echo $$x . \"\\n\"; // Display value of $Geeksecho \"$Geeks\"; ?>",
"e": 27581,
"s": 27336,
"text": null
},
{
"code": null,
"e": 27616,
"s": 27581,
"text": "Geeks\nGeeksforGeeks\nGeeksforGeeks\n"
},
{
"code": null,
"e": 27627,
"s": 27616,
"text": "Example-2:"
},
{
"code": "<?php // Declare variable and initialize it$var = \"Geeks\"; // Reference variable${$var}=\"GeeksforGeeks\"; // Use double reference variable${${$var}}=\"computer science\"; // Display the value of variableecho $var . \"\\n\"; echo $Geeks . \"\\n\"; echo $GeeksforGeeks . \"\\n\"; // Double referenceecho ${${$var}}. \"\\n\"; ?> ",
"e": 27950,
"s": 27627,
"text": null
},
{
"code": null,
"e": 28005,
"s": 27950,
"text": "Geeks\nGeeksforGeeks\ncomputer science\ncomputer science\n"
},
{
"code": null,
"e": 28012,
"s": 28005,
"text": "Picked"
},
{
"code": null,
"e": 28016,
"s": 28012,
"text": "PHP"
},
{
"code": null,
"e": 28029,
"s": 28016,
"text": "PHP Programs"
},
{
"code": null,
"e": 28046,
"s": 28029,
"text": "Web Technologies"
},
{
"code": null,
"e": 28050,
"s": 28046,
"text": "PHP"
},
{
"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": 28230,
"s": 28148,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 28272,
"s": 28230,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 28299,
"s": 28272,
"text": "PHP str_replace() Function"
},
{
"code": null,
"e": 28363,
"s": 28299,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 28414,
"s": 28363,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 28466,
"s": 28414,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 28548,
"s": 28466,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 28590,
"s": 28548,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 28654,
"s": 28590,
"text": "How to pass form variables from one page to other page in PHP ?"
}
] |
HTML5 <dialog> Tag - GeeksforGeeks
|
17 Mar, 2022
The <dialog> tag is used to specify the dialog box or window. This tag is used to create a popup dialog and models on a web page. This tag is new in HTML5.
Syntax:
<dialog open> Contents... </dialog>
Attributes: This tag accepts a single attribute open which is used to specify the dialog element is active and the user can interact with the tag element.Example:
HTML
<!DOCTYPE html><html> <body> <h1><dialog> tag</h1> <!--This is an open dialog Tag--> <dialog open>Welcome to GeeksforGeeks</dialog> </body></html>
Output:
Supported Browsers:
Google Chrome 37.0
Firefox 59.0
Opera 24.0
Safari 6.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
shubham_singh
shubhamyadav4
HTML-Tags
HTML5
HTML
HTML
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 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 ?
CSS to put icon inside an input element in a form
How to position a div at the bottom of its container using CSS?
|
[
{
"code": null,
"e": 24644,
"s": 24616,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 24801,
"s": 24644,
"text": "The <dialog> tag is used to specify the dialog box or window. This tag is used to create a popup dialog and models on a web page. This tag is new in HTML5. "
},
{
"code": null,
"e": 24810,
"s": 24801,
"text": "Syntax: "
},
{
"code": null,
"e": 24846,
"s": 24810,
"text": "<dialog open> Contents... </dialog>"
},
{
"code": null,
"e": 25010,
"s": 24846,
"text": "Attributes: This tag accepts a single attribute open which is used to specify the dialog element is active and the user can interact with the tag element.Example: "
},
{
"code": null,
"e": 25015,
"s": 25010,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1><dialog> tag</h1> <!--This is an open dialog Tag--> <dialog open>Welcome to GeeksforGeeks</dialog> </body></html>",
"e": 25199,
"s": 25015,
"text": null
},
{
"code": null,
"e": 25209,
"s": 25199,
"text": "Output: "
},
{
"code": null,
"e": 25230,
"s": 25209,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 25249,
"s": 25230,
"text": "Google Chrome 37.0"
},
{
"code": null,
"e": 25262,
"s": 25249,
"text": "Firefox 59.0"
},
{
"code": null,
"e": 25273,
"s": 25262,
"text": "Opera 24.0"
},
{
"code": null,
"e": 25284,
"s": 25273,
"text": "Safari 6.0"
},
{
"code": null,
"e": 25421,
"s": 25284,
"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": 25435,
"s": 25421,
"text": "shubham_singh"
},
{
"code": null,
"e": 25449,
"s": 25435,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 25459,
"s": 25449,
"text": "HTML-Tags"
},
{
"code": null,
"e": 25465,
"s": 25459,
"text": "HTML5"
},
{
"code": null,
"e": 25470,
"s": 25465,
"text": "HTML"
},
{
"code": null,
"e": 25475,
"s": 25470,
"text": "HTML"
},
{
"code": null,
"e": 25573,
"s": 25475,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25623,
"s": 25573,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 25685,
"s": 25623,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 25733,
"s": 25685,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 25793,
"s": 25733,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 25846,
"s": 25793,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 25907,
"s": 25846,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 25931,
"s": 25907,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 25981,
"s": 25931,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26031,
"s": 25981,
"text": "CSS to put icon inside an input element in a form"
}
] |
Plant Disease Detection using Advanced Deep Learning and ReactJS | by Dhruvil Shah | Towards Data Science
|
Myriads of papers and articles are available for the detection of leaf or plant disease using deep learning. Convolutional Neural Networks have revolutionized the agriculture field by providing the models that are helping detect the disease of the plant accurately. But detecting the disease is not enough and one should also be informed about the symptoms of the disease in the leaf or plant image. For localizing affected areas in the plant via object detection, Single Shot multi-box Detector (SSD), Faster Region-based Convolutional Neural Network (Faster RCNN) and Region-based Fully Convolutional Network (R-FCN) are utilized. Moreover, for real-time object detection, the You Only Look Once (YOLO) algorithm is employed. These all algorithms could be utilized for the diagnosis of plant disease and visualizing the affected areas but they lack transparency and act as a black-box in practice.
Before starting my article on my latest research, I would like to share the great news:
In this article, an interpretable state-of-the-art approach is employed which has transcended all the formerly proposed methods. A research paper that was recently published online in a Scopus indexed journal- Information Processing in Agriculture having 6.41 Impact factor is used as a foundation for this article.
www.sciencedirect.com
This paper proposes an advanced deep learning architecture named ResTS, an abbreviation of Residual Teacher/Student. It contains 2 classifiers namely, ResTeacher and ResStudent and a decoder. ResTeacher + Decoder functions as an autoencoder to remove the non-discriminant features from the input image and the ResStudent classifier helps to improve the reconstruction loss of this architecture. ResTS outputs a heatmap that highlights only the discriminant features of the leaf disease and the disease category. It was trained on the PlantVillage dataset (the segmented version). This proposed structure outperformed the previously discovered architectures for the diagnosis as well as visualization of plant diseases with the highest F1 score of 0.991. Figures 1–4 portray how the input image is manipulated by ResTS. The following sections explain how these images are constructed by the model and post-processed by few important formulas.
This article will construct a React application as our front-end and run the advanced deep learning architecture- ResTS from THE research paper in the backend. As a repercussion, the system will maneuver as depicted in Fig 5. We will create the whole system and run it, in the end, and see if all the parts fit together.
For access to the trained ResTS model, instructions are given at the end of the following section.
First, we will design the Flask server to accommodate the pre-trained ResTS architecture. The server will incorporate a route to handle the input image coming from the application and will return a new image that comprises only the salient features along with the disease name and probability. Secondly, we will develop an uncomplicated React application where images can be uploaded and manifested. We will not go into the particulars regarding the ResTS architecture. Please refer to the original paper to learn how this architecture operates to diagnose plant disease.
1. Comment your request with the proper reason on the below post on LinkedIn and I will share the personal links to access the pre-trained saved model in various formats:
www.linkedin.com
The architecture code is required to be put in the same file as the server. However, this can be changed but due to some errors, I decided to put the whole code of architecture in the same file and load the weights. Also, it is neat to have only one file to run instead of managing multiple files.
Source Code Access: You can find the links to the whole source code of this article and the ResTS architecture from the paper referenced above.
First, we will import all the necessary libraries into our Flask server file.
import osfrom flask import Flask, requestimport numpy as npimport matplotlib.pyplot as pltimport tensorflow as tfimport pandas as pdimport gevent.pywsgifrom flask_cors import CORSfrom datetime import datetimefrom tensorflow.python.keras.backend import set_sessionfrom keras import backend as Kimport tensorflow.compat.v1 as tfimport keras_preprocessingfrom keras.applications.xception import preprocess_input as xception_preprocess_inputfrom keras_preprocessing import imageimport jsonfrom PIL import Imagefrom hashlib import sha256###########################from tensorflow.keras.layers import Input, Dense, Conv2D, Activation, MaxPool2Dfrom tensorflow.keras.layers import *from tensorflow.keras.models import Model, Sequentialfrom tensorflow.keras.optimizers import Adam, SGDimport globimport argparsefrom keras import __version__from keras.applications.xception import preprocess_input as xception_preprocess_inputfrom keras.preprocessing.image import ImageDataGeneratorfrom keras.optimizers import SGDfrom keras import optimizersfrom keras import callbacksfrom keras.callbacks import ModelCheckpoint, LearningRateSchedulerfrom keras import backend as kerasfrom keras.regularizers import l2,l1import pandas as pd
These will necessitate huge processing power. The next step is to define the ‘app’ variable with some other important variables and the session using the tf.session. tf.disable_v2_behavior() and tf.get_default_graph() was required while running the server to steer clear of any graph-related errors.
input_shape = (224,224,3)nbr_of_classes=38tf.disable_v2_behavior()graph = tf.get_default_graph()app = Flask(__name__)CORS(app)sess = tf.Session()set_session(sess)
Note: If the errors still occur during the starting phase of the server, there are high chances that it is due to the version error of TensorFlow. Try searching Stackoverflow in that case.
After defining the session, the architecture code will be implemented. ResTS uses standard Xception architecture as ResTeacher and ResStudent and the decoder is generated in the exact inverse manner of Xception architecture to reproduce the images. It is out of the scope of this article to discuss the ResTS architecture in-depth. To understand the below code properly, refer to the original paper.
#ResTS ARCHITECTURE#RESTEACHERbase_model1 = tf.keras.applications.Xception(include_top=False, weights='imagenet',input_shape = input_shape)x1_0 = base_model1.outputx1_0 = Flatten(name='Flatten1')(x1_0)dense1 = Dense(256, name='fc1',activation='relu')(x1_0) x = classif_out_encoder1 = Dense(38, name='out1', activation = 'softmax')(dense1) # Latent Representation / Bottleneck#Get Xception's tensors for skip connection....#DECODERdense2 = Dense(256, activation='relu')(x)x = Add(name='first_merge')([dense1, dense2])x = Dense(7*7*2048)(x)reshape1 = Reshape((7, 7, 2048))(x)#BLOCK 1...#BLOCK 2...#BLOCK 3-10...#BLOCK 11...#BLOCK 12...#BLOCK 13...#BLOCK 14...x = Conv2D(2, 3, activation = 'relu', padding = 'same',)(x)mask = x = Conv2D(3, 1, activation = 'sigmoid',name='Mask')(x)#RESSTUDENTbase_model2 = tf.keras.applications.Xception(include_top=False, weights='imagenet',input_shape = (224,224,3))x2_0 = base_model2(mask)x2_0 = Flatten(name='Flatten2')(x2_0)x2_1 = Dense(256, name='fc2',activation='relu')(x2_0) classif_out_encoder2 = Dense(nbr_of_classes, name='out2',activation='softmax')(x2_1)#Create ResTS Model and Load Pre-trained weightsResTS = Model(base_model1.input, [classif_out_encoder1, classif_out_encoder2])ResTS.load_weights('tf/RTS')
ResTS architecture is designed in a way such that it screens the noisy regions from the input image of the leaf with the help of an autoencoder. the mask layer is the output of the decoder that is taken for visualizing the important regions of the leaf image. classif_out_encoder1 that is the output of ResTeacher assists in classifying the disease category with the help of softmax function.
#For visualization impetuslayer_name ='Mask'NewInput = ResTS.get_layer(layer_name).outputvisualization = K.function([ResTS.input], [NewInput])
In the above code, visualization is a function that aids in getting the image comprising only the important features of the leaf image. Next, we will define some important functions for envisioning the features of an image received from the visualization function.
def reduce_channels_sequare(heatmap): channel1 = heatmap[:,:,0] channel2 = heatmap[:,:,1] channel3 = heatmap[:,:,2] new_heatmap = np.sqrt(((channel1-0.149)*(channel1-0.149))+((channel2-0.1529)*(channel2-0.1529))+((channel3-0.3412)*(channel3-0.3412))) return new_heatmap
The reduce_channels_sequare function is required to convert the reconstructed RGB image into a one-channel image. It indirectly finds the distance between the dominant color in the reconstructed image (referred to as heatmap in this function).
def postprocess_vis(heatmap1,threshould = 0.9): heatmap = heatmap1.copy() heatmap = (heatmap - heatmap.min())/(heatmap.max() - heatmap.min()) heatmap = reduce_channels_sequare(heatmap) heatmap = (heatmap - heatmap.min())/(heatmap.max() - heatmap.min()) heatmap[heatmap>threshould] = 1 heatmap = heatmap*255 return heatmap
postprocess_vis function performs basic binary thresholding such that pixels having a value greater than 0.9 are set to 1. The heatmap (reconstructed image) is then multiplied by 255 so that we get the values in the range [0, 255].
Note: We are now dealing with only one-channel images instead of RGB channels. It is necessary to normalize the values in the heatmap before and after reducing the channels for getting the final heatmap as shown in Fig. 6 using OpenCV.
Note if using OpenCV: Had we not multiplied by 255, we would get the mostly blackish image in Fig. 6 because of the pixel values being in the range [0, 1]. Because OpenCV considers the range [0, 255] and outputs the image accordingly.
Note if using Matplotlib (cmap= ‘Reds’): Had we not multiplied by 255, we would get the same output as Fig. 4 using cmap= ‘Reds’. Because matplotlib only demands specific ranges when showing the RGB image.
def visualize_image(img_name): image_size = (224,224) original_image = image.load_img(img_name, target_size=image_size) img = image.img_to_array(original_image) img = np.expand_dims(img, axis=0) img = xception_preprocess_input(img) global sess global graph with graph.as_default(): set_session(sess) vis = visualization([img])[0][0] disease = ResTS.predict(img)[0] probab = max(disease[0]) disease = np.argmax(disease) heatmap = postprocess_vis(vis) img = plt.imshow(heatmap, cmap='Reds') plt.axis('off') plt.savefig(img_name, bbox_inches='tight') return disease, probab
Here, the vis variable consists of float values in the range [0, 1]. So, if you want to run the plt.imshow() method on the vis variable it will give the reconstructed image as output as in Fig 2. If you multiply the vis variable by 255, the float values will come in the range [0, 255] that is not supported by the plt.imshow() method as it requires the float values in the [0, 1] range and integer values in [0, 255] range for “RGB” images. Now, to obtain the output as in Fig 3., just multiply vis by 255 and use OpenCV to save it as described below.
#cv2.imwrite('vis.jpg',vis)
Matplotlib’s cmap = ‘Reds’ gives us the red heatmap as shown in Fig 4. The visualize_image function overwrites the input image with its heatmap (having the same filename).
Note: If we do not use the plt.imshow(heatmap, cmap= ‘Reds’) and instead, use cv2.imwrite(heatmap), we would get the output image as below. The reason is that we have generated a “one-channel” heatmap in the postprocess_vis function and also applied binary thresholding. OpenCV will write the image considering the pixel values as they are (255-pixel value = ‘white’ region, 0-pixel values = ‘black’ region and other values get ‘grayish’ regions).
The visualize_image function is the backbone of this system. It handles the prediction of disease along with the generation of visualization of symptoms in the disease. First, the input image is read by the name passed from the ‘/detect’ route and preprocessed by the default xception_preprocess_input function from the standard Xception architecture. visualization function is called to get the output of the decoder i.e. reconstructed image. .predict() method is called on the model to get the ResTeacher’s output that is the category of the disease. It returns the predicted disease name and its probability (that states how confident the model is about the prediction). It saves the heatmap having the same filename i.e. overwrites the original file.
‘/detect’ route gets the image from React application, generates the heatmap that highlights the disease's discriminant features, and reverts it along with the disease category to the application. It also returns the probability of the prediction. Fig 7. dictates the flow of this route.
Below is the code adaptation of this route. It works exactly in the same manner as shown in Fig 7. Hence, the code below is self-explanatory.
@app.route('/detect', methods=['POST'])def change(): image_size = (224,224) img_data = request.get_json()['image'] img_name = str(int(datetime.timestamp(datetime.now()))) + str(np.random.randint(1000000000)) img_name = sha256(img_name.encode()).hexdigest()[0:12] img_data = np.array(list(img_data.values())).reshape([224, 224, 3]) im = Image.fromarray((img_data).astype(np.uint8)) im.save(img_name+'.jpg') disease, probab = visualize_image(img_name+'.jpg') img = cv2.imread(img_name+'.jpg') img = cv2.resize(img, image_size) / 255.0 img = img.tolist() os.remove(img_name+'.jpg') return json.dumps({"image": img, "disease":int(disease), "probab":str(probab)})
1. Comment your request with the proper reason on the below post on LinkedIn and I will share the personal links to access the pre-trained saved model in various formats:
www.linkedin.com
Let’s get to the coding part (App.js) file in React directly.
First, we will import some libraries and define global variables.
import logo from './logo.svg';import './App.css';import React from 'react';import * as tf from '@tensorflow/tfjs';import cat from './cat.jpg';import {CLASSES} from './imagenet_classes';const axios = require('axios');const IMAGE_SIZE = 224;let mobilenet;let demoStatusElement;let status;let mobilenet2;
imagenet_classes is a file containing the names of all classes and corresponding numbers in a dictionary. Don’t mind the variable names! This code has gone through many attempts to get a perfect application for the task at hand. Next, we will start with the class ‘App’. The first method inside the class is the constructor method.
constructor(props){ super(props); this.state = { load:false, status: "F1 score of the model is: 0.9908 ", probab: "" }; this.mobilenetDemo = this.mobilenetDemo.bind(this); this.predict = this.predict.bind(this); this.showResults = this.showResults.bind(this); this.filechangehandler = this.filechangehandler.bind(this); }
load state is for the animation before loading the image. status is the default statement to be stated in the application. probab state changes each time an image has been passed containing the accuracy of its prediction. The four methods will be discussed in the following sections.
Now, we will define all these 4 methods for particular tasks. As I instructed before about the variable names, ignore those. ResTS architecture uses Xception architecture even if some variables say mobilenet.
async mobilenetDemo(){ const catElement = document.getElementById('cat'); if (catElement.complete && catElement.naturalHeight !== 0) { this.predict(catElement); catElement.style.display = ''; } else { catElement.onload = () => { this.predict(catElement); catElement.style.display = ''; } }};
mobilenetDemo() async method loads the first image when the app is rendered for the first time and its prediction by calling the prediction() method. prediction() method takes image element as input and calls the Flask server for relevant predictions. The server returns 3 parameters- disease, probability and heatmap.
async predict(imgElement) { let img = tf.browser.fromPixels(imgElement).toFloat().reshape([1, 224, 224, 3]); //img = tf.reverse(img, -1); this.setState({ load:true }); const image = await axios.post('http://localhost:5000/detect', {'image': img.dataSync()}); this.setState({ load:false }); // // Show the classes in the DOM. this.showResults(imgElement, image.data['disease'], image.data['probab'], tf.tensor3d([image.data['image']].flat(), [224, 224, 3])); }
At last, showResults() method is called to display the results in the app. showResults() method takes 4 values as parameters from the prediction() method. This method does some basic HTML operations to portray the results from the server into the application.
async showResults(imgElement, diseaseClass, probab, tensor) { const predictionContainer = document.createElement('div'); predictionContainer.className = 'pred-container'; const imgContainer = document.createElement('div'); imgContainer.appendChild(imgElement); predictionContainer.appendChild(imgContainer); const probsContainer = document.createElement('div'); const predictedCanvas = document.createElement('canvas'); probsContainer.appendChild(predictedCanvas); predictedCanvas.width = tensor.shape[0]; predictedCanvas.height = tensor.shape[1]; tensor = tf.reverse(tensor, -1); await tf.browser.toPixels(tensor, predictedCanvas); console.log(probab); this.setState({ probab: "The last prediction was " + parseFloat(probab)*100 + " % accurate!" }); const predictedDisease = document.createElement('p'); predictedDisease.innerHTML = 'Disease: '; const i = document.createElement('i'); i.innerHTML = CLASSES[diseaseClass]; predictedDisease.appendChild(i); //probsContainer.appendChild(predictedCanvas); //probsContainer.appendChild(predictedDisease); predictionContainer.appendChild(probsContainer); predictionContainer.appendChild(predictedDisease); const predictionsElement = document.getElementById('predictions'); predictionsElement.insertBefore( predictionContainer, predictionsElement.firstChild); }
The filechangehandler() method gets triggered whenever an image is uploaded via the upload button.
filechangehandler(evt){ let files = evt.target.files; for (let i = 0, f; f = files[i]; i++) { // Only process image files (skip non image files) if (!f.type.match('image.*')) { continue; } let reader = new FileReader(); reader.onload = e => { // Fill the image & call predict. let img = document.createElement('img'); img.src = e.target.result; img.width = IMAGE_SIZE; img.height = IMAGE_SIZE; img.onload = () => this.predict(img); };// Read in the image file as a data URL. reader.readAsDataURL(f); } }
Finally, we want to call the mobilenetDemo() method to load the first image and its prediction. For this task, we will use the componentDidMount() lifecycle method.
componentDidMount(){ this.mobilenetDemo(); }render(){ return ( <div className="tfjs-example-container"> <section className='title-area'> <h1>ResTS for Plant Disease Diagnosis</h1> </section><section> <p className='section-head'>Description</p> <p> This WebApp uses the ResTS model which will be made available soon for public use.It is not trained to recognize images that DO NOT have BLACK BACKGROUNDS. For best performance, upload images of leaf\/Plant with black background. You can see the disease categories it has been trained to recognize in <a href="https://github.com/spMohanty/PlantVillage-Dataset/tree/master/raw/segmented">this folder</a>. </p> </section><section> <p className='section-head'>Status</p> {this.state.load?<div id="status">{this.state.status}</div>:<div id="status">{this.state.status}<br></br>{this.state.probab}</div>} </section><section> <p className='section-head'>Model Output</p><div id="file-container"> Upload an image: <input type="file" id="files" name="files[]" onChange={this.filechangehandler} multiple /> </div> {this.state.load?<div className="lds-roller"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>:''}<div id="predictions"></div><img id="cat" src={cat}/> </section> </div>);}
The render() method contains the self-explanatory HTML elements.
The Gif below portrays the working of the web application that is connected with the flask server comprising the pre-trained ResTS model.
D. Shah, V. Trivedi, V. Sheth, A. Shah, U. Chauhan, ResTS: Residual DeepInterpretable Architecture for Plant Disease Detection, Information Processing in Agriculture (2021), doi: https://doi.org/10.1016/j.inpa.2021.06.001
D. Shah, V. Trivedi, V. Sheth, A. Shah, U. Chauhan, ResTS: Residual DeepInterpretable Architecture for Plant Disease Detection, Information Processing in Agriculture (2021), doi: https://doi.org/10.1016/j.inpa.2021.06.001
|
[
{
"code": null,
"e": 1072,
"s": 172,
"text": "Myriads of papers and articles are available for the detection of leaf or plant disease using deep learning. Convolutional Neural Networks have revolutionized the agriculture field by providing the models that are helping detect the disease of the plant accurately. But detecting the disease is not enough and one should also be informed about the symptoms of the disease in the leaf or plant image. For localizing affected areas in the plant via object detection, Single Shot multi-box Detector (SSD), Faster Region-based Convolutional Neural Network (Faster RCNN) and Region-based Fully Convolutional Network (R-FCN) are utilized. Moreover, for real-time object detection, the You Only Look Once (YOLO) algorithm is employed. These all algorithms could be utilized for the diagnosis of plant disease and visualizing the affected areas but they lack transparency and act as a black-box in practice."
},
{
"code": null,
"e": 1160,
"s": 1072,
"text": "Before starting my article on my latest research, I would like to share the great news:"
},
{
"code": null,
"e": 1476,
"s": 1160,
"text": "In this article, an interpretable state-of-the-art approach is employed which has transcended all the formerly proposed methods. A research paper that was recently published online in a Scopus indexed journal- Information Processing in Agriculture having 6.41 Impact factor is used as a foundation for this article."
},
{
"code": null,
"e": 1498,
"s": 1476,
"text": "www.sciencedirect.com"
},
{
"code": null,
"e": 2440,
"s": 1498,
"text": "This paper proposes an advanced deep learning architecture named ResTS, an abbreviation of Residual Teacher/Student. It contains 2 classifiers namely, ResTeacher and ResStudent and a decoder. ResTeacher + Decoder functions as an autoencoder to remove the non-discriminant features from the input image and the ResStudent classifier helps to improve the reconstruction loss of this architecture. ResTS outputs a heatmap that highlights only the discriminant features of the leaf disease and the disease category. It was trained on the PlantVillage dataset (the segmented version). This proposed structure outperformed the previously discovered architectures for the diagnosis as well as visualization of plant diseases with the highest F1 score of 0.991. Figures 1–4 portray how the input image is manipulated by ResTS. The following sections explain how these images are constructed by the model and post-processed by few important formulas."
},
{
"code": null,
"e": 2761,
"s": 2440,
"text": "This article will construct a React application as our front-end and run the advanced deep learning architecture- ResTS from THE research paper in the backend. As a repercussion, the system will maneuver as depicted in Fig 5. We will create the whole system and run it, in the end, and see if all the parts fit together."
},
{
"code": null,
"e": 2860,
"s": 2761,
"text": "For access to the trained ResTS model, instructions are given at the end of the following section."
},
{
"code": null,
"e": 3432,
"s": 2860,
"text": "First, we will design the Flask server to accommodate the pre-trained ResTS architecture. The server will incorporate a route to handle the input image coming from the application and will return a new image that comprises only the salient features along with the disease name and probability. Secondly, we will develop an uncomplicated React application where images can be uploaded and manifested. We will not go into the particulars regarding the ResTS architecture. Please refer to the original paper to learn how this architecture operates to diagnose plant disease."
},
{
"code": null,
"e": 3603,
"s": 3432,
"text": "1. Comment your request with the proper reason on the below post on LinkedIn and I will share the personal links to access the pre-trained saved model in various formats:"
},
{
"code": null,
"e": 3620,
"s": 3603,
"text": "www.linkedin.com"
},
{
"code": null,
"e": 3918,
"s": 3620,
"text": "The architecture code is required to be put in the same file as the server. However, this can be changed but due to some errors, I decided to put the whole code of architecture in the same file and load the weights. Also, it is neat to have only one file to run instead of managing multiple files."
},
{
"code": null,
"e": 4062,
"s": 3918,
"text": "Source Code Access: You can find the links to the whole source code of this article and the ResTS architecture from the paper referenced above."
},
{
"code": null,
"e": 4140,
"s": 4062,
"text": "First, we will import all the necessary libraries into our Flask server file."
},
{
"code": null,
"e": 5356,
"s": 4140,
"text": "import osfrom flask import Flask, requestimport numpy as npimport matplotlib.pyplot as pltimport tensorflow as tfimport pandas as pdimport gevent.pywsgifrom flask_cors import CORSfrom datetime import datetimefrom tensorflow.python.keras.backend import set_sessionfrom keras import backend as Kimport tensorflow.compat.v1 as tfimport keras_preprocessingfrom keras.applications.xception import preprocess_input as xception_preprocess_inputfrom keras_preprocessing import imageimport jsonfrom PIL import Imagefrom hashlib import sha256###########################from tensorflow.keras.layers import Input, Dense, Conv2D, Activation, MaxPool2Dfrom tensorflow.keras.layers import *from tensorflow.keras.models import Model, Sequentialfrom tensorflow.keras.optimizers import Adam, SGDimport globimport argparsefrom keras import __version__from keras.applications.xception import preprocess_input as xception_preprocess_inputfrom keras.preprocessing.image import ImageDataGeneratorfrom keras.optimizers import SGDfrom keras import optimizersfrom keras import callbacksfrom keras.callbacks import ModelCheckpoint, LearningRateSchedulerfrom keras import backend as kerasfrom keras.regularizers import l2,l1import pandas as pd"
},
{
"code": null,
"e": 5656,
"s": 5356,
"text": "These will necessitate huge processing power. The next step is to define the ‘app’ variable with some other important variables and the session using the tf.session. tf.disable_v2_behavior() and tf.get_default_graph() was required while running the server to steer clear of any graph-related errors."
},
{
"code": null,
"e": 5819,
"s": 5656,
"text": "input_shape = (224,224,3)nbr_of_classes=38tf.disable_v2_behavior()graph = tf.get_default_graph()app = Flask(__name__)CORS(app)sess = tf.Session()set_session(sess)"
},
{
"code": null,
"e": 6008,
"s": 5819,
"text": "Note: If the errors still occur during the starting phase of the server, there are high chances that it is due to the version error of TensorFlow. Try searching Stackoverflow in that case."
},
{
"code": null,
"e": 6408,
"s": 6008,
"text": "After defining the session, the architecture code will be implemented. ResTS uses standard Xception architecture as ResTeacher and ResStudent and the decoder is generated in the exact inverse manner of Xception architecture to reproduce the images. It is out of the scope of this article to discuss the ResTS architecture in-depth. To understand the below code properly, refer to the original paper."
},
{
"code": null,
"e": 7661,
"s": 6408,
"text": "#ResTS ARCHITECTURE#RESTEACHERbase_model1 = tf.keras.applications.Xception(include_top=False, weights='imagenet',input_shape = input_shape)x1_0 = base_model1.outputx1_0 = Flatten(name='Flatten1')(x1_0)dense1 = Dense(256, name='fc1',activation='relu')(x1_0) x = classif_out_encoder1 = Dense(38, name='out1', activation = 'softmax')(dense1) # Latent Representation / Bottleneck#Get Xception's tensors for skip connection....#DECODERdense2 = Dense(256, activation='relu')(x)x = Add(name='first_merge')([dense1, dense2])x = Dense(7*7*2048)(x)reshape1 = Reshape((7, 7, 2048))(x)#BLOCK 1...#BLOCK 2...#BLOCK 3-10...#BLOCK 11...#BLOCK 12...#BLOCK 13...#BLOCK 14...x = Conv2D(2, 3, activation = 'relu', padding = 'same',)(x)mask = x = Conv2D(3, 1, activation = 'sigmoid',name='Mask')(x)#RESSTUDENTbase_model2 = tf.keras.applications.Xception(include_top=False, weights='imagenet',input_shape = (224,224,3))x2_0 = base_model2(mask)x2_0 = Flatten(name='Flatten2')(x2_0)x2_1 = Dense(256, name='fc2',activation='relu')(x2_0) classif_out_encoder2 = Dense(nbr_of_classes, name='out2',activation='softmax')(x2_1)#Create ResTS Model and Load Pre-trained weightsResTS = Model(base_model1.input, [classif_out_encoder1, classif_out_encoder2])ResTS.load_weights('tf/RTS')"
},
{
"code": null,
"e": 8054,
"s": 7661,
"text": "ResTS architecture is designed in a way such that it screens the noisy regions from the input image of the leaf with the help of an autoencoder. the mask layer is the output of the decoder that is taken for visualizing the important regions of the leaf image. classif_out_encoder1 that is the output of ResTeacher assists in classifying the disease category with the help of softmax function."
},
{
"code": null,
"e": 8197,
"s": 8054,
"text": "#For visualization impetuslayer_name ='Mask'NewInput = ResTS.get_layer(layer_name).outputvisualization = K.function([ResTS.input], [NewInput])"
},
{
"code": null,
"e": 8462,
"s": 8197,
"text": "In the above code, visualization is a function that aids in getting the image comprising only the important features of the leaf image. Next, we will define some important functions for envisioning the features of an image received from the visualization function."
},
{
"code": null,
"e": 8747,
"s": 8462,
"text": "def reduce_channels_sequare(heatmap): channel1 = heatmap[:,:,0] channel2 = heatmap[:,:,1] channel3 = heatmap[:,:,2] new_heatmap = np.sqrt(((channel1-0.149)*(channel1-0.149))+((channel2-0.1529)*(channel2-0.1529))+((channel3-0.3412)*(channel3-0.3412))) return new_heatmap"
},
{
"code": null,
"e": 8991,
"s": 8747,
"text": "The reduce_channels_sequare function is required to convert the reconstructed RGB image into a one-channel image. It indirectly finds the distance between the dominant color in the reconstructed image (referred to as heatmap in this function)."
},
{
"code": null,
"e": 9334,
"s": 8991,
"text": "def postprocess_vis(heatmap1,threshould = 0.9): heatmap = heatmap1.copy() heatmap = (heatmap - heatmap.min())/(heatmap.max() - heatmap.min()) heatmap = reduce_channels_sequare(heatmap) heatmap = (heatmap - heatmap.min())/(heatmap.max() - heatmap.min()) heatmap[heatmap>threshould] = 1 heatmap = heatmap*255 return heatmap"
},
{
"code": null,
"e": 9566,
"s": 9334,
"text": "postprocess_vis function performs basic binary thresholding such that pixels having a value greater than 0.9 are set to 1. The heatmap (reconstructed image) is then multiplied by 255 so that we get the values in the range [0, 255]."
},
{
"code": null,
"e": 9802,
"s": 9566,
"text": "Note: We are now dealing with only one-channel images instead of RGB channels. It is necessary to normalize the values in the heatmap before and after reducing the channels for getting the final heatmap as shown in Fig. 6 using OpenCV."
},
{
"code": null,
"e": 10037,
"s": 9802,
"text": "Note if using OpenCV: Had we not multiplied by 255, we would get the mostly blackish image in Fig. 6 because of the pixel values being in the range [0, 1]. Because OpenCV considers the range [0, 255] and outputs the image accordingly."
},
{
"code": null,
"e": 10243,
"s": 10037,
"text": "Note if using Matplotlib (cmap= ‘Reds’): Had we not multiplied by 255, we would get the same output as Fig. 4 using cmap= ‘Reds’. Because matplotlib only demands specific ranges when showing the RGB image."
},
{
"code": null,
"e": 10892,
"s": 10243,
"text": "def visualize_image(img_name): image_size = (224,224) original_image = image.load_img(img_name, target_size=image_size) img = image.img_to_array(original_image) img = np.expand_dims(img, axis=0) img = xception_preprocess_input(img) global sess global graph with graph.as_default(): set_session(sess) vis = visualization([img])[0][0] disease = ResTS.predict(img)[0] probab = max(disease[0]) disease = np.argmax(disease) heatmap = postprocess_vis(vis) img = plt.imshow(heatmap, cmap='Reds') plt.axis('off') plt.savefig(img_name, bbox_inches='tight') return disease, probab"
},
{
"code": null,
"e": 11445,
"s": 10892,
"text": "Here, the vis variable consists of float values in the range [0, 1]. So, if you want to run the plt.imshow() method on the vis variable it will give the reconstructed image as output as in Fig 2. If you multiply the vis variable by 255, the float values will come in the range [0, 255] that is not supported by the plt.imshow() method as it requires the float values in the [0, 1] range and integer values in [0, 255] range for “RGB” images. Now, to obtain the output as in Fig 3., just multiply vis by 255 and use OpenCV to save it as described below."
},
{
"code": null,
"e": 11473,
"s": 11445,
"text": "#cv2.imwrite('vis.jpg',vis)"
},
{
"code": null,
"e": 11645,
"s": 11473,
"text": "Matplotlib’s cmap = ‘Reds’ gives us the red heatmap as shown in Fig 4. The visualize_image function overwrites the input image with its heatmap (having the same filename)."
},
{
"code": null,
"e": 12093,
"s": 11645,
"text": "Note: If we do not use the plt.imshow(heatmap, cmap= ‘Reds’) and instead, use cv2.imwrite(heatmap), we would get the output image as below. The reason is that we have generated a “one-channel” heatmap in the postprocess_vis function and also applied binary thresholding. OpenCV will write the image considering the pixel values as they are (255-pixel value = ‘white’ region, 0-pixel values = ‘black’ region and other values get ‘grayish’ regions)."
},
{
"code": null,
"e": 12848,
"s": 12093,
"text": "The visualize_image function is the backbone of this system. It handles the prediction of disease along with the generation of visualization of symptoms in the disease. First, the input image is read by the name passed from the ‘/detect’ route and preprocessed by the default xception_preprocess_input function from the standard Xception architecture. visualization function is called to get the output of the decoder i.e. reconstructed image. .predict() method is called on the model to get the ResTeacher’s output that is the category of the disease. It returns the predicted disease name and its probability (that states how confident the model is about the prediction). It saves the heatmap having the same filename i.e. overwrites the original file."
},
{
"code": null,
"e": 13136,
"s": 12848,
"text": "‘/detect’ route gets the image from React application, generates the heatmap that highlights the disease's discriminant features, and reverts it along with the disease category to the application. It also returns the probability of the prediction. Fig 7. dictates the flow of this route."
},
{
"code": null,
"e": 13278,
"s": 13136,
"text": "Below is the code adaptation of this route. It works exactly in the same manner as shown in Fig 7. Hence, the code below is self-explanatory."
},
{
"code": null,
"e": 13976,
"s": 13278,
"text": "@app.route('/detect', methods=['POST'])def change(): image_size = (224,224) img_data = request.get_json()['image'] img_name = str(int(datetime.timestamp(datetime.now()))) + str(np.random.randint(1000000000)) img_name = sha256(img_name.encode()).hexdigest()[0:12] img_data = np.array(list(img_data.values())).reshape([224, 224, 3]) im = Image.fromarray((img_data).astype(np.uint8)) im.save(img_name+'.jpg') disease, probab = visualize_image(img_name+'.jpg') img = cv2.imread(img_name+'.jpg') img = cv2.resize(img, image_size) / 255.0 img = img.tolist() os.remove(img_name+'.jpg') return json.dumps({\"image\": img, \"disease\":int(disease), \"probab\":str(probab)})"
},
{
"code": null,
"e": 14147,
"s": 13976,
"text": "1. Comment your request with the proper reason on the below post on LinkedIn and I will share the personal links to access the pre-trained saved model in various formats:"
},
{
"code": null,
"e": 14164,
"s": 14147,
"text": "www.linkedin.com"
},
{
"code": null,
"e": 14226,
"s": 14164,
"text": "Let’s get to the coding part (App.js) file in React directly."
},
{
"code": null,
"e": 14292,
"s": 14226,
"text": "First, we will import some libraries and define global variables."
},
{
"code": null,
"e": 14594,
"s": 14292,
"text": "import logo from './logo.svg';import './App.css';import React from 'react';import * as tf from '@tensorflow/tfjs';import cat from './cat.jpg';import {CLASSES} from './imagenet_classes';const axios = require('axios');const IMAGE_SIZE = 224;let mobilenet;let demoStatusElement;let status;let mobilenet2;"
},
{
"code": null,
"e": 14926,
"s": 14594,
"text": "imagenet_classes is a file containing the names of all classes and corresponding numbers in a dictionary. Don’t mind the variable names! This code has gone through many attempts to get a perfect application for the task at hand. Next, we will start with the class ‘App’. The first method inside the class is the constructor method."
},
{
"code": null,
"e": 15290,
"s": 14926,
"text": "constructor(props){ super(props); this.state = { load:false, status: \"F1 score of the model is: 0.9908 \", probab: \"\" }; this.mobilenetDemo = this.mobilenetDemo.bind(this); this.predict = this.predict.bind(this); this.showResults = this.showResults.bind(this); this.filechangehandler = this.filechangehandler.bind(this); }"
},
{
"code": null,
"e": 15574,
"s": 15290,
"text": "load state is for the animation before loading the image. status is the default statement to be stated in the application. probab state changes each time an image has been passed containing the accuracy of its prediction. The four methods will be discussed in the following sections."
},
{
"code": null,
"e": 15783,
"s": 15574,
"text": "Now, we will define all these 4 methods for particular tasks. As I instructed before about the variable names, ignore those. ResTS architecture uses Xception architecture even if some variables say mobilenet."
},
{
"code": null,
"e": 16121,
"s": 15783,
"text": "async mobilenetDemo(){ const catElement = document.getElementById('cat'); if (catElement.complete && catElement.naturalHeight !== 0) { this.predict(catElement); catElement.style.display = ''; } else { catElement.onload = () => { this.predict(catElement); catElement.style.display = ''; } }};"
},
{
"code": null,
"e": 16440,
"s": 16121,
"text": "mobilenetDemo() async method loads the first image when the app is rendered for the first time and its prediction by calling the prediction() method. prediction() method takes image element as input and calls the Flask server for relevant predictions. The server returns 3 parameters- disease, probability and heatmap."
},
{
"code": null,
"e": 16950,
"s": 16440,
"text": "async predict(imgElement) { let img = tf.browser.fromPixels(imgElement).toFloat().reshape([1, 224, 224, 3]); //img = tf.reverse(img, -1); this.setState({ load:true }); const image = await axios.post('http://localhost:5000/detect', {'image': img.dataSync()}); this.setState({ load:false }); // // Show the classes in the DOM. this.showResults(imgElement, image.data['disease'], image.data['probab'], tf.tensor3d([image.data['image']].flat(), [224, 224, 3])); }"
},
{
"code": null,
"e": 17210,
"s": 16950,
"text": "At last, showResults() method is called to display the results in the app. showResults() method takes 4 values as parameters from the prediction() method. This method does some basic HTML operations to portray the results from the server into the application."
},
{
"code": null,
"e": 18611,
"s": 17210,
"text": "async showResults(imgElement, diseaseClass, probab, tensor) { const predictionContainer = document.createElement('div'); predictionContainer.className = 'pred-container'; const imgContainer = document.createElement('div'); imgContainer.appendChild(imgElement); predictionContainer.appendChild(imgContainer); const probsContainer = document.createElement('div'); const predictedCanvas = document.createElement('canvas'); probsContainer.appendChild(predictedCanvas); predictedCanvas.width = tensor.shape[0]; predictedCanvas.height = tensor.shape[1]; tensor = tf.reverse(tensor, -1); await tf.browser.toPixels(tensor, predictedCanvas); console.log(probab); this.setState({ probab: \"The last prediction was \" + parseFloat(probab)*100 + \" % accurate!\" }); const predictedDisease = document.createElement('p'); predictedDisease.innerHTML = 'Disease: '; const i = document.createElement('i'); i.innerHTML = CLASSES[diseaseClass]; predictedDisease.appendChild(i); //probsContainer.appendChild(predictedCanvas); //probsContainer.appendChild(predictedDisease); predictionContainer.appendChild(probsContainer); predictionContainer.appendChild(predictedDisease); const predictionsElement = document.getElementById('predictions'); predictionsElement.insertBefore( predictionContainer, predictionsElement.firstChild); }"
},
{
"code": null,
"e": 18710,
"s": 18611,
"text": "The filechangehandler() method gets triggered whenever an image is uploaded via the upload button."
},
{
"code": null,
"e": 19308,
"s": 18710,
"text": "filechangehandler(evt){ let files = evt.target.files; for (let i = 0, f; f = files[i]; i++) { // Only process image files (skip non image files) if (!f.type.match('image.*')) { continue; } let reader = new FileReader(); reader.onload = e => { // Fill the image & call predict. let img = document.createElement('img'); img.src = e.target.result; img.width = IMAGE_SIZE; img.height = IMAGE_SIZE; img.onload = () => this.predict(img); };// Read in the image file as a data URL. reader.readAsDataURL(f); } }"
},
{
"code": null,
"e": 19473,
"s": 19308,
"text": "Finally, we want to call the mobilenetDemo() method to load the first image and its prediction. For this task, we will use the componentDidMount() lifecycle method."
},
{
"code": null,
"e": 20914,
"s": 19473,
"text": "componentDidMount(){ this.mobilenetDemo(); }render(){ return ( <div className=\"tfjs-example-container\"> <section className='title-area'> <h1>ResTS for Plant Disease Diagnosis</h1> </section><section> <p className='section-head'>Description</p> <p> This WebApp uses the ResTS model which will be made available soon for public use.It is not trained to recognize images that DO NOT have BLACK BACKGROUNDS. For best performance, upload images of leaf\\/Plant with black background. You can see the disease categories it has been trained to recognize in <a href=\"https://github.com/spMohanty/PlantVillage-Dataset/tree/master/raw/segmented\">this folder</a>. </p> </section><section> <p className='section-head'>Status</p> {this.state.load?<div id=\"status\">{this.state.status}</div>:<div id=\"status\">{this.state.status}<br></br>{this.state.probab}</div>} </section><section> <p className='section-head'>Model Output</p><div id=\"file-container\"> Upload an image: <input type=\"file\" id=\"files\" name=\"files[]\" onChange={this.filechangehandler} multiple /> </div> {this.state.load?<div className=\"lds-roller\"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>:''}<div id=\"predictions\"></div><img id=\"cat\" src={cat}/> </section> </div>);}"
},
{
"code": null,
"e": 20979,
"s": 20914,
"text": "The render() method contains the self-explanatory HTML elements."
},
{
"code": null,
"e": 21117,
"s": 20979,
"text": "The Gif below portrays the working of the web application that is connected with the flask server comprising the pre-trained ResTS model."
},
{
"code": null,
"e": 21339,
"s": 21117,
"text": "D. Shah, V. Trivedi, V. Sheth, A. Shah, U. Chauhan, ResTS: Residual DeepInterpretable Architecture for Plant Disease Detection, Information Processing in Agriculture (2021), doi: https://doi.org/10.1016/j.inpa.2021.06.001"
}
] |
How to change the font size of scientific notation in Matplotlib?
|
To change the fontsize of scientific notation in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Make a list of x and y values.
Make a list of x and y values.
Plot x and y data points using plot() method.
Plot x and y data points using plot() method.
To change the font size of scientific notation, we can use style="sci" class by name.
To change the font size of scientific notation, we can use style="sci" class by name.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = [10000, 20000, 300000, 34, 1, 10000]
y = [1, 2, 0, 4, 1, 5]
plt.plot(x, y, color='red')
plt.ticklabel_format(axis="x", style="sci", scilimits=(0, 0))
plt.show()
|
[
{
"code": null,
"e": 1157,
"s": 1062,
"text": "To change the fontsize of scientific notation in matplotlib, we can take the following steps −"
},
{
"code": null,
"e": 1233,
"s": 1157,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1309,
"s": 1233,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1340,
"s": 1309,
"text": "Make a list of x and y values."
},
{
"code": null,
"e": 1371,
"s": 1340,
"text": "Make a list of x and y values."
},
{
"code": null,
"e": 1417,
"s": 1371,
"text": "Plot x and y data points using plot() method."
},
{
"code": null,
"e": 1463,
"s": 1417,
"text": "Plot x and y data points using plot() method."
},
{
"code": null,
"e": 1549,
"s": 1463,
"text": "To change the font size of scientific notation, we can use style=\"sci\" class by name."
},
{
"code": null,
"e": 1635,
"s": 1549,
"text": "To change the font size of scientific notation, we can use style=\"sci\" class by name."
},
{
"code": null,
"e": 1677,
"s": 1635,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1719,
"s": 1677,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2012,
"s": 1719,
"text": "from matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = [10000, 20000, 300000, 34, 1, 10000]\ny = [1, 2, 0, 4, 1, 5]\n\nplt.plot(x, y, color='red')\nplt.ticklabel_format(axis=\"x\", style=\"sci\", scilimits=(0, 0))\n\nplt.show()"
}
] |
How to read a cookie using JavaScript?
|
Following is the code to read a cookie using JavaScript −
Note − A local server would be needed to run this example.
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: blueviolet
}
</style>
</head>
<body>
<h1>Read a cookie using JavaScript</h1>
<div class="result"></div>
<button class="Btn">Click here</button>
<h3>Click on the above button to read the cookie</h3>
<script>
let BtnEle = document.querySelector(".Btn");
let resEle = document.querySelector(".result");
document.cookie = "Name=Rohan Sharma";
BtnEle.addEventListener("click", () => {
resEle.innerHTML = document.cookie;
});
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
|
[
{
"code": null,
"e": 1120,
"s": 1062,
"text": "Following is the code to read a cookie using JavaScript −"
},
{
"code": null,
"e": 1179,
"s": 1120,
"text": "Note − A local server would be needed to run this example."
},
{
"code": null,
"e": 1190,
"s": 1179,
"text": " Live Demo"
},
{
"code": null,
"e": 1986,
"s": 1190,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: blueviolet\n }\n</style>\n</head>\n<body>\n<h1>Read a cookie using JavaScript</h1>\n<div class=\"result\"></div>\n<button class=\"Btn\">Click here</button>\n<h3>Click on the above button to read the cookie</h3>\n<script>\n let BtnEle = document.querySelector(\".Btn\");\n let resEle = document.querySelector(\".result\");\n document.cookie = \"Name=Rohan Sharma\";\n BtnEle.addEventListener(\"click\", () => {\n resEle.innerHTML = document.cookie;\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2024,
"s": 1986,
"text": "On clicking the ‘CLICK HERE’ button −"
}
] |
How to set locale programmatically in android app?
|
This example demonstrates how do I set locale programmatically in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:text="@string/Have_a_nice_day"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textStyle="bold"
android:textSize="24sp"/>
</RelativeLayout>
Step 3 – Create a directory (values-es) and copy the string.xml file into this directory and make the below changes
<resources>
<string name="app_name">Sample</string>
<string name="Have_a_nice_day">Que tengas un buen día</string>
</resources>
Step 4 − Add the following code to src/MainActivity.java
import android.content.res.Configuration;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setAppLocale("es");
setContentView(R.layout.activity_main);
}
private void setAppLocale(String localeCode){
Resources resources = getResources();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
Configuration configuration = resources.getConfiguration();
configuration.setLocale(new Locale(localeCode.toLowerCase()));
resources.updateConfiguration(configuration, displayMetrics);
configuration.locale = new Locale(localeCode.toLowerCase());
resources.updateConfiguration(configuration, displayMetrics);
}
}
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">
<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 Mobiledevice with your computer. To run the app from android studio, open one of your project'sactivity files and click Run icon from the toolbar. Select your mobile device as an optionand then check your mobile device which will display your default screen –
Click here to download the project code.
|
[
{
"code": null,
"e": 1137,
"s": 1062,
"text": "This example demonstrates how do I set locale programmatically in android."
},
{
"code": null,
"e": 1266,
"s": 1137,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1331,
"s": 1266,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1908,
"s": 1331,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:text=\"@string/Have_a_nice_day\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textStyle=\"bold\"\n android:textSize=\"24sp\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 2024,
"s": 1908,
"text": "Step 3 – Create a directory (values-es) and copy the string.xml file into this directory and make the below changes"
},
{
"code": null,
"e": 2159,
"s": 2024,
"text": "<resources>\n <string name=\"app_name\">Sample</string>\n <string name=\"Have_a_nice_day\">Que tengas un buen día</string>\n</resources>"
},
{
"code": null,
"e": 2216,
"s": 2159,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3181,
"s": 2216,
"text": "import android.content.res.Configuration;\nimport android.content.res.Resources;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.DisplayMetrics;\nimport java.util.Locale;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setAppLocale(\"es\");\n setContentView(R.layout.activity_main);\n }\n private void setAppLocale(String localeCode){\n Resources resources = getResources();\n DisplayMetrics displayMetrics = resources.getDisplayMetrics();\n Configuration configuration = resources.getConfiguration();\n configuration.setLocale(new Locale(localeCode.toLowerCase()));\n resources.updateConfiguration(configuration, displayMetrics);\n configuration.locale = new Locale(localeCode.toLowerCase());\n resources.updateConfiguration(configuration, displayMetrics);\n }\n}"
},
{
"code": null,
"e": 3236,
"s": 3181,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3906,
"s": 3236,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\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": 4250,
"s": 3906,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobiledevice with your computer. To run the app from android studio, open one of your project'sactivity files and click Run icon from the toolbar. Select your mobile device as an optionand then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 4291,
"s": 4250,
"text": "Click here to download the project code."
}
] |
Clinical Notes — The “Negative” Story | by Ranga Sampath (youplusai) | Towards Data Science
|
Abstract: In this article, you will learn what a clinical note is, why understanding clinical notes may be useful, what are some special characteristics of such notes, what is negation and how may it be useful, what are ways in which information in a clinical note may be retrieved and some ideas to explore further once we have a basic understanding.
Clinical notes contain valuable information that helps develop a more complete understanding of the patient.
Our mission is to find out how we can extract what is commonly used in a clinical note — Negations.
(If you are already aware of what this is and would like to jump right into the code, click here).
Let’s dive in!
A clinical note is written by a clinician or a healthcare professional when providing clinical care for patients. It describes patients, their history be it medical, family, socio-economic, dietary, hereditary etc., their present illness or condition, any findings from the physical exam that was carried out (if patient history taking interests you, check out this transcript of the You+AI podcast episode — the doctor-patient relationship).
It may also have details of lab tests that have been ordered, their results, the details of any procedures done, the medicines being taken by the patient and any dosage information.
Here is a sample of a clinical note that describes the condition of a patient when he showed up to seek care.
Patient is a 60 year old having difficulty in breathing. Not diabetic. He feels that he has been in good health until this current episode. Appetite — good. No chest pain. No weight loss or episodes of stomach pain. Hypertension absent.
Many more may be found at https:/mtsamples.com/.
Clinical notes can yield a wealth of information when examined. Some uses are as follows.
It adds to the primary diagnosis that has been done for the patient.
They act as references for the clinical team helping them in clinical decision support.
The patient history may be valuable in understanding what kind of patients present what types of conditions.
Mining clinical notes may help in the identification of new patterns of symptoms and disease.
Clinical notes may help add billing codes to the patient’s medical record.
A clinical note is written as part of medical care that is given. It may not be grammatically correct, it will most likely have spelling errors, it may have short phrases and a number of abbreviations and acronyms and there is hardly any standardization i.e. it will vary from one hospital or clinic to another and even from one clinician to another.
Negation — A typical clinical note in addition to reporting the conditions that the patient has, also reports the conditions that a patient does not have. This is important to have a better medical understanding of the patient. This is not something that you would see in a pronounced manner in regular language.
Examples of Negation
Not diabetic.
No chest pain.
No weight loss or episodes of stomach pain.
Hypertension absent.
Context — This refers to a condition that a patient had previously or a relevant condition that the patient’s family member had.
Examples of Context
Patient’s mother and father developed Diabetes in their 50s.
Patient — long history of common cold.
Our objective is to identify the negations in the clinical note presented above. As stated earlier, negation allows for a more complete understanding of the patient.
Many of the NLP frameworks available today from the key providers say Amazon, Microsoft and Google have APIs that will accept English language text and identify many aspects in that text.
So, we will pass the clinical note through the Google NLP API and see what it yields. For contrast, we will also pass in text that is not a clinical note to see what comes out.
Non-clinical text
Clinical text
When comparing the results above, the following is evident.
The API identifies a lot more entities in non-clinical English language text.
The API does not classify medical terms well i.e. diseases, medicines, treatments etc.
The API classifies some clinical terms in an unexpected manner.
Negation is not at all detected.
So, this API may not be the best suited for clinical note parsing. This is also the reason why Google (and it’s competitors) have a separate, specific Healthcare NLP API. I will share my experiments with this API in a subsequent post.
At this time, our discussion will continue to explore Open Source Software (OSS) options to meet our objective.
We use the following libraries and continue the work in Python.
spaCy — An open source NLP library in Python.
Negspacy : A spaCy NLP pipeline object for identifying negation in text. Based on the NegEx algorithm.
NegEx : — NegEx is an algorithm that locates trigger terms indicating a clinical condition is negated or possible and determines which text falls within the scope.
The first step is to install all these libraries in case you already don’t have them. Note that the model being used is a Spacy NER model trained on the BC5CDR corpus.
pip install spacypip install negspacypip install <Model URL> en_ner_bc5cdr_md
Model URL
The next step is to import the relevant modules into your python script.
This comprises two parts — adding a Negex component to the NLP pipeline and then using that on every sentence of the clinical note to identify the negation entities. Once all of them have identified, they are printed in a list.
From this table, we see that ‘Hypertension’ was not found as a negation entity. Note that the ‘absent’ keyword was used after ‘Hypertension’ in the clinical note.
A couple of ways that may be tried out to improve the findings are listed out below.
Change the clinical note
Change the clinical note
Change “Hypertension absent.” To “No Hypertension.”
Result: Hypertension is recognized as a Negation Entity.
Note: It is impractical to change the clinical note when considering a production use case. Therefore this experiment is only to show when a negation entity is easily recognized vs. when it isn’t.
2. Use custom patterns in Negspacy
Certain keywords or phrases that follow an entity and indicate negation (e.g. ‘absent’) may be added to Negex. In our example, this means changing the negation_model() function as follows.
Result: Hypertension is recognized as a Negation Entity.
Note: This is more practical to implement but the challenge may be to find such preceding or following phrase patterns in all of the clinical text corpus under consideration.
Termination patterns — Example: Diabetes denied, Stomach ache not present, Congestion none
Use of prefixes — Example: Patient is non-diabetic, non-hypertensive.
Double negatives — Example: The patient is not abnormal.
Symbols usage — Example: Hypertension +, Diabetes –
Positive/Negative usage — Example: Hypertension positive, Diabetes negative.
Yes/No phrases — Example: Hypertension — No, Diabetes — Yes, Urinary problems — No.
Use of more generic language than clinical terminology — Example — No complaint of high sugar (rather than No Diabetes).
This only means we need to test our solution more and more with a rich dataset of clinical notes to iron out as many cases as possible.
Mining negations in clinical notes is a way of mining useful information from unstructured data. Besides the use cases that we have delved into above, I see a few big areas this may have a significant impact in.
Building disease correlations
Building disease correlations
As an example, when reviewing clinical cases in a specific area, say infectious diseases as part of an Mortality & Morbidity (M & M) Review, a diagnosis of typhoid but with a negation entity of fever being documented in the clinical note may either point to an incorrect diagnosis or to an erroneous note.
So, analyzing a large volume of clinical notes may provide us the correlations that exist between diseases and symptoms. This may especially help for rare diseases.
2. Discovering best practices
Clinical notes taken within various medical departments of a hospital may be compared or clinical notes taken by the same specialty department, say gastroenterology may be compared across hospitals to discover the typical patterns of patient history taking or discharge summaries. The best practices in clinical note taking may surface from this and this may help inform clinical management.
3. Teaching
Taking down patient conditions when they get admitted and noting down patient history is an important aspect that is taught to medical students. In addition to having a repository of digital clinical notes, an understanding of correlations mined from these notes, best practices gleaned and the extent to which information from clinical notes may be mined to discover new insights may drive home the importance of taking down such notes in adequate and appropriate measure.
In this article, we started with what a clinical note is, explored what kinds of information may be available in such a note, pondered about how does negation play a role in understanding the patient’s condition better, tinkered with ways to extract the negation entities and experimented with ways to improve our solution.
This investigation project is one of many ideas that I would like to explore around healthcare data mining. I believe there’s huge potential in the application of Machine Learning in Healthcare but we need to peel one layer at a time.
Some more ideas to take this further may be –
Identify further interesting negation patterns in clinical notes — crowdsourcing will certainly help.
Try out the Healthcare NLP API from one of the big 3 cloud vendors — Amazon, Microsoft and Google. Identify what more does that achieve over what OSS does.
Compare the Healthcare NLP API of the big 3 cloud vendors.
I will be exploring these and more in this area. If you’re interested in such endeavors, please join along my journey by following me on Twitter and subscribing to the youplusai YouTube channel.
Many thanks to Dr. T. R. Gopalan, Madhusoodhana Chari, Umashankar S and Kurtis Pykes for their feedback on this blog.
Originally published @ youplusai.com.
|
[
{
"code": null,
"e": 523,
"s": 171,
"text": "Abstract: In this article, you will learn what a clinical note is, why understanding clinical notes may be useful, what are some special characteristics of such notes, what is negation and how may it be useful, what are ways in which information in a clinical note may be retrieved and some ideas to explore further once we have a basic understanding."
},
{
"code": null,
"e": 632,
"s": 523,
"text": "Clinical notes contain valuable information that helps develop a more complete understanding of the patient."
},
{
"code": null,
"e": 732,
"s": 632,
"text": "Our mission is to find out how we can extract what is commonly used in a clinical note — Negations."
},
{
"code": null,
"e": 831,
"s": 732,
"text": "(If you are already aware of what this is and would like to jump right into the code, click here)."
},
{
"code": null,
"e": 846,
"s": 831,
"text": "Let’s dive in!"
},
{
"code": null,
"e": 1289,
"s": 846,
"text": "A clinical note is written by a clinician or a healthcare professional when providing clinical care for patients. It describes patients, their history be it medical, family, socio-economic, dietary, hereditary etc., their present illness or condition, any findings from the physical exam that was carried out (if patient history taking interests you, check out this transcript of the You+AI podcast episode — the doctor-patient relationship)."
},
{
"code": null,
"e": 1471,
"s": 1289,
"text": "It may also have details of lab tests that have been ordered, their results, the details of any procedures done, the medicines being taken by the patient and any dosage information."
},
{
"code": null,
"e": 1581,
"s": 1471,
"text": "Here is a sample of a clinical note that describes the condition of a patient when he showed up to seek care."
},
{
"code": null,
"e": 1818,
"s": 1581,
"text": "Patient is a 60 year old having difficulty in breathing. Not diabetic. He feels that he has been in good health until this current episode. Appetite — good. No chest pain. No weight loss or episodes of stomach pain. Hypertension absent."
},
{
"code": null,
"e": 1867,
"s": 1818,
"text": "Many more may be found at https:/mtsamples.com/."
},
{
"code": null,
"e": 1957,
"s": 1867,
"text": "Clinical notes can yield a wealth of information when examined. Some uses are as follows."
},
{
"code": null,
"e": 2026,
"s": 1957,
"text": "It adds to the primary diagnosis that has been done for the patient."
},
{
"code": null,
"e": 2114,
"s": 2026,
"text": "They act as references for the clinical team helping them in clinical decision support."
},
{
"code": null,
"e": 2223,
"s": 2114,
"text": "The patient history may be valuable in understanding what kind of patients present what types of conditions."
},
{
"code": null,
"e": 2317,
"s": 2223,
"text": "Mining clinical notes may help in the identification of new patterns of symptoms and disease."
},
{
"code": null,
"e": 2392,
"s": 2317,
"text": "Clinical notes may help add billing codes to the patient’s medical record."
},
{
"code": null,
"e": 2743,
"s": 2392,
"text": "A clinical note is written as part of medical care that is given. It may not be grammatically correct, it will most likely have spelling errors, it may have short phrases and a number of abbreviations and acronyms and there is hardly any standardization i.e. it will vary from one hospital or clinic to another and even from one clinician to another."
},
{
"code": null,
"e": 3056,
"s": 2743,
"text": "Negation — A typical clinical note in addition to reporting the conditions that the patient has, also reports the conditions that a patient does not have. This is important to have a better medical understanding of the patient. This is not something that you would see in a pronounced manner in regular language."
},
{
"code": null,
"e": 3077,
"s": 3056,
"text": "Examples of Negation"
},
{
"code": null,
"e": 3091,
"s": 3077,
"text": "Not diabetic."
},
{
"code": null,
"e": 3106,
"s": 3091,
"text": "No chest pain."
},
{
"code": null,
"e": 3150,
"s": 3106,
"text": "No weight loss or episodes of stomach pain."
},
{
"code": null,
"e": 3171,
"s": 3150,
"text": "Hypertension absent."
},
{
"code": null,
"e": 3300,
"s": 3171,
"text": "Context — This refers to a condition that a patient had previously or a relevant condition that the patient’s family member had."
},
{
"code": null,
"e": 3320,
"s": 3300,
"text": "Examples of Context"
},
{
"code": null,
"e": 3381,
"s": 3320,
"text": "Patient’s mother and father developed Diabetes in their 50s."
},
{
"code": null,
"e": 3420,
"s": 3381,
"text": "Patient — long history of common cold."
},
{
"code": null,
"e": 3586,
"s": 3420,
"text": "Our objective is to identify the negations in the clinical note presented above. As stated earlier, negation allows for a more complete understanding of the patient."
},
{
"code": null,
"e": 3774,
"s": 3586,
"text": "Many of the NLP frameworks available today from the key providers say Amazon, Microsoft and Google have APIs that will accept English language text and identify many aspects in that text."
},
{
"code": null,
"e": 3951,
"s": 3774,
"text": "So, we will pass the clinical note through the Google NLP API and see what it yields. For contrast, we will also pass in text that is not a clinical note to see what comes out."
},
{
"code": null,
"e": 3969,
"s": 3951,
"text": "Non-clinical text"
},
{
"code": null,
"e": 3983,
"s": 3969,
"text": "Clinical text"
},
{
"code": null,
"e": 4043,
"s": 3983,
"text": "When comparing the results above, the following is evident."
},
{
"code": null,
"e": 4121,
"s": 4043,
"text": "The API identifies a lot more entities in non-clinical English language text."
},
{
"code": null,
"e": 4208,
"s": 4121,
"text": "The API does not classify medical terms well i.e. diseases, medicines, treatments etc."
},
{
"code": null,
"e": 4272,
"s": 4208,
"text": "The API classifies some clinical terms in an unexpected manner."
},
{
"code": null,
"e": 4305,
"s": 4272,
"text": "Negation is not at all detected."
},
{
"code": null,
"e": 4540,
"s": 4305,
"text": "So, this API may not be the best suited for clinical note parsing. This is also the reason why Google (and it’s competitors) have a separate, specific Healthcare NLP API. I will share my experiments with this API in a subsequent post."
},
{
"code": null,
"e": 4652,
"s": 4540,
"text": "At this time, our discussion will continue to explore Open Source Software (OSS) options to meet our objective."
},
{
"code": null,
"e": 4716,
"s": 4652,
"text": "We use the following libraries and continue the work in Python."
},
{
"code": null,
"e": 4762,
"s": 4716,
"text": "spaCy — An open source NLP library in Python."
},
{
"code": null,
"e": 4865,
"s": 4762,
"text": "Negspacy : A spaCy NLP pipeline object for identifying negation in text. Based on the NegEx algorithm."
},
{
"code": null,
"e": 5029,
"s": 4865,
"text": "NegEx : — NegEx is an algorithm that locates trigger terms indicating a clinical condition is negated or possible and determines which text falls within the scope."
},
{
"code": null,
"e": 5197,
"s": 5029,
"text": "The first step is to install all these libraries in case you already don’t have them. Note that the model being used is a Spacy NER model trained on the BC5CDR corpus."
},
{
"code": null,
"e": 5275,
"s": 5197,
"text": "pip install spacypip install negspacypip install <Model URL> en_ner_bc5cdr_md"
},
{
"code": null,
"e": 5285,
"s": 5275,
"text": "Model URL"
},
{
"code": null,
"e": 5358,
"s": 5285,
"text": "The next step is to import the relevant modules into your python script."
},
{
"code": null,
"e": 5586,
"s": 5358,
"text": "This comprises two parts — adding a Negex component to the NLP pipeline and then using that on every sentence of the clinical note to identify the negation entities. Once all of them have identified, they are printed in a list."
},
{
"code": null,
"e": 5749,
"s": 5586,
"text": "From this table, we see that ‘Hypertension’ was not found as a negation entity. Note that the ‘absent’ keyword was used after ‘Hypertension’ in the clinical note."
},
{
"code": null,
"e": 5834,
"s": 5749,
"text": "A couple of ways that may be tried out to improve the findings are listed out below."
},
{
"code": null,
"e": 5859,
"s": 5834,
"text": "Change the clinical note"
},
{
"code": null,
"e": 5884,
"s": 5859,
"text": "Change the clinical note"
},
{
"code": null,
"e": 5936,
"s": 5884,
"text": "Change “Hypertension absent.” To “No Hypertension.”"
},
{
"code": null,
"e": 5993,
"s": 5936,
"text": "Result: Hypertension is recognized as a Negation Entity."
},
{
"code": null,
"e": 6190,
"s": 5993,
"text": "Note: It is impractical to change the clinical note when considering a production use case. Therefore this experiment is only to show when a negation entity is easily recognized vs. when it isn’t."
},
{
"code": null,
"e": 6225,
"s": 6190,
"text": "2. Use custom patterns in Negspacy"
},
{
"code": null,
"e": 6414,
"s": 6225,
"text": "Certain keywords or phrases that follow an entity and indicate negation (e.g. ‘absent’) may be added to Negex. In our example, this means changing the negation_model() function as follows."
},
{
"code": null,
"e": 6471,
"s": 6414,
"text": "Result: Hypertension is recognized as a Negation Entity."
},
{
"code": null,
"e": 6646,
"s": 6471,
"text": "Note: This is more practical to implement but the challenge may be to find such preceding or following phrase patterns in all of the clinical text corpus under consideration."
},
{
"code": null,
"e": 6737,
"s": 6646,
"text": "Termination patterns — Example: Diabetes denied, Stomach ache not present, Congestion none"
},
{
"code": null,
"e": 6807,
"s": 6737,
"text": "Use of prefixes — Example: Patient is non-diabetic, non-hypertensive."
},
{
"code": null,
"e": 6864,
"s": 6807,
"text": "Double negatives — Example: The patient is not abnormal."
},
{
"code": null,
"e": 6916,
"s": 6864,
"text": "Symbols usage — Example: Hypertension +, Diabetes –"
},
{
"code": null,
"e": 6993,
"s": 6916,
"text": "Positive/Negative usage — Example: Hypertension positive, Diabetes negative."
},
{
"code": null,
"e": 7077,
"s": 6993,
"text": "Yes/No phrases — Example: Hypertension — No, Diabetes — Yes, Urinary problems — No."
},
{
"code": null,
"e": 7198,
"s": 7077,
"text": "Use of more generic language than clinical terminology — Example — No complaint of high sugar (rather than No Diabetes)."
},
{
"code": null,
"e": 7334,
"s": 7198,
"text": "This only means we need to test our solution more and more with a rich dataset of clinical notes to iron out as many cases as possible."
},
{
"code": null,
"e": 7546,
"s": 7334,
"text": "Mining negations in clinical notes is a way of mining useful information from unstructured data. Besides the use cases that we have delved into above, I see a few big areas this may have a significant impact in."
},
{
"code": null,
"e": 7576,
"s": 7546,
"text": "Building disease correlations"
},
{
"code": null,
"e": 7606,
"s": 7576,
"text": "Building disease correlations"
},
{
"code": null,
"e": 7912,
"s": 7606,
"text": "As an example, when reviewing clinical cases in a specific area, say infectious diseases as part of an Mortality & Morbidity (M & M) Review, a diagnosis of typhoid but with a negation entity of fever being documented in the clinical note may either point to an incorrect diagnosis or to an erroneous note."
},
{
"code": null,
"e": 8077,
"s": 7912,
"text": "So, analyzing a large volume of clinical notes may provide us the correlations that exist between diseases and symptoms. This may especially help for rare diseases."
},
{
"code": null,
"e": 8107,
"s": 8077,
"text": "2. Discovering best practices"
},
{
"code": null,
"e": 8499,
"s": 8107,
"text": "Clinical notes taken within various medical departments of a hospital may be compared or clinical notes taken by the same specialty department, say gastroenterology may be compared across hospitals to discover the typical patterns of patient history taking or discharge summaries. The best practices in clinical note taking may surface from this and this may help inform clinical management."
},
{
"code": null,
"e": 8511,
"s": 8499,
"text": "3. Teaching"
},
{
"code": null,
"e": 8985,
"s": 8511,
"text": "Taking down patient conditions when they get admitted and noting down patient history is an important aspect that is taught to medical students. In addition to having a repository of digital clinical notes, an understanding of correlations mined from these notes, best practices gleaned and the extent to which information from clinical notes may be mined to discover new insights may drive home the importance of taking down such notes in adequate and appropriate measure."
},
{
"code": null,
"e": 9309,
"s": 8985,
"text": "In this article, we started with what a clinical note is, explored what kinds of information may be available in such a note, pondered about how does negation play a role in understanding the patient’s condition better, tinkered with ways to extract the negation entities and experimented with ways to improve our solution."
},
{
"code": null,
"e": 9544,
"s": 9309,
"text": "This investigation project is one of many ideas that I would like to explore around healthcare data mining. I believe there’s huge potential in the application of Machine Learning in Healthcare but we need to peel one layer at a time."
},
{
"code": null,
"e": 9590,
"s": 9544,
"text": "Some more ideas to take this further may be –"
},
{
"code": null,
"e": 9692,
"s": 9590,
"text": "Identify further interesting negation patterns in clinical notes — crowdsourcing will certainly help."
},
{
"code": null,
"e": 9848,
"s": 9692,
"text": "Try out the Healthcare NLP API from one of the big 3 cloud vendors — Amazon, Microsoft and Google. Identify what more does that achieve over what OSS does."
},
{
"code": null,
"e": 9907,
"s": 9848,
"text": "Compare the Healthcare NLP API of the big 3 cloud vendors."
},
{
"code": null,
"e": 10102,
"s": 9907,
"text": "I will be exploring these and more in this area. If you’re interested in such endeavors, please join along my journey by following me on Twitter and subscribing to the youplusai YouTube channel."
},
{
"code": null,
"e": 10220,
"s": 10102,
"text": "Many thanks to Dr. T. R. Gopalan, Madhusoodhana Chari, Umashankar S and Kurtis Pykes for their feedback on this blog."
}
] |
Functions that are executed before and after main() in C
|
Here we will see how to write a code where two functions are present, and one function will be executed before the main function, and another function will be executed after the main function. These features are used to do some startup task before executing the main, and some cleanup task after executing main.
To do this task we have to put attribute for these two functions. When the attribute is constructor attribute, then it will be executed before main(), and when the attribute is destructor type, then it will be executed after main().
#include<stdio.h>
void before_main() __attribute__((constructor));
void after_main() __attribute__((destructor));
void before_main() {
printf("This is executed before main.\n");
}
void after_main() {
printf("This is executed after main.");
}
main() {
printf("Inside main\n");
}
This is executed before main.
Inside main
This is executed after main.
|
[
{
"code": null,
"e": 1374,
"s": 1062,
"text": "Here we will see how to write a code where two functions are present, and one function will be executed before the main function, and another function will be executed after the main function. These features are used to do some startup task before executing the main, and some cleanup task after executing main."
},
{
"code": null,
"e": 1607,
"s": 1374,
"text": "To do this task we have to put attribute for these two functions. When the attribute is constructor attribute, then it will be executed before main(), and when the attribute is destructor type, then it will be executed after main()."
},
{
"code": null,
"e": 1894,
"s": 1607,
"text": "#include<stdio.h>\nvoid before_main() __attribute__((constructor));\nvoid after_main() __attribute__((destructor));\nvoid before_main() {\n printf(\"This is executed before main.\\n\");\n}\nvoid after_main() {\n printf(\"This is executed after main.\");\n}\nmain() {\n printf(\"Inside main\\n\");\n}"
},
{
"code": null,
"e": 1965,
"s": 1894,
"text": "This is executed before main.\nInside main\nThis is executed after main."
}
] |
Boundary Traversal of binary tree | Practice | GeeksforGeeks
|
Given a Binary Tree, find its Boundary Traversal. The traversal should be in the following order:
Left boundary nodes: defined as the path from the root to the left-most node ie- the leaf node you could reach when you always travel preferring the left subtree over the right subtree.
Leaf nodes: All the leaf nodes except for the ones that are part of left or right boundary.
Reverse right boundary nodes: defined as the path from the right-most node to the root. The right-most node is the leaf node you could reach when you always travel preferring the right subtree over the left subtree. Exclude the root from this as it was already included in the traversal of left boundary nodes.
Left boundary nodes: defined as the path from the root to the left-most node ie- the leaf node you could reach when you always travel preferring the left subtree over the right subtree.
Leaf nodes: All the leaf nodes except for the ones that are part of left or right boundary.
Reverse right boundary nodes: defined as the path from the right-most node to the root. The right-most node is the leaf node you could reach when you always travel preferring the right subtree over the left subtree. Exclude the root from this as it was already included in the traversal of left boundary nodes.
Note: If the root doesn't have a left subtree or right subtree, then the root itself is the left or right boundary.
Example 1:
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
Output: 1 2 4 8 9 6 7 3
Explanation:
Example 2:
Input:
1
/
2
/ \
4 9
/ \ \
6 5 3
/ \
7 8
Output: 1 2 4 6 5 7 8
Explanation:
As you can see we have not taken right
subtree. See Note
Your Task:
This is a function problem. You don't have to take input. Just complete the function boundary() that takes the root node as input and returns an array containing the boundary values in anti-clockwise.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Constraints:
1 ≤ Number of nodes ≤ 105
1 ≤ Data of a node ≤ 105
+1
parasdhanwal268 hours ago
class Solution
{
ArrayList <Integer> boundary(Node root)
{
ArrayList<Integer> a = new ArrayList<>();
if(root==null)
{
return a;
}
if(isLeaf(root)==false)
{
a.add(root.data);
}
leftside(root,a);
leaf(root,a);
rightside(root,a);
return a;
}
static boolean isLeaf(Node root)
{
if(root.left==null && root.right==null)
{
return true;
}
else
{
return false;
}
}
public static void leftside(Node root,ArrayList<Integer> a)
{
Node temp=root.left;
while(temp!=null)
{
if(isLeaf(temp)==false)
{
a.add(temp.data);
}
if(temp.left!=null)
{
temp=temp.left;
}
else
{
temp=temp.right;
}
}
}
public static void rightside(Node root,ArrayList<Integer> a)
{
Node temp=root.right;
Stack<Integer> s = new Stack<>();
while(temp!=null)
{
if(isLeaf(temp)==false)
{
s.push(temp.data);
}
if(temp.right!=null)
{
temp=temp.right;
}
else
{
temp=temp.left;
}
}
while(!s.isEmpty())
{
a.add(s.pop());
}
}
public static void leaf(Node root,ArrayList<Integer> a)
{
if(isLeaf(root))
{
a.add(root.data);
return;
}
if(root.left!=null)
{
leaf(root.left,a);
}
if(root.right!=null)
{
leaf(root.right,a);
}
}
}
0
soumyajitpatnaik20012 days ago
// { Driver Code Starts#include <bits/stdc++.h>using namespace std;#define MAX_HEIGHT 100000
// Tree Nodestruct Node{ int data; Node* left; Node* right;};
// Utility function to create a new Tree NodeNode* newNode(int val){ Node* temp = new Node; temp->data = val; temp->left = NULL; temp->right = NULL;
return temp;}
// Function to Build TreeNode* buildTree(string str){ // Corner Case if(str.length() == 0 || str[0] == 'N') return NULL;
// Creating vector of strings from input // string after spliting by space vector<string> ip;
istringstream iss(str); for(string str; iss >> str; ) ip.push_back(str);
// Create the root of the tree Node* root = newNode(stoi(ip[0]));
// Push the root to the queue queue<Node*> queue; queue.push(root);
// Starting from the second element int i = 1; while(!queue.empty() && i < ip.size()) {
// Get and remove the front of the queue Node* currNode = queue.front(); queue.pop();
// Get the current node's value from the string string currVal = ip[i];
// If the left child is not null if(currVal != "N") {
// Create the left child for the current node currNode->left = newNode(stoi(currVal));
// Push it to the queue queue.push(currNode->left); }
// For the right child i++; if(i >= ip.size()) break; currVal = ip[i];
// If the right child is not null if(currVal != "N") {
// Create the right child for the current node currNode->right = newNode(stoi(currVal));
// Push it to the queue queue.push(currNode->right); } i++; }
return root;}
// } Driver Code Ends/* A binary tree Nodestruct Node{ int data; Node* left, * right;}; */
class Solution {public: void traverseLeft(Node* root, vector<int> &ans) { if(root == NULL){ return; } if(root->left == NULL && root->right == NULL) { return; } ans.push_back(root->data); if(root->left) { traverseLeft(root->left, ans); } else { traverseLeft(root->right, ans); } } void traverseLeaf(Node* root, vector<int> &ans) { //base case if(root == NULL) { return; } if(root->left == NULL && root->right == NULL) { ans.push_back(root->data); return; } traverseLeaf(root->left, ans); traverseLeaf(root->right, ans); } void traverseRight(Node* root, vector<int> &ans) { //base case if(root == NULL) { return; //kya hi kar lenge agar root hi null hai....return hi karna hai..band raasta } if(root->left == NULL && root->right == NULL) { return; } if(root->right){ traverseRight(root->right, ans); } else traverseRight(root->left, ans); //wapas aate waqt ans.push_back(root->data); } vector <int> boundary(Node *root) { //Your code here vector<int> ans; if(root == NULL) { return ans; } ans.push_back(root->data); traverseLeft(root->left, ans); traverseLeaf(root->left, ans); traverseLeaf(root->right, ans); traverseRight(root->right, ans); return ans; }};
// { Driver Code Starts.
/* Driver program to test size function*/
int main() { int t; string tc; getline(cin, tc); t=stoi(tc); while(t--) { string s ,ch; getline(cin, s); Node* root = buildTree(s); Solution ob; vector <int> res = ob.boundary(root); for (int i : res) cout << i << " "; cout << endl; } return 0;} // } Driver Code Ends
+1
priyalkhapekar14426 days ago
void traverseLeft(Node* root,vector<int> &ans){
if((root==NULL) || (root->left==NULL && root->right==NULL)){
return;
}
ans.push_back(root->data);
if(root->left)
traverseLeft(root->left , ans);
else if(root->right)
traverseLeft(root->right , ans);
}
void traverseLeaf(Node* root,vector<int> &ans){
if(root==NULL){
return;
}
if(root->left==NULL && root->right==NULL){
ans.push_back(root->data);
return;
}
traverseLeaf(root->left,ans);
traverseLeaf(root->right,ans);
}
void traverseRight(Node* root,vector<int> &ans){
if((root==NULL) || (root->left==NULL && root->right==NULL)){
return;
}
if(root->right)
traverseRight(root->right,ans);
else
traverseRight(root->left,ans);
ans.push_back(root->data);
}
vector <int> boundary(Node *root)
{
vector<int> ans;
if(root==NULL){
return ans;
}
//For ROOT Node
ans.push_back(root->data);
//Left Part
traverseLeft(root->left , ans);
//For Left LEAF Node
traverseLeaf(root->left , ans);
//For Right Leaf Node
traverseLeaf(root->right , ans);
//Right Part
traverseRight(root->right , ans);
return ans;
}
+1
wolfofsv6 days ago
void TravLeftBnd(Node* root, vector<int>& boundary){
if(root){
if(root -> left){
boundary.push_back(root -> data);
TravLeftBnd(root -> left, boundary);
}
else if(root -> right){
boundary.push_back(root -> data);
TravLeftBnd(root -> right, boundary);
}
}
}
void TravRightBnd(Node* root, vector<int>& boundary){
if(root){
if(root -> right){
TravRightBnd(root -> right, boundary);
boundary.push_back(root -> data);
}
else if(root -> left){
TravRightBnd(root -> left, boundary);
boundary.push_back(root -> data);
}
}
}
void TravLeaves(Node* root, vector<int>& boundary){
if(root){
if(root -> left == NULL && root -> right == NULL){
boundary.push_back(root -> data);
}
TravLeaves(root -> left, boundary);
TravLeaves(root -> right, boundary);
}
}
vector <int> boundary(Node *root)
{
//Your code here
vector<int>boundary;
boundary.push_back(root -> data);
TravLeftBnd(root -> left, boundary);
if(root -> left || root -> right)
TravLeaves(root, boundary);
TravRightBnd(root -> right, boundary);
return boundary;
}
0
aishapervin032 weeks ago
void solveleft(Node* node,vector<int> &left)
{
if(node==NULL || (node->left==NULL && node->right==NULL))
return;
left.push_back(node->data);
if(node->left)
solveleft(node->left,left);
else
solveleft(node->right,left);
}
void solveleaf(Node* node,vector<int> &leaf)
{
if(node==NULL)
return;
if(node->left==NULL && node->right==NULL)
leaf.push_back(node->data);
solveleaf(node->left,leaf);
solveleaf(node->right,leaf);
}
void solveright(Node* node,vector<int> &right)
{
if(node==NULL || (node->left==NULL && node->right==NULL))
return;
right.push_back(node->data);
if(node->right)
solveright(node->right,right);
else
solveright(node->left,right);
}
vector <int> boundary(Node *root)
{
if(root==NULL)
return {};
if(root->left==NULL && root->right==NULL)
return {root->data};
vector<int>ans;
ans.push_back(root->data);
vector<int>leaf;
vector<int>left;
vector<int>right;
solveleft(root->left,left);
solveleaf(root,leaf);
solveright(root->right,right);
reverse(right.begin(),right.end());
for(int i=0;i<left.size();i++)
ans.push_back(left[i]);
for(int i=0;i<leaf.size();i++)
ans.push_back(leaf[i]);
for(int i=0;i<right.size();i++)
ans.push_back(right[i]);
return ans;
}
0
koulikmaity3 weeks ago
void traversalLeft(Node* root, vector<int>& ans) { // base case if(root == NULL) return; if(root->left == NULL && root->right == NULL) return; ans.push_back(root->data); if(root->left) traversalLeft(root->left, ans); else traversalLeft(root->right, ans); } void traversalLeave(Node* root, vector<int>& ans) { // base case if(root == NULL) return; if(root->left == NULL && root->right == NULL) { ans.push_back(root->data); return; } traversalLeave(root->left, ans); traversalLeave(root->right, ans); } void traverselRight(Node* root, vector<int>& ans) { // base case if(root == NULL) return; if(root->left == NULL && root->right == NULL) return; if(root->right) traverselRight(root->right, ans); else traverselRight(root->left, ans); ans.push_back(root->data); } vector <int> boundary(Node *root) { vector<int>ans; if(root == NULL) { return ans; } ans.push_back(root->data); // left part print/store traversalLeft(root->left, ans); // leave part print/store traversalLeave(root->left, ans); traversalLeave(root->right, ans); // right part print/store traverselRight(root->right, ans); return ans; }
+2
amanasati13 weeks ago
class Solution:
def leftsolve(self,root):
if root:
if root.left:
self.stack.append(root.data)
self.leftsolve(root.left)
elif root.right:
self.stack.append(root.data)
self.leftsolve(root.right)
def rightsolve(self,root):
if root:
if root.right:
self.rightsolve(root.right)
self.stack.append(root.data)
elif root.left:
self.rightsolve(root.left)
self.stack.append(root.data)
def leavessolve(self,root):
if root:
self.leavessolve(root.left)
if (root.left is None) and (root.right is None):
self.stack.append(root.data)
self.leavessolve(root.right)
def printBoundaryView(self, root):
# Code here
self.stack=[]
if root:
self.stack.append(root.data)
self.leftsolve(root.left)
self.leavessolve(root.left)
self.leavessolve(root.right)
self.rightsolve(root.right)
return self.stack
0
amishasahu3281 month ago
class Solution {
bool isLeaf(Node *node)
{
return (!(node->left) && (!node->right));
}
void leftBoundary(Node *node, vector<int> &res)
{
Node *curr = node->left;
while(curr)
{
if(!isLeaf(curr)) res.push_back(curr->data);
if(curr->left) curr = curr->left;
else curr = curr->right;
}
}
void addLeaves(Node *node, vector<int> &res)
{
if(isLeaf(node))
{
res.push_back(node->data);
return;
}
if(node->left) addLeaves(node->left, res);
if(node->right) addLeaves(node->right, res);
}
void rightBoundary(Node *node, vector<int> &res)
{
Node *curr = node->right;
stack<int> s;
while(curr)
{
if(!isLeaf(curr)) s.push(curr->data);
if(curr->right) curr = curr->right;
else curr = curr->left;
}
while(!s.empty())
{
res.push_back(s.top());
s.pop();
}
}
public:
vector <int> boundary(Node *root)
{
//Your code here
vector<int> res;
if(!root) return res;
if(!isLeaf(root)) res.push_back(root->data);
leftBoundary(root, res);
addLeaves(root, res);
rightBoundary(root, res);
}
};
+1
jaydhurat1 month ago
class Solution
{
ArrayList <Integer> boundary(Node root)
{
ArrayList<Integer> a = new ArrayList<>();
if(root==null)
{
return a;
}
if(isLeaf(root))
{
a.add(root.data);
return a;
}
else
{
a.add(root.data);
}
leftside(root,a);
leaf(root,a);
rightside(root,a);
return a;
}
static boolean isLeaf(Node root)
{
if(root.left==null && root.right==null)
{
return true;
}
else
{
return false;
}
}
public static void leftside(Node root,ArrayList<Integer> a)
{
Node temp=root.left;
while(temp!=null)
{
if(isLeaf(temp)==false)
{
a.add(temp.data);
}
if(temp.left!=null)
{
temp=temp.left;
}
else
{
temp=temp.right;
}
}
}
public static void rightside(Node root,ArrayList<Integer> a)
{
Node temp=root.right;
Stack<Integer> s = new Stack<>();
while(temp!=null)
{
if(isLeaf(temp)==false)
{
s.push(temp.data);
}
if(temp.right!=null)
{
temp=temp.right;
}
else
{
temp=temp.left;
}
}
while(!s.isEmpty())
{
a.add(s.pop());
}
}
public static void leaf(Node root,ArrayList<Integer> a)
{
if(isLeaf(root))
{
a.add(root.data);
return;
}
if(root.left!=null)
{
leaf(root.left,a);
}
if(root.right!=null)
{
leaf(root.right,a);
}
}
}
0
kgeekcs2191 month ago
class Solution { bool isleaf(Node* root){ if(!root->left && !root->right) return true; return false; } void left_boundary(Node* root,vector<int> &v){ if(root==nullptr) return; if(!isleaf(root)) v.push_back(root->data); if(root->left) left_boundary(root->left,v); else if(root->right) left_boundary(root->right,v); }
void leaf_node(Node* root,vector<int> &v) //inorder Traversal{ if(root==nullptr) return; if(root->left) leaf_node(root->left,v); if(isleaf(root)) { v.push_back(root->data); } if(root->right) leaf_node(root->right,v); }
void right_boundary(Node* root,vector<int> &v){ if(root==nullptr) return; if(root->right) right_boundary(root->right,v); else if(root->left) right_boundary(root->left,v); if(!isleaf(root)) v.push_back(root->data); }
public: vector <int> boundary(Node *root) { //Your code here vector<int> v; if(root==nullptr) return v; v.push_back(root->data); if(isleaf(root)) { return v; } left_boundary( root->left,v); leaf_node( root,v); right_boundary(root->right,v); return v; }};
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": 337,
"s": 238,
"text": "Given a Binary Tree, find its Boundary Traversal. The traversal should be in the following order: "
},
{
"code": null,
"e": 929,
"s": 337,
"text": "\nLeft boundary nodes: defined as the path from the root to the left-most node ie- the leaf node you could reach when you always travel preferring the left subtree over the right subtree. \nLeaf nodes: All the leaf nodes except for the ones that are part of left or right boundary.\nReverse right boundary nodes: defined as the path from the right-most node to the root. The right-most node is the leaf node you could reach when you always travel preferring the right subtree over the left subtree. Exclude the root from this as it was already included in the traversal of left boundary nodes.\n"
},
{
"code": null,
"e": 1116,
"s": 929,
"text": "Left boundary nodes: defined as the path from the root to the left-most node ie- the leaf node you could reach when you always travel preferring the left subtree over the right subtree. "
},
{
"code": null,
"e": 1208,
"s": 1116,
"text": "Leaf nodes: All the leaf nodes except for the ones that are part of left or right boundary."
},
{
"code": null,
"e": 1519,
"s": 1208,
"text": "Reverse right boundary nodes: defined as the path from the right-most node to the root. The right-most node is the leaf node you could reach when you always travel preferring the right subtree over the left subtree. Exclude the root from this as it was already included in the traversal of left boundary nodes."
},
{
"code": null,
"e": 1648,
"s": 1519,
"text": "Note: If the root doesn't have a left subtree or right subtree, then the root itself is the left or right boundary. \n\nExample 1:"
},
{
"code": null,
"e": 1788,
"s": 1648,
"text": "Input:\n 1 \n / \\\n 2 3 \n / \\ / \\ \n 4 5 6 7\n / \\\n 8 9\n \nOutput: 1 2 4 8 9 6 7 3\nExplanation:\n\n\n"
},
{
"code": null,
"e": 1801,
"s": 1790,
"text": "Example 2:"
},
{
"code": null,
"e": 2040,
"s": 1801,
"text": "Input:\n 1\n / \n 2\n / \\\n 4 9\n / \\ \\\n 6 5 3\n / \\\n 7 8\n\nOutput: 1 2 4 6 5 7 8\nExplanation: \nAs you can see we have not taken right\nsubtree. See Note\n\n"
},
{
"code": null,
"e": 2254,
"s": 2042,
"text": "Your Task:\nThis is a function problem. You don't have to take input. Just complete the function boundary() that takes the root node as input and returns an array containing the boundary values in anti-clockwise."
},
{
"code": null,
"e": 2338,
"s": 2256,
"text": "Expected Time Complexity: O(N). \nExpected Auxiliary Space: O(Height of the Tree)."
},
{
"code": null,
"e": 2404,
"s": 2340,
"text": "Constraints:\n1 ≤ Number of nodes ≤ 105\n1 ≤ Data of a node ≤ 105"
},
{
"code": null,
"e": 2407,
"s": 2404,
"text": "+1"
},
{
"code": null,
"e": 2433,
"s": 2407,
"text": "parasdhanwal268 hours ago"
},
{
"code": null,
"e": 4201,
"s": 2433,
"text": "class Solution\n{\nArrayList <Integer> boundary(Node root)\n{\n ArrayList<Integer> a = new ArrayList<>();\n if(root==null)\n {\n return a;\n }\n if(isLeaf(root)==false)\n {\n a.add(root.data);\n \n }\n \n leftside(root,a);\n leaf(root,a);\n rightside(root,a);\n return a;\n \n}\n static boolean isLeaf(Node root)\n {\n if(root.left==null && root.right==null)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n public static void leftside(Node root,ArrayList<Integer> a)\n {\n Node temp=root.left;\n while(temp!=null)\n {\n if(isLeaf(temp)==false)\n {\n a.add(temp.data);\n }\n \n if(temp.left!=null)\n {\n temp=temp.left;\n }\n else\n {\n temp=temp.right;\n }\n }\n }\n public static void rightside(Node root,ArrayList<Integer> a)\n {\n Node temp=root.right;\n Stack<Integer> s = new Stack<>();\n while(temp!=null)\n {\n if(isLeaf(temp)==false)\n {\n s.push(temp.data);\n }\n \n if(temp.right!=null)\n {\n temp=temp.right;\n }\n else\n {\n temp=temp.left;\n }\n }\n while(!s.isEmpty())\n {\n a.add(s.pop());\n }\n }\n public static void leaf(Node root,ArrayList<Integer> a)\n {\n if(isLeaf(root))\n {\n a.add(root.data);\n return;\n }\n \n if(root.left!=null)\n {\n leaf(root.left,a);\n }\n if(root.right!=null)\n {\n leaf(root.right,a);\n }\n }\n \n}"
},
{
"code": null,
"e": 4203,
"s": 4201,
"text": "0"
},
{
"code": null,
"e": 4234,
"s": 4203,
"text": "soumyajitpatnaik20012 days ago"
},
{
"code": null,
"e": 4327,
"s": 4234,
"text": "// { Driver Code Starts#include <bits/stdc++.h>using namespace std;#define MAX_HEIGHT 100000"
},
{
"code": null,
"e": 4395,
"s": 4327,
"text": "// Tree Nodestruct Node{ int data; Node* left; Node* right;};"
},
{
"code": null,
"e": 4552,
"s": 4395,
"text": "// Utility function to create a new Tree NodeNode* newNode(int val){ Node* temp = new Node; temp->data = val; temp->left = NULL; temp->right = NULL;"
},
{
"code": null,
"e": 4569,
"s": 4552,
"text": " return temp;}"
},
{
"code": null,
"e": 4700,
"s": 4569,
"text": "// Function to Build TreeNode* buildTree(string str){ // Corner Case if(str.length() == 0 || str[0] == 'N') return NULL;"
},
{
"code": null,
"e": 4801,
"s": 4700,
"text": " // Creating vector of strings from input // string after spliting by space vector<string> ip;"
},
{
"code": null,
"e": 4885,
"s": 4801,
"text": " istringstream iss(str); for(string str; iss >> str; ) ip.push_back(str);"
},
{
"code": null,
"e": 4956,
"s": 4885,
"text": " // Create the root of the tree Node* root = newNode(stoi(ip[0]));"
},
{
"code": null,
"e": 5031,
"s": 4956,
"text": " // Push the root to the queue queue<Node*> queue; queue.push(root);"
},
{
"code": null,
"e": 5126,
"s": 5031,
"text": " // Starting from the second element int i = 1; while(!queue.empty() && i < ip.size()) {"
},
{
"code": null,
"e": 5231,
"s": 5126,
"text": " // Get and remove the front of the queue Node* currNode = queue.front(); queue.pop();"
},
{
"code": null,
"e": 5316,
"s": 5231,
"text": " // Get the current node's value from the string string currVal = ip[i];"
},
{
"code": null,
"e": 5383,
"s": 5316,
"text": " // If the left child is not null if(currVal != \"N\") {"
},
{
"code": null,
"e": 5491,
"s": 5383,
"text": " // Create the left child for the current node currNode->left = newNode(stoi(currVal));"
},
{
"code": null,
"e": 5572,
"s": 5491,
"text": " // Push it to the queue queue.push(currNode->left); }"
},
{
"code": null,
"e": 5678,
"s": 5572,
"text": " // For the right child i++; if(i >= ip.size()) break; currVal = ip[i];"
},
{
"code": null,
"e": 5746,
"s": 5678,
"text": " // If the right child is not null if(currVal != \"N\") {"
},
{
"code": null,
"e": 5856,
"s": 5746,
"text": " // Create the right child for the current node currNode->right = newNode(stoi(currVal));"
},
{
"code": null,
"e": 5953,
"s": 5856,
"text": " // Push it to the queue queue.push(currNode->right); } i++; }"
},
{
"code": null,
"e": 5970,
"s": 5953,
"text": " return root;}"
},
{
"code": null,
"e": 6073,
"s": 5978,
"text": "// } Driver Code Ends/* A binary tree Nodestruct Node{ int data; Node* left, * right;}; */"
},
{
"code": null,
"e": 7665,
"s": 6073,
"text": "class Solution {public: void traverseLeft(Node* root, vector<int> &ans) { if(root == NULL){ return; } if(root->left == NULL && root->right == NULL) { return; } ans.push_back(root->data); if(root->left) { traverseLeft(root->left, ans); } else { traverseLeft(root->right, ans); } } void traverseLeaf(Node* root, vector<int> &ans) { //base case if(root == NULL) { return; } if(root->left == NULL && root->right == NULL) { ans.push_back(root->data); return; } traverseLeaf(root->left, ans); traverseLeaf(root->right, ans); } void traverseRight(Node* root, vector<int> &ans) { //base case if(root == NULL) { return; //kya hi kar lenge agar root hi null hai....return hi karna hai..band raasta } if(root->left == NULL && root->right == NULL) { return; } if(root->right){ traverseRight(root->right, ans); } else traverseRight(root->left, ans); //wapas aate waqt ans.push_back(root->data); } vector <int> boundary(Node *root) { //Your code here vector<int> ans; if(root == NULL) { return ans; } ans.push_back(root->data); traverseLeft(root->left, ans); traverseLeaf(root->left, ans); traverseLeaf(root->right, ans); traverseRight(root->right, ans); return ans; }};"
},
{
"code": null,
"e": 7690,
"s": 7665,
"text": "// { Driver Code Starts."
},
{
"code": null,
"e": 7732,
"s": 7690,
"text": "/* Driver program to test size function*/"
},
{
"code": null,
"e": 8059,
"s": 7732,
"text": "int main() { int t; string tc; getline(cin, tc); t=stoi(tc); while(t--) { string s ,ch; getline(cin, s); Node* root = buildTree(s); Solution ob; vector <int> res = ob.boundary(root); for (int i : res) cout << i << \" \"; cout << endl; } return 0;} // } Driver Code Ends"
},
{
"code": null,
"e": 8062,
"s": 8059,
"text": "+1"
},
{
"code": null,
"e": 8091,
"s": 8062,
"text": "priyalkhapekar14426 days ago"
},
{
"code": null,
"e": 9515,
"s": 8091,
"text": "void traverseLeft(Node* root,vector<int> &ans){\n if((root==NULL) || (root->left==NULL && root->right==NULL)){\n return;\n }\n ans.push_back(root->data);\n if(root->left)\n traverseLeft(root->left , ans);\n else if(root->right)\n traverseLeft(root->right , ans);\n }\n void traverseLeaf(Node* root,vector<int> &ans){\n if(root==NULL){\n return;\n }\n if(root->left==NULL && root->right==NULL){\n ans.push_back(root->data);\n return;\n }\n traverseLeaf(root->left,ans);\n traverseLeaf(root->right,ans);\n }\n void traverseRight(Node* root,vector<int> &ans){\n if((root==NULL) || (root->left==NULL && root->right==NULL)){\n return;\n }\n if(root->right)\n traverseRight(root->right,ans);\n else\n traverseRight(root->left,ans);\n ans.push_back(root->data);\n }\n vector <int> boundary(Node *root)\n {\n vector<int> ans;\n if(root==NULL){\n return ans;\n }\n //For ROOT Node\n ans.push_back(root->data);\n //Left Part\n traverseLeft(root->left , ans);\n //For Left LEAF Node\n traverseLeaf(root->left , ans);\n //For Right Leaf Node\n traverseLeaf(root->right , ans);\n //Right Part\n traverseRight(root->right , ans);\n return ans;\n }"
},
{
"code": null,
"e": 9518,
"s": 9515,
"text": "+1"
},
{
"code": null,
"e": 9537,
"s": 9518,
"text": "wolfofsv6 days ago"
},
{
"code": null,
"e": 10999,
"s": 9537,
"text": "void TravLeftBnd(Node* root, vector<int>& boundary){\n if(root){\n if(root -> left){\n boundary.push_back(root -> data);\n TravLeftBnd(root -> left, boundary);\n }\n else if(root -> right){\n boundary.push_back(root -> data);\n TravLeftBnd(root -> right, boundary);\n }\n }\n }\n \n void TravRightBnd(Node* root, vector<int>& boundary){\n if(root){\n if(root -> right){\n TravRightBnd(root -> right, boundary);\n boundary.push_back(root -> data);\n }\n else if(root -> left){\n TravRightBnd(root -> left, boundary);\n boundary.push_back(root -> data);\n }\n }\n }\n \n void TravLeaves(Node* root, vector<int>& boundary){\n if(root){\n if(root -> left == NULL && root -> right == NULL){\n boundary.push_back(root -> data);\n }\n TravLeaves(root -> left, boundary);\n TravLeaves(root -> right, boundary);\n }\n }\n\n vector <int> boundary(Node *root)\n {\n //Your code here\n vector<int>boundary;\n boundary.push_back(root -> data);\n TravLeftBnd(root -> left, boundary);\n if(root -> left || root -> right)\n TravLeaves(root, boundary);\n TravRightBnd(root -> right, boundary);\n \n return boundary;\n }"
},
{
"code": null,
"e": 11001,
"s": 10999,
"text": "0"
},
{
"code": null,
"e": 11026,
"s": 11001,
"text": "aishapervin032 weeks ago"
},
{
"code": null,
"e": 12496,
"s": 11026,
"text": "void solveleft(Node* node,vector<int> &left)\n{\n \n if(node==NULL || (node->left==NULL && node->right==NULL))\n return;\n left.push_back(node->data);\n if(node->left)\n solveleft(node->left,left);\n else\n solveleft(node->right,left);\n \n}\n\n\nvoid solveleaf(Node* node,vector<int> &leaf)\n{\n if(node==NULL)\n return;\n \n if(node->left==NULL && node->right==NULL)\n leaf.push_back(node->data);\n \n solveleaf(node->left,leaf);\n solveleaf(node->right,leaf);\n}\n\nvoid solveright(Node* node,vector<int> &right)\n{\n \n if(node==NULL || (node->left==NULL && node->right==NULL))\n return;\n right.push_back(node->data);\n if(node->right)\n solveright(node->right,right);\n else\n solveright(node->left,right);\n \n}\n\n\n vector <int> boundary(Node *root)\n {\n if(root==NULL)\n return {};\n if(root->left==NULL && root->right==NULL)\n return {root->data};\n vector<int>ans;\n ans.push_back(root->data);\n vector<int>leaf;\n vector<int>left;\n vector<int>right;\n solveleft(root->left,left);\n solveleaf(root,leaf);\n solveright(root->right,right);\n reverse(right.begin(),right.end());\n for(int i=0;i<left.size();i++)\n ans.push_back(left[i]);\n for(int i=0;i<leaf.size();i++)\n ans.push_back(leaf[i]);\n for(int i=0;i<right.size();i++)\n ans.push_back(right[i]);\n return ans;\n }"
},
{
"code": null,
"e": 12498,
"s": 12496,
"text": "0"
},
{
"code": null,
"e": 12521,
"s": 12498,
"text": "koulikmaity3 weeks ago"
},
{
"code": null,
"e": 14034,
"s": 12521,
"text": "void traversalLeft(Node* root, vector<int>& ans) { // base case if(root == NULL) return; if(root->left == NULL && root->right == NULL) return; ans.push_back(root->data); if(root->left) traversalLeft(root->left, ans); else traversalLeft(root->right, ans); } void traversalLeave(Node* root, vector<int>& ans) { // base case if(root == NULL) return; if(root->left == NULL && root->right == NULL) { ans.push_back(root->data); return; } traversalLeave(root->left, ans); traversalLeave(root->right, ans); } void traverselRight(Node* root, vector<int>& ans) { // base case if(root == NULL) return; if(root->left == NULL && root->right == NULL) return; if(root->right) traverselRight(root->right, ans); else traverselRight(root->left, ans); ans.push_back(root->data); } vector <int> boundary(Node *root) { vector<int>ans; if(root == NULL) { return ans; } ans.push_back(root->data); // left part print/store traversalLeft(root->left, ans); // leave part print/store traversalLeave(root->left, ans); traversalLeave(root->right, ans); // right part print/store traverselRight(root->right, ans); return ans; }"
},
{
"code": null,
"e": 14037,
"s": 14034,
"text": "+2"
},
{
"code": null,
"e": 14059,
"s": 14037,
"text": "amanasati13 weeks ago"
},
{
"code": null,
"e": 15270,
"s": 14059,
"text": "class Solution:\n def leftsolve(self,root):\n if root:\n if root.left:\n self.stack.append(root.data)\n self.leftsolve(root.left)\n elif root.right:\n self.stack.append(root.data)\n self.leftsolve(root.right)\n \n def rightsolve(self,root):\n if root:\n if root.right:\n self.rightsolve(root.right)\n self.stack.append(root.data)\n elif root.left:\n self.rightsolve(root.left)\n self.stack.append(root.data)\n \n def leavessolve(self,root):\n if root:\n self.leavessolve(root.left)\n \n if (root.left is None) and (root.right is None):\n self.stack.append(root.data)\n \n self.leavessolve(root.right)\n \n \n def printBoundaryView(self, root):\n # Code here\n self.stack=[]\n if root:\n self.stack.append(root.data)\n self.leftsolve(root.left)\n self.leavessolve(root.left)\n self.leavessolve(root.right)\n self.rightsolve(root.right)\n return self.stack"
},
{
"code": null,
"e": 15272,
"s": 15270,
"text": "0"
},
{
"code": null,
"e": 15297,
"s": 15272,
"text": "amishasahu3281 month ago"
},
{
"code": null,
"e": 16645,
"s": 15297,
"text": "class Solution {\n bool isLeaf(Node *node)\n {\n return (!(node->left) && (!node->right));\n }\n void leftBoundary(Node *node, vector<int> &res)\n {\n Node *curr = node->left;\n while(curr)\n {\n if(!isLeaf(curr)) res.push_back(curr->data);\n if(curr->left) curr = curr->left;\n else curr = curr->right;\n }\n }\n void addLeaves(Node *node, vector<int> &res)\n {\n if(isLeaf(node))\n {\n res.push_back(node->data);\n return;\n }\n if(node->left) addLeaves(node->left, res);\n if(node->right) addLeaves(node->right, res);\n }\n void rightBoundary(Node *node, vector<int> &res)\n {\n Node *curr = node->right;\n stack<int> s;\n while(curr)\n {\n if(!isLeaf(curr)) s.push(curr->data);\n if(curr->right) curr = curr->right;\n else curr = curr->left;\n }\n while(!s.empty())\n {\n res.push_back(s.top());\n s.pop();\n }\n }\npublic:\n vector <int> boundary(Node *root)\n {\n //Your code here\n vector<int> res;\n if(!root) return res;\n if(!isLeaf(root)) res.push_back(root->data);\n leftBoundary(root, res);\n addLeaves(root, res);\n rightBoundary(root, res);\n }\n};"
},
{
"code": null,
"e": 16648,
"s": 16645,
"text": "+1"
},
{
"code": null,
"e": 16669,
"s": 16648,
"text": "jaydhurat1 month ago"
},
{
"code": null,
"e": 18483,
"s": 16669,
"text": "class Solution\n{\nArrayList <Integer> boundary(Node root)\n{\n ArrayList<Integer> a = new ArrayList<>();\n if(root==null)\n {\n return a;\n }\n if(isLeaf(root))\n {\n a.add(root.data);\n return a;\n }\n else\n {\n a.add(root.data);\n }\n leftside(root,a);\n leaf(root,a);\n rightside(root,a);\n return a;\n \n}\n static boolean isLeaf(Node root)\n {\n if(root.left==null && root.right==null)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n public static void leftside(Node root,ArrayList<Integer> a)\n {\n Node temp=root.left;\n while(temp!=null)\n {\n if(isLeaf(temp)==false)\n {\n a.add(temp.data);\n }\n \n if(temp.left!=null)\n {\n temp=temp.left;\n }\n else\n {\n temp=temp.right;\n }\n }\n }\n public static void rightside(Node root,ArrayList<Integer> a)\n {\n Node temp=root.right;\n Stack<Integer> s = new Stack<>();\n while(temp!=null)\n {\n if(isLeaf(temp)==false)\n {\n s.push(temp.data);\n }\n \n if(temp.right!=null)\n {\n temp=temp.right;\n }\n else\n {\n temp=temp.left;\n }\n }\n while(!s.isEmpty())\n {\n a.add(s.pop());\n }\n }\n public static void leaf(Node root,ArrayList<Integer> a)\n {\n if(isLeaf(root))\n {\n a.add(root.data);\n return;\n }\n \n if(root.left!=null)\n {\n leaf(root.left,a);\n }\n if(root.right!=null)\n {\n leaf(root.right,a);\n }\n }\n \n}\n"
},
{
"code": null,
"e": 18485,
"s": 18483,
"text": "0"
},
{
"code": null,
"e": 18507,
"s": 18485,
"text": "kgeekcs2191 month ago"
},
{
"code": null,
"e": 18864,
"s": 18507,
"text": "class Solution { bool isleaf(Node* root){ if(!root->left && !root->right) return true; return false; } void left_boundary(Node* root,vector<int> &v){ if(root==nullptr) return; if(!isleaf(root)) v.push_back(root->data); if(root->left) left_boundary(root->left,v); else if(root->right) left_boundary(root->right,v); }"
},
{
"code": null,
"e": 19113,
"s": 18866,
"text": "void leaf_node(Node* root,vector<int> &v) //inorder Traversal{ if(root==nullptr) return; if(root->left) leaf_node(root->left,v); if(isleaf(root)) { v.push_back(root->data); } if(root->right) leaf_node(root->right,v); }"
},
{
"code": null,
"e": 19357,
"s": 19115,
"text": "void right_boundary(Node* root,vector<int> &v){ if(root==nullptr) return; if(root->right) right_boundary(root->right,v); else if(root->left) right_boundary(root->left,v); if(!isleaf(root)) v.push_back(root->data); }"
},
{
"code": null,
"e": 19681,
"s": 19357,
"text": "public: vector <int> boundary(Node *root) { //Your code here vector<int> v; if(root==nullptr) return v; v.push_back(root->data); if(isleaf(root)) { return v; } left_boundary( root->left,v); leaf_node( root,v); right_boundary(root->right,v); return v; }}; "
},
{
"code": null,
"e": 19827,
"s": 19681,
"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": 19863,
"s": 19827,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 19873,
"s": 19863,
"text": "\nProblem\n"
},
{
"code": null,
"e": 19883,
"s": 19873,
"text": "\nContest\n"
},
{
"code": null,
"e": 19946,
"s": 19883,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 20094,
"s": 19946,
"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": 20302,
"s": 20094,
"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": 20408,
"s": 20302,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Support Vector Machines explained with Python examples | by Carolina Bento | Towards Data Science
|
Support vector machines (SVM) is a supervised machine learning technique. And, even though it’s mostly used in classification, it can also be applied to regression problems.
SVMs define a decision boundary along with a maximal margin that separates almost all the points into two classes. While also leaving some room for misclassifications.
Support vector machines are an improvement over maximal margin algorithms. Its biggest advantage is that it can define both a linear or a non-linear decision boundary by using kernel functions. This makes it more suitable for real-world problems, where data are not always completely separable with a straight line.
The main goal of an SVM is to define an hyperplane that separates the points in two different classes. The hyperplane is also called separating hyperplane or decision boundary.
So let’s start with hyperplanes. The easiest away to visualize an hyperplane is if think about a 2-dimensional dataset.
There’s going to be an infinite number of hyperplanes that separate points into two classes. But, since we’re working in a 2-dimensional space, any hyperplane we define will always have (2–1) = 1 dimensions. So, we can represent the hyperplane with a simple regression line.
With the decision boundary defined, we can now classify points based on where they fall in relation to it.
If you are working with more than two dimensions, as in, your feature vector X has more than two features, you’re classifying vectors, instead of points.
So, to generalize, all vectors that fall below the decision boundary belong to class -1, and if they fall above it they belong to class 1.
We used training data to define the decision boundary. But what about the quality of predictions for the testing set?
If a vector is far from the decision boundary we can be confident about its class, even if the model has some error. But, what happens when we classify a vector and it is very close to decision boundary? How can we be sure about which class to assign?
To tackle this issue, support vector machines also draws a margin around the decision boundary. The goal of this margin is to separate the vectors from the decision boundary, as much as possible. The intuition behind it is that a margin gives us more confidence in our predictions. Because the vectors are at least the length of the margin away from the decision boundary, there’s less ambiguity during classification.
The position of the margin is defined using the vectors that are closest to the decision boundary. That’s why the vectors that lie on top of the margin are the support vectors.
And with the margin working as a buffer, we can classify a vector based on where they fall relative to the margin. Where M is the width of the margin.
The addition of a margin improves the quality of the predictions in the testing set, but it assumes the classes are completely separable.
But, in most real world problems, data is messy and it’s usually not completely separable.
That’s why SVM shares an important characteristic with the algorithm that came before it, support vector classifiers. It allows the algorithm to make mistakes, and assign the wrong class to some vectors.
So, instead of trying to completely separate the vectors in into two classes, SMV make a trade-off. It allows for some vectors to fall inside the margin and on the wrong side of the decision boundary.
Support vector machines allow some misclassification during the learning process. So they can do a better job at classifying most vectors in the testing set.
Besides the margin, our model now includes slack variables, which will tell us two things:
if a test observation misclassified,
where the observation is relative to the decision boundary and the margin.
Slack variables can have three possible values:
And number of misclassified vectors is bound by a parameter C.
We can see the model captures much more nuance. But it’s still built on top of maximum margin classifiers. For instance, if you set parameter C to zero, meaning it allows zero slack variables, it falls back to a maximum margin classifier. So you have a linear decision boundary, a margin that is as large as possible and no vectors allowed inside it.
The higher the number of slack variables, the higher the number of misclassified vectors allowed. This impacts the width of the margin, because picking different support vectors. And it also controls the Bias-Variance tradeoff of the model.
Having some room for misclassification makes SMVs more flexibility, but it only applies to a limited set of problems.
In most real world problems, it’s hard to separate data into two classes with a linear decision boundary. Even with some room for error.
SVMs share the characteristics of the margin classifiers that came before it. What is unique about them is how they can define both linear and non-linear decision boundaries.
To support non-linear decision boundaries, SMVs use functions to transform the original feature space into a new space can represent those non-linear relationships.
For instance, say you augment the original feature space with the square its features. In this case, you applied a quadratic function to the original feature set to create the square of those features. Now you have your original feature and their quadratic version, in this augmented space. And so, implicitly, there’s a function that maps these two feature spaces.
If you try to draw the decision boundary in the original feature space it has a quadratic shape. But if you train your model in the augmented feature space, you’ll find a linear decision boundary that separates the two classes. Because it is a transformation, the quadratic boundary in original feature space corresponds to a linear one in the augmented feature space.
The functions that define these transformations are called kernels. They work as similarity functions between observations in the training and testing sets.
Whenever you have a model that is represented with inner products, you can plug in a kernel function. For instance, a linear kernel is the same as applying linear transformations to feature space. And, in this case, it’s the same as a support vector classifier, because the decision boundary is linear.
With polynomial kernels, you’re projecting the original feature space into a polynomial feature space. So the decision boundary that separates the classes is defined with a higher order polynomial.
The use of kernels is what distinguishes support vector classifiers from support vector machines. And they open up the possibility to tackle more complex problems. But augmenting the feature space could mean extra computational needs. Because, with a big enough feature space, it can be expensive to fit a model, both in terms of both time and resources.
Despite the the augmented feature space, kernels bring a significant advantage. SVMs don’t actually compute the transformation of each observation into the augmented space. They use a trick and instead compute the inner product of observations in the augmented space which, computationally, is much cheaper. This is called the kernel trick.
In the end, SVMs make two important assumptions:
Data is linearly separable. Even if the linear boundary is in an augmented feature space.
The model is represented using inner products, so that kernels can be used.
To see support vector machines in action, I’ve generated a random dataset and split it into two different classes. Here's the code snippet that generates and plots the data.
import randomimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltdef generate_random_dataset(size): """ Generate a random dataset and that follows a quadratic distribution """ x = [] y = [] target = [] for i in range(size): # class zero x.append(np.round(random.uniform(0, 2.5), 1)) y.append(np.round(random.uniform(0, 20), 1)) target.append(0) # class one x.append(np.round(random.uniform(1, 5), 2)) y.append(np.round(random.uniform(20, 25), 2)) target.append(1) x.append(np.round(random.uniform(3, 5), 2)) y.append(np.round(random.uniform(5, 25), 2)) target.append(1) df_x = pd.DataFrame(data=x) df_y = pd.DataFrame(data=y) df_target = pd.DataFrame(data=target) data_frame = pd.concat([df_x, df_y], ignore_index=True, axis=1) data_frame = pd.concat([data_frame, df_target], ignore_index=True, axis=1) data_frame.columns = ['x', 'y', 'target'] return data_frame# Generate datasetsize = 100dataset = generate_random_dataset(size)features = dataset[['x', 'y']]label = dataset['target']# Hold out 20% of the dataset for trainingtest_size = int(np.round(size * 0.2, 0))# Split dataset into training and testing setsx_train = features[:-test_size].valuesy_train = label[:-test_size].valuesx_test = features[-test_size:].valuesy_test = label[-test_size:].values# Plotting the training setfig, ax = plt.subplots(figsize=(12, 7))# removing to and right borderax.spines['top'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['right'].set_visible(False)# adding major gridlinesax.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)ax.scatter(features[:-test_size]['x'], features[:-test_size]['y'], color="#8C7298")plt.show()
Before any classification, the training set looks like this.
There’s a little space between the two groups of data points. But closer to the center, it’s not clear which data point belongs to which class.
A quadratic curve might be a good candidate to separate these classes. So let’s fit an SVM with a second-degree polynomial kernel.
from sklearn import svmmodel = svm.SVC(kernel='poly', degree=2)model.fit(x_train, y_train)
To see the result of fitting this model, we can plot the decision boundary and the margin along with the dataset.
Here’s the code to plot the decision boundary and margins.
fig, ax = plt.subplots(figsize=(12, 7))# Removing to and right borderax.spines['top'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['right'].set_visible(False)# Create grid to evaluate modelxx = np.linspace(-1, max(features['x']) + 1, len(x_train))yy = np.linspace(0, max(features['y']) + 1, len(y_train))YY, XX = np.meshgrid(yy, xx)xy = np.vstack([XX.ravel(), YY.ravel()]).Ttrain_size = len(features[:-test_size]['x'])# Assigning different colors to the classescolors = y_traincolors = np.where(colors == 1, '#8C7298', '#4786D1')# Plot the datasetax.scatter(features[:-test_size]['x'], features[:-test_size]['y'], c=colors)# Get the separating hyperplaneZ = model.decision_function(xy).reshape(XX.shape)# Draw the decision boundary and marginsax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--'])# Highlight support vectors with a circle around themax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], s=100, linewidth=1, facecolors='none', edgecolors='k')plt.show()
If we calculate the accuracy of this model against the testing set we get a good result, granted the dataset is very small and generated at random.
from sklearn.metrics import accuracy_scorepredictions_poly = model.predict(x_test)accuracy_poly = accuracy_score(y_test, predictions_poly)print("2nd degree polynomial Kernel\nAccuracy (normalized): " + str(accuracy_poly))
The accuracy is good, but let's see if a more simplistic approach could have solved our problem. To fit an SVM with a linear kernel we just need to update the kernel parameter.
model = svm.SVC(kernel='linear')model.fit(x_train, y_train)
And plot the decision boundary the same way we did back there.
Now it looks like there are fewer points inside the margin, and fewer misclassified points. Calculating the accuracy of this model, it has slightly better accuracy than the one with a polynomial kernel.
So it turns out that for this problem a simpler model, an SVM with a linear kernel, was the best solution.
Hope you enjoyed these examples, and that you got a better understanding of SVMs and what kinds of problems they can be applied to.
Thanks for reading!
|
[
{
"code": null,
"e": 345,
"s": 171,
"text": "Support vector machines (SVM) is a supervised machine learning technique. And, even though it’s mostly used in classification, it can also be applied to regression problems."
},
{
"code": null,
"e": 513,
"s": 345,
"text": "SVMs define a decision boundary along with a maximal margin that separates almost all the points into two classes. While also leaving some room for misclassifications."
},
{
"code": null,
"e": 829,
"s": 513,
"text": "Support vector machines are an improvement over maximal margin algorithms. Its biggest advantage is that it can define both a linear or a non-linear decision boundary by using kernel functions. This makes it more suitable for real-world problems, where data are not always completely separable with a straight line."
},
{
"code": null,
"e": 1006,
"s": 829,
"text": "The main goal of an SVM is to define an hyperplane that separates the points in two different classes. The hyperplane is also called separating hyperplane or decision boundary."
},
{
"code": null,
"e": 1126,
"s": 1006,
"text": "So let’s start with hyperplanes. The easiest away to visualize an hyperplane is if think about a 2-dimensional dataset."
},
{
"code": null,
"e": 1401,
"s": 1126,
"text": "There’s going to be an infinite number of hyperplanes that separate points into two classes. But, since we’re working in a 2-dimensional space, any hyperplane we define will always have (2–1) = 1 dimensions. So, we can represent the hyperplane with a simple regression line."
},
{
"code": null,
"e": 1508,
"s": 1401,
"text": "With the decision boundary defined, we can now classify points based on where they fall in relation to it."
},
{
"code": null,
"e": 1662,
"s": 1508,
"text": "If you are working with more than two dimensions, as in, your feature vector X has more than two features, you’re classifying vectors, instead of points."
},
{
"code": null,
"e": 1801,
"s": 1662,
"text": "So, to generalize, all vectors that fall below the decision boundary belong to class -1, and if they fall above it they belong to class 1."
},
{
"code": null,
"e": 1919,
"s": 1801,
"text": "We used training data to define the decision boundary. But what about the quality of predictions for the testing set?"
},
{
"code": null,
"e": 2171,
"s": 1919,
"text": "If a vector is far from the decision boundary we can be confident about its class, even if the model has some error. But, what happens when we classify a vector and it is very close to decision boundary? How can we be sure about which class to assign?"
},
{
"code": null,
"e": 2590,
"s": 2171,
"text": "To tackle this issue, support vector machines also draws a margin around the decision boundary. The goal of this margin is to separate the vectors from the decision boundary, as much as possible. The intuition behind it is that a margin gives us more confidence in our predictions. Because the vectors are at least the length of the margin away from the decision boundary, there’s less ambiguity during classification."
},
{
"code": null,
"e": 2767,
"s": 2590,
"text": "The position of the margin is defined using the vectors that are closest to the decision boundary. That’s why the vectors that lie on top of the margin are the support vectors."
},
{
"code": null,
"e": 2918,
"s": 2767,
"text": "And with the margin working as a buffer, we can classify a vector based on where they fall relative to the margin. Where M is the width of the margin."
},
{
"code": null,
"e": 3056,
"s": 2918,
"text": "The addition of a margin improves the quality of the predictions in the testing set, but it assumes the classes are completely separable."
},
{
"code": null,
"e": 3147,
"s": 3056,
"text": "But, in most real world problems, data is messy and it’s usually not completely separable."
},
{
"code": null,
"e": 3351,
"s": 3147,
"text": "That’s why SVM shares an important characteristic with the algorithm that came before it, support vector classifiers. It allows the algorithm to make mistakes, and assign the wrong class to some vectors."
},
{
"code": null,
"e": 3552,
"s": 3351,
"text": "So, instead of trying to completely separate the vectors in into two classes, SMV make a trade-off. It allows for some vectors to fall inside the margin and on the wrong side of the decision boundary."
},
{
"code": null,
"e": 3710,
"s": 3552,
"text": "Support vector machines allow some misclassification during the learning process. So they can do a better job at classifying most vectors in the testing set."
},
{
"code": null,
"e": 3801,
"s": 3710,
"text": "Besides the margin, our model now includes slack variables, which will tell us two things:"
},
{
"code": null,
"e": 3838,
"s": 3801,
"text": "if a test observation misclassified,"
},
{
"code": null,
"e": 3913,
"s": 3838,
"text": "where the observation is relative to the decision boundary and the margin."
},
{
"code": null,
"e": 3961,
"s": 3913,
"text": "Slack variables can have three possible values:"
},
{
"code": null,
"e": 4024,
"s": 3961,
"text": "And number of misclassified vectors is bound by a parameter C."
},
{
"code": null,
"e": 4375,
"s": 4024,
"text": "We can see the model captures much more nuance. But it’s still built on top of maximum margin classifiers. For instance, if you set parameter C to zero, meaning it allows zero slack variables, it falls back to a maximum margin classifier. So you have a linear decision boundary, a margin that is as large as possible and no vectors allowed inside it."
},
{
"code": null,
"e": 4616,
"s": 4375,
"text": "The higher the number of slack variables, the higher the number of misclassified vectors allowed. This impacts the width of the margin, because picking different support vectors. And it also controls the Bias-Variance tradeoff of the model."
},
{
"code": null,
"e": 4734,
"s": 4616,
"text": "Having some room for misclassification makes SMVs more flexibility, but it only applies to a limited set of problems."
},
{
"code": null,
"e": 4871,
"s": 4734,
"text": "In most real world problems, it’s hard to separate data into two classes with a linear decision boundary. Even with some room for error."
},
{
"code": null,
"e": 5046,
"s": 4871,
"text": "SVMs share the characteristics of the margin classifiers that came before it. What is unique about them is how they can define both linear and non-linear decision boundaries."
},
{
"code": null,
"e": 5211,
"s": 5046,
"text": "To support non-linear decision boundaries, SMVs use functions to transform the original feature space into a new space can represent those non-linear relationships."
},
{
"code": null,
"e": 5577,
"s": 5211,
"text": "For instance, say you augment the original feature space with the square its features. In this case, you applied a quadratic function to the original feature set to create the square of those features. Now you have your original feature and their quadratic version, in this augmented space. And so, implicitly, there’s a function that maps these two feature spaces."
},
{
"code": null,
"e": 5946,
"s": 5577,
"text": "If you try to draw the decision boundary in the original feature space it has a quadratic shape. But if you train your model in the augmented feature space, you’ll find a linear decision boundary that separates the two classes. Because it is a transformation, the quadratic boundary in original feature space corresponds to a linear one in the augmented feature space."
},
{
"code": null,
"e": 6103,
"s": 5946,
"text": "The functions that define these transformations are called kernels. They work as similarity functions between observations in the training and testing sets."
},
{
"code": null,
"e": 6406,
"s": 6103,
"text": "Whenever you have a model that is represented with inner products, you can plug in a kernel function. For instance, a linear kernel is the same as applying linear transformations to feature space. And, in this case, it’s the same as a support vector classifier, because the decision boundary is linear."
},
{
"code": null,
"e": 6604,
"s": 6406,
"text": "With polynomial kernels, you’re projecting the original feature space into a polynomial feature space. So the decision boundary that separates the classes is defined with a higher order polynomial."
},
{
"code": null,
"e": 6959,
"s": 6604,
"text": "The use of kernels is what distinguishes support vector classifiers from support vector machines. And they open up the possibility to tackle more complex problems. But augmenting the feature space could mean extra computational needs. Because, with a big enough feature space, it can be expensive to fit a model, both in terms of both time and resources."
},
{
"code": null,
"e": 7300,
"s": 6959,
"text": "Despite the the augmented feature space, kernels bring a significant advantage. SVMs don’t actually compute the transformation of each observation into the augmented space. They use a trick and instead compute the inner product of observations in the augmented space which, computationally, is much cheaper. This is called the kernel trick."
},
{
"code": null,
"e": 7349,
"s": 7300,
"text": "In the end, SVMs make two important assumptions:"
},
{
"code": null,
"e": 7439,
"s": 7349,
"text": "Data is linearly separable. Even if the linear boundary is in an augmented feature space."
},
{
"code": null,
"e": 7515,
"s": 7439,
"text": "The model is represented using inner products, so that kernels can be used."
},
{
"code": null,
"e": 7689,
"s": 7515,
"text": "To see support vector machines in action, I’ve generated a random dataset and split it into two different classes. Here's the code snippet that generates and plots the data."
},
{
"code": null,
"e": 9463,
"s": 7689,
"text": "import randomimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltdef generate_random_dataset(size): \"\"\" Generate a random dataset and that follows a quadratic distribution \"\"\" x = [] y = [] target = [] for i in range(size): # class zero x.append(np.round(random.uniform(0, 2.5), 1)) y.append(np.round(random.uniform(0, 20), 1)) target.append(0) # class one x.append(np.round(random.uniform(1, 5), 2)) y.append(np.round(random.uniform(20, 25), 2)) target.append(1) x.append(np.round(random.uniform(3, 5), 2)) y.append(np.round(random.uniform(5, 25), 2)) target.append(1) df_x = pd.DataFrame(data=x) df_y = pd.DataFrame(data=y) df_target = pd.DataFrame(data=target) data_frame = pd.concat([df_x, df_y], ignore_index=True, axis=1) data_frame = pd.concat([data_frame, df_target], ignore_index=True, axis=1) data_frame.columns = ['x', 'y', 'target'] return data_frame# Generate datasetsize = 100dataset = generate_random_dataset(size)features = dataset[['x', 'y']]label = dataset['target']# Hold out 20% of the dataset for trainingtest_size = int(np.round(size * 0.2, 0))# Split dataset into training and testing setsx_train = features[:-test_size].valuesy_train = label[:-test_size].valuesx_test = features[-test_size:].valuesy_test = label[-test_size:].values# Plotting the training setfig, ax = plt.subplots(figsize=(12, 7))# removing to and right borderax.spines['top'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['right'].set_visible(False)# adding major gridlinesax.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)ax.scatter(features[:-test_size]['x'], features[:-test_size]['y'], color=\"#8C7298\")plt.show()"
},
{
"code": null,
"e": 9524,
"s": 9463,
"text": "Before any classification, the training set looks like this."
},
{
"code": null,
"e": 9668,
"s": 9524,
"text": "There’s a little space between the two groups of data points. But closer to the center, it’s not clear which data point belongs to which class."
},
{
"code": null,
"e": 9799,
"s": 9668,
"text": "A quadratic curve might be a good candidate to separate these classes. So let’s fit an SVM with a second-degree polynomial kernel."
},
{
"code": null,
"e": 9890,
"s": 9799,
"text": "from sklearn import svmmodel = svm.SVC(kernel='poly', degree=2)model.fit(x_train, y_train)"
},
{
"code": null,
"e": 10004,
"s": 9890,
"text": "To see the result of fitting this model, we can plot the decision boundary and the margin along with the dataset."
},
{
"code": null,
"e": 10063,
"s": 10004,
"text": "Here’s the code to plot the decision boundary and margins."
},
{
"code": null,
"e": 11107,
"s": 10063,
"text": "fig, ax = plt.subplots(figsize=(12, 7))# Removing to and right borderax.spines['top'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['right'].set_visible(False)# Create grid to evaluate modelxx = np.linspace(-1, max(features['x']) + 1, len(x_train))yy = np.linspace(0, max(features['y']) + 1, len(y_train))YY, XX = np.meshgrid(yy, xx)xy = np.vstack([XX.ravel(), YY.ravel()]).Ttrain_size = len(features[:-test_size]['x'])# Assigning different colors to the classescolors = y_traincolors = np.where(colors == 1, '#8C7298', '#4786D1')# Plot the datasetax.scatter(features[:-test_size]['x'], features[:-test_size]['y'], c=colors)# Get the separating hyperplaneZ = model.decision_function(xy).reshape(XX.shape)# Draw the decision boundary and marginsax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--'])# Highlight support vectors with a circle around themax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], s=100, linewidth=1, facecolors='none', edgecolors='k')plt.show()"
},
{
"code": null,
"e": 11255,
"s": 11107,
"text": "If we calculate the accuracy of this model against the testing set we get a good result, granted the dataset is very small and generated at random."
},
{
"code": null,
"e": 11477,
"s": 11255,
"text": "from sklearn.metrics import accuracy_scorepredictions_poly = model.predict(x_test)accuracy_poly = accuracy_score(y_test, predictions_poly)print(\"2nd degree polynomial Kernel\\nAccuracy (normalized): \" + str(accuracy_poly))"
},
{
"code": null,
"e": 11654,
"s": 11477,
"text": "The accuracy is good, but let's see if a more simplistic approach could have solved our problem. To fit an SVM with a linear kernel we just need to update the kernel parameter."
},
{
"code": null,
"e": 11714,
"s": 11654,
"text": "model = svm.SVC(kernel='linear')model.fit(x_train, y_train)"
},
{
"code": null,
"e": 11777,
"s": 11714,
"text": "And plot the decision boundary the same way we did back there."
},
{
"code": null,
"e": 11980,
"s": 11777,
"text": "Now it looks like there are fewer points inside the margin, and fewer misclassified points. Calculating the accuracy of this model, it has slightly better accuracy than the one with a polynomial kernel."
},
{
"code": null,
"e": 12087,
"s": 11980,
"text": "So it turns out that for this problem a simpler model, an SVM with a linear kernel, was the best solution."
},
{
"code": null,
"e": 12219,
"s": 12087,
"text": "Hope you enjoyed these examples, and that you got a better understanding of SVMs and what kinds of problems they can be applied to."
}
] |
|| operator in Java - GeeksforGeeks
|
01 Nov, 2020
|| is a type of Logical Operator and is read as “OR OR” or “Logical OR“. This operator is used to perform “logical OR” operation, i.e. the function similar to OR gate in digital electronics.
One thing to keep in mind is the second condition is not evaluated if the first one is true, i.e. it has a short-circuiting effect. Used extensively to test for several conditions for making a decision.Syntax:
Condition1 || Condition2
// returns true if one of the conditions is true.
Below is an example to demonstrate || operator:Example:
Java
// Java program to illustrate// logical OR operator import java.util.*; public class operators { public static void main(String[] args) { char ch = 'a'; // check if character is alphabet or digit // using || operator if (ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122) System.out.println( ch + " is an alphabet."); else if (ch >= 48 && ch <= 57) System.out.println( ch + " is a digit."); else System.out.println( ch + " is a special character."); }}
a is an alphabet.
user_uxfa
Java-Operators
Picked
Java
Java-Operators
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Singleton Class in Java
Overriding in Java
Collections in Java
Multithreading in Java
|
[
{
"code": null,
"e": 24170,
"s": 24142,
"text": "\n01 Nov, 2020"
},
{
"code": null,
"e": 24363,
"s": 24170,
"text": "|| is a type of Logical Operator and is read as “OR OR” or “Logical OR“. This operator is used to perform “logical OR” operation, i.e. the function similar to OR gate in digital electronics. "
},
{
"code": null,
"e": 24575,
"s": 24363,
"text": "One thing to keep in mind is the second condition is not evaluated if the first one is true, i.e. it has a short-circuiting effect. Used extensively to test for several conditions for making a decision.Syntax: "
},
{
"code": null,
"e": 24652,
"s": 24575,
"text": "Condition1 || Condition2\n\n// returns true if one of the conditions is true.\n"
},
{
"code": null,
"e": 24710,
"s": 24652,
"text": "Below is an example to demonstrate || operator:Example: "
},
{
"code": null,
"e": 24715,
"s": 24710,
"text": "Java"
},
{
"code": "// Java program to illustrate// logical OR operator import java.util.*; public class operators { public static void main(String[] args) { char ch = 'a'; // check if character is alphabet or digit // using || operator if (ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122) System.out.println( ch + \" is an alphabet.\"); else if (ch >= 48 && ch <= 57) System.out.println( ch + \" is a digit.\"); else System.out.println( ch + \" is a special character.\"); }}",
"e": 25351,
"s": 24715,
"text": null
},
{
"code": null,
"e": 25372,
"s": 25351,
"text": "a is an alphabet.\n\n\n"
},
{
"code": null,
"e": 25384,
"s": 25374,
"text": "user_uxfa"
},
{
"code": null,
"e": 25399,
"s": 25384,
"text": "Java-Operators"
},
{
"code": null,
"e": 25406,
"s": 25399,
"text": "Picked"
},
{
"code": null,
"e": 25411,
"s": 25406,
"text": "Java"
},
{
"code": null,
"e": 25426,
"s": 25411,
"text": "Java-Operators"
},
{
"code": null,
"e": 25431,
"s": 25426,
"text": "Java"
},
{
"code": null,
"e": 25529,
"s": 25431,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25538,
"s": 25529,
"text": "Comments"
},
{
"code": null,
"e": 25551,
"s": 25538,
"text": "Old Comments"
},
{
"code": null,
"e": 25581,
"s": 25551,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 25600,
"s": 25581,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 25651,
"s": 25600,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 25669,
"s": 25651,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 25700,
"s": 25669,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 25732,
"s": 25700,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 25756,
"s": 25732,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 25775,
"s": 25756,
"text": "Overriding in Java"
},
{
"code": null,
"e": 25795,
"s": 25775,
"text": "Collections in Java"
}
] |
Predictive maintenance using machine learning | Towards Data Science
|
Different types of maintenance strategies have been widely deployed in oil and gas industry. Oil and gas industry today can utilize data science or machine learning instead of relying on old maintenance practices to better predict equipment failures and for conducting root cause analysis. Maintenance activities can be broadly divided into three major categories Corrective, Preventive and Predictive maintenance. Corrective maintenance refers to repair work after equipment outage occur. Preventive maintenance is based on certain periodic intervals to prevent equipment failure before it occurs. Predictive maintenance relies on engineering tools and statistical analysis to process the data and analyze health condition of equipment. Condition monitoring is also a form of predictive maintenance which relies on equipment sensors data to predict any failure.
Oil and gas companies have a complex system of machinery, like huge extractions platforms and thousands of kilometers of hydraulic systems to transport the product. Guarantee the perfect functioning of this structure is not an easy task. Oil and gas companies spend millions of dollars in maintenance cost to keep their equipment running 24/7. Using better data analytics approach they can not only cut down their maintenance cost but can increase their asset productivity to many folds. In this article we will discuss and present a real-life scenario where hydraulic systems data is used to train machine learning model for better predicting equipment failure.
Monitoring sensors in hydraulic systems capture measures such as pressures, volume flows and temperatures. This sensor collects this information at tiny periods (every 60 seconds, per example)
These extractions generate a huge time-series raw data set, with thousand or even millions of observations! This data is used by the computers to predict failures in these systems. The monitoring reduces downtime and maintenance costs and allows preventive health checks.
There is a large variety of models to use on the data collected. A powerful one is Neural Networks or more precisely, Artificial Neural Networks (ANN). How fun this name is! If you are imagining some brain activity with synapses occurring, you are not totally wrong.
This name comes from the idea that a unique neuron alone is a fairly complex structure, but when we join together some thousand of them, related all its connections and the exchange of information that occurs from this interaction, this structure becomes highly intricate and the brain could do incredible things.
In the Machine Learning environment, Artificial Neuron Networks could be used for a regression or a classification problem. Remember that we can divide the Machine Learning into two groups, the regression models and the classification models. They simply differentiate one from the other by the class of its variable of interest. Regression models: the output is a continuous variable. Classification models: the output is a categorical variable (discrete).
So, let’s go to work!
doing a good job.
#The ann_leakage data frame contains data from a sensor installed on #a hydraulic system in an oil and gas company. Take a look!kable(head(ann_leakage[,-(8:9)]))
The variable ann_leakage is 0 if the is no pump leakage, 1 if the is a weak leakage, and 2 for a severe leakage. PSxx stands for pressure measures, FSxx is the measures for volume flow, and TSxx is temperature measures. I take just 2 attributes for each variable.
To work on Neural Networks, we can divide the process into 4 steps:
1. Transform the categorical variables into binary variables;
2. Subset the data into a train set and a test set;
3. Train the data;
4. Test the data.
Ok, does this sound very technical to you? Don’t worry, I will explain each step separately.
Step 1: Transform the categorical variables into binary variables
Categorical variables describe characteristics of something. In the hydraulic systems of an oil and gas company, per example, a categorical variable could be an internal pump leakage, this is a preoccupation for the company’s engineers. We can classify this problem into three categories: No leakage; weak leakage; severe weak leakage.
So, to evaluate the probability for one of them, we have to set a binary variable of 1 if it is the category of interest and 0 if not. Doing this, we have the output variable.
#One should transform the ann_leakage variable into binary #variables. To predict just pump leakage I join weak and severe pump #leakage in the same variable.ann_leakage <- profile[,3]ann_leakage <- cbind(ann_leakage, PS1[,1:2], FS1[,1:2], TS1[,1:2])ann_leakage <- cbind(ann_leakage, ann_leakage$ann_leakage == 0)ann_leakage <- cbind(ann_leakage, ann_leakage$ann_leakage >= 1) colnames(ann_leakage)[8] <- “no”colnames(ann_leakage)[9] <- “leakage” kable(head(ann_leakage[,c(1,8,9)]))
Step 2: Subset the data
We have to separate the data set into two groups. With the first we perform a test model, to tell the data how it will handle the data. The other set, the train set, is to verify if the models are efficient in predicting the output.
#shuffle the data. subset into training and test setsset.seed(2403)redux <- sample(nrow(ann_leakage), 2000)ann_leakage <- ann_leakage[redux,] #scaling data ann_leakage <- cbind(scale(ann_leakage[,-(c(8,9))]), ann_leakage[,c(8,9)]) n <- nrow(ann_leakage)ntrain <- round(n*0.6) # 60% for the training settindex <- sample(n, ntrain) # create an indextrain_ann <- ann_leakage[tindex,] # create training settest_ann <- ann_leakage[-tindex,] #create test set
Neural Networks model is a non-linear regression that uses as its argument linear combinations from the variables in the data. Despite this fancy name, Artificial Neural Networks (ANN), can be defined by this simple phrase. It doesn’t look so complicated now, does it?
Step 3: Training the data
Training the data means to tell the computer how it will handle the data and how it will relate the input (sensor measures) with the output (binary variable from the pump leakage categories). We can use the Neural Network specification to do this.
#training the data set using the training datasetlibrary(neuralnet)ann <- neuralnet(no+leakage ~ PS11+PS12+FS11+FS12+TS11+TS12,data = train_ann, hidden = c(3)stepmax = 1e+05, threshold = 0.3) plot(ann, show.weights = FALSE, col.entry = “darkgreen”,col.hidden = “blue”, col.hidden.synapse = “blue”, col.out = “red”, col.out.synapse = “red”,col.entry.synapse = “darkgreen”, intercept = FALSE, information = FALSE)
The circles are the neurons and the arrow are the synapses. In green are the inputs, in blue the hidden layer (neurons), and in red the output.
Step 4: Test the data
Once we perform the model, we obtain the parameters associated. Now we have to predict the values using a different input data set (the test set) and compare the results from the predicted model and the output variable in the test set cresting what is named the confusion matrix, that counts how many predictions the model did correctly and how many predictions the model missed.
#Validate the model by predicting using the test data set predict <- neuralnet::compute(ann, test_ann[-1])predict <- predict$net.result#create a vector containing the response variables predcited#by the neural network and create a confusion matrix#to check the accuracy of the model pred_idx <- function(x) {return(which(x == max(x)))}idx <- apply(predict, c(1), pred_idx)predict_leakage <- c(“no”, “leakage”)[idx]library(expss)test_leakage <- if_else(test_ann[,”leakage”] == TRUE, “leakage”, “no”)xtab <- table(predict_leakage, test_leakage)library(knitr)kable(table(xtab, 1))
Doing this we are able to calculate the accuracy rate, that is simply a percentage rate of right predictions. So in this case, the model predicts 94 % of the pump leakages. It is very accurate and very fun, doesn’t?
Conclusion
Oil and Gas industry now a days is struggling for its survival due to downturn in oil prices. Instead of using old fashioned methods which relies on OEM manuals and best practices for predicting equipment failures, machine learning can be used for predicting equipment failures. The prediction from the ANN model emphasizes proactive maintenance and provides the right time to conduct inspection. ANN captures the possible reasons, like the timeline of the equipment failure event, reasons, duration and relevance information of the equipment by triggered sensory information. With systematic maintenance in advanced, unplanned equipment failure can be eliminated which will result in increased profits and productivity
1. Gutierrez DD (2015) Machine Learning and Data Science: An Introduction to Statistical Learning Methods with R. Technics Publications. LLC.
2. Hastie T, Tibshirani R, Friedman J (2013) The Elements of Statistical Learning: Data Mining, Inference, and Prediction, 2nd ed.
3. Helwig N, Pignanelli E, Schutze A (2015) Condition monitoring of a complex hydraulic system using multivariate statistics. 2015 IEEE International Instrumentation and Measurement Technology Conference (I2MTC) Proceedings
4. Nikolai Kelwig, Eliseo Pignalli, Andreas Schutze (2015) Detecting and compensating sensor faults in a hydraulic condition monitoring system. AMA Conferences 2015 — SENSOR 2015 and IRS2 2015
|
[
{
"code": null,
"e": 1035,
"s": 172,
"text": "Different types of maintenance strategies have been widely deployed in oil and gas industry. Oil and gas industry today can utilize data science or machine learning instead of relying on old maintenance practices to better predict equipment failures and for conducting root cause analysis. Maintenance activities can be broadly divided into three major categories Corrective, Preventive and Predictive maintenance. Corrective maintenance refers to repair work after equipment outage occur. Preventive maintenance is based on certain periodic intervals to prevent equipment failure before it occurs. Predictive maintenance relies on engineering tools and statistical analysis to process the data and analyze health condition of equipment. Condition monitoring is also a form of predictive maintenance which relies on equipment sensors data to predict any failure."
},
{
"code": null,
"e": 1698,
"s": 1035,
"text": "Oil and gas companies have a complex system of machinery, like huge extractions platforms and thousands of kilometers of hydraulic systems to transport the product. Guarantee the perfect functioning of this structure is not an easy task. Oil and gas companies spend millions of dollars in maintenance cost to keep their equipment running 24/7. Using better data analytics approach they can not only cut down their maintenance cost but can increase their asset productivity to many folds. In this article we will discuss and present a real-life scenario where hydraulic systems data is used to train machine learning model for better predicting equipment failure."
},
{
"code": null,
"e": 1891,
"s": 1698,
"text": "Monitoring sensors in hydraulic systems capture measures such as pressures, volume flows and temperatures. This sensor collects this information at tiny periods (every 60 seconds, per example)"
},
{
"code": null,
"e": 2163,
"s": 1891,
"text": "These extractions generate a huge time-series raw data set, with thousand or even millions of observations! This data is used by the computers to predict failures in these systems. The monitoring reduces downtime and maintenance costs and allows preventive health checks."
},
{
"code": null,
"e": 2430,
"s": 2163,
"text": "There is a large variety of models to use on the data collected. A powerful one is Neural Networks or more precisely, Artificial Neural Networks (ANN). How fun this name is! If you are imagining some brain activity with synapses occurring, you are not totally wrong."
},
{
"code": null,
"e": 2744,
"s": 2430,
"text": "This name comes from the idea that a unique neuron alone is a fairly complex structure, but when we join together some thousand of them, related all its connections and the exchange of information that occurs from this interaction, this structure becomes highly intricate and the brain could do incredible things."
},
{
"code": null,
"e": 3202,
"s": 2744,
"text": "In the Machine Learning environment, Artificial Neuron Networks could be used for a regression or a classification problem. Remember that we can divide the Machine Learning into two groups, the regression models and the classification models. They simply differentiate one from the other by the class of its variable of interest. Regression models: the output is a continuous variable. Classification models: the output is a categorical variable (discrete)."
},
{
"code": null,
"e": 3224,
"s": 3202,
"text": "So, let’s go to work!"
},
{
"code": null,
"e": 3242,
"s": 3224,
"text": "doing a good job."
},
{
"code": null,
"e": 3404,
"s": 3242,
"text": "#The ann_leakage data frame contains data from a sensor installed on #a hydraulic system in an oil and gas company. Take a look!kable(head(ann_leakage[,-(8:9)]))"
},
{
"code": null,
"e": 3668,
"s": 3404,
"text": "The variable ann_leakage is 0 if the is no pump leakage, 1 if the is a weak leakage, and 2 for a severe leakage. PSxx stands for pressure measures, FSxx is the measures for volume flow, and TSxx is temperature measures. I take just 2 attributes for each variable."
},
{
"code": null,
"e": 3736,
"s": 3668,
"text": "To work on Neural Networks, we can divide the process into 4 steps:"
},
{
"code": null,
"e": 3798,
"s": 3736,
"text": "1. Transform the categorical variables into binary variables;"
},
{
"code": null,
"e": 3850,
"s": 3798,
"text": "2. Subset the data into a train set and a test set;"
},
{
"code": null,
"e": 3869,
"s": 3850,
"text": "3. Train the data;"
},
{
"code": null,
"e": 3887,
"s": 3869,
"text": "4. Test the data."
},
{
"code": null,
"e": 3980,
"s": 3887,
"text": "Ok, does this sound very technical to you? Don’t worry, I will explain each step separately."
},
{
"code": null,
"e": 4046,
"s": 3980,
"text": "Step 1: Transform the categorical variables into binary variables"
},
{
"code": null,
"e": 4382,
"s": 4046,
"text": "Categorical variables describe characteristics of something. In the hydraulic systems of an oil and gas company, per example, a categorical variable could be an internal pump leakage, this is a preoccupation for the company’s engineers. We can classify this problem into three categories: No leakage; weak leakage; severe weak leakage."
},
{
"code": null,
"e": 4558,
"s": 4382,
"text": "So, to evaluate the probability for one of them, we have to set a binary variable of 1 if it is the category of interest and 0 if not. Doing this, we have the output variable."
},
{
"code": null,
"e": 5041,
"s": 4558,
"text": "#One should transform the ann_leakage variable into binary #variables. To predict just pump leakage I join weak and severe pump #leakage in the same variable.ann_leakage <- profile[,3]ann_leakage <- cbind(ann_leakage, PS1[,1:2], FS1[,1:2], TS1[,1:2])ann_leakage <- cbind(ann_leakage, ann_leakage$ann_leakage == 0)ann_leakage <- cbind(ann_leakage, ann_leakage$ann_leakage >= 1) colnames(ann_leakage)[8] <- “no”colnames(ann_leakage)[9] <- “leakage” kable(head(ann_leakage[,c(1,8,9)]))"
},
{
"code": null,
"e": 5065,
"s": 5041,
"text": "Step 2: Subset the data"
},
{
"code": null,
"e": 5298,
"s": 5065,
"text": "We have to separate the data set into two groups. With the first we perform a test model, to tell the data how it will handle the data. The other set, the train set, is to verify if the models are efficient in predicting the output."
},
{
"code": null,
"e": 5751,
"s": 5298,
"text": "#shuffle the data. subset into training and test setsset.seed(2403)redux <- sample(nrow(ann_leakage), 2000)ann_leakage <- ann_leakage[redux,] #scaling data ann_leakage <- cbind(scale(ann_leakage[,-(c(8,9))]), ann_leakage[,c(8,9)]) n <- nrow(ann_leakage)ntrain <- round(n*0.6) # 60% for the training settindex <- sample(n, ntrain) # create an indextrain_ann <- ann_leakage[tindex,] # create training settest_ann <- ann_leakage[-tindex,] #create test set"
},
{
"code": null,
"e": 6020,
"s": 5751,
"text": "Neural Networks model is a non-linear regression that uses as its argument linear combinations from the variables in the data. Despite this fancy name, Artificial Neural Networks (ANN), can be defined by this simple phrase. It doesn’t look so complicated now, does it?"
},
{
"code": null,
"e": 6046,
"s": 6020,
"text": "Step 3: Training the data"
},
{
"code": null,
"e": 6294,
"s": 6046,
"text": "Training the data means to tell the computer how it will handle the data and how it will relate the input (sensor measures) with the output (binary variable from the pump leakage categories). We can use the Neural Network specification to do this."
},
{
"code": null,
"e": 6706,
"s": 6294,
"text": "#training the data set using the training datasetlibrary(neuralnet)ann <- neuralnet(no+leakage ~ PS11+PS12+FS11+FS12+TS11+TS12,data = train_ann, hidden = c(3)stepmax = 1e+05, threshold = 0.3) plot(ann, show.weights = FALSE, col.entry = “darkgreen”,col.hidden = “blue”, col.hidden.synapse = “blue”, col.out = “red”, col.out.synapse = “red”,col.entry.synapse = “darkgreen”, intercept = FALSE, information = FALSE)"
},
{
"code": null,
"e": 6850,
"s": 6706,
"text": "The circles are the neurons and the arrow are the synapses. In green are the inputs, in blue the hidden layer (neurons), and in red the output."
},
{
"code": null,
"e": 6872,
"s": 6850,
"text": "Step 4: Test the data"
},
{
"code": null,
"e": 7252,
"s": 6872,
"text": "Once we perform the model, we obtain the parameters associated. Now we have to predict the values using a different input data set (the test set) and compare the results from the predicted model and the output variable in the test set cresting what is named the confusion matrix, that counts how many predictions the model did correctly and how many predictions the model missed."
},
{
"code": null,
"e": 7830,
"s": 7252,
"text": "#Validate the model by predicting using the test data set predict <- neuralnet::compute(ann, test_ann[-1])predict <- predict$net.result#create a vector containing the response variables predcited#by the neural network and create a confusion matrix#to check the accuracy of the model pred_idx <- function(x) {return(which(x == max(x)))}idx <- apply(predict, c(1), pred_idx)predict_leakage <- c(“no”, “leakage”)[idx]library(expss)test_leakage <- if_else(test_ann[,”leakage”] == TRUE, “leakage”, “no”)xtab <- table(predict_leakage, test_leakage)library(knitr)kable(table(xtab, 1))"
},
{
"code": null,
"e": 8046,
"s": 7830,
"text": "Doing this we are able to calculate the accuracy rate, that is simply a percentage rate of right predictions. So in this case, the model predicts 94 % of the pump leakages. It is very accurate and very fun, doesn’t?"
},
{
"code": null,
"e": 8057,
"s": 8046,
"text": "Conclusion"
},
{
"code": null,
"e": 8777,
"s": 8057,
"text": "Oil and Gas industry now a days is struggling for its survival due to downturn in oil prices. Instead of using old fashioned methods which relies on OEM manuals and best practices for predicting equipment failures, machine learning can be used for predicting equipment failures. The prediction from the ANN model emphasizes proactive maintenance and provides the right time to conduct inspection. ANN captures the possible reasons, like the timeline of the equipment failure event, reasons, duration and relevance information of the equipment by triggered sensory information. With systematic maintenance in advanced, unplanned equipment failure can be eliminated which will result in increased profits and productivity"
},
{
"code": null,
"e": 8919,
"s": 8777,
"text": "1. Gutierrez DD (2015) Machine Learning and Data Science: An Introduction to Statistical Learning Methods with R. Technics Publications. LLC."
},
{
"code": null,
"e": 9050,
"s": 8919,
"text": "2. Hastie T, Tibshirani R, Friedman J (2013) The Elements of Statistical Learning: Data Mining, Inference, and Prediction, 2nd ed."
},
{
"code": null,
"e": 9274,
"s": 9050,
"text": "3. Helwig N, Pignanelli E, Schutze A (2015) Condition monitoring of a complex hydraulic system using multivariate statistics. 2015 IEEE International Instrumentation and Measurement Technology Conference (I2MTC) Proceedings"
}
] |
Why do we need reference variables if we have pointers - GeeksforGeeks
|
01 Dec, 2021
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.References: A Reference can be called as a constant pointer that becomes de referenced implicitly. When we access the reference it means we are accessing the storage.Why do we need reference variables if we have pointers?In Pointers to access the value of the actual variable, we need to explicitly dereference the pointer variable by using ‘value at address’ dereferencing operator(*).In References to access the value of the actual variable, we do not need to explicitly dereference the reference variable, they get de-referenced automatically.Pointers and References are equivalent, except:
A reference is like a constant name for an address. We need to initialize the reference during the declaration. Once a reference is established to a variable, we cannot change the reference to reference another variable.
To get the value pointed to by a pointer, we need to use the dereferencing operator(*).
For Example: If a is a pointer to integer type, *a returns the value pointed to by a. To assign an address of a variable b into a pointer, we need to use the address-of operator(&).For Example: int *a= &b.
Reference are used over pointer to avoid Object Slicing.
Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object.
In references, referencing and de-referencing are done implicitly. No explicit de-referencing operator(*) and to assign the address of a variable to reference variable, no address-of operator(&).
A reference variable provides a new name to the existing variable. It is de-referenced implicitly and does not need a de-referencing operator(*) to retrieve the value referenced. Whereas, to retrieve the value pointed to by a pointer we need de-referencing operator(*) which is known as explicit de-referencing.
Reference can be treated as a constant pointer. It has to be initialized during declaration and its content cannot be changed.
Below is the program for the illustration of pointer and references:
C++14
// C++ program to illustrate// pointer and references #include <iostream>using namespace std; // function to illustrate// pointer and referencesvoid pointer_vs_reference(){ int num1 = 20, num2 = 23; // Pointer pointing to num1 // Explicit referencing int* ptr1 = &num1; cout << *ptr1 << endl; // 20 // Explicit dereferencing *ptr1 = 26; cout << *ptr1 << endl; // 26 // pointer can be reassigned to // store another address ptr1 = &num2; cout << *ptr1 << endl; // 23 // Reference to num1 // Implicit referencing int& ref1 = num1; cout << ref1 << endl; // 26 not 20 // Implicit dereferencing ref1 = 18; cout << ref1 << endl; // 18 // reference cannot be reassigned} // Driver codeint main(){ pointer_vs_reference(); return 0;}
20
26
23
26
18
Explanation of output:
when pointer ptr pointed to num1 var then it printed 20
when *ptr was de-referred and changed the value then it printed 26
similar for another variable called num2, printed 23
when reference ref1 was initialized by num1 then it printed 26 not 20
finally when 18 was assigned into ref1 then it printed 18 due to implicit de-referencing
Illustration of Reference Variable:Best example of the reference variable is the concept of copy constructor. Copy constructor takes a reference variable as an argument, pointer cannot be used here.
C++
#include <iostream>using namespace std; class complex {private: int a, b; public: // Parametric constructor complex(int x, int y) { a = x; b = y; } // Copy constructor complex(const complex& c) { a = c.a; b = c.b; } // Function to print data void printData() { cout << "a = " << a << endl; cout << "b = " << b; }}; int main(){ complex c1(5, 10); complex c2(c1); c2.printData();}
a = 5
b = 10
Explanation: In the above example if we take pointer in the argument of copy constructor then object of complex class will be created again and again which will never be stopped and it is error in oops concept. choosing reference is only the solution in this condition.
surindertarika1234
Advanced Pointer
C++-References
C-Advanced Pointer
C-Pointer Basics
C-Pointers
cpp-pointer
cpp-references
Picked
pointer
Pointers
References
C Language
C++
Pointers
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Constructors in C++
Socket Programming in C/C++
|
[
{
"code": null,
"e": 24013,
"s": 23985,
"text": "\n01 Dec, 2021"
},
{
"code": null,
"e": 24784,
"s": 24013,
"text": "Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.References: A Reference can be called as a constant pointer that becomes de referenced implicitly. When we access the reference it means we are accessing the storage.Why do we need reference variables if we have pointers?In Pointers to access the value of the actual variable, we need to explicitly dereference the pointer variable by using ‘value at address’ dereferencing operator(*).In References to access the value of the actual variable, we do not need to explicitly dereference the reference variable, they get de-referenced automatically.Pointers and References are equivalent, except: "
},
{
"code": null,
"e": 25005,
"s": 24784,
"text": "A reference is like a constant name for an address. We need to initialize the reference during the declaration. Once a reference is established to a variable, we cannot change the reference to reference another variable."
},
{
"code": null,
"e": 25093,
"s": 25005,
"text": "To get the value pointed to by a pointer, we need to use the dereferencing operator(*)."
},
{
"code": null,
"e": 25300,
"s": 25093,
"text": "For Example: If a is a pointer to integer type, *a returns the value pointed to by a. To assign an address of a variable b into a pointer, we need to use the address-of operator(&).For Example: int *a= &b. "
},
{
"code": null,
"e": 25359,
"s": 25300,
"text": "Reference are used over pointer to avoid Object Slicing. "
},
{
"code": null,
"e": 25540,
"s": 25359,
"text": "Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object."
},
{
"code": null,
"e": 25736,
"s": 25540,
"text": "In references, referencing and de-referencing are done implicitly. No explicit de-referencing operator(*) and to assign the address of a variable to reference variable, no address-of operator(&)."
},
{
"code": null,
"e": 26048,
"s": 25736,
"text": "A reference variable provides a new name to the existing variable. It is de-referenced implicitly and does not need a de-referencing operator(*) to retrieve the value referenced. Whereas, to retrieve the value pointed to by a pointer we need de-referencing operator(*) which is known as explicit de-referencing."
},
{
"code": null,
"e": 26175,
"s": 26048,
"text": "Reference can be treated as a constant pointer. It has to be initialized during declaration and its content cannot be changed."
},
{
"code": null,
"e": 26245,
"s": 26175,
"text": "Below is the program for the illustration of pointer and references: "
},
{
"code": null,
"e": 26251,
"s": 26245,
"text": "C++14"
},
{
"code": "// C++ program to illustrate// pointer and references #include <iostream>using namespace std; // function to illustrate// pointer and referencesvoid pointer_vs_reference(){ int num1 = 20, num2 = 23; // Pointer pointing to num1 // Explicit referencing int* ptr1 = &num1; cout << *ptr1 << endl; // 20 // Explicit dereferencing *ptr1 = 26; cout << *ptr1 << endl; // 26 // pointer can be reassigned to // store another address ptr1 = &num2; cout << *ptr1 << endl; // 23 // Reference to num1 // Implicit referencing int& ref1 = num1; cout << ref1 << endl; // 26 not 20 // Implicit dereferencing ref1 = 18; cout << ref1 << endl; // 18 // reference cannot be reassigned} // Driver codeint main(){ pointer_vs_reference(); return 0;}",
"e": 27049,
"s": 26251,
"text": null
},
{
"code": null,
"e": 27064,
"s": 27049,
"text": "20\n26\n23\n26\n18"
},
{
"code": null,
"e": 27090,
"s": 27066,
"text": "Explanation of output: "
},
{
"code": null,
"e": 27147,
"s": 27090,
"text": "when pointer ptr pointed to num1 var then it printed 20 "
},
{
"code": null,
"e": 27214,
"s": 27147,
"text": "when *ptr was de-referred and changed the value then it printed 26"
},
{
"code": null,
"e": 27267,
"s": 27214,
"text": "similar for another variable called num2, printed 23"
},
{
"code": null,
"e": 27337,
"s": 27267,
"text": "when reference ref1 was initialized by num1 then it printed 26 not 20"
},
{
"code": null,
"e": 27426,
"s": 27337,
"text": "finally when 18 was assigned into ref1 then it printed 18 due to implicit de-referencing"
},
{
"code": null,
"e": 27625,
"s": 27426,
"text": "Illustration of Reference Variable:Best example of the reference variable is the concept of copy constructor. Copy constructor takes a reference variable as an argument, pointer cannot be used here."
},
{
"code": null,
"e": 27629,
"s": 27625,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class complex {private: int a, b; public: // Parametric constructor complex(int x, int y) { a = x; b = y; } // Copy constructor complex(const complex& c) { a = c.a; b = c.b; } // Function to print data void printData() { cout << \"a = \" << a << endl; cout << \"b = \" << b; }}; int main(){ complex c1(5, 10); complex c2(c1); c2.printData();}",
"e": 28100,
"s": 27629,
"text": null
},
{
"code": null,
"e": 28113,
"s": 28100,
"text": "a = 5\nb = 10"
},
{
"code": null,
"e": 28385,
"s": 28115,
"text": "Explanation: In the above example if we take pointer in the argument of copy constructor then object of complex class will be created again and again which will never be stopped and it is error in oops concept. choosing reference is only the solution in this condition."
},
{
"code": null,
"e": 28404,
"s": 28385,
"text": "surindertarika1234"
},
{
"code": null,
"e": 28421,
"s": 28404,
"text": "Advanced Pointer"
},
{
"code": null,
"e": 28436,
"s": 28421,
"text": "C++-References"
},
{
"code": null,
"e": 28455,
"s": 28436,
"text": "C-Advanced Pointer"
},
{
"code": null,
"e": 28472,
"s": 28455,
"text": "C-Pointer Basics"
},
{
"code": null,
"e": 28483,
"s": 28472,
"text": "C-Pointers"
},
{
"code": null,
"e": 28495,
"s": 28483,
"text": "cpp-pointer"
},
{
"code": null,
"e": 28510,
"s": 28495,
"text": "cpp-references"
},
{
"code": null,
"e": 28517,
"s": 28510,
"text": "Picked"
},
{
"code": null,
"e": 28525,
"s": 28517,
"text": "pointer"
},
{
"code": null,
"e": 28534,
"s": 28525,
"text": "Pointers"
},
{
"code": null,
"e": 28545,
"s": 28534,
"text": "References"
},
{
"code": null,
"e": 28556,
"s": 28545,
"text": "C Language"
},
{
"code": null,
"e": 28560,
"s": 28556,
"text": "C++"
},
{
"code": null,
"e": 28569,
"s": 28560,
"text": "Pointers"
},
{
"code": null,
"e": 28573,
"s": 28569,
"text": "CPP"
},
{
"code": null,
"e": 28671,
"s": 28573,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28680,
"s": 28671,
"text": "Comments"
},
{
"code": null,
"e": 28693,
"s": 28680,
"text": "Old Comments"
},
{
"code": null,
"e": 28728,
"s": 28693,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 28756,
"s": 28728,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 28802,
"s": 28756,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 28814,
"s": 28802,
"text": "fork() in C"
},
{
"code": null,
"e": 28846,
"s": 28814,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 28864,
"s": 28846,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 28910,
"s": 28864,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 28953,
"s": 28910,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28973,
"s": 28953,
"text": "Constructors in C++"
}
] |
Python - Hilbert Curve using turtle - GeeksforGeeks
|
27 Feb, 2020
Fractal is a curve or a figure which repeats itself. It comprises a recursive pattern that repeats itself up to a desired level of nesting. Turtle graphics are provided in the turtle module which is used for drawing various shapes and patterns in Python.
A Hilbert curve is a curve which is formed by connecting a sequence of U-shaped curves arranged and oriented in different directions. These U-shaped curves are placed at a certain step size distance apart.
Let us examine a Level-1 Hilbert Curve. The following steps will draw a simple U curve.
Let y = 90 degree
Rotate y degree towards the rightMove step sizeRotate y degree towards the leftMove step sizeRotate y degree towards the leftMove step sizeRotate y degree towards the right
Rotate y degree towards the right
Move step size
Rotate y degree towards the left
Move step size
Rotate y degree towards the left
Move step size
Rotate y degree towards the right
Let us examine and try to understand the level-2 Hilbert Curve.
Again, we assume that the turtle pointer points towards right initially. The following steps may be used to draw the curve:
Rotate 90 degrees towards the rightCreate a hilbert curve at level 1 rotated by -y degrees (ie, y degrees in anticlockwise direction)Move step sizeRotate y degrees towards the rightCreate a level 1 hilbert curve rotated by y degrees (ie, y degrees in clockwise direction)Rotate y degrees towards the left.Move step sizeCreate a level 1 hilbert curve rotated by -y degreesRotate y degrees towards the right
Rotate 90 degrees towards the right
Create a hilbert curve at level 1 rotated by -y degrees (ie, y degrees in anticlockwise direction)
Move step size
Rotate y degrees towards the right
Create a level 1 hilbert curve rotated by y degrees (ie, y degrees in clockwise direction)
Rotate y degrees towards the left.
Move step size
Create a level 1 hilbert curve rotated by -y degrees
Rotate y degrees towards the right
turtle methods used in this section are as follows :
forward(): Used for moving the turtle forward by a given distance in the direction of the turtle.
backward(): Used for moving the turtle backward by a given distance in the direction of the turtle.
left(): Used for rotating the turtle in the left direction by a specified angle.
right(): Used for rotating the turtle in the right direction by a specified angle.
goto(): Used for moving the turtle to the location specified ((x, y) coordinates).
penup(): Used for specifying that no drawing will be made while moving.
pendown(): Used for specifying that that drawing will be made while moving.
done(): Used to specify that the turtle work is completed.
from turtle import * def hilbert(level, angle, step): # Input Parameters are numeric # Return Value: None if level == 0: return right(angle) hilbert(level-1, -angle, step) forward(step) left(angle) hilbert(level-1, angle, step) forward(step) hilbert(level-1, angle, step) left(angle) forward(step) hilbert(level-1, -angle, step) right(angle) def main(): level = int(input()) size = 200 penup() goto(-size / 2.0, size / 2.0) pendown() # For positioning turtle hilbert(level, 90, size/(2**level-1)) done() if __name__=='__main__': main()
Python-turtle
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 24224,
"s": 24196,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 24479,
"s": 24224,
"text": "Fractal is a curve or a figure which repeats itself. It comprises a recursive pattern that repeats itself up to a desired level of nesting. Turtle graphics are provided in the turtle module which is used for drawing various shapes and patterns in Python."
},
{
"code": null,
"e": 24685,
"s": 24479,
"text": "A Hilbert curve is a curve which is formed by connecting a sequence of U-shaped curves arranged and oriented in different directions. These U-shaped curves are placed at a certain step size distance apart."
},
{
"code": null,
"e": 24773,
"s": 24685,
"text": "Let us examine a Level-1 Hilbert Curve. The following steps will draw a simple U curve."
},
{
"code": null,
"e": 24791,
"s": 24773,
"text": "Let y = 90 degree"
},
{
"code": null,
"e": 24964,
"s": 24791,
"text": "Rotate y degree towards the rightMove step sizeRotate y degree towards the leftMove step sizeRotate y degree towards the leftMove step sizeRotate y degree towards the right"
},
{
"code": null,
"e": 24998,
"s": 24964,
"text": "Rotate y degree towards the right"
},
{
"code": null,
"e": 25013,
"s": 24998,
"text": "Move step size"
},
{
"code": null,
"e": 25046,
"s": 25013,
"text": "Rotate y degree towards the left"
},
{
"code": null,
"e": 25061,
"s": 25046,
"text": "Move step size"
},
{
"code": null,
"e": 25094,
"s": 25061,
"text": "Rotate y degree towards the left"
},
{
"code": null,
"e": 25109,
"s": 25094,
"text": "Move step size"
},
{
"code": null,
"e": 25143,
"s": 25109,
"text": "Rotate y degree towards the right"
},
{
"code": null,
"e": 25207,
"s": 25143,
"text": "Let us examine and try to understand the level-2 Hilbert Curve."
},
{
"code": null,
"e": 25331,
"s": 25207,
"text": "Again, we assume that the turtle pointer points towards right initially. The following steps may be used to draw the curve:"
},
{
"code": null,
"e": 25737,
"s": 25331,
"text": "Rotate 90 degrees towards the rightCreate a hilbert curve at level 1 rotated by -y degrees (ie, y degrees in anticlockwise direction)Move step sizeRotate y degrees towards the rightCreate a level 1 hilbert curve rotated by y degrees (ie, y degrees in clockwise direction)Rotate y degrees towards the left.Move step sizeCreate a level 1 hilbert curve rotated by -y degreesRotate y degrees towards the right"
},
{
"code": null,
"e": 25773,
"s": 25737,
"text": "Rotate 90 degrees towards the right"
},
{
"code": null,
"e": 25872,
"s": 25773,
"text": "Create a hilbert curve at level 1 rotated by -y degrees (ie, y degrees in anticlockwise direction)"
},
{
"code": null,
"e": 25887,
"s": 25872,
"text": "Move step size"
},
{
"code": null,
"e": 25922,
"s": 25887,
"text": "Rotate y degrees towards the right"
},
{
"code": null,
"e": 26013,
"s": 25922,
"text": "Create a level 1 hilbert curve rotated by y degrees (ie, y degrees in clockwise direction)"
},
{
"code": null,
"e": 26048,
"s": 26013,
"text": "Rotate y degrees towards the left."
},
{
"code": null,
"e": 26063,
"s": 26048,
"text": "Move step size"
},
{
"code": null,
"e": 26116,
"s": 26063,
"text": "Create a level 1 hilbert curve rotated by -y degrees"
},
{
"code": null,
"e": 26151,
"s": 26116,
"text": "Rotate y degrees towards the right"
},
{
"code": null,
"e": 26204,
"s": 26151,
"text": "turtle methods used in this section are as follows :"
},
{
"code": null,
"e": 26302,
"s": 26204,
"text": "forward(): Used for moving the turtle forward by a given distance in the direction of the turtle."
},
{
"code": null,
"e": 26402,
"s": 26302,
"text": "backward(): Used for moving the turtle backward by a given distance in the direction of the turtle."
},
{
"code": null,
"e": 26483,
"s": 26402,
"text": "left(): Used for rotating the turtle in the left direction by a specified angle."
},
{
"code": null,
"e": 26566,
"s": 26483,
"text": "right(): Used for rotating the turtle in the right direction by a specified angle."
},
{
"code": null,
"e": 26649,
"s": 26566,
"text": "goto(): Used for moving the turtle to the location specified ((x, y) coordinates)."
},
{
"code": null,
"e": 26721,
"s": 26649,
"text": "penup(): Used for specifying that no drawing will be made while moving."
},
{
"code": null,
"e": 26797,
"s": 26721,
"text": "pendown(): Used for specifying that that drawing will be made while moving."
},
{
"code": null,
"e": 26856,
"s": 26797,
"text": "done(): Used to specify that the turtle work is completed."
},
{
"code": "from turtle import * def hilbert(level, angle, step): # Input Parameters are numeric # Return Value: None if level == 0: return right(angle) hilbert(level-1, -angle, step) forward(step) left(angle) hilbert(level-1, angle, step) forward(step) hilbert(level-1, angle, step) left(angle) forward(step) hilbert(level-1, -angle, step) right(angle) def main(): level = int(input()) size = 200 penup() goto(-size / 2.0, size / 2.0) pendown() # For positioning turtle hilbert(level, 90, size/(2**level-1)) done() if __name__=='__main__': main()",
"e": 27494,
"s": 26856,
"text": null
},
{
"code": null,
"e": 27508,
"s": 27494,
"text": "Python-turtle"
},
{
"code": null,
"e": 27532,
"s": 27508,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 27539,
"s": 27532,
"text": "Python"
},
{
"code": null,
"e": 27558,
"s": 27539,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27656,
"s": 27558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27665,
"s": 27656,
"text": "Comments"
},
{
"code": null,
"e": 27678,
"s": 27665,
"text": "Old Comments"
},
{
"code": null,
"e": 27696,
"s": 27678,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27731,
"s": 27696,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27753,
"s": 27731,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27785,
"s": 27753,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27815,
"s": 27785,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27857,
"s": 27815,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27900,
"s": 27857,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27926,
"s": 27900,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27970,
"s": 27926,
"text": "Reading and Writing to text files in Python"
}
] |
Bootstrap - Button Groups
|
Button groups allow multiple buttons to be stacked together on a single line. This is useful when you want to place items like alignment buttons together. You can add on optional JavaScript radio and checkbox style behavior with Bootstrap Button Plugin.
Following table summarizes the important classes Bootstrap provides to use button groups −
<div class = "btn-group">
<button type = "button" class = "btn btn-default">Button1</button>
<button type = "button" class = "btn btn-default">Button2</button>
</div>
<div class = "btn-toolbar" role = "toolbar">
<div class = "btn-group">...</div>
<div class = "btn-group">...</div>
</div>
<div class = "btn-group btn-group-lg">...</div>
<div class = "btn-group btn-group-sm">...</div>
<div class = "btn-group btn-group-xs">...</div>
<div class = "btn-group-vertical">
...
</div>
The following example demonstrates the use of class .btn-group discussed in the above table −
<div class = "btn-group">
<button type = "button" class = "btn btn-default">Button 1</button>
<button type = "button" class = "btn btn-default">Button 2</button>
<button type = "button" class = "btn btn-default">Button 3</button>
</div>
The following example demonstrates the use of class .btn-toolbar discussed in the above table −
<div class = "btn-toolbar" role = "toolbar">
<div class = "btn-group">
<button type = "button" class = "btn btn-default">Button 1</button>
<button type = "button" class = "btn btn-default">Button 2</button>
<button type = "button" class = "btn btn-default">Button 3</button>
</div>
<div class = "btn-group">
<button type = "button" class = "btn btn-default">Button 4</button>
<button type = "button" class = "btn btn-default">Button 5</button>
<button type = "button" class = "btn btn-default">Button 6</button>
</div>
<div class = "btn-group">
<button type = "button" class = "btn btn-default">Button 7</button>
<button type = "button" class = "btn btn-default">Button 8</button>
<button type = "button" class = "btn btn-default">Button 9</button>
</div>
</div>
The following example demonstrates the use of class .btn-group-* discussed in the above table −
<div class = "btn-group btn-group-lg">
<button type = "button" class = "btn btn-default">Button 1</button>
<button type = "button" class = "btn btn-default">Button 2</button>
<button type = "button" class = "btn btn-default">Button 3</button>
</div>
<div class = "btn-group btn-group-sm">
<button type = "button" class = "btn btn-default">Button 4</button>
<button type = "button" class = "btn btn-default">Button 5</button>
<button type = "button" class = "btn btn-default">Button 6</button>
</div>
<div class = "btn-group btn-group-xs">
<button type = "button" class = "btn btn-default">Button 7</button>
<button type = "button" class = "btn btn-default">Button 8</button>
<button type = "button" class = "btn btn-default">Button 9</button>
</div>
You can nest button groups within another button group i.e, place a .btn-group within another .btn-group . This is done when you want dropdown menus mixed with a series of buttons.
<div class = "btn-group">
<button type = "button" class = "btn btn-default">Button 1</button>
<button type = "button" class = "btn btn-default">Button 2</button>
<div class = "btn-group">
<button type = "button" class = "btn btn-default dropdown-toggle" data-toggle = "dropdown">
Dropdown
<span class = "caret"></span>
</button>
<ul class = "dropdown-menu">
<li><a href = "#">Dropdown link 1</a></li>
<li><a href = "#">Dropdown link 2</a></li>
</ul>
</div>
</div>
Dropdown link 1
Dropdown link 2
The following example demonstrates the use of class .btn-group-vertical discussed in the above table −
<div class = "btn-group-vertical">
<button type = "button" class = "btn btn-default">Button 1</button>
<button type = "button" class = "btn btn-default">Button 2</button>
<div class = "btn-group-vertical">
<button type = "button" class = "btn btn-default dropdown-toggle" data-toggle = "dropdown">
Dropdown
<span class = "caret"></span>
</button>
<ul class = "dropdown-menu">
<li><a href = "#">Dropdown link 1</a></li>
<li><a href = "#">Dropdown link 2</a></li>
</ul>
</div>
</div>
Dropdown link 1
Dropdown link 2
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3585,
"s": 3331,
"text": "Button groups allow multiple buttons to be stacked together on a single line. This is useful when you want to place items like alignment buttons together. You can add on optional JavaScript radio and checkbox style behavior with Bootstrap Button Plugin."
},
{
"code": null,
"e": 3676,
"s": 3585,
"text": "Following table summarizes the important classes Bootstrap provides to use button groups −"
},
{
"code": null,
"e": 3849,
"s": 3676,
"text": "<div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-default\">Button1</button>\n <button type = \"button\" class = \"btn btn-default\">Button2</button>\n</div>"
},
{
"code": null,
"e": 3977,
"s": 3849,
"text": "<div class = \"btn-toolbar\" role = \"toolbar\">\n <div class = \"btn-group\">...</div>\n <div class = \"btn-group\">...</div>\n</div>"
},
{
"code": null,
"e": 4121,
"s": 3977,
"text": "<div class = \"btn-group btn-group-lg\">...</div>\n<div class = \"btn-group btn-group-sm\">...</div>\n<div class = \"btn-group btn-group-xs\">...</div>"
},
{
"code": null,
"e": 4170,
"s": 4121,
"text": "<div class = \"btn-group-vertical\">\n ...\n</div>"
},
{
"code": null,
"e": 4264,
"s": 4170,
"text": "The following example demonstrates the use of class .btn-group discussed in the above table −"
},
{
"code": null,
"e": 4518,
"s": 4264,
"text": "<div class = \"btn-group\">\n \n <button type = \"button\" class = \"btn btn-default\">Button 1</button>\n <button type = \"button\" class = \"btn btn-default\">Button 2</button>\n <button type = \"button\" class = \"btn btn-default\">Button 3</button>\n \n</div>"
},
{
"code": null,
"e": 4614,
"s": 4518,
"text": "The following example demonstrates the use of class .btn-toolbar discussed in the above table −"
},
{
"code": null,
"e": 5465,
"s": 4614,
"text": "<div class = \"btn-toolbar\" role = \"toolbar\">\n \n <div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-default\">Button 1</button>\n <button type = \"button\" class = \"btn btn-default\">Button 2</button>\n <button type = \"button\" class = \"btn btn-default\">Button 3</button>\n </div>\n \n <div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-default\">Button 4</button>\n <button type = \"button\" class = \"btn btn-default\">Button 5</button>\n <button type = \"button\" class = \"btn btn-default\">Button 6</button>\n </div>\n \n <div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-default\">Button 7</button>\n <button type = \"button\" class = \"btn btn-default\">Button 8</button>\n <button type = \"button\" class = \"btn btn-default\">Button 9</button>\n </div>\n \n</div>"
},
{
"code": null,
"e": 5561,
"s": 5465,
"text": "The following example demonstrates the use of class .btn-group-* discussed in the above table −"
},
{
"code": null,
"e": 6340,
"s": 5561,
"text": "<div class = \"btn-group btn-group-lg\">\n <button type = \"button\" class = \"btn btn-default\">Button 1</button>\n <button type = \"button\" class = \"btn btn-default\">Button 2</button>\n <button type = \"button\" class = \"btn btn-default\">Button 3</button>\n</div>\n\n<div class = \"btn-group btn-group-sm\">\n <button type = \"button\" class = \"btn btn-default\">Button 4</button>\n <button type = \"button\" class = \"btn btn-default\">Button 5</button>\n <button type = \"button\" class = \"btn btn-default\">Button 6</button>\n</div>\n\n<div class = \"btn-group btn-group-xs\">\n <button type = \"button\" class = \"btn btn-default\">Button 7</button>\n <button type = \"button\" class = \"btn btn-default\">Button 8</button>\n <button type = \"button\" class = \"btn btn-default\">Button 9</button>\n</div>"
},
{
"code": null,
"e": 6521,
"s": 6340,
"text": "You can nest button groups within another button group i.e, place a .btn-group within another .btn-group . This is done when you want dropdown menus mixed with a series of buttons."
},
{
"code": null,
"e": 7071,
"s": 6521,
"text": "<div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-default\">Button 1</button>\n <button type = \"button\" class = \"btn btn-default\">Button 2</button>\n \n <div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-default dropdown-toggle\" data-toggle = \"dropdown\">\n Dropdown\n <span class = \"caret\"></span>\n </button>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">Dropdown link 1</a></li>\n <li><a href = \"#\">Dropdown link 2</a></li>\n </ul>\n </div>\n \n</div>"
},
{
"code": null,
"e": 7087,
"s": 7071,
"text": "Dropdown link 1"
},
{
"code": null,
"e": 7103,
"s": 7087,
"text": "Dropdown link 2"
},
{
"code": null,
"e": 7206,
"s": 7103,
"text": "The following example demonstrates the use of class .btn-group-vertical discussed in the above table −"
},
{
"code": null,
"e": 7774,
"s": 7206,
"text": "<div class = \"btn-group-vertical\">\n <button type = \"button\" class = \"btn btn-default\">Button 1</button>\n <button type = \"button\" class = \"btn btn-default\">Button 2</button>\n \n <div class = \"btn-group-vertical\">\n <button type = \"button\" class = \"btn btn-default dropdown-toggle\" data-toggle = \"dropdown\">\n Dropdown\n <span class = \"caret\"></span>\n </button>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">Dropdown link 1</a></li>\n <li><a href = \"#\">Dropdown link 2</a></li>\n </ul>\n </div>\n \n</div>"
},
{
"code": null,
"e": 7790,
"s": 7774,
"text": "Dropdown link 1"
},
{
"code": null,
"e": 7806,
"s": 7790,
"text": "Dropdown link 2"
},
{
"code": null,
"e": 7839,
"s": 7806,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7853,
"s": 7839,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7888,
"s": 7853,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7905,
"s": 7888,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7942,
"s": 7905,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 7970,
"s": 7942,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8003,
"s": 7970,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8015,
"s": 8003,
"text": " Azaz Patel"
},
{
"code": null,
"e": 8050,
"s": 8015,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8067,
"s": 8050,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 8100,
"s": 8067,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 8120,
"s": 8100,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 8127,
"s": 8120,
"text": " Print"
},
{
"code": null,
"e": 8138,
"s": 8127,
"text": " Add Notes"
}
] |
Random list of M non-negative integers whose sum is N - GeeksforGeeks
|
19 Mar, 2022
Given two integers M and N, the task is to create a list of M non-negative integers whose sum is N. In case when more than one list is possible, find any one.Examples:
Input: M = 4, N = 8 Output: 1 3 3 1 1 + 3 + 3 + 1 = 8Input: M = 5, N = 3 Output: 0 1 1 0 1
Approach: To get a complete random list of integers, create an array of size M where every element is initialised with 0. Now run a loop from 0 to N – 1 and increment any randomly chosen element from the array by 1 using the rand() function. This way, sum of the resuntant list will be N.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; // Utility function to print the// elements of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Function to generate a list of// m random non-negative integers// whose sum is nvoid randomList(int m, int n){ // Create an array of size m where // every element is initialized to 0 int arr[m] = { 0 }; srand(time(0)); // To make the sum of the final list as n for (int i = 0; i < n; i++) { // Increment any random element // from the array by 1 arr[rand() % m]++; } // Print the generated list printArr(arr, m);} // Driver codeint main(){ int m = 4, n = 8; randomList(m, n); return 0;}
// Java implementation of the approachclass GFG{ // Utility function to print the// elements of an arraystatic void printArr(int arr[], int n){ for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");} // Function to generate a list of// m random non-negative integers// whose sum is nstatic void randomList(int m, int n){ // Create an array of size m where // every element is initialized to 0 int arr[] = new int[m]; // To make the sum of the final list as n for (int i = 0; i < n; i++) { // Increment any random element // from the array by 1 arr[(int)(Math.random() * m)]++; } // Print the generated list printArr(arr, m);} // Driver codepublic static void main(String args[]){ int m = 4, n = 8; randomList(m, n);}} // This code is contributed by Arnab Kundu
# Python3 implementation of the approachfrom random import randint # Utility function to print the# elements of an arraydef printArr(arr, n) : for i in range(n) : print(arr[i], end = " "); # Function to generate a list of# m random non-negative integers# whose sum is ndef randomList(m, n): # Create an array of size m where # every element is initialized to 0 arr = [0] * m; # To make the sum of the final list as n for i in range(n) : # Increment any random element # from the array by 1 arr[randint(0, n) % m] += 1; # Print the generated list printArr(arr, m); # Driver codeif __name__ == "__main__" : m = 4; n = 8; randomList(m, n); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Utility function to print the// elements of an arraystatic void printArr(int []arr, int n){ for (int i = 0; i < n; i++) Console.Write(arr[i] + " ");} // Function to generate a list of// m random non-negative integers// whose sum is nstatic void randomList(int m, int n){ // Create an array of size m where // every element is initialized to 0 int [] arr = new int[m]; // To make the sum of the final list as n for (int i = 0; i < n; i++) { // Increment any random element // from the array by 1 Random rnd = new Random(); arr[rnd.Next(0, n) % m]++; } // Print the generated list printArr(arr, m);} // Driver codepublic static void Main(){ int m = 4, n = 8; randomList(m, n);}} // This code is contributed by Mohit kumar
<script>// Javascript implementation of the approach // Utility function to print the// elements of an array function printArr(arr,n) { for (let i = 0; i < n; i++) document.write(arr[i] + " "); } // Function to generate a list of// m random non-negative integers// whose sum is n function randomList(m,n) { // Create an array of size m where // every element is initialized to 0 let arr = new Array(m); for(let i=0;i<arr.length;i++) { arr[i]=0; } // To make the sum of the final list as n for (let i = 0; i < n; i++) { // Increment any random element // from the array by 1 arr[(Math.floor((Math.random() * n) )%m)]++; } // Print the generated list printArr(arr, m); } // Driver code let m = 4, n = 8; randomList(m, n); // This code is contributed by patel2127</script>
1 3 3 1
Time Complexity: O(max(M, N))
Auxiliary Space: O(M)
ankthon
andrew1234
mohit kumar 29
patel2127
subham348
Numbers
Analysis
Greedy
Mathematical
Greedy
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
3-coloring is NP Complete
Proof that Dominant Set of a Graph is NP-Complete
Difference between Deterministic and Non-deterministic Algorithms
Set partition is NP complete
Dijkstra's shortest path algorithm | Greedy Algo-7
Program for array rotation
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 24629,
"s": 24601,
"text": "\n19 Mar, 2022"
},
{
"code": null,
"e": 24799,
"s": 24629,
"text": "Given two integers M and N, the task is to create a list of M non-negative integers whose sum is N. In case when more than one list is possible, find any one.Examples: "
},
{
"code": null,
"e": 24892,
"s": 24799,
"text": "Input: M = 4, N = 8 Output: 1 3 3 1 1 + 3 + 3 + 1 = 8Input: M = 5, N = 3 Output: 0 1 1 0 1 "
},
{
"code": null,
"e": 25235,
"s": 24894,
"text": "Approach: To get a complete random list of integers, create an array of size M where every element is initialised with 0. Now run a loop from 0 to N – 1 and increment any randomly chosen element from the array by 1 using the rand() function. This way, sum of the resuntant list will be N.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25239,
"s": 25235,
"text": "C++"
},
{
"code": null,
"e": 25244,
"s": 25239,
"text": "Java"
},
{
"code": null,
"e": 25252,
"s": 25244,
"text": "Python3"
},
{
"code": null,
"e": 25255,
"s": 25252,
"text": "C#"
},
{
"code": null,
"e": 25266,
"s": 25255,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the// elements of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Function to generate a list of// m random non-negative integers// whose sum is nvoid randomList(int m, int n){ // Create an array of size m where // every element is initialized to 0 int arr[m] = { 0 }; srand(time(0)); // To make the sum of the final list as n for (int i = 0; i < n; i++) { // Increment any random element // from the array by 1 arr[rand() % m]++; } // Print the generated list printArr(arr, m);} // Driver codeint main(){ int m = 4, n = 8; randomList(m, n); return 0;}",
"e": 26051,
"s": 25266,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Utility function to print the// elements of an arraystatic void printArr(int arr[], int n){ for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \");} // Function to generate a list of// m random non-negative integers// whose sum is nstatic void randomList(int m, int n){ // Create an array of size m where // every element is initialized to 0 int arr[] = new int[m]; // To make the sum of the final list as n for (int i = 0; i < n; i++) { // Increment any random element // from the array by 1 arr[(int)(Math.random() * m)]++; } // Print the generated list printArr(arr, m);} // Driver codepublic static void main(String args[]){ int m = 4, n = 8; randomList(m, n);}} // This code is contributed by Arnab Kundu",
"e": 26894,
"s": 26051,
"text": null
},
{
"code": "# Python3 implementation of the approachfrom random import randint # Utility function to print the# elements of an arraydef printArr(arr, n) : for i in range(n) : print(arr[i], end = \" \"); # Function to generate a list of# m random non-negative integers# whose sum is ndef randomList(m, n): # Create an array of size m where # every element is initialized to 0 arr = [0] * m; # To make the sum of the final list as n for i in range(n) : # Increment any random element # from the array by 1 arr[randint(0, n) % m] += 1; # Print the generated list printArr(arr, m); # Driver codeif __name__ == \"__main__\" : m = 4; n = 8; randomList(m, n); # This code is contributed by AnkitRai01",
"e": 27641,
"s": 26894,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Utility function to print the// elements of an arraystatic void printArr(int []arr, int n){ for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \");} // Function to generate a list of// m random non-negative integers// whose sum is nstatic void randomList(int m, int n){ // Create an array of size m where // every element is initialized to 0 int [] arr = new int[m]; // To make the sum of the final list as n for (int i = 0; i < n; i++) { // Increment any random element // from the array by 1 Random rnd = new Random(); arr[rnd.Next(0, n) % m]++; } // Print the generated list printArr(arr, m);} // Driver codepublic static void Main(){ int m = 4, n = 8; randomList(m, n);}} // This code is contributed by Mohit kumar",
"e": 28510,
"s": 27641,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach // Utility function to print the// elements of an array function printArr(arr,n) { for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); } // Function to generate a list of// m random non-negative integers// whose sum is n function randomList(m,n) { // Create an array of size m where // every element is initialized to 0 let arr = new Array(m); for(let i=0;i<arr.length;i++) { arr[i]=0; } // To make the sum of the final list as n for (let i = 0; i < n; i++) { // Increment any random element // from the array by 1 arr[(Math.floor((Math.random() * n) )%m)]++; } // Print the generated list printArr(arr, m); } // Driver code let m = 4, n = 8; randomList(m, n); // This code is contributed by patel2127</script>",
"e": 29438,
"s": 28510,
"text": null
},
{
"code": null,
"e": 29446,
"s": 29438,
"text": "1 3 3 1"
},
{
"code": null,
"e": 29478,
"s": 29448,
"text": "Time Complexity: O(max(M, N))"
},
{
"code": null,
"e": 29501,
"s": 29478,
"text": "Auxiliary Space: O(M) "
},
{
"code": null,
"e": 29509,
"s": 29501,
"text": "ankthon"
},
{
"code": null,
"e": 29520,
"s": 29509,
"text": "andrew1234"
},
{
"code": null,
"e": 29535,
"s": 29520,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 29545,
"s": 29535,
"text": "patel2127"
},
{
"code": null,
"e": 29555,
"s": 29545,
"text": "subham348"
},
{
"code": null,
"e": 29563,
"s": 29555,
"text": "Numbers"
},
{
"code": null,
"e": 29572,
"s": 29563,
"text": "Analysis"
},
{
"code": null,
"e": 29579,
"s": 29572,
"text": "Greedy"
},
{
"code": null,
"e": 29592,
"s": 29579,
"text": "Mathematical"
},
{
"code": null,
"e": 29599,
"s": 29592,
"text": "Greedy"
},
{
"code": null,
"e": 29612,
"s": 29599,
"text": "Mathematical"
},
{
"code": null,
"e": 29620,
"s": 29612,
"text": "Numbers"
},
{
"code": null,
"e": 29718,
"s": 29620,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29727,
"s": 29718,
"text": "Comments"
},
{
"code": null,
"e": 29740,
"s": 29727,
"text": "Old Comments"
},
{
"code": null,
"e": 29807,
"s": 29740,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 29833,
"s": 29807,
"text": "3-coloring is NP Complete"
},
{
"code": null,
"e": 29883,
"s": 29833,
"text": "Proof that Dominant Set of a Graph is NP-Complete"
},
{
"code": null,
"e": 29949,
"s": 29883,
"text": "Difference between Deterministic and Non-deterministic Algorithms"
},
{
"code": null,
"e": 29978,
"s": 29949,
"text": "Set partition is NP complete"
},
{
"code": null,
"e": 30029,
"s": 29978,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 30056,
"s": 30029,
"text": "Program for array rotation"
},
{
"code": null,
"e": 30107,
"s": 30056,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 30165,
"s": 30107,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
Adding options to a <select> using jQuery?
|
To add options to a <select>, you need to use append(). Following is the JavaScript code −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<select name="mySelection" id="selectCategory">
<option value="Book">Book</option>
<option value="TV">TV</option>
</select>
<script>
var mySelection = new Option("Mobile", "Samsung Mobile");
$(mySelection).html("Samsung Mobile");
$("#selectCategory").append(mySelection);
</script>
</body>
</html>
To run the above program, save the file name anyName.html(index.html) and right-click on the file and select the option open with live server in VS Code editor.
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "To add options to a <select>, you need to use append(). Following is the JavaScript code −"
},
{
"code": null,
"e": 1164,
"s": 1153,
"text": " Live Demo"
},
{
"code": null,
"e": 1866,
"s": 1164,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Document</title>\n\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<select name=\"mySelection\" id=\"selectCategory\">\n<option value=\"Book\">Book</option>\n<option value=\"TV\">TV</option>\n</select>\n<script>\n var mySelection = new Option(\"Mobile\", \"Samsung Mobile\");\n $(mySelection).html(\"Samsung Mobile\");\n $(\"#selectCategory\").append(mySelection);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2027,
"s": 1866,
"text": "To run the above program, save the file name anyName.html(index.html) and right-click on the file and select the option open with live server in VS Code editor."
}
] |
Syntax Tree – Natural Language Processing
|
12 Jul, 2021
Natural Language Processing (NLP) is a field of study that deals with understanding, interpreting, and manipulating human spoken languages using computers. Since most of the significant information is written down in natural languages such as English, French, German, etc. thus, NLP helps computers communicate with humans in their own languages and perform other language-related tasks. In conclusion, NLP makes it possible for computers to read the text, hear speech, interpret and realize it, understand the sentiment, and identify important parts of a text or speech.What is Syntax?A natural language typically follows a hierarchical structure, and contains the following components:
Sentences
Clauses
Phrases
Words
Syntax refers to the set of rules, principles, processes that govern the structure of sentences in a natural language. One basic description of syntax is how different words such as Subject, Verbs, Nouns, Noun Phrases, etc. are sequenced in a sentence.Some of the syntactic categories of a natural language are as follows:
Sentence(S)
Noun Phrase(NP)
Determiner(Det)
Verb Phrase(VP)
Prepositional Phrase(PP)
Verb(V)
Noun(N)
Syntax Tree: A Syntax tree or a parse tree is a tree representation of different syntactic categories of a sentence. It helps us to understand the syntactical structure of a sentence.Example:The syntax tree for the sentence given below is as follows: I drive a car to my college.
Code: Syntax Tree in Python
Python3
# Import required librariesimport nltknltk.download('punkt')nltk.download('averaged_perceptron_tagger')from nltk import pos_tag, word_tokenize, RegexpParser # Example textsample_text = "The quick brown fox jumps over the lazy dog" # Find all parts of speech in above sentencetagged = pos_tag(word_tokenize(sample_text)) #Extract all parts of speech from any textchunker = RegexpParser(""" NP: {<DT>?<JJ>*<NN>} #To extract Noun Phrases P: {<IN>} #To extract Prepositions V: {<V.*>} #To extract Verbs PP: { <p> <NP>} #To extract Prepositional Phrases VP: {<V> <NP|PP>*} #To extract Verb Phrases """) # Print all parts of speech in above sentenceoutput = chunker.parse(tagged)print("After Extracting\n", output)
Output:
Code: To draw the syntax free for the above sentence
Python3
# To draw the parse treeoutput.draw()
Output:
gabaa406
Natural-language-processing
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Jul, 2021"
},
{
"code": null,
"e": 744,
"s": 54,
"text": "Natural Language Processing (NLP) is a field of study that deals with understanding, interpreting, and manipulating human spoken languages using computers. Since most of the significant information is written down in natural languages such as English, French, German, etc. thus, NLP helps computers communicate with humans in their own languages and perform other language-related tasks. In conclusion, NLP makes it possible for computers to read the text, hear speech, interpret and realize it, understand the sentiment, and identify important parts of a text or speech.What is Syntax?A natural language typically follows a hierarchical structure, and contains the following components: "
},
{
"code": null,
"e": 754,
"s": 744,
"text": "Sentences"
},
{
"code": null,
"e": 762,
"s": 754,
"text": "Clauses"
},
{
"code": null,
"e": 770,
"s": 762,
"text": "Phrases"
},
{
"code": null,
"e": 776,
"s": 770,
"text": "Words"
},
{
"code": null,
"e": 1100,
"s": 776,
"text": "Syntax refers to the set of rules, principles, processes that govern the structure of sentences in a natural language. One basic description of syntax is how different words such as Subject, Verbs, Nouns, Noun Phrases, etc. are sequenced in a sentence.Some of the syntactic categories of a natural language are as follows: "
},
{
"code": null,
"e": 1112,
"s": 1100,
"text": "Sentence(S)"
},
{
"code": null,
"e": 1128,
"s": 1112,
"text": "Noun Phrase(NP)"
},
{
"code": null,
"e": 1144,
"s": 1128,
"text": "Determiner(Det)"
},
{
"code": null,
"e": 1160,
"s": 1144,
"text": "Verb Phrase(VP)"
},
{
"code": null,
"e": 1185,
"s": 1160,
"text": "Prepositional Phrase(PP)"
},
{
"code": null,
"e": 1193,
"s": 1185,
"text": "Verb(V)"
},
{
"code": null,
"e": 1201,
"s": 1193,
"text": "Noun(N)"
},
{
"code": null,
"e": 1483,
"s": 1201,
"text": "Syntax Tree: A Syntax tree or a parse tree is a tree representation of different syntactic categories of a sentence. It helps us to understand the syntactical structure of a sentence.Example:The syntax tree for the sentence given below is as follows: I drive a car to my college. "
},
{
"code": null,
"e": 1513,
"s": 1483,
"text": "Code: Syntax Tree in Python "
},
{
"code": null,
"e": 1521,
"s": 1513,
"text": "Python3"
},
{
"code": "# Import required librariesimport nltknltk.download('punkt')nltk.download('averaged_perceptron_tagger')from nltk import pos_tag, word_tokenize, RegexpParser # Example textsample_text = \"The quick brown fox jumps over the lazy dog\" # Find all parts of speech in above sentencetagged = pos_tag(word_tokenize(sample_text)) #Extract all parts of speech from any textchunker = RegexpParser(\"\"\" NP: {<DT>?<JJ>*<NN>} #To extract Noun Phrases P: {<IN>} #To extract Prepositions V: {<V.*>} #To extract Verbs PP: { <p> <NP>} #To extract Prepositional Phrases VP: {<V> <NP|PP>*} #To extract Verb Phrases \"\"\") # Print all parts of speech in above sentenceoutput = chunker.parse(tagged)print(\"After Extracting\\n\", output)",
"e": 2409,
"s": 1521,
"text": null
},
{
"code": null,
"e": 2419,
"s": 2409,
"text": "Output: "
},
{
"code": null,
"e": 2474,
"s": 2419,
"text": "Code: To draw the syntax free for the above sentence "
},
{
"code": null,
"e": 2482,
"s": 2474,
"text": "Python3"
},
{
"code": "# To draw the parse treeoutput.draw()",
"e": 2520,
"s": 2482,
"text": null
},
{
"code": null,
"e": 2530,
"s": 2520,
"text": "Output: "
},
{
"code": null,
"e": 2541,
"s": 2532,
"text": "gabaa406"
},
{
"code": null,
"e": 2569,
"s": 2541,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 2586,
"s": 2569,
"text": "Machine Learning"
},
{
"code": null,
"e": 2593,
"s": 2586,
"text": "Python"
},
{
"code": null,
"e": 2610,
"s": 2593,
"text": "Machine Learning"
}
] |
Read and Write path in Cassandra
|
24 Jul, 2020
Prerequisites –
Introduction to Apache Cassandra
Apache Cassandra (NOSQL database)
Architecture of Cassandra
Write Path Execution in Cassandra :
In Cassandra, while writing data, writes are written to any node in the cluster (coordinator).
when any user will insert data, it means they write the data first to commit log then to memtable.
When any user will write the data, every write will include a timestamp.
Once memtable starts getting full then it is flushed to disk periodically (SSTable).
After that a new memtable is created in memory.
In the case of write path execution, deletes are special write cases which are called a tombstone.
Inserting Data :In case of inserting data in Cassandra, we will create a keyspace and then create a table and then insert data into the table.
Example –
// Creating a keyspace
create keyspace UniersityData
replication = {'class': 'SimpleStrategy', 'replication_factor' : '3' };
// Creating a table and declaring the columns
create table CSE_Student(
student_id int,
name text,
email text,
primary key(student_id)
);
// Using the newly created keyspace
use UniersityData;
// Inserting values in the table for all the columns
Insert into CSE_student(student_id, name, email)
values(012345, 'Ashish', 'ashish@gmail.com');
Insert into CSE_student(student_id, name, email)
values(012346, 'Abi', 'abi@gmail.com');
Insert into CSE_student(student_id, name, email)
values(012347, 'Rana', 'rana@gmail.com');
Insert into CSE_student(student_id, name, email)
values(012348, 'Aayush', 'aayush@gmail.com');
Insert into CSE_student(student_id, name, email)
values(012349, 'harsh', 'haarsh@gmail.com');
Read Path Execution :
In Cassandra while reading data, any server may be queried which acts as the coordinator.
when we want to access read data then we contact nodes with requested key.
In a data center, on each node, data is pulled from SStable and is merged.
In Cassandra, while considering read consistency, we can check –Consistency < ALL performs read repair in the background (read_repair_chance).
Reading Data :Write a cqlsh query to read data from CSE_student and give output for the same.
select *
from CSE_student;
Output :
Apache
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jul, 2020"
},
{
"code": null,
"e": 44,
"s": 28,
"text": "Prerequisites –"
},
{
"code": null,
"e": 77,
"s": 44,
"text": "Introduction to Apache Cassandra"
},
{
"code": null,
"e": 111,
"s": 77,
"text": "Apache Cassandra (NOSQL database)"
},
{
"code": null,
"e": 137,
"s": 111,
"text": "Architecture of Cassandra"
},
{
"code": null,
"e": 173,
"s": 137,
"text": "Write Path Execution in Cassandra :"
},
{
"code": null,
"e": 268,
"s": 173,
"text": "In Cassandra, while writing data, writes are written to any node in the cluster (coordinator)."
},
{
"code": null,
"e": 367,
"s": 268,
"text": "when any user will insert data, it means they write the data first to commit log then to memtable."
},
{
"code": null,
"e": 440,
"s": 367,
"text": "When any user will write the data, every write will include a timestamp."
},
{
"code": null,
"e": 525,
"s": 440,
"text": "Once memtable starts getting full then it is flushed to disk periodically (SSTable)."
},
{
"code": null,
"e": 573,
"s": 525,
"text": "After that a new memtable is created in memory."
},
{
"code": null,
"e": 672,
"s": 573,
"text": "In the case of write path execution, deletes are special write cases which are called a tombstone."
},
{
"code": null,
"e": 815,
"s": 672,
"text": "Inserting Data :In case of inserting data in Cassandra, we will create a keyspace and then create a table and then insert data into the table."
},
{
"code": null,
"e": 825,
"s": 815,
"text": "Example –"
},
{
"code": null,
"e": 1673,
"s": 825,
"text": "// Creating a keyspace\ncreate keyspace UniersityData\nreplication = {'class': 'SimpleStrategy', 'replication_factor' : '3' };\n\n// Creating a table and declaring the columns\ncreate table CSE_Student(\nstudent_id int,\nname text,\nemail text,\nprimary key(student_id)\n);\n\n// Using the newly created keyspace\nuse UniersityData;\n\n// Inserting values in the table for all the columns\nInsert into CSE_student(student_id, name, email) \nvalues(012345, 'Ashish', 'ashish@gmail.com');\n\nInsert into CSE_student(student_id, name, email) \nvalues(012346, 'Abi', 'abi@gmail.com');\n\nInsert into CSE_student(student_id, name, email) \nvalues(012347, 'Rana', 'rana@gmail.com');\n\nInsert into CSE_student(student_id, name, email) \nvalues(012348, 'Aayush', 'aayush@gmail.com');\n\nInsert into CSE_student(student_id, name, email) \nvalues(012349, 'harsh', 'haarsh@gmail.com'); "
},
{
"code": null,
"e": 1695,
"s": 1673,
"text": "Read Path Execution :"
},
{
"code": null,
"e": 1785,
"s": 1695,
"text": "In Cassandra while reading data, any server may be queried which acts as the coordinator."
},
{
"code": null,
"e": 1860,
"s": 1785,
"text": "when we want to access read data then we contact nodes with requested key."
},
{
"code": null,
"e": 1935,
"s": 1860,
"text": "In a data center, on each node, data is pulled from SStable and is merged."
},
{
"code": null,
"e": 2078,
"s": 1935,
"text": "In Cassandra, while considering read consistency, we can check –Consistency < ALL performs read repair in the background (read_repair_chance)."
},
{
"code": null,
"e": 2172,
"s": 2078,
"text": "Reading Data :Write a cqlsh query to read data from CSE_student and give output for the same."
},
{
"code": null,
"e": 2201,
"s": 2172,
"text": "select * \nfrom CSE_student;\n"
},
{
"code": null,
"e": 2210,
"s": 2201,
"text": "Output :"
},
{
"code": null,
"e": 2217,
"s": 2210,
"text": "Apache"
},
{
"code": null,
"e": 2222,
"s": 2217,
"text": "DBMS"
},
{
"code": null,
"e": 2227,
"s": 2222,
"text": "DBMS"
}
] |
Python: Pillow (a fork of PIL)
|
03 Jul, 2021
Python Imaging Library (expansion of PIL) is the de facto image processing package for Python language. It incorporates lightweight image processing tools that aids in editing, creating and saving images. Support for Python Imaging Library got discontinued in 2011, but a project named pillow forked the original PIL project and added Python3.x support to it. Pillow was announced as a replacement for PIL for future usage. Pillow supports a large number of image file formats including BMP, PNG, JPEG, and TIFF. The library encourages adding support for newer formats in the library by creating new file decoders.This module is not preloaded with Python. So to install it execute the following command in the command-line:
pip install pillow
Note: Several Linux distributions tend to have Python and PIL preinstalled into them.
1. Opening an image using open(): The PIL.Image.Image class represents the image object. This class provides the open() method that is used to open the image.
Example: Let’s suppose the image is:
Python3
from PIL import Image # test.png => location_of_imageimg = Image.open(r"test.png")
Note: Location of image should be relative only if the image is in the same directory as the Python program, otherwise absolute (full) path of the image should be provided.
2. Displaying the image using show(): This method is used to display the image. For displaying the image Pillow first converts the image to a .png format (on Windows OS) and stores it in a temporary buffer and then displays it. Therefore, due to the conversion of the image format to .png some properties of the original image file format might be lost (like animation). Therefore, it is advised to use this method only for test purposes.
Python3
from PIL import Image img = Image.open(r"test.png")img.show()
Output:
3. Obtaining information about the opened image
A) Getting the mode (color mode) of the image: The mode attribute of the image tells the type and depth of the pixel in the image. A 1-bit pixel has a range of 0-1, and an 8-bit pixel has a range of 0-255. There are different modes provided by this module. Few of them are:
Example:
Python3
from PIL import Image img = Image.open(r"test.png")print(img.mode)
Output:
RGBA
Note: Refer to the documentation to know about the modes.
B) Getting the size of the image: This attribute provides the size of the image. It returns a tuple that contains width and height.
Example:
Python3
from PIL import Image img = Image.open(r"test.png")print(img.size)
Output:
(180, 263)
C) Getting the format of the image: This method returns the format of the image file.
Python3
from PIL import Image img = Image.open(r"test.png")print(img.format)
Output:
PNG
4. Rotating an image using rotate(): After rotating the image, the sections of the image having no pixel values are filled with black (for non-alpha images) and with completely transparent pixels (for images supporting transparency)
Example:
Python3
from PIL import Image angle = 40img = Image.open(r"test.png")r_img = img.rotate(angle)
Output:
5. Resizing an image using resize(): Interpolation happens during the resize process, due to which the quality of image changes whether it is being upscaled (resized to a higher dimension than original) or downscaled (resized to a lower Image then original). Therefore resize() should be used cautiously and while providing suitable value for resampling argument.
Example:
Python3
from PIL import Image size = (40, 40)img = Image.open(r"test.png")r_img = img.resize(size) r_img.show()
Output:
6. Saving an image using save(): While using the save() method Destination_path must have the image filename and extension as well. The extension could be omitted in Destination_path if the extension is specified in the format argument.
Python3
from PIL import Image size = (40, 40)img = Image.open(r"test.png")r_img = img.resize(size, resample = Image.BILINEAR) # resized_test.png => Destination_pathr_img.save("resized_test.png") # Opening the new imageimg = Image.open(r"resized_test.png")print(img.size)
Output:
(40, 40)
VasuDev4
sagar0719kumar
python-modules
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Python Dictionary
Python OOPs Concepts
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Python Classes and Objects
Introduction To PYTHON
Stack in Python
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 Jul, 2021"
},
{
"code": null,
"e": 778,
"s": 53,
"text": "Python Imaging Library (expansion of PIL) is the de facto image processing package for Python language. It incorporates lightweight image processing tools that aids in editing, creating and saving images. Support for Python Imaging Library got discontinued in 2011, but a project named pillow forked the original PIL project and added Python3.x support to it. Pillow was announced as a replacement for PIL for future usage. Pillow supports a large number of image file formats including BMP, PNG, JPEG, and TIFF. The library encourages adding support for newer formats in the library by creating new file decoders.This module is not preloaded with Python. So to install it execute the following command in the command-line: "
},
{
"code": null,
"e": 797,
"s": 778,
"text": "pip install pillow"
},
{
"code": null,
"e": 883,
"s": 797,
"text": "Note: Several Linux distributions tend to have Python and PIL preinstalled into them."
},
{
"code": null,
"e": 1042,
"s": 883,
"text": "1. Opening an image using open(): The PIL.Image.Image class represents the image object. This class provides the open() method that is used to open the image."
},
{
"code": null,
"e": 1079,
"s": 1042,
"text": "Example: Let’s suppose the image is:"
},
{
"code": null,
"e": 1087,
"s": 1079,
"text": "Python3"
},
{
"code": "from PIL import Image # test.png => location_of_imageimg = Image.open(r\"test.png\") ",
"e": 1173,
"s": 1087,
"text": null
},
{
"code": null,
"e": 1347,
"s": 1173,
"text": "Note: Location of image should be relative only if the image is in the same directory as the Python program, otherwise absolute (full) path of the image should be provided. "
},
{
"code": null,
"e": 1786,
"s": 1347,
"text": "2. Displaying the image using show(): This method is used to display the image. For displaying the image Pillow first converts the image to a .png format (on Windows OS) and stores it in a temporary buffer and then displays it. Therefore, due to the conversion of the image format to .png some properties of the original image file format might be lost (like animation). Therefore, it is advised to use this method only for test purposes."
},
{
"code": null,
"e": 1794,
"s": 1786,
"text": "Python3"
},
{
"code": "from PIL import Image img = Image.open(r\"test.png\")img.show()",
"e": 1857,
"s": 1794,
"text": null
},
{
"code": null,
"e": 1866,
"s": 1857,
"text": "Output: "
},
{
"code": null,
"e": 1914,
"s": 1866,
"text": "3. Obtaining information about the opened image"
},
{
"code": null,
"e": 2188,
"s": 1914,
"text": "A) Getting the mode (color mode) of the image: The mode attribute of the image tells the type and depth of the pixel in the image. A 1-bit pixel has a range of 0-1, and an 8-bit pixel has a range of 0-255. There are different modes provided by this module. Few of them are:"
},
{
"code": null,
"e": 2197,
"s": 2188,
"text": "Example:"
},
{
"code": null,
"e": 2205,
"s": 2197,
"text": "Python3"
},
{
"code": "from PIL import Image img = Image.open(r\"test.png\")print(img.mode)",
"e": 2273,
"s": 2205,
"text": null
},
{
"code": null,
"e": 2281,
"s": 2273,
"text": "Output:"
},
{
"code": null,
"e": 2286,
"s": 2281,
"text": "RGBA"
},
{
"code": null,
"e": 2344,
"s": 2286,
"text": "Note: Refer to the documentation to know about the modes."
},
{
"code": null,
"e": 2476,
"s": 2344,
"text": "B) Getting the size of the image: This attribute provides the size of the image. It returns a tuple that contains width and height."
},
{
"code": null,
"e": 2485,
"s": 2476,
"text": "Example:"
},
{
"code": null,
"e": 2493,
"s": 2485,
"text": "Python3"
},
{
"code": "from PIL import Image img = Image.open(r\"test.png\")print(img.size)",
"e": 2561,
"s": 2493,
"text": null
},
{
"code": null,
"e": 2569,
"s": 2561,
"text": "Output:"
},
{
"code": null,
"e": 2580,
"s": 2569,
"text": "(180, 263)"
},
{
"code": null,
"e": 2666,
"s": 2580,
"text": "C) Getting the format of the image: This method returns the format of the image file."
},
{
"code": null,
"e": 2674,
"s": 2666,
"text": "Python3"
},
{
"code": "from PIL import Image img = Image.open(r\"test.png\")print(img.format)",
"e": 2744,
"s": 2674,
"text": null
},
{
"code": null,
"e": 2752,
"s": 2744,
"text": "Output:"
},
{
"code": null,
"e": 2756,
"s": 2752,
"text": "PNG"
},
{
"code": null,
"e": 2989,
"s": 2756,
"text": "4. Rotating an image using rotate(): After rotating the image, the sections of the image having no pixel values are filled with black (for non-alpha images) and with completely transparent pixels (for images supporting transparency)"
},
{
"code": null,
"e": 2998,
"s": 2989,
"text": "Example:"
},
{
"code": null,
"e": 3006,
"s": 2998,
"text": "Python3"
},
{
"code": "from PIL import Image angle = 40img = Image.open(r\"test.png\")r_img = img.rotate(angle)",
"e": 3094,
"s": 3006,
"text": null
},
{
"code": null,
"e": 3102,
"s": 3094,
"text": "Output:"
},
{
"code": null,
"e": 3466,
"s": 3102,
"text": "5. Resizing an image using resize(): Interpolation happens during the resize process, due to which the quality of image changes whether it is being upscaled (resized to a higher dimension than original) or downscaled (resized to a lower Image then original). Therefore resize() should be used cautiously and while providing suitable value for resampling argument."
},
{
"code": null,
"e": 3475,
"s": 3466,
"text": "Example:"
},
{
"code": null,
"e": 3483,
"s": 3475,
"text": "Python3"
},
{
"code": "from PIL import Image size = (40, 40)img = Image.open(r\"test.png\")r_img = img.resize(size) r_img.show()",
"e": 3588,
"s": 3483,
"text": null
},
{
"code": null,
"e": 3596,
"s": 3588,
"text": "Output:"
},
{
"code": null,
"e": 3833,
"s": 3596,
"text": "6. Saving an image using save(): While using the save() method Destination_path must have the image filename and extension as well. The extension could be omitted in Destination_path if the extension is specified in the format argument."
},
{
"code": null,
"e": 3841,
"s": 3833,
"text": "Python3"
},
{
"code": "from PIL import Image size = (40, 40)img = Image.open(r\"test.png\")r_img = img.resize(size, resample = Image.BILINEAR) # resized_test.png => Destination_pathr_img.save(\"resized_test.png\") # Opening the new imageimg = Image.open(r\"resized_test.png\")print(img.size)",
"e": 4105,
"s": 3841,
"text": null
},
{
"code": null,
"e": 4113,
"s": 4105,
"text": "Output:"
},
{
"code": null,
"e": 4123,
"s": 4113,
"text": "(40, 40)\n"
},
{
"code": null,
"e": 4134,
"s": 4125,
"text": "VasuDev4"
},
{
"code": null,
"e": 4149,
"s": 4134,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 4164,
"s": 4149,
"text": "python-modules"
},
{
"code": null,
"e": 4175,
"s": 4164,
"text": "Python-pil"
},
{
"code": null,
"e": 4182,
"s": 4175,
"text": "Python"
},
{
"code": null,
"e": 4280,
"s": 4182,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4310,
"s": 4280,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 4355,
"s": 4310,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 4377,
"s": 4355,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4395,
"s": 4377,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4416,
"s": 4395,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4458,
"s": 4416,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4487,
"s": 4458,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4514,
"s": 4487,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4537,
"s": 4514,
"text": "Introduction To PYTHON"
}
] |
jQuery | trigger() Method
|
01 Mar, 2019
The trigger() method is a method in jQuery which is used to trigger a specified event handler on selected element.
Syntax:
$(selector).trigger(event, param1, param2)
Note: Extra parameters can be passed in trigger() method.
Example 1: This method triggered two methods to increase the value of method.
<!DOCTYPE html><html> <head> <title> jQuery trigger() Method </title></head> <body> <div class="box-1"> <h1>0</h1> </div> <button id="btn1">Increase #1</button> <div class="box-2"> <h1>0</h1> </div> <button id="btn2">Increase #2</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- Script to use trigger() method --> <script> $(document).ready(function() { $("#btn1").click(function() { Increase($(".box-1>h1")) }) $("#btn2").click(function() { $("#btn1").trigger("click"); Increase($(".box-2>h1")) }) function Increase(obj) { var text = parseInt(obj.text(), 10); obj.text(text + 1); } }); </script></html>
Output:In the above example, uses a Increase(obj) function which takes an html element as an object and increases the value of numeric text inside it by one by using parseInt() function to convert string to integer.
function Increase(obj) {
var text = parseInt(obj.text(), 10);
obj.text(text + 1);
}
Further, jQuery selector is used to select buttons and attached click event method to it and inside it we are calling Increase(obj) function.
$("#btn1").click(function(){
Increase($(".box-1>h1"))
})
$("#btn2").click(function(){
$("#btn1").trigger("click");
Increase($(".box-2>h1"))
})
When click on Increase #1 button it will increase the value inside corresponding div’s by 1. But when click on Increase #2 button it increases values in both div’s by one. Because we are firing ‘click’ with help of trigger() method event inside bind click method of #btn2.
Example 2: This example fires the focus event of input element with the help of trigger() method.
<!DOCTYPE html><html> <head> <title> jQuery trigger() Method </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <style> div { width: 300px; height: 100px; border: 1px solid green; text-align: center; } </style></head> <body> <div> <input id="name" type="text" placeholder="Input text..."/> <br/> <p> click anywhere inside div to focus input element. </p> </div> <!-- Script to use trigger() method --> <script> $(document).ready(function() { $("div").click(function() { $("#name").trigger("focus"); }) }); </script></body> </html>
Output:
jQuery-Events
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Mar, 2019"
},
{
"code": null,
"e": 143,
"s": 28,
"text": "The trigger() method is a method in jQuery which is used to trigger a specified event handler on selected element."
},
{
"code": null,
"e": 151,
"s": 143,
"text": "Syntax:"
},
{
"code": null,
"e": 194,
"s": 151,
"text": "$(selector).trigger(event, param1, param2)"
},
{
"code": null,
"e": 252,
"s": 194,
"text": "Note: Extra parameters can be passed in trigger() method."
},
{
"code": null,
"e": 330,
"s": 252,
"text": "Example 1: This method triggered two methods to increase the value of method."
},
{
"code": "<!DOCTYPE html><html> <head> <title> jQuery trigger() Method </title></head> <body> <div class=\"box-1\"> <h1>0</h1> </div> <button id=\"btn1\">Increase #1</button> <div class=\"box-2\"> <h1>0</h1> </div> <button id=\"btn2\">Increase #2</button> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- Script to use trigger() method --> <script> $(document).ready(function() { $(\"#btn1\").click(function() { Increase($(\".box-1>h1\")) }) $(\"#btn2\").click(function() { $(\"#btn1\").trigger(\"click\"); Increase($(\".box-2>h1\")) }) function Increase(obj) { var text = parseInt(obj.text(), 10); obj.text(text + 1); } }); </script></html> ",
"e": 1273,
"s": 330,
"text": null
},
{
"code": null,
"e": 1489,
"s": 1273,
"text": "Output:In the above example, uses a Increase(obj) function which takes an html element as an object and increases the value of numeric text inside it by one by using parseInt() function to convert string to integer."
},
{
"code": null,
"e": 1596,
"s": 1489,
"text": "function Increase(obj) {\n var text = parseInt(obj.text(), 10);\n obj.text(text + 1);\n }\n"
},
{
"code": null,
"e": 1738,
"s": 1596,
"text": "Further, jQuery selector is used to select buttons and attached click event method to it and inside it we are calling Increase(obj) function."
},
{
"code": null,
"e": 1951,
"s": 1738,
"text": " $(\"#btn1\").click(function(){\n Increase($(\".box-1>h1\"))\n })\n\n $(\"#btn2\").click(function(){\n $(\"#btn1\").trigger(\"click\");\n Increase($(\".box-2>h1\"))\n })\n"
},
{
"code": null,
"e": 2224,
"s": 1951,
"text": "When click on Increase #1 button it will increase the value inside corresponding div’s by 1. But when click on Increase #2 button it increases values in both div’s by one. Because we are firing ‘click’ with help of trigger() method event inside bind click method of #btn2."
},
{
"code": null,
"e": 2322,
"s": 2224,
"text": "Example 2: This example fires the focus event of input element with the help of trigger() method."
},
{
"code": "<!DOCTYPE html><html> <head> <title> jQuery trigger() Method </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <style> div { width: 300px; height: 100px; border: 1px solid green; text-align: center; } </style></head> <body> <div> <input id=\"name\" type=\"text\" placeholder=\"Input text...\"/> <br/> <p> click anywhere inside div to focus input element. </p> </div> <!-- Script to use trigger() method --> <script> $(document).ready(function() { $(\"div\").click(function() { $(\"#name\").trigger(\"focus\"); }) }); </script></body> </html> ",
"e": 3178,
"s": 2322,
"text": null
},
{
"code": null,
"e": 3186,
"s": 3178,
"text": "Output:"
},
{
"code": null,
"e": 3200,
"s": 3186,
"text": "jQuery-Events"
},
{
"code": null,
"e": 3207,
"s": 3200,
"text": "Picked"
},
{
"code": null,
"e": 3214,
"s": 3207,
"text": "JQuery"
},
{
"code": null,
"e": 3231,
"s": 3214,
"text": "Web Technologies"
}
] |
Finding Inverse of a Matrix in R Programming - inv() Function - GeeksforGeeks
|
19 Jun, 2020
inv() function in R Language is used to calculate inverse of a matrix.
Note: Determinant of the matrix must not be zero
Syntax: inv(x)
Parameters:x: Matrix
Example 1:
# R program to calculate # inverse of a matrix # Loading librarylibrary(matlib) # Create 3 different vectors. a1 <- c(3, 2, 8) a2 <- c(6, 3, 2) a3 <- c(5, 2, 4) # Bind the 3 matrices row-wise # using the rbind() function. A <- rbind(a1, a2, a3) # find inverse using the inv() function. print(inv(A))
Output:
[, 1] [, 2] [, 3]
[1, ] -0.2857143 -0.2857143 0.7142857
[2, ] 0.5000000 1.0000000 -1.5000000
[3, ] 0.1071429 -0.1428571 0.1071429
Example 2:
# R program to calculate# inverse of a matrix # Loading Librarylibrary(matlib) # Creating a matrixA = matrix(c(2, 5, 3, 4, 5, 2, 6, 3, 4), 3, 3) det(A) # Calling inv() functioncat("Inverse of A:\n") inv(A)
Output:
[1] -46
Inverse of A:
[, 1] [, 2] [, 3]
[1, ] -0.3043478 0.08695652 0.3913044
[2, ] 0.2391304 0.21739130 -0.5217391
[3, ] 0.1086957 -0.17391304 0.2173913
R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
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?
K-Means Clustering in R Programming
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame
How to filter R DataFrame by values in a column?
|
[
{
"code": null,
"e": 25867,
"s": 25839,
"text": "\n19 Jun, 2020"
},
{
"code": null,
"e": 25938,
"s": 25867,
"text": "inv() function in R Language is used to calculate inverse of a matrix."
},
{
"code": null,
"e": 25987,
"s": 25938,
"text": "Note: Determinant of the matrix must not be zero"
},
{
"code": null,
"e": 26002,
"s": 25987,
"text": "Syntax: inv(x)"
},
{
"code": null,
"e": 26023,
"s": 26002,
"text": "Parameters:x: Matrix"
},
{
"code": null,
"e": 26034,
"s": 26023,
"text": "Example 1:"
},
{
"code": "# R program to calculate # inverse of a matrix # Loading librarylibrary(matlib) # Create 3 different vectors. a1 <- c(3, 2, 8) a2 <- c(6, 3, 2) a3 <- c(5, 2, 4) # Bind the 3 matrices row-wise # using the rbind() function. A <- rbind(a1, a2, a3) # find inverse using the inv() function. print(inv(A))",
"e": 26345,
"s": 26034,
"text": null
},
{
"code": null,
"e": 26353,
"s": 26345,
"text": "Output:"
},
{
"code": null,
"e": 26512,
"s": 26353,
"text": " [, 1] [, 2] [, 3]\n[1, ] -0.2857143 -0.2857143 0.7142857\n[2, ] 0.5000000 1.0000000 -1.5000000\n[3, ] 0.1071429 -0.1428571 0.1071429\n"
},
{
"code": null,
"e": 26523,
"s": 26512,
"text": "Example 2:"
},
{
"code": "# R program to calculate# inverse of a matrix # Loading Librarylibrary(matlib) # Creating a matrixA = matrix(c(2, 5, 3, 4, 5, 2, 6, 3, 4), 3, 3) det(A) # Calling inv() functioncat(\"Inverse of A:\\n\") inv(A)",
"e": 26734,
"s": 26523,
"text": null
},
{
"code": null,
"e": 26742,
"s": 26734,
"text": "Output:"
},
{
"code": null,
"e": 26927,
"s": 26742,
"text": "[1] -46\nInverse of A:\n [, 1] [, 2] [, 3]\n[1, ] -0.3043478 0.08695652 0.3913044\n[2, ] 0.2391304 0.21739130 -0.5217391\n[3, ] 0.1086957 -0.17391304 0.2173913\n"
},
{
"code": null,
"e": 26945,
"s": 26927,
"text": "R Matrix-Function"
},
{
"code": null,
"e": 26956,
"s": 26945,
"text": "R Language"
},
{
"code": null,
"e": 27054,
"s": 26956,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27106,
"s": 27054,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 27150,
"s": 27106,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 27202,
"s": 27150,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27237,
"s": 27202,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27275,
"s": 27237,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27333,
"s": 27275,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27369,
"s": 27333,
"text": "K-Means Clustering in R Programming"
},
{
"code": null,
"e": 27412,
"s": 27369,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27461,
"s": 27412,
"text": "Remove rows with NA in one column of R DataFrame"
}
] |
Arrays.toString() in Java with Examples - GeeksforGeeks
|
07 Dec, 2018
Today we are going to discuss the simplest way to print the array as a string in Java: Arrays.toString() method.
How to use Arrays.toString() method?
Description:Returns a string representation of the contents of the specified array. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters “, ” (a comma followed by a space). Returns “null” if a is null.
In case of an Object Array, if the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents.
Variants:
public static String toString(boolean[] arr)
public static String toString(byte[] arr)
public static String toString(char[] arr)
public static String toString(double[] arr)
public static String toString(float[] arr)
public static String toString(int[] arr)
public static String toString(long[] arr)
public static String toString(Object[] arr)
public static String toString(short[] arr)
Parameters:arr – the array whose string representation to return
Returns:the string representation of arr
Usage:The below mentioned Java code depicts the usage of the toString() method of Arrays class with examples:
// Java program to demonstrate working of Arrays.toString()import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Let us create different types of arrays and // print their contents using Arrays.toString() boolean[] boolArr = new boolean[] { true, true, false, true }; byte[] byteArr = new byte[] { 10, 20, 30 }; char[] charArr = new char[] { 'g', 'e', 'e', 'k', 's' }; double[] dblArr = new double[] { 1, 2, 3, 4 }; float[] floatArr = new float[] { 1, 2, 3, 4 }; int[] intArr = new int[] { 1, 2, 3, 4 }; long[] lomgArr = new long[] { 1, 2, 3, 4 }; Object[] objArr = new Object[] { 1, 2, 3, 4 }; short[] shortArr = new short[] { 1, 2, 3, 4 }; System.out.println(Arrays.toString(boolArr)); System.out.println(Arrays.toString(byteArr)); System.out.println(Arrays.toString(charArr)); System.out.println(Arrays.toString(dblArr)); System.out.println(Arrays.toString(floatArr)); System.out.println(Arrays.toString(intArr)); System.out.println(Arrays.toString(lomgArr)); System.out.println(Arrays.toString(objArr)); System.out.println(Arrays.toString(shortArr)); }}
Output:
[true, true, false, true]
[10, 20, 30]
[g, e, e, k, s]
[1.0, 2.0, 3.0, 4.0]
[1.0, 2.0, 3.0, 4.0]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
We can also use Arrays.toString() for objects of user defined class.Since Arrays.toString() is overloaded for array of Object class (there exist a method Arrays.toString(Object [])) and Object is ancestor of all classes, we can use call it for an array of any type of object.
// Java program to demonstrate working of Arrays.toString()// for user defined objects.import java.lang.*;import java.util.*; // Driver classclass Main { public static void main(String[] args) { Student[] arr = { new Student(111, "bbbb", "london"), new Student(131, "aaaa", "nyc"), new Student(121, "cccc", "jaipur") }; System.out.println(Arrays.toString(arr)); }} // A class to represent a student.class Student { int rollno; String name, address; // Constructor public Student(int rollno, String name, String address) { this.rollno = rollno; this.name = name; this.address = address; } // Used to print student details in main() @override public String toString() { return this.rollno + " " + this.name + " " + this.address; }}
Output:
[111 bbbb london, 131 aaaa nyc, 121 cccc jaipur]
Why does Object.toString() not work for Arrays?Using the toString() method on Arrays might not work. It considers an array as a typical object and returns default string, i.e., a ‘[‘ representing an array, followed by a character representing the primitive data type of array followed by an Identity Hex Code [See this for details]
This article is contributed by Shikhar Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.
KartikaPatil
Java - util package
Java-Arrays
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 26289,
"s": 26261,
"text": "\n07 Dec, 2018"
},
{
"code": null,
"e": 26402,
"s": 26289,
"text": "Today we are going to discuss the simplest way to print the array as a string in Java: Arrays.toString() method."
},
{
"code": null,
"e": 26439,
"s": 26402,
"text": "How to use Arrays.toString() method?"
},
{
"code": null,
"e": 26744,
"s": 26439,
"text": "Description:Returns a string representation of the contents of the specified array. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters “, ” (a comma followed by a space). Returns “null” if a is null."
},
{
"code": null,
"e": 26966,
"s": 26744,
"text": "In case of an Object Array, if the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents."
},
{
"code": null,
"e": 26976,
"s": 26966,
"text": "Variants:"
},
{
"code": null,
"e": 27021,
"s": 26976,
"text": "public static String toString(boolean[] arr)"
},
{
"code": null,
"e": 27063,
"s": 27021,
"text": "public static String toString(byte[] arr)"
},
{
"code": null,
"e": 27105,
"s": 27063,
"text": "public static String toString(char[] arr)"
},
{
"code": null,
"e": 27149,
"s": 27105,
"text": "public static String toString(double[] arr)"
},
{
"code": null,
"e": 27192,
"s": 27149,
"text": "public static String toString(float[] arr)"
},
{
"code": null,
"e": 27233,
"s": 27192,
"text": "public static String toString(int[] arr)"
},
{
"code": null,
"e": 27275,
"s": 27233,
"text": "public static String toString(long[] arr)"
},
{
"code": null,
"e": 27319,
"s": 27275,
"text": "public static String toString(Object[] arr)"
},
{
"code": null,
"e": 27362,
"s": 27319,
"text": "public static String toString(short[] arr)"
},
{
"code": null,
"e": 27427,
"s": 27362,
"text": "Parameters:arr – the array whose string representation to return"
},
{
"code": null,
"e": 27468,
"s": 27427,
"text": "Returns:the string representation of arr"
},
{
"code": null,
"e": 27578,
"s": 27468,
"text": "Usage:The below mentioned Java code depicts the usage of the toString() method of Arrays class with examples:"
},
{
"code": "// Java program to demonstrate working of Arrays.toString()import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Let us create different types of arrays and // print their contents using Arrays.toString() boolean[] boolArr = new boolean[] { true, true, false, true }; byte[] byteArr = new byte[] { 10, 20, 30 }; char[] charArr = new char[] { 'g', 'e', 'e', 'k', 's' }; double[] dblArr = new double[] { 1, 2, 3, 4 }; float[] floatArr = new float[] { 1, 2, 3, 4 }; int[] intArr = new int[] { 1, 2, 3, 4 }; long[] lomgArr = new long[] { 1, 2, 3, 4 }; Object[] objArr = new Object[] { 1, 2, 3, 4 }; short[] shortArr = new short[] { 1, 2, 3, 4 }; System.out.println(Arrays.toString(boolArr)); System.out.println(Arrays.toString(byteArr)); System.out.println(Arrays.toString(charArr)); System.out.println(Arrays.toString(dblArr)); System.out.println(Arrays.toString(floatArr)); System.out.println(Arrays.toString(intArr)); System.out.println(Arrays.toString(lomgArr)); System.out.println(Arrays.toString(objArr)); System.out.println(Arrays.toString(shortArr)); }}",
"e": 28827,
"s": 27578,
"text": null
},
{
"code": null,
"e": 28835,
"s": 28827,
"text": "Output:"
},
{
"code": null,
"e": 28985,
"s": 28835,
"text": "[true, true, false, true]\n[10, 20, 30]\n[g, e, e, k, s]\n[1.0, 2.0, 3.0, 4.0]\n[1.0, 2.0, 3.0, 4.0]\n[1, 2, 3, 4]\n[1, 2, 3, 4]\n[1, 2, 3, 4]\n[1, 2, 3, 4]\n"
},
{
"code": null,
"e": 29261,
"s": 28985,
"text": "We can also use Arrays.toString() for objects of user defined class.Since Arrays.toString() is overloaded for array of Object class (there exist a method Arrays.toString(Object [])) and Object is ancestor of all classes, we can use call it for an array of any type of object."
},
{
"code": "// Java program to demonstrate working of Arrays.toString()// for user defined objects.import java.lang.*;import java.util.*; // Driver classclass Main { public static void main(String[] args) { Student[] arr = { new Student(111, \"bbbb\", \"london\"), new Student(131, \"aaaa\", \"nyc\"), new Student(121, \"cccc\", \"jaipur\") }; System.out.println(Arrays.toString(arr)); }} // A class to represent a student.class Student { int rollno; String name, address; // Constructor public Student(int rollno, String name, String address) { this.rollno = rollno; this.name = name; this.address = address; } // Used to print student details in main() @override public String toString() { return this.rollno + \" \" + this.name + \" \" + this.address; }}",
"e": 30151,
"s": 29261,
"text": null
},
{
"code": null,
"e": 30159,
"s": 30151,
"text": "Output:"
},
{
"code": null,
"e": 30209,
"s": 30159,
"text": "[111 bbbb london, 131 aaaa nyc, 121 cccc jaipur]\n"
},
{
"code": null,
"e": 30541,
"s": 30209,
"text": "Why does Object.toString() not work for Arrays?Using the toString() method on Arrays might not work. It considers an array as a typical object and returns default string, i.e., a ‘[‘ representing an array, followed by a character representing the primitive data type of array followed by an Identity Hex Code [See this for details]"
},
{
"code": null,
"e": 30841,
"s": 30541,
"text": "This article is contributed by Shikhar Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30966,
"s": 30841,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30979,
"s": 30966,
"text": "KartikaPatil"
},
{
"code": null,
"e": 30999,
"s": 30979,
"text": "Java - util package"
},
{
"code": null,
"e": 31011,
"s": 30999,
"text": "Java-Arrays"
},
{
"code": null,
"e": 31028,
"s": 31011,
"text": "Java-Collections"
},
{
"code": null,
"e": 31033,
"s": 31028,
"text": "Java"
},
{
"code": null,
"e": 31038,
"s": 31033,
"text": "Java"
},
{
"code": null,
"e": 31055,
"s": 31038,
"text": "Java-Collections"
},
{
"code": null,
"e": 31153,
"s": 31055,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31204,
"s": 31153,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 31234,
"s": 31204,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 31249,
"s": 31234,
"text": "Stream In Java"
},
{
"code": null,
"e": 31268,
"s": 31249,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31299,
"s": 31268,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 31317,
"s": 31299,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 31349,
"s": 31317,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31369,
"s": 31349,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 31393,
"s": 31369,
"text": "Singleton Class in Java"
}
] |
Python | Pandas Series.shape - GeeksforGeeks
|
28 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.shape attribute returns a tuple of the shape of the underlying data for the given series objects.
Syntax:Series.shape
Parameter : None
Returns : shape
Example #1: Use Series.shape attribute to find the shape of the underlying data of the given series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # Print the seriesprint(sr)
Output :
Now we will use Series.shape attribute to find the shape of the underlying data of the given Series object.
# return the shapesr.shape
Output :
As we can see in the output, the Series.shape attribute has returned a tuple indicating the shape of the underlying data of the given series object. Example #2 : Use Series.shape attribute to find the shape of the underlying data of the given series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)
Output :
Now we will use Series.shape attribute to find the shape of the underlying data of the given Series object.
# return the shapesr.shape
Output :As we can see in the output, the Series.shape attribute has returned a tuple indicating the shape of the underlying data of the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 25775,
"s": 25561,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 26032,
"s": 25775,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 26144,
"s": 26032,
"text": "Pandas Series.shape attribute returns a tuple of the shape of the underlying data for the given series objects."
},
{
"code": null,
"e": 26164,
"s": 26144,
"text": "Syntax:Series.shape"
},
{
"code": null,
"e": 26181,
"s": 26164,
"text": "Parameter : None"
},
{
"code": null,
"e": 26197,
"s": 26181,
"text": "Returns : shape"
},
{
"code": null,
"e": 26305,
"s": 26197,
"text": "Example #1: Use Series.shape attribute to find the shape of the underlying data of the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # Print the seriesprint(sr)",
"e": 26562,
"s": 26305,
"text": null
},
{
"code": null,
"e": 26571,
"s": 26562,
"text": "Output :"
},
{
"code": null,
"e": 26679,
"s": 26571,
"text": "Now we will use Series.shape attribute to find the shape of the underlying data of the given Series object."
},
{
"code": "# return the shapesr.shape",
"e": 26706,
"s": 26679,
"text": null
},
{
"code": null,
"e": 26715,
"s": 26706,
"text": "Output :"
},
{
"code": null,
"e": 26973,
"s": 26715,
"text": "As we can see in the output, the Series.shape attribute has returned a tuple indicating the shape of the underlying data of the given series object. Example #2 : Use Series.shape attribute to find the shape of the underlying data of the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)",
"e": 27212,
"s": 26973,
"text": null
},
{
"code": null,
"e": 27221,
"s": 27212,
"text": "Output :"
},
{
"code": null,
"e": 27329,
"s": 27221,
"text": "Now we will use Series.shape attribute to find the shape of the underlying data of the given Series object."
},
{
"code": "# return the shapesr.shape",
"e": 27356,
"s": 27329,
"text": null
},
{
"code": null,
"e": 27513,
"s": 27356,
"text": "Output :As we can see in the output, the Series.shape attribute has returned a tuple indicating the shape of the underlying data of the given series object."
},
{
"code": null,
"e": 27534,
"s": 27513,
"text": "Python pandas-series"
},
{
"code": null,
"e": 27563,
"s": 27534,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 27577,
"s": 27563,
"text": "Python-pandas"
},
{
"code": null,
"e": 27584,
"s": 27577,
"text": "Python"
},
{
"code": null,
"e": 27682,
"s": 27584,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27714,
"s": 27682,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27756,
"s": 27714,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27798,
"s": 27756,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27854,
"s": 27798,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27881,
"s": 27854,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27920,
"s": 27881,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27951,
"s": 27920,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27973,
"s": 27951,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28002,
"s": 27973,
"text": "Create a directory in Python"
}
] |
Scala Stack toList() method with example - GeeksforGeeks
|
03 Nov, 2019
In Scala Stack class, the toList() method is utilized to return a list consisting of all the elements of the stack.
Method Definition: def toList: List[A]
Return Type: It returns a list consisting of all the elements of the stack.
Example #1:
// Scala program of toList() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(1, 2, 3, 4, 5) // Print the stack println(s1) // Applying toList method val result = s1.toList // Display output print("Elements in the list: ") for(elem <- result) print(elem + " ") } }
Stack(1, 2, 3, 4, 5)
Elements in the list: 1 2 3 4 5
Example #2:
// Scala program of toList() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(5, 2, 13, 7, 1) // Print the stack println(s1) // Applying toList method val result = s1.toList // Display output print("Elements in the list: ") for(elem <- result) print(elem + " ") } }
Stack(5, 2, 13, 7, 1)
Elements in the list: 5 2 13 7 1
Scala
scala-collection
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Scala Constructors
Scala String substring() method with example
Scala | Arrays
How to get the first element of List in Scala
Lambda Expression in Scala
|
[
{
"code": null,
"e": 25353,
"s": 25325,
"text": "\n03 Nov, 2019"
},
{
"code": null,
"e": 25469,
"s": 25353,
"text": "In Scala Stack class, the toList() method is utilized to return a list consisting of all the elements of the stack."
},
{
"code": null,
"e": 25508,
"s": 25469,
"text": "Method Definition: def toList: List[A]"
},
{
"code": null,
"e": 25584,
"s": 25508,
"text": "Return Type: It returns a list consisting of all the elements of the stack."
},
{
"code": null,
"e": 25596,
"s": 25584,
"text": "Example #1:"
},
{
"code": "// Scala program of toList() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(1, 2, 3, 4, 5) // Print the stack println(s1) // Applying toList method val result = s1.toList // Display output print(\"Elements in the list: \") for(elem <- result) print(elem + \" \") } } ",
"e": 26146,
"s": 25596,
"text": null
},
{
"code": null,
"e": 26200,
"s": 26146,
"text": "Stack(1, 2, 3, 4, 5)\nElements in the list: 1 2 3 4 5\n"
},
{
"code": null,
"e": 26212,
"s": 26200,
"text": "Example #2:"
},
{
"code": "// Scala program of toList() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(5, 2, 13, 7, 1) // Print the stack println(s1) // Applying toList method val result = s1.toList // Display output print(\"Elements in the list: \") for(elem <- result) print(elem + \" \") } } ",
"e": 26763,
"s": 26212,
"text": null
},
{
"code": null,
"e": 26819,
"s": 26763,
"text": "Stack(5, 2, 13, 7, 1)\nElements in the list: 5 2 13 7 1\n"
},
{
"code": null,
"e": 26825,
"s": 26819,
"text": "Scala"
},
{
"code": null,
"e": 26842,
"s": 26825,
"text": "scala-collection"
},
{
"code": null,
"e": 26855,
"s": 26842,
"text": "Scala-Method"
},
{
"code": null,
"e": 26861,
"s": 26855,
"text": "Scala"
},
{
"code": null,
"e": 26959,
"s": 26861,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26981,
"s": 26959,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 27007,
"s": 26981,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 27019,
"s": 27007,
"text": "Scala Lists"
},
{
"code": null,
"e": 27072,
"s": 27019,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 27091,
"s": 27072,
"text": "Operators in Scala"
},
{
"code": null,
"e": 27110,
"s": 27091,
"text": "Scala Constructors"
},
{
"code": null,
"e": 27155,
"s": 27110,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 27170,
"s": 27155,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 27216,
"s": 27170,
"text": "How to get the first element of List in Scala"
}
] |
Machine Instructions - GeeksforGeeks
|
17 Jan, 2022
Machine Instructions are commands or programs written in machine code of a machine (computer) that it can recognize and execute.
A machine instruction consists of several bytes in memory that tells the processor to perform one machine operation.
The processor looks at machine instructions in main memory one after another, and performs one machine operation for each machine instruction.
The collection of machine instructions in main memory is called a machine language program.
Machine code or machine language is a set of instructions executed directly by a computer’s central processing unit (CPU). Each instruction performs a very specific task, such as a load, a jump, or an ALU operation on a unit of data in a CPU register or memory. Every program directly executed by a CPU is made up of a series of such instructions.
The general format of a machine instruction is
Brackets indicate that a field is optional
Label is an identifier that is assigned the address of the first byte of the instruction in which it appears. It must be followed by “:”
Inclusion of spaces is arbitrary, except that at least one space must be inserted; no space would lead to an ambiguity.
Comment field begins with a semicolon “ ; ”
Example:
Machine instructions used in 8086 microprocessor
1. Data transfer instructions– move, load exchange, input, output.
MOV: Move byte or word to register or memory .
IN, OUT: Input byte or word from port, output word to port.
LEA: Load effective address
LDS, LES Load pointer using data segment, extra segment .
PUSH, POP: Push word onto stack, pop word off stack.
XCHG: Exchange byte or word.
XLAT: Translate byte using look-up table.
2. Arithmetic instructions – add, subtract, increment, decrement, convert byte/word and compare.
ADD, SUB: Add, subtract byte or word
ADC, SBB: Add, subtract byte or word and carry (borrow).
INC, DEC: Increment, decrement byte or word.
NEG: Negate byte or word (two’s complement).
CMP: Compare byte or word (subtract without storing).
MUL, DIV: Multiply, divide byte or word (unsigned).
IMUL, IDIV: Integer multiply, divide byte or word (signed)
CBW, CWD: Convert byte to word, word to double word
AAA, AAS, AAM ,AAD: ASCII adjust for add, sub, mul, div .
DAA, DAS: Decimal adjust for addition, subtraction (BCD numbers)
3. Logic instructions – AND, OR, exclusive OR, shift/rotate and test
NOT: Logical NOT of byte or word (one’s complement)
AND: Logical AND of byte or word
OR: Logical OR of byte or word.
XOR: Logical exclusive-OR of byte or word
TEST: Test byte or word (AND without storing).
SHL, SHR: Logical Shift rotate instruction shift left, right byte or word? by 1or CL
SAL, SAR: Arithmetic shift left, right byte or word? by 1 or CL
ROL, ROR: Rotate left, right byte or word? by 1 or CL.
RCL, RCR: Rotate left, right through carry byte or word? by 1 or CL.
String manipulation instruction – load, store, move, compare and scan for byte/word
String manipulation instruction – load, store, move, compare and scan for byte/word
MOVS: Move byte or word string
MOVSB, MOVSW: Move byte, word string.
CMPS: Compare byte or word string.
SCAS S: can byte or word string (comparing to A or AX)
LODS, STOS: Load, store byte or word string to AL.
5. Control transfer instructions – conditional, unconditional, call subroutine and return from subroutine.
JMP: Unconditional jump .it includes loop transfer and subroutine and interrupt instructions.
JNZ: jump till the counter value decreases to zero. It runs the loop till the value stored in CX becomes zero
6. Loop control instructions-
LOOP: Loop unconditional, count in CX, short jump to target address.
LOOPE (LOOPZ): Loop if equal (zero), count in CX, short jump to target address.
LOOPNE (LOOPNZ): Loop if not equal (not zero), count in CX, short jump to target address.
JCXZ: Jump if CX equals zero (used to skip code in loop).
Subroutine and Interrupt instructions-
CALL, RET: Call, return from procedure (inside or outside current segment).
INT, INTO: Software interrupt, interrupt if overflow.IRET: Return from interrupt.
7. Processor control instructions-
Flag manipulation:
STC, CLC, CMC: Set, clear, complement carry flag.
STD, CLD: Set, clear direction flag.STI, CLI: Set, clear interrupt enable flag.
PUSHF, POPF: Push flags onto stack, pop flags off stack.
Sample GATE Question
Consider the sequence of machine instructions given below:
MUL R5, R0, R1
DIV R6, R2, R3
ADD R7, R5, R6
SUB R8, R7, R4
In the above sequence, R0 to R8 are general purpose registers. In the instructions shown, the first register stores the result of the operation performed on the second and the third registers. This sequence of instructions is to be executed in a pipelined instruction processor with the following 4 stages: (1) Instruction Fetch and Decode (IF), (2) Operand Fetch (OF), (3) Perform Operation (PO) and (4) Write back the Result (WB). The IF, OF and WB stages take 1 clock cycle each for any instruction. The PO stage takes 1 clock cycle for ADD or SUB instruction, 3 clock cycles for MUL instruction and 5 clock cycles for DIV instruction. The pipelined processor uses operand forwarding from the PO stage to the OF stage. The number of clock cycles taken for the execution of the above sequence of instructions is ___________(A) 11(B) 12(C) 13(D) 14
Answer: (C)
Explanation:
1 2 3 4 5 6 7 8 9 10 11 12 13
IF OF PO PO PO WB
IF OF PO PO PO PO PO WB
IF OF PO WB
IF OF PO WB
Article Contributed by Pooja Taneja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
PranavGautam1
surinderdawra388
vaibhavsinghtanwar
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Decimal to Binary Conversion
Logical and Physical Address in Operating System
Direct Access Media (DMA) Controller in Computer Architecture
Interrupts
Addressing modes in 8085 microprocessor
Flag register of 8086 microprocessor
Programmable peripheral interface 8255
Flag register in 8085 microprocessor
IEEE Standard 754 Floating Point Numbers
Addressing modes in 8086 microprocessor
|
[
{
"code": null,
"e": 28709,
"s": 28681,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 28838,
"s": 28709,
"text": "Machine Instructions are commands or programs written in machine code of a machine (computer) that it can recognize and execute."
},
{
"code": null,
"e": 28955,
"s": 28838,
"text": "A machine instruction consists of several bytes in memory that tells the processor to perform one machine operation."
},
{
"code": null,
"e": 29098,
"s": 28955,
"text": "The processor looks at machine instructions in main memory one after another, and performs one machine operation for each machine instruction."
},
{
"code": null,
"e": 29190,
"s": 29098,
"text": "The collection of machine instructions in main memory is called a machine language program."
},
{
"code": null,
"e": 29538,
"s": 29190,
"text": "Machine code or machine language is a set of instructions executed directly by a computer’s central processing unit (CPU). Each instruction performs a very specific task, such as a load, a jump, or an ALU operation on a unit of data in a CPU register or memory. Every program directly executed by a CPU is made up of a series of such instructions."
},
{
"code": null,
"e": 29585,
"s": 29538,
"text": "The general format of a machine instruction is"
},
{
"code": null,
"e": 29628,
"s": 29585,
"text": "Brackets indicate that a field is optional"
},
{
"code": null,
"e": 29765,
"s": 29628,
"text": "Label is an identifier that is assigned the address of the first byte of the instruction in which it appears. It must be followed by “:”"
},
{
"code": null,
"e": 29885,
"s": 29765,
"text": "Inclusion of spaces is arbitrary, except that at least one space must be inserted; no space would lead to an ambiguity."
},
{
"code": null,
"e": 29929,
"s": 29885,
"text": "Comment field begins with a semicolon “ ; ”"
},
{
"code": null,
"e": 29938,
"s": 29929,
"text": "Example:"
},
{
"code": null,
"e": 29987,
"s": 29938,
"text": "Machine instructions used in 8086 microprocessor"
},
{
"code": null,
"e": 30054,
"s": 29987,
"text": "1. Data transfer instructions– move, load exchange, input, output."
},
{
"code": null,
"e": 30101,
"s": 30054,
"text": "MOV: Move byte or word to register or memory ."
},
{
"code": null,
"e": 30161,
"s": 30101,
"text": "IN, OUT: Input byte or word from port, output word to port."
},
{
"code": null,
"e": 30189,
"s": 30161,
"text": "LEA: Load effective address"
},
{
"code": null,
"e": 30247,
"s": 30189,
"text": "LDS, LES Load pointer using data segment, extra segment ."
},
{
"code": null,
"e": 30300,
"s": 30247,
"text": "PUSH, POP: Push word onto stack, pop word off stack."
},
{
"code": null,
"e": 30329,
"s": 30300,
"text": "XCHG: Exchange byte or word."
},
{
"code": null,
"e": 30371,
"s": 30329,
"text": "XLAT: Translate byte using look-up table."
},
{
"code": null,
"e": 30468,
"s": 30371,
"text": "2. Arithmetic instructions – add, subtract, increment, decrement, convert byte/word and compare."
},
{
"code": null,
"e": 30505,
"s": 30468,
"text": "ADD, SUB: Add, subtract byte or word"
},
{
"code": null,
"e": 30562,
"s": 30505,
"text": "ADC, SBB: Add, subtract byte or word and carry (borrow)."
},
{
"code": null,
"e": 30607,
"s": 30562,
"text": "INC, DEC: Increment, decrement byte or word."
},
{
"code": null,
"e": 30654,
"s": 30607,
"text": "NEG: Negate byte or word (two’s complement)."
},
{
"code": null,
"e": 30708,
"s": 30654,
"text": "CMP: Compare byte or word (subtract without storing)."
},
{
"code": null,
"e": 30760,
"s": 30708,
"text": "MUL, DIV: Multiply, divide byte or word (unsigned)."
},
{
"code": null,
"e": 30819,
"s": 30760,
"text": "IMUL, IDIV: Integer multiply, divide byte or word (signed)"
},
{
"code": null,
"e": 30871,
"s": 30819,
"text": "CBW, CWD: Convert byte to word, word to double word"
},
{
"code": null,
"e": 30930,
"s": 30871,
"text": "AAA, AAS, AAM ,AAD: ASCII adjust for add, sub, mul, div ."
},
{
"code": null,
"e": 30995,
"s": 30930,
"text": "DAA, DAS: Decimal adjust for addition, subtraction (BCD numbers)"
},
{
"code": null,
"e": 31064,
"s": 30995,
"text": "3. Logic instructions – AND, OR, exclusive OR, shift/rotate and test"
},
{
"code": null,
"e": 31116,
"s": 31064,
"text": "NOT: Logical NOT of byte or word (one’s complement)"
},
{
"code": null,
"e": 31149,
"s": 31116,
"text": "AND: Logical AND of byte or word"
},
{
"code": null,
"e": 31181,
"s": 31149,
"text": "OR: Logical OR of byte or word."
},
{
"code": null,
"e": 31223,
"s": 31181,
"text": "XOR: Logical exclusive-OR of byte or word"
},
{
"code": null,
"e": 31270,
"s": 31223,
"text": "TEST: Test byte or word (AND without storing)."
},
{
"code": null,
"e": 31355,
"s": 31270,
"text": "SHL, SHR: Logical Shift rotate instruction shift left, right byte or word? by 1or CL"
},
{
"code": null,
"e": 31419,
"s": 31355,
"text": "SAL, SAR: Arithmetic shift left, right byte or word? by 1 or CL"
},
{
"code": null,
"e": 31474,
"s": 31419,
"text": "ROL, ROR: Rotate left, right byte or word? by 1 or CL."
},
{
"code": null,
"e": 31544,
"s": 31474,
"text": "RCL, RCR: Rotate left, right through carry byte or word? by 1 or CL."
},
{
"code": null,
"e": 31628,
"s": 31544,
"text": "String manipulation instruction – load, store, move, compare and scan for byte/word"
},
{
"code": null,
"e": 31712,
"s": 31628,
"text": "String manipulation instruction – load, store, move, compare and scan for byte/word"
},
{
"code": null,
"e": 31743,
"s": 31712,
"text": "MOVS: Move byte or word string"
},
{
"code": null,
"e": 31781,
"s": 31743,
"text": "MOVSB, MOVSW: Move byte, word string."
},
{
"code": null,
"e": 31817,
"s": 31781,
"text": "CMPS: Compare byte or word string."
},
{
"code": null,
"e": 31872,
"s": 31817,
"text": "SCAS S: can byte or word string (comparing to A or AX)"
},
{
"code": null,
"e": 31924,
"s": 31872,
"text": "LODS, STOS: Load, store byte or word string to AL."
},
{
"code": null,
"e": 32031,
"s": 31924,
"text": "5. Control transfer instructions – conditional, unconditional, call subroutine and return from subroutine."
},
{
"code": null,
"e": 32125,
"s": 32031,
"text": "JMP: Unconditional jump .it includes loop transfer and subroutine and interrupt instructions."
},
{
"code": null,
"e": 32235,
"s": 32125,
"text": "JNZ: jump till the counter value decreases to zero. It runs the loop till the value stored in CX becomes zero"
},
{
"code": null,
"e": 32266,
"s": 32235,
"text": " 6. Loop control instructions-"
},
{
"code": null,
"e": 32336,
"s": 32266,
"text": " LOOP: Loop unconditional, count in CX, short jump to target address."
},
{
"code": null,
"e": 32416,
"s": 32336,
"text": "LOOPE (LOOPZ): Loop if equal (zero), count in CX, short jump to target address."
},
{
"code": null,
"e": 32506,
"s": 32416,
"text": "LOOPNE (LOOPNZ): Loop if not equal (not zero), count in CX, short jump to target address."
},
{
"code": null,
"e": 32564,
"s": 32506,
"text": "JCXZ: Jump if CX equals zero (used to skip code in loop)."
},
{
"code": null,
"e": 32603,
"s": 32564,
"text": "Subroutine and Interrupt instructions-"
},
{
"code": null,
"e": 32680,
"s": 32603,
"text": "CALL, RET: Call, return from procedure (inside or outside current segment)."
},
{
"code": null,
"e": 32763,
"s": 32680,
"text": "INT, INTO: Software interrupt, interrupt if overflow.IRET: Return from interrupt."
},
{
"code": null,
"e": 32798,
"s": 32763,
"text": "7. Processor control instructions-"
},
{
"code": null,
"e": 32817,
"s": 32798,
"text": "Flag manipulation:"
},
{
"code": null,
"e": 32868,
"s": 32817,
"text": "STC, CLC, CMC: Set, clear, complement carry flag."
},
{
"code": null,
"e": 32949,
"s": 32868,
"text": "STD, CLD: Set, clear direction flag.STI, CLI: Set, clear interrupt enable flag."
},
{
"code": null,
"e": 33006,
"s": 32949,
"text": "PUSHF, POPF: Push flags onto stack, pop flags off stack."
},
{
"code": null,
"e": 33027,
"s": 33006,
"text": "Sample GATE Question"
},
{
"code": null,
"e": 33086,
"s": 33027,
"text": "Consider the sequence of machine instructions given below:"
},
{
"code": null,
"e": 33154,
"s": 33086,
"text": " MUL R5, R0, R1\n DIV R6, R2, R3\n ADD R7, R5, R6\n SUB R8, R7, R4"
},
{
"code": null,
"e": 34004,
"s": 33154,
"text": "In the above sequence, R0 to R8 are general purpose registers. In the instructions shown, the first register stores the result of the operation performed on the second and the third registers. This sequence of instructions is to be executed in a pipelined instruction processor with the following 4 stages: (1) Instruction Fetch and Decode (IF), (2) Operand Fetch (OF), (3) Perform Operation (PO) and (4) Write back the Result (WB). The IF, OF and WB stages take 1 clock cycle each for any instruction. The PO stage takes 1 clock cycle for ADD or SUB instruction, 3 clock cycles for MUL instruction and 5 clock cycles for DIV instruction. The pipelined processor uses operand forwarding from the PO stage to the OF stage. The number of clock cycles taken for the execution of the above sequence of instructions is ___________(A) 11(B) 12(C) 13(D) 14"
},
{
"code": null,
"e": 34016,
"s": 34004,
"text": "Answer: (C)"
},
{
"code": null,
"e": 34029,
"s": 34016,
"text": "Explanation:"
},
{
"code": null,
"e": 34262,
"s": 34029,
"text": " 1 2 3 4 5 6 7 8 9 10 11 12 13\n IF OF PO PO PO WB\n IF OF PO PO PO PO PO WB\n IF OF PO WB\n IF OF PO WB"
},
{
"code": null,
"e": 34424,
"s": 34262,
"text": "Article Contributed by Pooja Taneja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 34440,
"s": 34426,
"text": "PranavGautam1"
},
{
"code": null,
"e": 34457,
"s": 34440,
"text": "surinderdawra388"
},
{
"code": null,
"e": 34476,
"s": 34457,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 34513,
"s": 34476,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 34611,
"s": 34513,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34652,
"s": 34611,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 34701,
"s": 34652,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 34763,
"s": 34701,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 34774,
"s": 34763,
"text": "Interrupts"
},
{
"code": null,
"e": 34814,
"s": 34774,
"text": "Addressing modes in 8085 microprocessor"
},
{
"code": null,
"e": 34851,
"s": 34814,
"text": "Flag register of 8086 microprocessor"
},
{
"code": null,
"e": 34890,
"s": 34851,
"text": "Programmable peripheral interface 8255"
},
{
"code": null,
"e": 34927,
"s": 34890,
"text": "Flag register in 8085 microprocessor"
},
{
"code": null,
"e": 34968,
"s": 34927,
"text": "IEEE Standard 754 Floating Point Numbers"
}
] |
Java Program to Print Diamond Shape Star Pattern - GeeksforGeeks
|
08 Mar, 2022
In this article, we are going to learn how to print diamond shape star patterns in Java.
Illustration:
Input: number = 7
Output:
*
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*
Methods: When it comes to pattern printing we do opt for standard ways of printing them via loops only. We will try out different types of loops to print the same pattern.
Example 1: Using do-while Loop
Java
// Java program to Print Diamond Star Pattern// Using do-while loop // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing variables // Variable initialized to the row where max star // should be there as after that they decreases to // give diamond pattern int number = 7; // Diamond starting with single star in first row,so // initialized int m = 1; // Columnar printing int n; // Outer loop 1 // Prints the first half diamond do { n = 1; // Inner loop 1 // Prints space until ++n <= number - m + 1 is // false do { // Print whitespace between System.out.print(" "); } // Condition for inside do-while loop 1 while (++n <= number - m + 1); // Now n = 1; // Inner loop 2 // Prints star until ++n <= m * 2 - 1 is false do { // Print star System.out.print("*"); } // Condition for inner do-while loop 2 while (++n <= m * 2 - 1); // A new row requires a new line System.out.println(); } // Condition for outer do-while loop 1 while (++m <= number); // Now we are done with printing the upper half // diamond. // Note: Not to print the bottom row again in lower // half diamond printing Hence variable to be // initialized should one lesser than number m = number - 1; // Outer loop 2 // Prints the second half diamond do { n = 1; // Inner loop 1 // Prints space until ++n <= number - m + 1 is // false do { // Print whitespace between System.out.print(" "); } while (++n <= number - m + 1); n = 1; // Inner loop 2 // Prints star until ++n <= m * 2 - 1 is false do { // Prints star System.out.print("*"); } while (++n <= m * 2 - 1); // By now done with one row of lower diamond // printing so a new line is required System.out.println(); } // Condition for outer do-while loop 2 while (--m > 0); }}
*
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*
Example 2: Using while Loop
Java
// Java program to print diamond star pattern// Using while loop // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing variables // Variable initialized to the row where max star // should be there as after that they decreases to // give diamond pattern int number = 7; // Diamond starting with single star in first row int m = 1; // Columnar printing int n; // Outer loop 1 // Prints the first half diamond // Condition holding true till // number of rows initialized while (m <= number) { n = 1; // Inner loop 1 // Prints space until n++ <= number - m is false while (n++ <= number - m) { // Print whitespaces inbetween System.out.print(" "); } n = 1; // Inner loop 2 // Prints star until n++ <= m * 2 - 1 is false while (n++ <= m * 2 - 1) { // Print star System.out.print("*"); } // By now we are done for above pyramid printing // ending line after each row System.out.println(); // Incrementing as we want pyramid generation m++; } // Now we are done with printing the upper half // diamond. // Note: Not to print the bottom row again in lower // half diamond printing Hence variable t be // initialized should one lesser than number m = number - 1; // Outer loop 2 // Prints the second half diamond while (m > 0) { n = 1; // Inner loop 1 // Prints spaces until n++ <= number - m is // false while (n++ <= number - m) { // Print whitespace in between System.out.print(" "); } n = 1; // Inner loop 2 // Prints star until n++ <= m * 2 - 1 is false while (n++ <= m * 2 - 1) { // Print star System.out.print("*"); } // Ending line after each row System.out.println(); // Decrementing as we want reverse pyramid // generation m--; } }}
*
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*
Example 3: Using for Loop
Java
// Java program to print diamond star pattern// Using for loop // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing variables // Variable initialized to the row where max star // should be there as after that they decreases to // give diamond pattern int number = 7; int m, n; // Outer loop 1 // prints the first half diamond for (m = 1; m <= number; m++) { // Inner loop 1 print whitespaces inbetween for (n = 1; n <= number - m; n++) { System.out.print(" "); } // Inner loop 2 prints star for (n = 1; n <= m * 2 - 1; n++) { System.out.print("*"); } // Ending line after each row System.out.println(); } // Outer loop 2 // Prints the second half diamond for (m = number - 1; m > 0; m--) { // Inner loop 1 print whitespaces inbetween for (n = 1; n <= number - m; n++) { System.out.print(" "); } // Inner loop 2 print star for (n = 1; n <= m * 2 - 1; n++) { System.out.print("*"); } // Ending line after each row System.out.println(); } }}
*
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*
kashishsoda
sagartomar9927
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 25603,
"s": 25513,
"text": "In this article, we are going to learn how to print diamond shape star patterns in Java. "
},
{
"code": null,
"e": 25617,
"s": 25603,
"text": "Illustration:"
},
{
"code": null,
"e": 25799,
"s": 25617,
"text": "Input: number = 7\n \nOutput:\n\n *\n ***\n *****\n *******\n *********\n ***********\n *************\n ***********\n *********\n *******\n *****\n ***\n *"
},
{
"code": null,
"e": 25971,
"s": 25799,
"text": "Methods: When it comes to pattern printing we do opt for standard ways of printing them via loops only. We will try out different types of loops to print the same pattern."
},
{
"code": null,
"e": 26002,
"s": 25971,
"text": "Example 1: Using do-while Loop"
},
{
"code": null,
"e": 26007,
"s": 26002,
"text": "Java"
},
{
"code": "// Java program to Print Diamond Star Pattern// Using do-while loop // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing variables // Variable initialized to the row where max star // should be there as after that they decreases to // give diamond pattern int number = 7; // Diamond starting with single star in first row,so // initialized int m = 1; // Columnar printing int n; // Outer loop 1 // Prints the first half diamond do { n = 1; // Inner loop 1 // Prints space until ++n <= number - m + 1 is // false do { // Print whitespace between System.out.print(\" \"); } // Condition for inside do-while loop 1 while (++n <= number - m + 1); // Now n = 1; // Inner loop 2 // Prints star until ++n <= m * 2 - 1 is false do { // Print star System.out.print(\"*\"); } // Condition for inner do-while loop 2 while (++n <= m * 2 - 1); // A new row requires a new line System.out.println(); } // Condition for outer do-while loop 1 while (++m <= number); // Now we are done with printing the upper half // diamond. // Note: Not to print the bottom row again in lower // half diamond printing Hence variable to be // initialized should one lesser than number m = number - 1; // Outer loop 2 // Prints the second half diamond do { n = 1; // Inner loop 1 // Prints space until ++n <= number - m + 1 is // false do { // Print whitespace between System.out.print(\" \"); } while (++n <= number - m + 1); n = 1; // Inner loop 2 // Prints star until ++n <= m * 2 - 1 is false do { // Prints star System.out.print(\"*\"); } while (++n <= m * 2 - 1); // By now done with one row of lower diamond // printing so a new line is required System.out.println(); } // Condition for outer do-while loop 2 while (--m > 0); }}",
"e": 28532,
"s": 26007,
"text": null
},
{
"code": null,
"e": 28688,
"s": 28535,
"text": " *\n ***\n *****\n *******\n *********\n ***********\n *************\n ***********\n *********\n *******\n *****\n ***\n *"
},
{
"code": null,
"e": 28718,
"s": 28690,
"text": "Example 2: Using while Loop"
},
{
"code": null,
"e": 28725,
"s": 28720,
"text": "Java"
},
{
"code": "// Java program to print diamond star pattern// Using while loop // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing variables // Variable initialized to the row where max star // should be there as after that they decreases to // give diamond pattern int number = 7; // Diamond starting with single star in first row int m = 1; // Columnar printing int n; // Outer loop 1 // Prints the first half diamond // Condition holding true till // number of rows initialized while (m <= number) { n = 1; // Inner loop 1 // Prints space until n++ <= number - m is false while (n++ <= number - m) { // Print whitespaces inbetween System.out.print(\" \"); } n = 1; // Inner loop 2 // Prints star until n++ <= m * 2 - 1 is false while (n++ <= m * 2 - 1) { // Print star System.out.print(\"*\"); } // By now we are done for above pyramid printing // ending line after each row System.out.println(); // Incrementing as we want pyramid generation m++; } // Now we are done with printing the upper half // diamond. // Note: Not to print the bottom row again in lower // half diamond printing Hence variable t be // initialized should one lesser than number m = number - 1; // Outer loop 2 // Prints the second half diamond while (m > 0) { n = 1; // Inner loop 1 // Prints spaces until n++ <= number - m is // false while (n++ <= number - m) { // Print whitespace in between System.out.print(\" \"); } n = 1; // Inner loop 2 // Prints star until n++ <= m * 2 - 1 is false while (n++ <= m * 2 - 1) { // Print star System.out.print(\"*\"); } // Ending line after each row System.out.println(); // Decrementing as we want reverse pyramid // generation m--; } }}",
"e": 31155,
"s": 28725,
"text": null
},
{
"code": null,
"e": 31311,
"s": 31158,
"text": " *\n ***\n *****\n *******\n *********\n ***********\n *************\n ***********\n *********\n *******\n *****\n ***\n *"
},
{
"code": null,
"e": 31339,
"s": 31313,
"text": "Example 3: Using for Loop"
},
{
"code": null,
"e": 31346,
"s": 31341,
"text": "Java"
},
{
"code": "// Java program to print diamond star pattern// Using for loop // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing variables // Variable initialized to the row where max star // should be there as after that they decreases to // give diamond pattern int number = 7; int m, n; // Outer loop 1 // prints the first half diamond for (m = 1; m <= number; m++) { // Inner loop 1 print whitespaces inbetween for (n = 1; n <= number - m; n++) { System.out.print(\" \"); } // Inner loop 2 prints star for (n = 1; n <= m * 2 - 1; n++) { System.out.print(\"*\"); } // Ending line after each row System.out.println(); } // Outer loop 2 // Prints the second half diamond for (m = number - 1; m > 0; m--) { // Inner loop 1 print whitespaces inbetween for (n = 1; n <= number - m; n++) { System.out.print(\" \"); } // Inner loop 2 print star for (n = 1; n <= m * 2 - 1; n++) { System.out.print(\"*\"); } // Ending line after each row System.out.println(); } }}",
"e": 32767,
"s": 31346,
"text": null
},
{
"code": null,
"e": 32910,
"s": 32770,
"text": " *\n ***\n *****\n *******\n *********\n ***********\n*************\n ***********\n *********\n *******\n *****\n ***\n *"
},
{
"code": null,
"e": 32924,
"s": 32912,
"text": "kashishsoda"
},
{
"code": null,
"e": 32939,
"s": 32924,
"text": "sagartomar9927"
},
{
"code": null,
"e": 32946,
"s": 32939,
"text": "Picked"
},
{
"code": null,
"e": 32951,
"s": 32946,
"text": "Java"
},
{
"code": null,
"e": 32965,
"s": 32951,
"text": "Java Programs"
},
{
"code": null,
"e": 32970,
"s": 32965,
"text": "Java"
},
{
"code": null,
"e": 33068,
"s": 32970,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33119,
"s": 33068,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 33149,
"s": 33119,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 33164,
"s": 33149,
"text": "Stream In Java"
},
{
"code": null,
"e": 33183,
"s": 33164,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 33214,
"s": 33183,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 33242,
"s": 33214,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 33286,
"s": 33242,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 33312,
"s": 33286,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 33346,
"s": 33312,
"text": "Convert Double to Integer in Java"
}
] |
Precedence Graph For Testing Conflict Serializability in DBMS - GeeksforGeeks
|
15 Nov, 2021
Prerequisite: Conflict Serializability
Precedence Graph or Serialization Graph is used commonly to test Conflict Serializability of a schedule.It is a directed Graph (V, E) consisting of a set of nodes V = {T1, T2, T3..........Tn} and a set of directed edges E = {e1, e2, e3..................em}.The graph contains one node for each Transaction Ti. An edge ei is of the form Tj –> Tk where Tj is the starting node of ei and Tk is the ending node of ei. An edge ei is constructed between nodes Tj to Tk if one of the operations in Tj appears in the schedule before some conflicting operation in Tk .
The Algorithm can be written as:
Create a node T in the graph for each participating transaction in the schedule.For the conflicting operation read_item(X) and write_item(X) – If a Transaction Tj executes a read_item (X) after Ti executes a write_item (X), draw an edge from Ti to Tj in the graph.For the conflicting operation write_item(X) and read_item(X) – If a Transaction Tj executes a write_item (X) after Ti executes a read_item (X), draw an edge from Ti to Tj in the graph.For the conflicting operation write_item(X) and write_item(X) – If a Transaction Tj executes a write_item (X) after Ti executes a write_item (X), draw an edge from Ti to Tj in the graph.The Schedule S is serializable if there is no cycle in the precedence graph.
Create a node T in the graph for each participating transaction in the schedule.
For the conflicting operation read_item(X) and write_item(X) – If a Transaction Tj executes a read_item (X) after Ti executes a write_item (X), draw an edge from Ti to Tj in the graph.
For the conflicting operation write_item(X) and read_item(X) – If a Transaction Tj executes a write_item (X) after Ti executes a read_item (X), draw an edge from Ti to Tj in the graph.
For the conflicting operation write_item(X) and write_item(X) – If a Transaction Tj executes a write_item (X) after Ti executes a write_item (X), draw an edge from Ti to Tj in the graph.
The Schedule S is serializable if there is no cycle in the precedence graph.
If there is no cycle in the precedence graph, it means we can construct a serial schedule S’ which is conflict equivalent to schedule S.The serial schedule S’ can be found by Topological Sorting of the acyclic precedence graph. Such schedules can be more than 1.
For example,Consider the schedule S :
S : r1(x) r1(y) w2(x) w1(x) r2(y)
Creating Precedence graph:
Make two nodes corresponding to Transaction T1 and T2.For the conflicting pair r1(x) w2(x), where r1(x) happens before w2(x), draw an edge from T1 to T2.For the conflicting pair w2(x) w1(x), where w2(x) happens before w1(x), draw an edge from T2 to T1.
Make two nodes corresponding to Transaction T1 and T2.
For the conflicting pair r1(x) w2(x), where r1(x) happens before w2(x), draw an edge from T1 to T2.
For the conflicting pair w2(x) w1(x), where w2(x) happens before w1(x), draw an edge from T2 to T1.
Since the graph is cyclic, we can conclude that it is not conflict serializable to any schedule serial schedule.Let us try to infer a serial schedule from this graph using topological ordering.The edge T1–>T2 tells that T1 should come before T2 in the linear ordering.The edge T2 –> T1 tells that T2 should come before T1 in the linear ordering.So, we can not predict any particular order (when the graph is cyclic). Therefore, no serial schedule can be obtained from this graph.Consider the another schedule S1 :
S1: r1(x) r3(y) w1(x) w2(y) r3(x) w2(x)
The graph for this schedule is :
Since the graph is acyclic, the schedule is conflict serializable. Performing Topological Sort on this graph would give us a possible serial schedule that is conflict equivalent to schedule S1.In Topological Sort, we first select the node with in-degree 0, which is T1. This would be followed by T3 and T2.So, S1 is conflict serializable since it is conflict equivalent to the serial schedule T1 T3 T2.
Source: Operating Systems book, Silberschatz, Galvin and Gagne
This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
niharikatanwar61
DBMS-Transactions and Concurrency Control
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | WITH clause
SQL | Join (Inner, Left, Right and Full Joins)
SQL query to find second highest salary?
SQL Interview Questions
CTE in SQL
Layers of OSI Model
TCP/IP Model
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
|
[
{
"code": null,
"e": 30871,
"s": 30843,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 30910,
"s": 30871,
"text": "Prerequisite: Conflict Serializability"
},
{
"code": null,
"e": 31470,
"s": 30910,
"text": "Precedence Graph or Serialization Graph is used commonly to test Conflict Serializability of a schedule.It is a directed Graph (V, E) consisting of a set of nodes V = {T1, T2, T3..........Tn} and a set of directed edges E = {e1, e2, e3..................em}.The graph contains one node for each Transaction Ti. An edge ei is of the form Tj –> Tk where Tj is the starting node of ei and Tk is the ending node of ei. An edge ei is constructed between nodes Tj to Tk if one of the operations in Tj appears in the schedule before some conflicting operation in Tk ."
},
{
"code": null,
"e": 31503,
"s": 31470,
"text": "The Algorithm can be written as:"
},
{
"code": null,
"e": 32214,
"s": 31503,
"text": "Create a node T in the graph for each participating transaction in the schedule.For the conflicting operation read_item(X) and write_item(X) – If a Transaction Tj executes a read_item (X) after Ti executes a write_item (X), draw an edge from Ti to Tj in the graph.For the conflicting operation write_item(X) and read_item(X) – If a Transaction Tj executes a write_item (X) after Ti executes a read_item (X), draw an edge from Ti to Tj in the graph.For the conflicting operation write_item(X) and write_item(X) – If a Transaction Tj executes a write_item (X) after Ti executes a write_item (X), draw an edge from Ti to Tj in the graph.The Schedule S is serializable if there is no cycle in the precedence graph."
},
{
"code": null,
"e": 32295,
"s": 32214,
"text": "Create a node T in the graph for each participating transaction in the schedule."
},
{
"code": null,
"e": 32480,
"s": 32295,
"text": "For the conflicting operation read_item(X) and write_item(X) – If a Transaction Tj executes a read_item (X) after Ti executes a write_item (X), draw an edge from Ti to Tj in the graph."
},
{
"code": null,
"e": 32665,
"s": 32480,
"text": "For the conflicting operation write_item(X) and read_item(X) – If a Transaction Tj executes a write_item (X) after Ti executes a read_item (X), draw an edge from Ti to Tj in the graph."
},
{
"code": null,
"e": 32852,
"s": 32665,
"text": "For the conflicting operation write_item(X) and write_item(X) – If a Transaction Tj executes a write_item (X) after Ti executes a write_item (X), draw an edge from Ti to Tj in the graph."
},
{
"code": null,
"e": 32929,
"s": 32852,
"text": "The Schedule S is serializable if there is no cycle in the precedence graph."
},
{
"code": null,
"e": 33192,
"s": 32929,
"text": "If there is no cycle in the precedence graph, it means we can construct a serial schedule S’ which is conflict equivalent to schedule S.The serial schedule S’ can be found by Topological Sorting of the acyclic precedence graph. Such schedules can be more than 1."
},
{
"code": null,
"e": 33230,
"s": 33192,
"text": "For example,Consider the schedule S :"
},
{
"code": null,
"e": 33266,
"s": 33230,
"text": " S : r1(x) r1(y) w2(x) w1(x) r2(y) "
},
{
"code": null,
"e": 33293,
"s": 33266,
"text": "Creating Precedence graph:"
},
{
"code": null,
"e": 33546,
"s": 33293,
"text": "Make two nodes corresponding to Transaction T1 and T2.For the conflicting pair r1(x) w2(x), where r1(x) happens before w2(x), draw an edge from T1 to T2.For the conflicting pair w2(x) w1(x), where w2(x) happens before w1(x), draw an edge from T2 to T1."
},
{
"code": null,
"e": 33601,
"s": 33546,
"text": "Make two nodes corresponding to Transaction T1 and T2."
},
{
"code": null,
"e": 33701,
"s": 33601,
"text": "For the conflicting pair r1(x) w2(x), where r1(x) happens before w2(x), draw an edge from T1 to T2."
},
{
"code": null,
"e": 33801,
"s": 33701,
"text": "For the conflicting pair w2(x) w1(x), where w2(x) happens before w1(x), draw an edge from T2 to T1."
},
{
"code": null,
"e": 34315,
"s": 33801,
"text": "Since the graph is cyclic, we can conclude that it is not conflict serializable to any schedule serial schedule.Let us try to infer a serial schedule from this graph using topological ordering.The edge T1–>T2 tells that T1 should come before T2 in the linear ordering.The edge T2 –> T1 tells that T2 should come before T1 in the linear ordering.So, we can not predict any particular order (when the graph is cyclic). Therefore, no serial schedule can be obtained from this graph.Consider the another schedule S1 :"
},
{
"code": null,
"e": 34356,
"s": 34315,
"text": " S1: r1(x) r3(y) w1(x) w2(y) r3(x) w2(x)"
},
{
"code": null,
"e": 34389,
"s": 34356,
"text": "The graph for this schedule is :"
},
{
"code": null,
"e": 34792,
"s": 34389,
"text": "Since the graph is acyclic, the schedule is conflict serializable. Performing Topological Sort on this graph would give us a possible serial schedule that is conflict equivalent to schedule S1.In Topological Sort, we first select the node with in-degree 0, which is T1. This would be followed by T3 and T2.So, S1 is conflict serializable since it is conflict equivalent to the serial schedule T1 T3 T2."
},
{
"code": null,
"e": 34855,
"s": 34792,
"text": "Source: Operating Systems book, Silberschatz, Galvin and Gagne"
},
{
"code": null,
"e": 35152,
"s": 34855,
"text": "This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 35169,
"s": 35152,
"text": "niharikatanwar61"
},
{
"code": null,
"e": 35211,
"s": 35169,
"text": "DBMS-Transactions and Concurrency Control"
},
{
"code": null,
"e": 35216,
"s": 35211,
"text": "DBMS"
},
{
"code": null,
"e": 35224,
"s": 35216,
"text": "GATE CS"
},
{
"code": null,
"e": 35229,
"s": 35224,
"text": "DBMS"
},
{
"code": null,
"e": 35327,
"s": 35229,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35345,
"s": 35327,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 35392,
"s": 35345,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 35433,
"s": 35392,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 35457,
"s": 35433,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 35468,
"s": 35457,
"text": "CTE in SQL"
},
{
"code": null,
"e": 35488,
"s": 35468,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 35501,
"s": 35488,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 35528,
"s": 35501,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 35577,
"s": 35528,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
Matcher group() method in Java with Examples - GeeksforGeeks
|
26 Nov, 2018
The group() method of Matcher Class is used to get the input subsequence matched by the previous match result.
Syntax:
public String group()
Parameters: This method do not takes any parameter.
Return Value: This method returns the String which is the input subsequence matched by the previous match.
Exception: This method throws IllegalStateException if no match has yet been attempted, or if the previous match operation failed.
Below examples illustrate the Matcher.group() method:
Example 1:
// Java code to illustrate end() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(G*s)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GeeksForGeeks"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the current matcher state MatchResult result = matcher.toMatchResult(); System.out.println("Current Matcher: " + result); while (matcher.find()) { // Get the group matched using group() method System.out.println(matcher.group()); } }}
Current Matcher: java.util.regex.Matcher[pattern=(G*s) region=0, 13 lastmatch=]ss
Example 2:
// Java code to illustrate end() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(G*G)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFG FGF GFG"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the current matcher state MatchResult result = matcher.toMatchResult(); System.out.println("Current Matcher: " + result); while (matcher.find()) { // Get the group matched using group() method System.out.println(matcher.group()); } }}
Current Matcher: java.util.regex.Matcher[pattern=(G*G) region=0, 11 lastmatch=]GGGGG
Reference: Oracle Doc
Java - util package
Java-Functions
Java-Matcher
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 26309,
"s": 26281,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 26420,
"s": 26309,
"text": "The group() method of Matcher Class is used to get the input subsequence matched by the previous match result."
},
{
"code": null,
"e": 26428,
"s": 26420,
"text": "Syntax:"
},
{
"code": null,
"e": 26451,
"s": 26428,
"text": "public String group()\n"
},
{
"code": null,
"e": 26503,
"s": 26451,
"text": "Parameters: This method do not takes any parameter."
},
{
"code": null,
"e": 26610,
"s": 26503,
"text": "Return Value: This method returns the String which is the input subsequence matched by the previous match."
},
{
"code": null,
"e": 26741,
"s": 26610,
"text": "Exception: This method throws IllegalStateException if no match has yet been attempted, or if the previous match operation failed."
},
{
"code": null,
"e": 26795,
"s": 26741,
"text": "Below examples illustrate the Matcher.group() method:"
},
{
"code": null,
"e": 26806,
"s": 26795,
"text": "Example 1:"
},
{
"code": "// Java code to illustrate end() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"(G*s)\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GeeksForGeeks\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the current matcher state MatchResult result = matcher.toMatchResult(); System.out.println(\"Current Matcher: \" + result); while (matcher.find()) { // Get the group matched using group() method System.out.println(matcher.group()); } }}",
"e": 27697,
"s": 26806,
"text": null
},
{
"code": null,
"e": 27779,
"s": 27697,
"text": "Current Matcher: java.util.regex.Matcher[pattern=(G*s) region=0, 13 lastmatch=]ss"
},
{
"code": null,
"e": 27790,
"s": 27779,
"text": "Example 2:"
},
{
"code": "// Java code to illustrate end() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"(G*G)\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GFG FGF GFG\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the current matcher state MatchResult result = matcher.toMatchResult(); System.out.println(\"Current Matcher: \" + result); while (matcher.find()) { // Get the group matched using group() method System.out.println(matcher.group()); } }}",
"e": 28679,
"s": 27790,
"text": null
},
{
"code": null,
"e": 28764,
"s": 28679,
"text": "Current Matcher: java.util.regex.Matcher[pattern=(G*G) region=0, 11 lastmatch=]GGGGG"
},
{
"code": null,
"e": 28786,
"s": 28764,
"text": "Reference: Oracle Doc"
},
{
"code": null,
"e": 28806,
"s": 28786,
"text": "Java - util package"
},
{
"code": null,
"e": 28821,
"s": 28806,
"text": "Java-Functions"
},
{
"code": null,
"e": 28834,
"s": 28821,
"text": "Java-Matcher"
},
{
"code": null,
"e": 28839,
"s": 28834,
"text": "Java"
},
{
"code": null,
"e": 28844,
"s": 28839,
"text": "Java"
},
{
"code": null,
"e": 28942,
"s": 28844,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28993,
"s": 28942,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29023,
"s": 28993,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29038,
"s": 29023,
"text": "Stream In Java"
},
{
"code": null,
"e": 29057,
"s": 29038,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29088,
"s": 29057,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29106,
"s": 29088,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29138,
"s": 29106,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29158,
"s": 29138,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29182,
"s": 29158,
"text": "Singleton Class in Java"
}
] |
Exponential Squaring (Fast Modulo Multiplication) - GeeksforGeeks
|
07 Feb, 2020
Given two numbers base and exp, we need to compute baseexp under Modulo 10^9+7
Examples:
Input : base = 2, exp = 2
Output : 4
Input : base = 5, exp = 100000
Output : 754573817
In competitions, for calculating large powers of a number we are given a modulus value(a large prime number) because as the values of is being calculated it can get very large so instead we have to calculate (%modulus value.)We can use the modulus in our naive way by using modulus on all the intermediate steps and take modulus at the end,but in competitions it will definitely show TLE. So, what we can do.The answer is we can try exponentiation by squaring which is a fast method for calculating exponentiation of a number.Here we will be discussing two most common/important methods:
Basic Method(Binary Exponentiation)-ary method.
Basic Method(Binary Exponentiation)
-ary method.
Binary Exponentiation
As described in this article we will be using following formula to recursively calculate (%modulus value):
C++
Java
Python3
C#
PHP
// C++ program to compute exponential // value under modulo using binary // exponentiation.#include<iostream>using namespace std; #define N 1000000007 // prime modulo value long int exponentiation(long int base, long int exp){ if (exp == 0) return 1; if (exp == 1) return base % N; long int t = exponentiation(base, exp / 2); t = (t * t) % N; // if exponent is even value if (exp % 2 == 0) return t; // if exponent is odd value else return ((base % N) * t) % N;} // Driver Codeint main(){ long int base = 5; long int exp = 100000; long int modulo = exponentiation(base, exp); cout << modulo << endl; return 0;} // This Code is contributed by mits
// Java program to compute exponential value under modulo// using binary exponentiation.import java.util.*;import java.lang.*;import java.io.*; class exp_sq { static long N = 1000000007L; // prime modulo value public static void main(String[] args) { long base = 5; long exp = 100000; long modulo = exponentiation(base, exp); System.out.println(modulo); } static long exponentiation(long base, long exp) { if (exp == 0) return 1; if (exp == 1) return base % N; long t = exponentiation(base, exp / 2); t = (t * t) % N; // if exponent is even value if (exp % 2 == 0) return t; // if exponent is odd value else return ((base % N) * t) % N; }}
# Python3 program to compute # exponential value under# modulo using binary # exponentiation. # prime modulo valueN = 1000000007; # Function code def exponentiation(bas, exp): if (exp == 0): return 1; if (exp == 1): return bas % N; t = exponentiation(bas, int(exp / 2)); t = (t * t) % N; # if exponent is # even value if (exp % 2 == 0): return t; # if exponent is # odd value else: return ((bas % N) * t) % N; # Driver codebas = 5;exp = 100000; modulo = exponentiation(bas, exp);print(modulo); # This code is contributed# by mits
// C# program to compute exponential// value under modulo using binary // exponentiation.using System; class GFG { // prime modulo value static long N = 1000000007L; // Driver code public static void Main() { long bas = 5; long exp = 100000; long modulo = exponentiation(bas, exp); Console.Write(modulo); } static long exponentiation(long bas, long exp) { if (exp == 0) return 1; if (exp == 1) return bas % N; long t = exponentiation(bas, exp / 2); t = (t * t) % N; // if exponent is even value if (exp % 2 == 0) return t; // if exponent is odd value else return ((bas % N) * t) % N; }} // This code is contributed by nitin mittal.
<?php// PHP program to compute exponential// value under modulo using binary // exponentiation. // prime modulo value$N = 1000000007; // Function code function exponentiation($bas, $exp){ global $N ; if ($exp == 0) return 1; if ($exp == 1) return $bas % $N; $t = exponentiation($bas, $exp / 2); $t = ($t * $t) % $N; // if exponent is // even value if ($exp % 2 == 0) return $t; // if exponent is // odd value else return (($bas % $N) * $t) % $N;} // Driver code$bas = 5;$exp = 100000; $modulo = exponentiation($bas, $exp);echo ($modulo); // This code is contributed by ajit?>
754573817
-ary method:
In this algorithm we will be expanding the exponent in base (k>=1), which is somehow similar to above method except we are not using recursion this method uses comparatively less memory and time.
C++
Java
Python3
C#
PHP
// C++ program to compute exponential value using (2^k)// -ary method.#include<bits/stdc++.h>using namespace std; #define N 1000000007L; // prime modulo value long exponentiation(long base, long exp){ long t = 1L; while (exp > 0) { // for cases where exponent // is not an even value if (exp % 2 != 0) t = (t * base) % N; base = (base * base) % N; exp /= 2; } return t % N;} // Driver codeint main(){ long base = 5; long exp = 100000; long modulo = exponentiation(base, exp); cout << (modulo); return 0;} // This code is contributed by Rajput-Ji
// Java program to compute exponential value using (2^k)// -ary method.import java.util.*;import java.lang.*;import java.io.*; class exp_sq { static long N = 1000000007L; // prime modulo value public static void main(String[] args) { long base = 5; long exp = 100000; long modulo = exponentiation(base, exp); System.out.println(modulo); } static long exponentiation(long base, long exp) { long t = 1L; while (exp > 0) { // for cases where exponent // is not an even value if (exp % 2 != 0) t = (t * base) % N; base = (base * base) % N; exp /= 2; } return t % N; }}
# Python3 program to compute # exponential value # using (2^k) -ary method. # prime modulo valueN = 1000000007; def exponentiation(bas, exp): t = 1; while(exp > 0): # for cases where exponent # is not an even value if (exp % 2 != 0): t = (t * bas) % N; bas = (bas * bas) % N; exp = int(exp / 2); return t % N; # Driver Code bas = 5;exp = 100000; modulo = exponentiation(bas,exp);print(modulo); # This code is contributed# by mits
// C# program to compute // exponential value // using (2^k) -ary method.using System; class GFG{// prime modulo valuestatic long N = 1000000007L; static long exponentiation(long bas, long exp){ long t = 1L; while (exp > 0) { // for cases where exponent // is not an even value if (exp % 2 != 0) t = (t * bas) % N; bas = (bas * bas) % N; exp /= 2; } return t % N;} // Driver Code public static void Main (){ long bas = 5; long exp = 100000; long modulo = exponentiation(bas, exp); Console.WriteLine(modulo);}} //This code is contributed by ajit
<?php// PHP program to compute // exponential value // using (2^k) -ary method. // prime modulo value$N = 1000000007; function exponentiation($bas, $exp){ global $N; $t = 1; while ($exp > 0) { // for cases where exponent // is not an even value if ($exp % 2 != 0) $t = ($t * $bas) % $N; $bas = ($bas * $bas) % $N; $exp = (int)$exp / 2; } return $t % $N;} // Driver Code $bas = 5;$exp = 100000; $modulo = exponentiation($bas, $exp);echo ($modulo); // This code is contributed// by ajit?>
754573817
Applications:Besides fast calculation of this method have several other advantages, like it is used in cryptography, in calculating Matrix Exponentiation et cetera.
nitin mittal
jit_t
Mithun Kumar
Rajput-Ji
Modular Arithmetic
Mathematical
Technical Scripter
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
Program to print prime numbers from 1 to N.
Minimum number of jumps to reach end
|
[
{
"code": null,
"e": 25849,
"s": 25821,
"text": "\n07 Feb, 2020"
},
{
"code": null,
"e": 25928,
"s": 25849,
"text": "Given two numbers base and exp, we need to compute baseexp under Modulo 10^9+7"
},
{
"code": null,
"e": 25938,
"s": 25928,
"text": "Examples:"
},
{
"code": null,
"e": 26028,
"s": 25938,
"text": "Input : base = 2, exp = 2\nOutput : 4\n\nInput : base = 5, exp = 100000\nOutput : 754573817\n"
},
{
"code": null,
"e": 26617,
"s": 26028,
"text": "In competitions, for calculating large powers of a number we are given a modulus value(a large prime number) because as the values of is being calculated it can get very large so instead we have to calculate (%modulus value.)We can use the modulus in our naive way by using modulus on all the intermediate steps and take modulus at the end,but in competitions it will definitely show TLE. So, what we can do.The answer is we can try exponentiation by squaring which is a fast method for calculating exponentiation of a number.Here we will be discussing two most common/important methods:"
},
{
"code": null,
"e": 26665,
"s": 26617,
"text": "Basic Method(Binary Exponentiation)-ary method."
},
{
"code": null,
"e": 26701,
"s": 26665,
"text": "Basic Method(Binary Exponentiation)"
},
{
"code": null,
"e": 26714,
"s": 26701,
"text": "-ary method."
},
{
"code": null,
"e": 26736,
"s": 26714,
"text": "Binary Exponentiation"
},
{
"code": null,
"e": 26843,
"s": 26736,
"text": "As described in this article we will be using following formula to recursively calculate (%modulus value):"
},
{
"code": null,
"e": 26847,
"s": 26843,
"text": "C++"
},
{
"code": null,
"e": 26852,
"s": 26847,
"text": "Java"
},
{
"code": null,
"e": 26860,
"s": 26852,
"text": "Python3"
},
{
"code": null,
"e": 26863,
"s": 26860,
"text": "C#"
},
{
"code": null,
"e": 26867,
"s": 26863,
"text": "PHP"
},
{
"code": "// C++ program to compute exponential // value under modulo using binary // exponentiation.#include<iostream>using namespace std; #define N 1000000007 // prime modulo value long int exponentiation(long int base, long int exp){ if (exp == 0) return 1; if (exp == 1) return base % N; long int t = exponentiation(base, exp / 2); t = (t * t) % N; // if exponent is even value if (exp % 2 == 0) return t; // if exponent is odd value else return ((base % N) * t) % N;} // Driver Codeint main(){ long int base = 5; long int exp = 100000; long int modulo = exponentiation(base, exp); cout << modulo << endl; return 0;} // This Code is contributed by mits",
"e": 27618,
"s": 26867,
"text": null
},
{
"code": "// Java program to compute exponential value under modulo// using binary exponentiation.import java.util.*;import java.lang.*;import java.io.*; class exp_sq { static long N = 1000000007L; // prime modulo value public static void main(String[] args) { long base = 5; long exp = 100000; long modulo = exponentiation(base, exp); System.out.println(modulo); } static long exponentiation(long base, long exp) { if (exp == 0) return 1; if (exp == 1) return base % N; long t = exponentiation(base, exp / 2); t = (t * t) % N; // if exponent is even value if (exp % 2 == 0) return t; // if exponent is odd value else return ((base % N) * t) % N; }}",
"e": 28420,
"s": 27618,
"text": null
},
{
"code": "# Python3 program to compute # exponential value under# modulo using binary # exponentiation. # prime modulo valueN = 1000000007; # Function code def exponentiation(bas, exp): if (exp == 0): return 1; if (exp == 1): return bas % N; t = exponentiation(bas, int(exp / 2)); t = (t * t) % N; # if exponent is # even value if (exp % 2 == 0): return t; # if exponent is # odd value else: return ((bas % N) * t) % N; # Driver codebas = 5;exp = 100000; modulo = exponentiation(bas, exp);print(modulo); # This code is contributed# by mits",
"e": 29039,
"s": 28420,
"text": null
},
{
"code": "// C# program to compute exponential// value under modulo using binary // exponentiation.using System; class GFG { // prime modulo value static long N = 1000000007L; // Driver code public static void Main() { long bas = 5; long exp = 100000; long modulo = exponentiation(bas, exp); Console.Write(modulo); } static long exponentiation(long bas, long exp) { if (exp == 0) return 1; if (exp == 1) return bas % N; long t = exponentiation(bas, exp / 2); t = (t * t) % N; // if exponent is even value if (exp % 2 == 0) return t; // if exponent is odd value else return ((bas % N) * t) % N; }} // This code is contributed by nitin mittal.",
"e": 29852,
"s": 29039,
"text": null
},
{
"code": "<?php// PHP program to compute exponential// value under modulo using binary // exponentiation. // prime modulo value$N = 1000000007; // Function code function exponentiation($bas, $exp){ global $N ; if ($exp == 0) return 1; if ($exp == 1) return $bas % $N; $t = exponentiation($bas, $exp / 2); $t = ($t * $t) % $N; // if exponent is // even value if ($exp % 2 == 0) return $t; // if exponent is // odd value else return (($bas % $N) * $t) % $N;} // Driver code$bas = 5;$exp = 100000; $modulo = exponentiation($bas, $exp);echo ($modulo); // This code is contributed by ajit?>",
"e": 30546,
"s": 29852,
"text": null
},
{
"code": null,
"e": 30557,
"s": 30546,
"text": "754573817\n"
},
{
"code": null,
"e": 30570,
"s": 30557,
"text": "-ary method:"
},
{
"code": null,
"e": 30766,
"s": 30570,
"text": "In this algorithm we will be expanding the exponent in base (k>=1), which is somehow similar to above method except we are not using recursion this method uses comparatively less memory and time."
},
{
"code": null,
"e": 30770,
"s": 30766,
"text": "C++"
},
{
"code": null,
"e": 30775,
"s": 30770,
"text": "Java"
},
{
"code": null,
"e": 30783,
"s": 30775,
"text": "Python3"
},
{
"code": null,
"e": 30786,
"s": 30783,
"text": "C#"
},
{
"code": null,
"e": 30790,
"s": 30786,
"text": "PHP"
},
{
"code": "// C++ program to compute exponential value using (2^k)// -ary method.#include<bits/stdc++.h>using namespace std; #define N 1000000007L; // prime modulo value long exponentiation(long base, long exp){ long t = 1L; while (exp > 0) { // for cases where exponent // is not an even value if (exp % 2 != 0) t = (t * base) % N; base = (base * base) % N; exp /= 2; } return t % N;} // Driver codeint main(){ long base = 5; long exp = 100000; long modulo = exponentiation(base, exp); cout << (modulo); return 0;} // This code is contributed by Rajput-Ji",
"e": 31423,
"s": 30790,
"text": null
},
{
"code": "// Java program to compute exponential value using (2^k)// -ary method.import java.util.*;import java.lang.*;import java.io.*; class exp_sq { static long N = 1000000007L; // prime modulo value public static void main(String[] args) { long base = 5; long exp = 100000; long modulo = exponentiation(base, exp); System.out.println(modulo); } static long exponentiation(long base, long exp) { long t = 1L; while (exp > 0) { // for cases where exponent // is not an even value if (exp % 2 != 0) t = (t * base) % N; base = (base * base) % N; exp /= 2; } return t % N; }}",
"e": 32144,
"s": 31423,
"text": null
},
{
"code": "# Python3 program to compute # exponential value # using (2^k) -ary method. # prime modulo valueN = 1000000007; def exponentiation(bas, exp): t = 1; while(exp > 0): # for cases where exponent # is not an even value if (exp % 2 != 0): t = (t * bas) % N; bas = (bas * bas) % N; exp = int(exp / 2); return t % N; # Driver Code bas = 5;exp = 100000; modulo = exponentiation(bas,exp);print(modulo); # This code is contributed# by mits",
"e": 32640,
"s": 32144,
"text": null
},
{
"code": "// C# program to compute // exponential value // using (2^k) -ary method.using System; class GFG{// prime modulo valuestatic long N = 1000000007L; static long exponentiation(long bas, long exp){ long t = 1L; while (exp > 0) { // for cases where exponent // is not an even value if (exp % 2 != 0) t = (t * bas) % N; bas = (bas * bas) % N; exp /= 2; } return t % N;} // Driver Code public static void Main (){ long bas = 5; long exp = 100000; long modulo = exponentiation(bas, exp); Console.WriteLine(modulo);}} //This code is contributed by ajit",
"e": 33333,
"s": 32640,
"text": null
},
{
"code": "<?php// PHP program to compute // exponential value // using (2^k) -ary method. // prime modulo value$N = 1000000007; function exponentiation($bas, $exp){ global $N; $t = 1; while ($exp > 0) { // for cases where exponent // is not an even value if ($exp % 2 != 0) $t = ($t * $bas) % $N; $bas = ($bas * $bas) % $N; $exp = (int)$exp / 2; } return $t % $N;} // Driver Code $bas = 5;$exp = 100000; $modulo = exponentiation($bas, $exp);echo ($modulo); // This code is contributed// by ajit?>",
"e": 33945,
"s": 33333,
"text": null
},
{
"code": null,
"e": 33956,
"s": 33945,
"text": "754573817\n"
},
{
"code": null,
"e": 34122,
"s": 33956,
"text": "Applications:Besides fast calculation of this method have several other advantages, like it is used in cryptography, in calculating Matrix Exponentiation et cetera."
},
{
"code": null,
"e": 34135,
"s": 34122,
"text": "nitin mittal"
},
{
"code": null,
"e": 34141,
"s": 34135,
"text": "jit_t"
},
{
"code": null,
"e": 34154,
"s": 34141,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 34164,
"s": 34154,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34183,
"s": 34164,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 34196,
"s": 34183,
"text": "Mathematical"
},
{
"code": null,
"e": 34215,
"s": 34196,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34228,
"s": 34215,
"text": "Mathematical"
},
{
"code": null,
"e": 34247,
"s": 34228,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 34345,
"s": 34247,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34369,
"s": 34345,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 34412,
"s": 34369,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 34485,
"s": 34412,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 34506,
"s": 34485,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 34549,
"s": 34506,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 34583,
"s": 34549,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 34636,
"s": 34583,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 34685,
"s": 34636,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 34729,
"s": 34685,
"text": "Program to print prime numbers from 1 to N."
}
] |
How to create PDF document in Node.js ? - GeeksforGeeks
|
24 Feb, 2022
In this article, we will see how to generate PDF documents in NodeJS.
Prerequisites:
Basic knowledge of Node.js. Node.js installed (version 12+).npm installed (version 6+).
Node.js installed (version 12+).npm installed (version 6+).
Node.js installed (version 12+).
npm installed (version 6+).
Step 1: Install PDF module. The PDFkit– It is an Inbuilt Module for generating the PDF documents in the NodeJS in a very simpler and easy way in which we can make graphics, load images and also provide link of the website.
For installing it in the project write the following command on the terminal or command prompt.
npm install pdfkit
Syntax:
const PDFDocument = require('pdfkit');
const doc = new PDFDocument;
For adding new page in the PDF.
doc.addPage()
For saving PDF document in root directory.
doc.pipe(fs.createWriteStream('PDF Name'));
Step 2: Installing Module for setting NodeJS environment. Also we need to configure the package.json file.
npm install express
Filename: package.json
Javascript
{ "name": "node_func", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node app.js", "dev": "nodemon app.js" }, "author": "", "license": "ISC", "dependencies": { "fs": "^0.0.1-security", "pdfkit": "^0.11.0" }}
Folder Structure: We can see that the PDF file is created in root directory.
Folder Structure
Example: Here is the JavaScript code that should be written in app.js which is for NodeJS.
Filename: index.js
index.js
// Importing modulesimport PDFDocument from 'pdfkit'import fs from 'fs' // Create a documentconst doc = new PDFDocument(); // Saving the pdf file in root directory.doc.pipe(fs.createWriteStream('example.pdf')); // Adding functionalitydoc .fontSize(27) .text('This the article for GeeksforGeeks', 100, 100); // Adding an image in the pdf. doc.image('download3.jpg', { fit: [300, 300], align: 'center', valign: 'center' }); doc .addPage() .fontSize(15) .text('Generating PDF with the help of pdfkit', 100, 100); // Apply some transforms and render an SVG path with the // 'even-odd' fill ruledoc .scale(0.6) .translate(470, -380) .path('M 250,75 L 323,301 131,161 369,161 177,301 z') .fill('red', 'even-odd') .restore(); // Add some text with annotationsdoc .addPage() .fillColor('blue') .text('The link for GeeksforGeeks website', 100, 100) .link(100, 100, 160, 27, 'https://www.geeksforgeeks.org/'); // Finalize PDF filedoc.end();
Output: Created PDF file will look like this.
prachisoda1234
NodeJS-Questions
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
Node.js Export Module
How to connect Node.js with React.js ?
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 26337,
"s": 26267,
"text": "In this article, we will see how to generate PDF documents in NodeJS."
},
{
"code": null,
"e": 26352,
"s": 26337,
"text": "Prerequisites:"
},
{
"code": null,
"e": 26440,
"s": 26352,
"text": "Basic knowledge of Node.js. Node.js installed (version 12+).npm installed (version 6+)."
},
{
"code": null,
"e": 26500,
"s": 26440,
"text": "Node.js installed (version 12+).npm installed (version 6+)."
},
{
"code": null,
"e": 26533,
"s": 26500,
"text": "Node.js installed (version 12+)."
},
{
"code": null,
"e": 26561,
"s": 26533,
"text": "npm installed (version 6+)."
},
{
"code": null,
"e": 26784,
"s": 26561,
"text": "Step 1: Install PDF module. The PDFkit– It is an Inbuilt Module for generating the PDF documents in the NodeJS in a very simpler and easy way in which we can make graphics, load images and also provide link of the website."
},
{
"code": null,
"e": 26880,
"s": 26784,
"text": "For installing it in the project write the following command on the terminal or command prompt."
},
{
"code": null,
"e": 26899,
"s": 26880,
"text": "npm install pdfkit"
},
{
"code": null,
"e": 26907,
"s": 26899,
"text": "Syntax:"
},
{
"code": null,
"e": 26975,
"s": 26907,
"text": "const PDFDocument = require('pdfkit');\nconst doc = new PDFDocument;"
},
{
"code": null,
"e": 27007,
"s": 26975,
"text": "For adding new page in the PDF."
},
{
"code": null,
"e": 27021,
"s": 27007,
"text": "doc.addPage()"
},
{
"code": null,
"e": 27064,
"s": 27021,
"text": "For saving PDF document in root directory."
},
{
"code": null,
"e": 27108,
"s": 27064,
"text": "doc.pipe(fs.createWriteStream('PDF Name'));"
},
{
"code": null,
"e": 27215,
"s": 27108,
"text": "Step 2: Installing Module for setting NodeJS environment. Also we need to configure the package.json file."
},
{
"code": null,
"e": 27235,
"s": 27215,
"text": "npm install express"
},
{
"code": null,
"e": 27258,
"s": 27235,
"text": "Filename: package.json"
},
{
"code": null,
"e": 27269,
"s": 27258,
"text": "Javascript"
},
{
"code": "{ \"name\": \"node_func\", \"version\": \"1.0.0\", \"description\": \"\", \"main\": \"index.js\", \"scripts\": { \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\", \"start\": \"node app.js\", \"dev\": \"nodemon app.js\" }, \"author\": \"\", \"license\": \"ISC\", \"dependencies\": { \"fs\": \"^0.0.1-security\", \"pdfkit\": \"^0.11.0\" }}",
"e": 27593,
"s": 27269,
"text": null
},
{
"code": null,
"e": 27670,
"s": 27593,
"text": "Folder Structure: We can see that the PDF file is created in root directory."
},
{
"code": null,
"e": 27687,
"s": 27670,
"text": "Folder Structure"
},
{
"code": null,
"e": 27778,
"s": 27687,
"text": "Example: Here is the JavaScript code that should be written in app.js which is for NodeJS."
},
{
"code": null,
"e": 27797,
"s": 27778,
"text": "Filename: index.js"
},
{
"code": null,
"e": 27806,
"s": 27797,
"text": "index.js"
},
{
"code": "// Importing modulesimport PDFDocument from 'pdfkit'import fs from 'fs' // Create a documentconst doc = new PDFDocument(); // Saving the pdf file in root directory.doc.pipe(fs.createWriteStream('example.pdf')); // Adding functionalitydoc .fontSize(27) .text('This the article for GeeksforGeeks', 100, 100); // Adding an image in the pdf. doc.image('download3.jpg', { fit: [300, 300], align: 'center', valign: 'center' }); doc .addPage() .fontSize(15) .text('Generating PDF with the help of pdfkit', 100, 100); // Apply some transforms and render an SVG path with the // 'even-odd' fill ruledoc .scale(0.6) .translate(470, -380) .path('M 250,75 L 323,301 131,161 369,161 177,301 z') .fill('red', 'even-odd') .restore(); // Add some text with annotationsdoc .addPage() .fillColor('blue') .text('The link for GeeksforGeeks website', 100, 100) .link(100, 100, 160, 27, 'https://www.geeksforgeeks.org/'); // Finalize PDF filedoc.end();",
"e": 28789,
"s": 27806,
"text": null
},
{
"code": null,
"e": 28835,
"s": 28789,
"text": "Output: Created PDF file will look like this."
},
{
"code": null,
"e": 28850,
"s": 28835,
"text": "prachisoda1234"
},
{
"code": null,
"e": 28867,
"s": 28850,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 28875,
"s": 28867,
"text": "Node.js"
},
{
"code": null,
"e": 28892,
"s": 28875,
"text": "Web Technologies"
},
{
"code": null,
"e": 28990,
"s": 28892,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29060,
"s": 28990,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 29082,
"s": 29060,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 29121,
"s": 29082,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 29146,
"s": 29121,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 29173,
"s": 29146,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 29213,
"s": 29173,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29258,
"s": 29213,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29301,
"s": 29258,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29351,
"s": 29301,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Node.js os.freemem() Method - GeeksforGeeks
|
13 Oct, 2021
The os.freemem() method is an inbuilt application programming interface of the os module which is used to get the amount of free system memory.
Syntax:
os.freemem()
Parameters: This method does not accept any parameters.
Return Value: This method returns an integer value that specifies the amount of free system memory in bytes.
Below examples illustrate the use of os.freemem() method in Node.js:
Example 1:
// Node.js program to demonstrate the // os.freemem() method // Allocating os moduleconst os = require('os'); // Printing os.freemem() valueconsole.log(os.freemem());
Output:
4158910464
Example 2:
// Node.js program to demonstrate the // os.freemem() method // Allocating os moduleconst os = require('os'); // Printing os.freemem() valuevar free_memory = os.freemem();var free_mem_in_kb = free_memory/1024;var free_mem_in_mb = free_mem_in_kb/1024;var free_mem_in_gb = free_mem_in_mb/1024; free_mem_in_kb = Math.floor(free_mem_in_kb);free_mem_in_mb = Math.floor(free_mem_in_mb);free_mem_in_gb = Math.floor(free_mem_in_gb); free_mem_in_mb = free_mem_in_mb%1024;free_mem_in_kb = free_mem_in_kb%1024;free_memory = free_memory%1024; console.log("Free memory: " + free_mem_in_gb + "GB " + free_mem_in_mb + "MB " + free_mem_in_kb + "KB and " + free_memory + "Bytes");
Output:
Free memory: 4GB 110MB 88KB and 0Bytes
Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/os.html#os_os_freemem
Node.js-os-module
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 ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 38501,
"s": 38473,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 38645,
"s": 38501,
"text": "The os.freemem() method is an inbuilt application programming interface of the os module which is used to get the amount of free system memory."
},
{
"code": null,
"e": 38653,
"s": 38645,
"text": "Syntax:"
},
{
"code": null,
"e": 38666,
"s": 38653,
"text": "os.freemem()"
},
{
"code": null,
"e": 38722,
"s": 38666,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 38831,
"s": 38722,
"text": "Return Value: This method returns an integer value that specifies the amount of free system memory in bytes."
},
{
"code": null,
"e": 38900,
"s": 38831,
"text": "Below examples illustrate the use of os.freemem() method in Node.js:"
},
{
"code": null,
"e": 38911,
"s": 38900,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the // os.freemem() method // Allocating os moduleconst os = require('os'); // Printing os.freemem() valueconsole.log(os.freemem());",
"e": 39082,
"s": 38911,
"text": null
},
{
"code": null,
"e": 39090,
"s": 39082,
"text": "Output:"
},
{
"code": null,
"e": 39102,
"s": 39090,
"text": "4158910464\n"
},
{
"code": null,
"e": 39113,
"s": 39102,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the // os.freemem() method // Allocating os moduleconst os = require('os'); // Printing os.freemem() valuevar free_memory = os.freemem();var free_mem_in_kb = free_memory/1024;var free_mem_in_mb = free_mem_in_kb/1024;var free_mem_in_gb = free_mem_in_mb/1024; free_mem_in_kb = Math.floor(free_mem_in_kb);free_mem_in_mb = Math.floor(free_mem_in_mb);free_mem_in_gb = Math.floor(free_mem_in_gb); free_mem_in_mb = free_mem_in_mb%1024;free_mem_in_kb = free_mem_in_kb%1024;free_memory = free_memory%1024; console.log(\"Free memory: \" + free_mem_in_gb + \"GB \" + free_mem_in_mb + \"MB \" + free_mem_in_kb + \"KB and \" + free_memory + \"Bytes\");",
"e": 39796,
"s": 39113,
"text": null
},
{
"code": null,
"e": 39804,
"s": 39796,
"text": "Output:"
},
{
"code": null,
"e": 39844,
"s": 39804,
"text": "Free memory: 4GB 110MB 88KB and 0Bytes\n"
},
{
"code": null,
"e": 39925,
"s": 39844,
"text": "Note: The above program will compile and run by using the node index.js command."
},
{
"code": null,
"e": 39981,
"s": 39925,
"text": "Reference: https://nodejs.org/api/os.html#os_os_freemem"
},
{
"code": null,
"e": 39999,
"s": 39981,
"text": "Node.js-os-module"
},
{
"code": null,
"e": 40007,
"s": 39999,
"text": "Node.js"
},
{
"code": null,
"e": 40024,
"s": 40007,
"text": "Web Technologies"
},
{
"code": null,
"e": 40122,
"s": 40024,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40170,
"s": 40122,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 40203,
"s": 40170,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 40233,
"s": 40203,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 40253,
"s": 40233,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 40307,
"s": 40253,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 40347,
"s": 40307,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 40392,
"s": 40347,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 40435,
"s": 40392,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 40485,
"s": 40435,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
HTML | DOM baseURI Property - GeeksforGeeks
|
13 Aug, 2021
The DOM baseURI property is used to return the base Uniform Resource Identifier (URI) of the document. This property is used for read-only. This property returns a string value that represents the base URI of the page.Syntax:
node.baseURI
Return Value: It returns a string value which represents the URL of the node;s page.
Example:
html
<!DOCTYPE html><html> <body> <title>baseURI property</title> <style> h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>DOM baseURI Property</h2> </h2> <button onclick = "geeks()">Submit</button> <p id="gfg"></p> <script> function geeks() { var x = document.baseURI; document.getElementById("gfg").innerHTML = "The base URI of the page: " + x; } </script> </body></html>
Output:
Supported Browsers: The browser supported by DOM baseURI Property are listed below:
Google Chrome
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
HTML-DOM
CSS
HTML
Web Technologies
HTML
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?
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 set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 31624,
"s": 31596,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 31852,
"s": 31624,
"text": "The DOM baseURI property is used to return the base Uniform Resource Identifier (URI) of the document. This property is used for read-only. This property returns a string value that represents the base URI of the page.Syntax: "
},
{
"code": null,
"e": 31865,
"s": 31852,
"text": "node.baseURI"
},
{
"code": null,
"e": 31951,
"s": 31865,
"text": "Return Value: It returns a string value which represents the URL of the node;s page. "
},
{
"code": null,
"e": 31962,
"s": 31951,
"text": "Example: "
},
{
"code": null,
"e": 31967,
"s": 31962,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body> <title>baseURI property</title> <style> h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>DOM baseURI Property</h2> </h2> <button onclick = \"geeks()\">Submit</button> <p id=\"gfg\"></p> <script> function geeks() { var x = document.baseURI; document.getElementById(\"gfg\").innerHTML = \"The base URI of the page: \" + x; } </script> </body></html> ",
"e": 32634,
"s": 31967,
"text": null
},
{
"code": null,
"e": 32644,
"s": 32634,
"text": "Output: "
},
{
"code": null,
"e": 32731,
"s": 32644,
"text": "Supported Browsers: The browser supported by DOM baseURI Property are listed below: "
},
{
"code": null,
"e": 32745,
"s": 32731,
"text": "Google Chrome"
},
{
"code": null,
"e": 32753,
"s": 32745,
"text": "Firefox"
},
{
"code": null,
"e": 32759,
"s": 32753,
"text": "Opera"
},
{
"code": null,
"e": 32766,
"s": 32759,
"text": "Safari"
},
{
"code": null,
"e": 32905,
"s": 32768,
"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": 32925,
"s": 32905,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 32934,
"s": 32925,
"text": "HTML-DOM"
},
{
"code": null,
"e": 32938,
"s": 32934,
"text": "CSS"
},
{
"code": null,
"e": 32943,
"s": 32938,
"text": "HTML"
},
{
"code": null,
"e": 32960,
"s": 32943,
"text": "Web Technologies"
},
{
"code": null,
"e": 32965,
"s": 32960,
"text": "HTML"
},
{
"code": null,
"e": 33063,
"s": 32965,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33113,
"s": 33063,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 33175,
"s": 33113,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 33223,
"s": 33175,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 33281,
"s": 33223,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 33336,
"s": 33281,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 33386,
"s": 33336,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 33448,
"s": 33386,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 33496,
"s": 33448,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 33556,
"s": 33496,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Python calendar module : monthdatescalendar() method - GeeksforGeeks
|
05 Jul, 2021
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions.
monthdatescalendar() method in Python is used to get a list of the weeks in the month of the year as full weeks.
Syntax: monthdatescalendar(year, month)
Parameter:
year: year of the calendar
month: month of the calendar
Returns: a list of the weeks in the month.
Code #1:
Python3
# Python program to demonstrate working# of monthdatescalendar() method # importing calendar moduleimport calendar obj = calendar.Calendar() year = 2018month = 9 # printing with monthdatescalendarprint(obj.monthdatescalendar(year, month))
Output:
[[datetime.date(2018, 8, 27), datetime.date(2018, 8, 28), datetime.date(2018, 8, 29), datetime.date(2018, 8, 30), datetime.date(2018, 8, 31), datetime.date(2018, 9, 1), datetime.date(2018, 9, 2)], [datetime.date(2018, 9, 3), datetime.date(2018, 9, 4), datetime.date(2018, 9, 5), datetime.date(2018, 9, 6), datetime.date(2018, 9, 7), datetime.date(2018, 9, 8), datetime.date(2018, 9, 9)], [datetime.date(2018, 9, 10), datetime.date(2018, 9, 11), datetime.date(2018, 9, 12), datetime.date(2018, 9, 13), datetime.date(2018, 9, 14), datetime.date(2018, 9, 15), datetime.date(2018, 9, 16)], [datetime.date(2018, 9, 17), datetime.date(2018, 9, 18), datetime.date(2018, 9, 19), datetime.date(2018, 9, 20), datetime.date(2018, 9, 21), datetime.date(2018, 9, 22), datetime.date(2018, 9, 23)], [datetime.date(2018, 9, 24), datetime.date(2018, 9, 25), datetime.date(2018, 9, 26), datetime.date(2018, 9, 27), datetime.date(2018, 9, 28), datetime.date(2018, 9, 29), datetime.date(2018, 9, 30)]]
Note that weeks in the output are lists of seven datetime.date objects. Code #2: iterating the list of weeks
Python3
# Python program to demonstrate working# of monthdatescalendar() method # importing calendar moduleimport calendar obj = calendar.Calendar() # iterating with monthdatescalendarfor day in obj.monthdatescalendar(2018, 9): print(day)
Output:
[datetime.date(2018, 8, 27), datetime.date(2018, 8, 28), datetime.date(2018, 8, 29), datetime.date(2018, 8, 30), datetime.date(2018, 8, 31), datetime.date(2018, 9, 1), datetime.date(2018, 9, 2)] [datetime.date(2018, 9, 3), datetime.date(2018, 9, 4), datetime.date(2018, 9, 5), datetime.date(2018, 9, 6), datetime.date(2018, 9, 7), datetime.date(2018, 9, 8), datetime.date(2018, 9, 9)] [datetime.date(2018, 9, 10), datetime.date(2018, 9, 11), datetime.date(2018, 9, 12), datetime.date(2018, 9, 13), datetime.date(2018, 9, 14), datetime.date(2018, 9, 15), datetime.date(2018, 9, 16)] [datetime.date(2018, 9, 17), datetime.date(2018, 9, 18), datetime.date(2018, 9, 19), datetime.date(2018, 9, 20), datetime.date(2018, 9, 21), datetime.date(2018, 9, 22), datetime.date(2018, 9, 23)] [datetime.date(2018, 9, 24), datetime.date(2018, 9, 25), datetime.date(2018, 9, 26), datetime.date(2018, 9, 27), datetime.date(2018, 9, 28), datetime.date(2018, 9, 29), datetime.date(2018, 9, 30)]
anikakapoor
Python Calander-module
python-modules
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 25810,
"s": 25537,
"text": "Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. "
},
{
"code": null,
"e": 25923,
"s": 25810,
"text": "monthdatescalendar() method in Python is used to get a list of the weeks in the month of the year as full weeks."
},
{
"code": null,
"e": 26076,
"s": 25923,
"text": "Syntax: monthdatescalendar(year, month)\n\nParameter: \nyear: year of the calendar\nmonth: month of the calendar\n\nReturns: a list of the weeks in the month."
},
{
"code": null,
"e": 26086,
"s": 26076,
"text": "Code #1: "
},
{
"code": null,
"e": 26094,
"s": 26086,
"text": "Python3"
},
{
"code": "# Python program to demonstrate working# of monthdatescalendar() method # importing calendar moduleimport calendar obj = calendar.Calendar() year = 2018month = 9 # printing with monthdatescalendarprint(obj.monthdatescalendar(year, month))",
"e": 26333,
"s": 26094,
"text": null
},
{
"code": null,
"e": 26342,
"s": 26333,
"text": "Output: "
},
{
"code": null,
"e": 27324,
"s": 26342,
"text": "[[datetime.date(2018, 8, 27), datetime.date(2018, 8, 28), datetime.date(2018, 8, 29), datetime.date(2018, 8, 30), datetime.date(2018, 8, 31), datetime.date(2018, 9, 1), datetime.date(2018, 9, 2)], [datetime.date(2018, 9, 3), datetime.date(2018, 9, 4), datetime.date(2018, 9, 5), datetime.date(2018, 9, 6), datetime.date(2018, 9, 7), datetime.date(2018, 9, 8), datetime.date(2018, 9, 9)], [datetime.date(2018, 9, 10), datetime.date(2018, 9, 11), datetime.date(2018, 9, 12), datetime.date(2018, 9, 13), datetime.date(2018, 9, 14), datetime.date(2018, 9, 15), datetime.date(2018, 9, 16)], [datetime.date(2018, 9, 17), datetime.date(2018, 9, 18), datetime.date(2018, 9, 19), datetime.date(2018, 9, 20), datetime.date(2018, 9, 21), datetime.date(2018, 9, 22), datetime.date(2018, 9, 23)], [datetime.date(2018, 9, 24), datetime.date(2018, 9, 25), datetime.date(2018, 9, 26), datetime.date(2018, 9, 27), datetime.date(2018, 9, 28), datetime.date(2018, 9, 29), datetime.date(2018, 9, 30)]]"
},
{
"code": null,
"e": 27435,
"s": 27324,
"text": "Note that weeks in the output are lists of seven datetime.date objects. Code #2: iterating the list of weeks "
},
{
"code": null,
"e": 27443,
"s": 27435,
"text": "Python3"
},
{
"code": "# Python program to demonstrate working# of monthdatescalendar() method # importing calendar moduleimport calendar obj = calendar.Calendar() # iterating with monthdatescalendarfor day in obj.monthdatescalendar(2018, 9): print(day)",
"e": 27677,
"s": 27443,
"text": null
},
{
"code": null,
"e": 27685,
"s": 27677,
"text": "Output:"
},
{
"code": null,
"e": 28661,
"s": 27685,
"text": "[datetime.date(2018, 8, 27), datetime.date(2018, 8, 28), datetime.date(2018, 8, 29), datetime.date(2018, 8, 30), datetime.date(2018, 8, 31), datetime.date(2018, 9, 1), datetime.date(2018, 9, 2)] [datetime.date(2018, 9, 3), datetime.date(2018, 9, 4), datetime.date(2018, 9, 5), datetime.date(2018, 9, 6), datetime.date(2018, 9, 7), datetime.date(2018, 9, 8), datetime.date(2018, 9, 9)] [datetime.date(2018, 9, 10), datetime.date(2018, 9, 11), datetime.date(2018, 9, 12), datetime.date(2018, 9, 13), datetime.date(2018, 9, 14), datetime.date(2018, 9, 15), datetime.date(2018, 9, 16)] [datetime.date(2018, 9, 17), datetime.date(2018, 9, 18), datetime.date(2018, 9, 19), datetime.date(2018, 9, 20), datetime.date(2018, 9, 21), datetime.date(2018, 9, 22), datetime.date(2018, 9, 23)] [datetime.date(2018, 9, 24), datetime.date(2018, 9, 25), datetime.date(2018, 9, 26), datetime.date(2018, 9, 27), datetime.date(2018, 9, 28), datetime.date(2018, 9, 29), datetime.date(2018, 9, 30)]"
},
{
"code": null,
"e": 28675,
"s": 28663,
"text": "anikakapoor"
},
{
"code": null,
"e": 28698,
"s": 28675,
"text": "Python Calander-module"
},
{
"code": null,
"e": 28713,
"s": 28698,
"text": "python-modules"
},
{
"code": null,
"e": 28720,
"s": 28713,
"text": "Python"
},
{
"code": null,
"e": 28818,
"s": 28720,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28850,
"s": 28818,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28892,
"s": 28850,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28934,
"s": 28892,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28961,
"s": 28934,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29017,
"s": 28961,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29039,
"s": 29017,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29078,
"s": 29039,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29109,
"s": 29078,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29138,
"s": 29109,
"text": "Create a directory in Python"
}
] |
Difference between Traditional and Agile Software Development - GeeksforGeeks
|
03 Oct, 2019
Traditional Software Development:Traditional software development is the software development process used to design and develop the simple software. It is basically used when the security and many other factors of the software are not much important. It is used by freshers in order to develop the software.It consists of five phases:
1. Requirements analysis
2. Design
3. Implementation
4. Coding and Testing
5. Maintenance
Agile Software Development:Agile software development is the software development process used to design complicated software. It is basically used when the software is quite sensitive and complicated. It is used when security is much important. It is used by professionals in order to develop the software.It consists of three phases:
1. Project initiation
2. Sprint planning
3. Demos
Difference between Traditional and Agile Software Development:
Difference Between
Software Engineering
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 IPv4 and IPv6
Difference Between Method Overloading and Method Overriding in Java
Stack vs Heap Memory Allocation
Differences between JDK, JRE and JVM
Types of Software Testing
Software Engineering | COCOMO Model
Software Engineering | Classical Waterfall Model
Differences between Verification and Validation
Software Testing | Basics
|
[
{
"code": null,
"e": 26327,
"s": 26299,
"text": "\n03 Oct, 2019"
},
{
"code": null,
"e": 26663,
"s": 26327,
"text": "Traditional Software Development:Traditional software development is the software development process used to design and develop the simple software. It is basically used when the security and many other factors of the software are not much important. It is used by freshers in order to develop the software.It consists of five phases:"
},
{
"code": null,
"e": 26754,
"s": 26663,
"text": "1. Requirements analysis\n2. Design\n3. Implementation\n4. Coding and Testing\n5. Maintenance "
},
{
"code": null,
"e": 27090,
"s": 26754,
"text": "Agile Software Development:Agile software development is the software development process used to design complicated software. It is basically used when the software is quite sensitive and complicated. It is used when security is much important. It is used by professionals in order to develop the software.It consists of three phases:"
},
{
"code": null,
"e": 27141,
"s": 27090,
"text": "1. Project initiation\n2. Sprint planning\n3. Demos "
},
{
"code": null,
"e": 27204,
"s": 27141,
"text": "Difference between Traditional and Agile Software Development:"
},
{
"code": null,
"e": 27223,
"s": 27204,
"text": "Difference Between"
},
{
"code": null,
"e": 27244,
"s": 27223,
"text": "Software Engineering"
},
{
"code": null,
"e": 27342,
"s": 27244,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27403,
"s": 27342,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27437,
"s": 27403,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 27505,
"s": 27437,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 27537,
"s": 27505,
"text": "Stack vs Heap Memory Allocation"
},
{
"code": null,
"e": 27574,
"s": 27537,
"text": "Differences between JDK, JRE and JVM"
},
{
"code": null,
"e": 27600,
"s": 27574,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 27636,
"s": 27600,
"text": "Software Engineering | COCOMO Model"
},
{
"code": null,
"e": 27685,
"s": 27636,
"text": "Software Engineering | Classical Waterfall Model"
},
{
"code": null,
"e": 27733,
"s": 27685,
"text": "Differences between Verification and Validation"
}
] |
How to access cache data in Node.js ? - GeeksforGeeks
|
15 Mar, 2021
Cache: Caching is a technique used for improving the performance of servers and a lot of devices used in day-to-day life.In caching, the result of certain computation or task is stored somewhere, and if the same computation is required again, it is served from that location itself rather than doing the computation again. This reduces computation and improves performance, thereby providing a better user experience.A lot of apps cache data for the first time they’re fired, hence are able to efficiently provide responses. Similarly, the majority of servers have advanced cached mechanisms for endpoints that serve the same response for the majority of the time.
Cache can be stored using various techniques like in-memory cache, file cache or a separate cache database.This article demonstrates usage of caching in Node.js using package node-cache which is an in-memory caching module.
Implementing cache demo using node-cache.
Create basic node js server. Building simple nodejs REST API using express
Ensure that node is installed, by following command:
node -v
Navigate to desired project directory and Install express (for creating server) and node-cache npm packages using the following command:
npm i express node-cache
Project structure:
Example: Create a file server.js in the directory with following code:
server.js
// Importing express moduleconst express = require('express') // Creating an express objectconst app = express() // Starting server using listen function on port 8000app.listen(8000, err => { if(err) console.log("Error while starting server") else console.log("Server has been started at port 8000")}) app.get('/', (req, res)=>{ res.send('Home page !')})
Run the following command:
node server.js
Output: Open the link: http://localhost:8000/ in desired browser to verify
Home Page
Create a simple API that performs a costly operation to serve response (To simulate an external API / Database query).
Add following code at the end of server.js
server.js
function heavyComputation(){ let temp = 0; for(let i=0; i<100000; i++) temp = (Math.random()*5342)%i; return 123;} app.get('/api', (req, res)=>{ let result = heavyComputation(); res.send("Result: "+result);})
Stop server by Ctrl+C and start again by node server.js. In the browser, open Network tab in Chrome Dev Tools and check time required to get response.
Implement node-cache: Import Node-cache npm module and create a new NodeCache object
const NodeCache = require( "node-cache" );
const myCache = new NodeCache();
Node-cache has following major functions:
.set(key, val, [ ttl ]): Used to set some value corresponding to a particular key in the cache. This same key must be used to retrieve this value.
.get(key):Used to get value set to specified key. It returns undefined, if the key is not already present.
has(key): Used to check if the cache already has some value set for specified key. Returns true if present otherwise false.
Implement caching with following approach:
On API request, check if the cache has key already set using has(key) function
If the cache has the key, retrieve the cached value by get(key) function and use it instead of performing operation again. (This saves time)
If the cache doesn’t have a key, perform the operations required, and before sending the response, set the value for that key so that further requests can be responded to directly through cached data.
Final code in server.js:
server.js
// Importing express moduleconst express = require('express') // Importing NodeCache and creating a // new object called myCacheconst NodeCache = require('node-cache')const myCache = new NodeCache() // Creating an express objectconst app = express() // Starting server using listen// function on port 8000app.listen(8000, err => { if(err) console.log("Error while starting server") else console.log( "Server has been started at port 8000")}) app.get('/', (req, res)=>{ res.send('Home page !')}) // Function to demonstrate heavy computation// like API requests, database queries, etc.function heavyComputation(){ let temp = 0; for(let i=0; i<100000; i++) temp = (Math.random()*5342)%i; return 123;} app.get('/api', (req, res)=>{ // If cache has key, retrieve value // from cache itself if(myCache.has('uniqueKey')){ console.log('Retrieved value from cache !!') // Serve response from cache using // myCache.get(key) res.send("Result: " + myCache.get('uniqueKey')) }else{ // Perform operation, since cache // doesn't have key let result = heavyComputation() // Set value for same key, in order to // serve future requests efficiently myCache.set('uniqueKey', result) console.log('Value not present in cache,' + ' performing computation') res.send("Result: " + result) }})
Stop server by Ctrl+C and start again by node server.js.
Reload the webpage once. This time computation is performed. It can be seen on console also
Reload the webpage again. This time data is served from cache as seen on console.
Further reloads will serve data from cache, thereby saving computations.
Note: The difference between response time is not significant here, since the computation is very less, however for large and scaled projects, it provides a massive performance boost. For example, GeeksforGeeks also uses advanced caching mechanisms for various purposes to achieve efficiency.
Node.js-Methods
NodeJS-Questions
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect Node.js with React.js ?
Difference between dependencies, devDependencies and peerDependencies
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26293,
"s": 26265,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 26958,
"s": 26293,
"text": "Cache: Caching is a technique used for improving the performance of servers and a lot of devices used in day-to-day life.In caching, the result of certain computation or task is stored somewhere, and if the same computation is required again, it is served from that location itself rather than doing the computation again. This reduces computation and improves performance, thereby providing a better user experience.A lot of apps cache data for the first time they’re fired, hence are able to efficiently provide responses. Similarly, the majority of servers have advanced cached mechanisms for endpoints that serve the same response for the majority of the time."
},
{
"code": null,
"e": 27182,
"s": 26958,
"text": "Cache can be stored using various techniques like in-memory cache, file cache or a separate cache database.This article demonstrates usage of caching in Node.js using package node-cache which is an in-memory caching module."
},
{
"code": null,
"e": 27224,
"s": 27182,
"text": "Implementing cache demo using node-cache."
},
{
"code": null,
"e": 27299,
"s": 27224,
"text": "Create basic node js server. Building simple nodejs REST API using express"
},
{
"code": null,
"e": 27352,
"s": 27299,
"text": "Ensure that node is installed, by following command:"
},
{
"code": null,
"e": 27360,
"s": 27352,
"text": "node -v"
},
{
"code": null,
"e": 27497,
"s": 27360,
"text": "Navigate to desired project directory and Install express (for creating server) and node-cache npm packages using the following command:"
},
{
"code": null,
"e": 27522,
"s": 27497,
"text": "npm i express node-cache"
},
{
"code": null,
"e": 27541,
"s": 27522,
"text": "Project structure:"
},
{
"code": null,
"e": 27612,
"s": 27541,
"text": "Example: Create a file server.js in the directory with following code:"
},
{
"code": null,
"e": 27622,
"s": 27612,
"text": "server.js"
},
{
"code": "// Importing express moduleconst express = require('express') // Creating an express objectconst app = express() // Starting server using listen function on port 8000app.listen(8000, err => { if(err) console.log(\"Error while starting server\") else console.log(\"Server has been started at port 8000\")}) app.get('/', (req, res)=>{ res.send('Home page !')})",
"e": 28007,
"s": 27622,
"text": null
},
{
"code": null,
"e": 28034,
"s": 28007,
"text": "Run the following command:"
},
{
"code": null,
"e": 28049,
"s": 28034,
"text": "node server.js"
},
{
"code": null,
"e": 28124,
"s": 28049,
"text": "Output: Open the link: http://localhost:8000/ in desired browser to verify"
},
{
"code": null,
"e": 28134,
"s": 28124,
"text": "Home Page"
},
{
"code": null,
"e": 28253,
"s": 28134,
"text": "Create a simple API that performs a costly operation to serve response (To simulate an external API / Database query)."
},
{
"code": null,
"e": 28296,
"s": 28253,
"text": "Add following code at the end of server.js"
},
{
"code": null,
"e": 28306,
"s": 28296,
"text": "server.js"
},
{
"code": "function heavyComputation(){ let temp = 0; for(let i=0; i<100000; i++) temp = (Math.random()*5342)%i; return 123;} app.get('/api', (req, res)=>{ let result = heavyComputation(); res.send(\"Result: \"+result);})",
"e": 28546,
"s": 28306,
"text": null
},
{
"code": null,
"e": 28697,
"s": 28546,
"text": "Stop server by Ctrl+C and start again by node server.js. In the browser, open Network tab in Chrome Dev Tools and check time required to get response."
},
{
"code": null,
"e": 28782,
"s": 28697,
"text": "Implement node-cache: Import Node-cache npm module and create a new NodeCache object"
},
{
"code": null,
"e": 28858,
"s": 28782,
"text": "const NodeCache = require( \"node-cache\" );\nconst myCache = new NodeCache();"
},
{
"code": null,
"e": 28900,
"s": 28858,
"text": "Node-cache has following major functions:"
},
{
"code": null,
"e": 29047,
"s": 28900,
"text": ".set(key, val, [ ttl ]): Used to set some value corresponding to a particular key in the cache. This same key must be used to retrieve this value."
},
{
"code": null,
"e": 29154,
"s": 29047,
"text": ".get(key):Used to get value set to specified key. It returns undefined, if the key is not already present."
},
{
"code": null,
"e": 29278,
"s": 29154,
"text": "has(key): Used to check if the cache already has some value set for specified key. Returns true if present otherwise false."
},
{
"code": null,
"e": 29321,
"s": 29278,
"text": "Implement caching with following approach:"
},
{
"code": null,
"e": 29400,
"s": 29321,
"text": "On API request, check if the cache has key already set using has(key) function"
},
{
"code": null,
"e": 29541,
"s": 29400,
"text": "If the cache has the key, retrieve the cached value by get(key) function and use it instead of performing operation again. (This saves time)"
},
{
"code": null,
"e": 29742,
"s": 29541,
"text": "If the cache doesn’t have a key, perform the operations required, and before sending the response, set the value for that key so that further requests can be responded to directly through cached data."
},
{
"code": null,
"e": 29767,
"s": 29742,
"text": "Final code in server.js:"
},
{
"code": null,
"e": 29777,
"s": 29767,
"text": "server.js"
},
{
"code": "// Importing express moduleconst express = require('express') // Importing NodeCache and creating a // new object called myCacheconst NodeCache = require('node-cache')const myCache = new NodeCache() // Creating an express objectconst app = express() // Starting server using listen// function on port 8000app.listen(8000, err => { if(err) console.log(\"Error while starting server\") else console.log( \"Server has been started at port 8000\")}) app.get('/', (req, res)=>{ res.send('Home page !')}) // Function to demonstrate heavy computation// like API requests, database queries, etc.function heavyComputation(){ let temp = 0; for(let i=0; i<100000; i++) temp = (Math.random()*5342)%i; return 123;} app.get('/api', (req, res)=>{ // If cache has key, retrieve value // from cache itself if(myCache.has('uniqueKey')){ console.log('Retrieved value from cache !!') // Serve response from cache using // myCache.get(key) res.send(\"Result: \" + myCache.get('uniqueKey')) }else{ // Perform operation, since cache // doesn't have key let result = heavyComputation() // Set value for same key, in order to // serve future requests efficiently myCache.set('uniqueKey', result) console.log('Value not present in cache,' + ' performing computation') res.send(\"Result: \" + result) }})",
"e": 31298,
"s": 29777,
"text": null
},
{
"code": null,
"e": 31355,
"s": 31298,
"text": "Stop server by Ctrl+C and start again by node server.js."
},
{
"code": null,
"e": 31447,
"s": 31355,
"text": "Reload the webpage once. This time computation is performed. It can be seen on console also"
},
{
"code": null,
"e": 31529,
"s": 31447,
"text": "Reload the webpage again. This time data is served from cache as seen on console."
},
{
"code": null,
"e": 31602,
"s": 31529,
"text": "Further reloads will serve data from cache, thereby saving computations."
},
{
"code": null,
"e": 31897,
"s": 31602,
"text": "Note: The difference between response time is not significant here, since the computation is very less, however for large and scaled projects, it provides a massive performance boost. For example, GeeksforGeeks also uses advanced caching mechanisms for various purposes to achieve efficiency. "
},
{
"code": null,
"e": 31913,
"s": 31897,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 31930,
"s": 31913,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 31954,
"s": 31930,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31962,
"s": 31954,
"text": "Node.js"
},
{
"code": null,
"e": 31981,
"s": 31962,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31998,
"s": 31981,
"text": "Web Technologies"
},
{
"code": null,
"e": 32096,
"s": 31998,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32135,
"s": 32096,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 32205,
"s": 32135,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 32227,
"s": 32205,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 32254,
"s": 32227,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 32279,
"s": 32254,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 32319,
"s": 32279,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32364,
"s": 32319,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32407,
"s": 32364,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32457,
"s": 32407,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Difference between ServletConfig and ServletContext in Java Servlet - GeeksforGeeks
|
20 Aug, 2019
ServletConfig and ServletContext, both are objects created at the time of servlet initialization and used to provide some initial parameters or configuration information to the servlet. But, the difference lies in the fact that information shared by ServletConfig is for a specific servlet, while information shared by ServletContext is available for all servlets in the web application.
ServletConfig:
ServletConfig is an object containing some initial parameters or configuration information created by Servlet Container and passed to the servlet during initialization.
ServletConfig is for a particular servlet, that means one should store servlet specific information in web.xml and retrieve them using this object.
Example:Suppose, one is building a job portal and desires to share different email ids (which may get change over time) to recruiter and job applicant.So, he decides to write two servlets one for handling recruiter’s request and another one for the job applicant.Where to store email-ids?Put email-id as a name-value pair for different servlet inside web.xml which can further be retrieved using getServletConfig().getInitParameter(“name”) in the servlet.
ServletContext:
ServletContext is the object created by Servlet Container to share initial parameters or configuration information to the whole application.
Example:Suppose, the name of one’s job portal is “NewWebsite.tg”. Showing the website name at the top of webpages delivered by different servlets, one needs to store the website name in every servlet inviting redundancy. Since the information shared by ServletContext can be accessed by every Servlet, it is better to go with ServletContext and retrieve the website name using getServletContext.getInitParameter(“Name”) whenever required.
Implementation of examples of ServletConfig and ServletContext is shown below.
web.xml
Servlet for recruiter
Servlet for applicant
<web-app> <servlet> <servlet-name>recruiter</servlet-name> <servlet-class>Recruiter</servlet-class> <init-param> <param-name>Email</param-name> <param-value>forRecruiter@xyz.com</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>recruiter</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>applicant</servlet-name> <servlet-class>Applicant</servlet-class> <init-param> <param-name>Email</param-name> <param-value>forApplicant@xyz.com</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>applicant</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> <context-param> <param-name>Website-name</param-name> <param-value>NewWebsite.tg</param-value> </context-param> </web-app>
import java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class Recruiter extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = getServletConfig() .getInitParameter("Email"); String website = getServletContext() .getInitParameter("Website-name"); PrintWriter out = response.getWriter(); out.println("<center><h1>" + website + "</h1></center><br><p>Contact us:" + email); }}
import java.io.*;import javax.servlet.ServletException;import javax.servlet.http.*; public class Applicant extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = getServletConfig() .getInitParameter("Email"); String website = getServletContext() .getInitParameter("Website-name"); PrintWriter out = response.getWriter(); out.println("<center><h1>" + website + "</h1></center><br><p>Contact us:" + email); }}
Output: Deploy the app and open urls on localhost:/servlet1:/servlet2:
/servlet1:/servlet2:
/servlet1:
/servlet2:
As shown above, different servlets get different email-id with same parameter name “Email” because of different values attached to it in the web.xml.Each servlet has got their own <init-param> inside <servlet> containing email-id.
Both servlets got the access of ServletContext parameter “Website-name”.Since, <context-param> is outside of <servlet> in web.xml, hence it is independent of servlet and accessible from whole app.
Below is the table of comparison between the two:
java-servlet
Difference Between
Java
Java
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 IPv4 and IPv6
Difference Between Method Overloading and Method Overriding in Java
Difference between Process and Thread
Difference between Clustered and Non-clustered index
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
|
[
{
"code": null,
"e": 26017,
"s": 25989,
"text": "\n20 Aug, 2019"
},
{
"code": null,
"e": 26405,
"s": 26017,
"text": "ServletConfig and ServletContext, both are objects created at the time of servlet initialization and used to provide some initial parameters or configuration information to the servlet. But, the difference lies in the fact that information shared by ServletConfig is for a specific servlet, while information shared by ServletContext is available for all servlets in the web application."
},
{
"code": null,
"e": 26420,
"s": 26405,
"text": "ServletConfig:"
},
{
"code": null,
"e": 26589,
"s": 26420,
"text": "ServletConfig is an object containing some initial parameters or configuration information created by Servlet Container and passed to the servlet during initialization."
},
{
"code": null,
"e": 26737,
"s": 26589,
"text": "ServletConfig is for a particular servlet, that means one should store servlet specific information in web.xml and retrieve them using this object."
},
{
"code": null,
"e": 27193,
"s": 26737,
"text": "Example:Suppose, one is building a job portal and desires to share different email ids (which may get change over time) to recruiter and job applicant.So, he decides to write two servlets one for handling recruiter’s request and another one for the job applicant.Where to store email-ids?Put email-id as a name-value pair for different servlet inside web.xml which can further be retrieved using getServletConfig().getInitParameter(“name”) in the servlet."
},
{
"code": null,
"e": 27209,
"s": 27193,
"text": "ServletContext:"
},
{
"code": null,
"e": 27350,
"s": 27209,
"text": "ServletContext is the object created by Servlet Container to share initial parameters or configuration information to the whole application."
},
{
"code": null,
"e": 27789,
"s": 27350,
"text": "Example:Suppose, the name of one’s job portal is “NewWebsite.tg”. Showing the website name at the top of webpages delivered by different servlets, one needs to store the website name in every servlet inviting redundancy. Since the information shared by ServletContext can be accessed by every Servlet, it is better to go with ServletContext and retrieve the website name using getServletContext.getInitParameter(“Name”) whenever required."
},
{
"code": null,
"e": 27868,
"s": 27789,
"text": "Implementation of examples of ServletConfig and ServletContext is shown below."
},
{
"code": null,
"e": 27876,
"s": 27868,
"text": "web.xml"
},
{
"code": null,
"e": 27898,
"s": 27876,
"text": "Servlet for recruiter"
},
{
"code": null,
"e": 27920,
"s": 27898,
"text": "Servlet for applicant"
},
{
"code": "<web-app> <servlet> <servlet-name>recruiter</servlet-name> <servlet-class>Recruiter</servlet-class> <init-param> <param-name>Email</param-name> <param-value>forRecruiter@xyz.com</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>recruiter</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>applicant</servlet-name> <servlet-class>Applicant</servlet-class> <init-param> <param-name>Email</param-name> <param-value>forApplicant@xyz.com</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>applicant</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> <context-param> <param-name>Website-name</param-name> <param-value>NewWebsite.tg</param-value> </context-param> </web-app>",
"e": 28774,
"s": 27920,
"text": null
},
{
"code": "import java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class Recruiter extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = getServletConfig() .getInitParameter(\"Email\"); String website = getServletContext() .getInitParameter(\"Website-name\"); PrintWriter out = response.getWriter(); out.println(\"<center><h1>\" + website + \"</h1></center><br><p>Contact us:\" + email); }}",
"e": 29432,
"s": 28774,
"text": null
},
{
"code": "import java.io.*;import javax.servlet.ServletException;import javax.servlet.http.*; public class Applicant extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = getServletConfig() .getInitParameter(\"Email\"); String website = getServletContext() .getInitParameter(\"Website-name\"); PrintWriter out = response.getWriter(); out.println(\"<center><h1>\" + website + \"</h1></center><br><p>Contact us:\" + email); }}",
"e": 30107,
"s": 29432,
"text": null
},
{
"code": null,
"e": 30178,
"s": 30107,
"text": "Output: Deploy the app and open urls on localhost:/servlet1:/servlet2:"
},
{
"code": null,
"e": 30199,
"s": 30178,
"text": "/servlet1:/servlet2:"
},
{
"code": null,
"e": 30210,
"s": 30199,
"text": "/servlet1:"
},
{
"code": null,
"e": 30221,
"s": 30210,
"text": "/servlet2:"
},
{
"code": null,
"e": 30452,
"s": 30221,
"text": "As shown above, different servlets get different email-id with same parameter name “Email” because of different values attached to it in the web.xml.Each servlet has got their own <init-param> inside <servlet> containing email-id."
},
{
"code": null,
"e": 30649,
"s": 30452,
"text": "Both servlets got the access of ServletContext parameter “Website-name”.Since, <context-param> is outside of <servlet> in web.xml, hence it is independent of servlet and accessible from whole app."
},
{
"code": null,
"e": 30699,
"s": 30649,
"text": "Below is the table of comparison between the two:"
},
{
"code": null,
"e": 30712,
"s": 30699,
"text": "java-servlet"
},
{
"code": null,
"e": 30731,
"s": 30712,
"text": "Difference Between"
},
{
"code": null,
"e": 30736,
"s": 30731,
"text": "Java"
},
{
"code": null,
"e": 30741,
"s": 30736,
"text": "Java"
},
{
"code": null,
"e": 30839,
"s": 30741,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30900,
"s": 30839,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30934,
"s": 30900,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 31002,
"s": 30934,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 31040,
"s": 31002,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 31093,
"s": 31040,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 31108,
"s": 31093,
"text": "Arrays in Java"
},
{
"code": null,
"e": 31152,
"s": 31108,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 31174,
"s": 31152,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 31225,
"s": 31174,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
How to add custom google search bar inside your web-page? - GeeksforGeeks
|
28 May, 2020
A search bar is necessary for a good website. Creating your own search engine from scratch might be a difficult task but this task can be skipped with the help of Google. Google has created a website to create a custom search bar, to create your own check the below link.
https://programmablesearchengine.google.com/about/.
https://programmablesearchengine.google.com/about/
.
Creating a Custom Search Bar: On this website, anyone can easily program their search bar by just selecting the sites you want to be searched for. Follow the steps explained below.
Step 1: Go to the following site and hit Get Started button.
Step 2: Select the New search engine button to create a new search engine.
Step 3: Fill the details as directed on the page and then click the create button.
Step 4: After hitting create you will get your code by hitting the Get Code button on the screen shown.
Note: You can modify your setting about searching sites, searching images, safe search from control panel and you can also set to show advertisement while searching through your search bar.
Embedding the Search Bar on a Webpage: After getting your code you can simply paste it inside your web page to see the working search bar.
Example: You can see that the output screen has a search bar with an option to search which shows the result from the sites or domain you have selected while creating this search bar. Moreover, this search option will automatically change as you change the sites from the control panel. Currently, the search results are been shown in the default manner. Apart from that, you can manipulate the result displaying manner and much more as directed on the below linkshttps://developers.google.com/custom-search/docs/element.HTMLHTML<!DOCTYPE html><html> <head> <title>Custom Search-Bar</title> <style> body { background-image: linear-gradient(to left, white, green); color: lawngreen; } </style> </head> <body> <h1 style="text-align: center;">GeeksforGeeks</h1> <script async src="https://cse.google.com/cse.js?cx=007019498718139788174:amtiepdpgeg"> </script> <div class="gcse-search"></div> </body></html>
https://developers.google.com/custom-search/docs/element
.
HTML
<!DOCTYPE html><html> <head> <title>Custom Search-Bar</title> <style> body { background-image: linear-gradient(to left, white, green); color: lawngreen; } </style> </head> <body> <h1 style="text-align: center;">GeeksforGeeks</h1> <script async src="https://cse.google.com/cse.js?cx=007019498718139788174:amtiepdpgeg"> </script> <div class="gcse-search"></div> </body></html>
Output:
HTML-Misc
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to create footer to stay at the bottom of a Web page?
Remove elements from a JavaScript Array
File uploading in React.js
How to Open URL in New Tab using JavaScript ?
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26713,
"s": 26685,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 26985,
"s": 26713,
"text": "A search bar is necessary for a good website. Creating your own search engine from scratch might be a difficult task but this task can be skipped with the help of Google. Google has created a website to create a custom search bar, to create your own check the below link."
},
{
"code": null,
"e": 27037,
"s": 26985,
"text": "https://programmablesearchengine.google.com/about/."
},
{
"code": null,
"e": 27088,
"s": 27037,
"text": "https://programmablesearchengine.google.com/about/"
},
{
"code": null,
"e": 27090,
"s": 27088,
"text": "."
},
{
"code": null,
"e": 27271,
"s": 27090,
"text": "Creating a Custom Search Bar: On this website, anyone can easily program their search bar by just selecting the sites you want to be searched for. Follow the steps explained below."
},
{
"code": null,
"e": 27332,
"s": 27271,
"text": "Step 1: Go to the following site and hit Get Started button."
},
{
"code": null,
"e": 27408,
"s": 27332,
"text": "Step 2: Select the New search engine button to create a new search engine. "
},
{
"code": null,
"e": 27491,
"s": 27408,
"text": "Step 3: Fill the details as directed on the page and then click the create button."
},
{
"code": null,
"e": 27595,
"s": 27491,
"text": "Step 4: After hitting create you will get your code by hitting the Get Code button on the screen shown."
},
{
"code": null,
"e": 27785,
"s": 27595,
"text": "Note: You can modify your setting about searching sites, searching images, safe search from control panel and you can also set to show advertisement while searching through your search bar."
},
{
"code": null,
"e": 27924,
"s": 27785,
"text": "Embedding the Search Bar on a Webpage: After getting your code you can simply paste it inside your web page to see the working search bar."
},
{
"code": null,
"e": 28941,
"s": 27924,
"text": "Example: You can see that the output screen has a search bar with an option to search which shows the result from the sites or domain you have selected while creating this search bar. Moreover, this search option will automatically change as you change the sites from the control panel. Currently, the search results are been shown in the default manner. Apart from that, you can manipulate the result displaying manner and much more as directed on the below linkshttps://developers.google.com/custom-search/docs/element.HTMLHTML<!DOCTYPE html><html> <head> <title>Custom Search-Bar</title> <style> body { background-image: linear-gradient(to left, white, green); color: lawngreen; } </style> </head> <body> <h1 style=\"text-align: center;\">GeeksforGeeks</h1> <script async src=\"https://cse.google.com/cse.js?cx=007019498718139788174:amtiepdpgeg\"> </script> <div class=\"gcse-search\"></div> </body></html>"
},
{
"code": null,
"e": 28998,
"s": 28941,
"text": "https://developers.google.com/custom-search/docs/element"
},
{
"code": null,
"e": 29000,
"s": 28998,
"text": "."
},
{
"code": null,
"e": 29005,
"s": 29000,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Custom Search-Bar</title> <style> body { background-image: linear-gradient(to left, white, green); color: lawngreen; } </style> </head> <body> <h1 style=\"text-align: center;\">GeeksforGeeks</h1> <script async src=\"https://cse.google.com/cse.js?cx=007019498718139788174:amtiepdpgeg\"> </script> <div class=\"gcse-search\"></div> </body></html>",
"e": 29493,
"s": 29005,
"text": null
},
{
"code": null,
"e": 29502,
"s": 29493,
"text": "Output: "
},
{
"code": null,
"e": 29512,
"s": 29502,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29529,
"s": 29512,
"text": "Web Technologies"
},
{
"code": null,
"e": 29556,
"s": 29529,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29654,
"s": 29556,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29694,
"s": 29654,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29739,
"s": 29694,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29782,
"s": 29739,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29843,
"s": 29782,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29901,
"s": 29843,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 29941,
"s": 29901,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29968,
"s": 29941,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 30014,
"s": 29968,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 30059,
"s": 30014,
"text": "How to execute PHP code using command line ?"
}
] |
Python | Pandas Panel.add() - GeeksforGeeks
|
28 Jan, 2019
In Pandas, Panel is a very important container for three-dimensional data. The names for the 3 axes are intended to give some semantic meaning to describing operations involving panel data and, in particular, econometric analysis of panel data.
In Pandas Panel.add() function is used for element-wise addition of series and series/dataframe.
Syntax: Panel.add(other, axis=0)
Parameters:other : DataFrame or Panelaxis : Axis to broadcast over
Returns: Panel
Code #1:
# importing pandas module import pandas as pd import numpy as np df1 = pd.DataFrame({'a': ['Geeks', 'For', 'geeks', 'for', 'real'], 'b': [11, 1.025, 333, 114.48, 1333]}) data = {'item1':df1, 'item2':df1} # creating Panel panel = pd.Panel.from_dict(data, orient ='minor') print("panel['b'] is - \n\n", panel['b'], '\n') print("\nAdding panel['b'] with df1['b'] using add() method - \n") print("\n", panel['b'].add(df1['b'], axis = 0))
Output:
Code #2:
# importing pandas module import pandas as pd import numpy as np df1 = pd.DataFrame({'a': ['Geeks', 'For', 'geeks', 'for', 'real'], 'b': [11, 1.025, 333, 114.48, 1333]}) data = {'item1':df1, 'item2':df1} # creating Panel panel = pd.Panel.from_dict(data, orient ='minor') print("panel['b'] is - \n\n", panel['b'], '\n') # Create a 5 * 5 dataframe df2 = pd.DataFrame(np.random.rand(5, 2), columns =['item1', 'item2']) print("Newly create dataframe with random values is - \n\n", df2) print("\nAdding panel['b'] with df2 using add() method - \n") print(panel['b'].add(df2, axis = 0))
Output:
Code #3:
# importing pandas module import pandas as pd import numpy as np df1 = pd.DataFrame({'a': ['Geeks', 'For', 'geeks', 'real'], 'b': [-11, +1.025, -114.48, 1333]}) df2 = pd.DataFrame({'a': ['I', 'am', 'dataframe', 'two'], 'b': [100, 100, 100, 100]}) data = {'item1':df1, 'item2':df2} # creating Panel panel = pd.Panel.from_dict(data, orient ='minor') print("panel['b'] is - \n\n", panel['b']) print("\nAdding panel['b'] with df2['b'] using add() method - \n") print("\n", panel['b'].add(df2['b'], axis = 0))
Output:
Python pandas-panel
Python pandas-panel-methods
Python-pandas
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 | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 25782,
"s": 25537,
"text": "In Pandas, Panel is a very important container for three-dimensional data. The names for the 3 axes are intended to give some semantic meaning to describing operations involving panel data and, in particular, econometric analysis of panel data."
},
{
"code": null,
"e": 25879,
"s": 25782,
"text": "In Pandas Panel.add() function is used for element-wise addition of series and series/dataframe."
},
{
"code": null,
"e": 25912,
"s": 25879,
"text": "Syntax: Panel.add(other, axis=0)"
},
{
"code": null,
"e": 25979,
"s": 25912,
"text": "Parameters:other : DataFrame or Panelaxis : Axis to broadcast over"
},
{
"code": null,
"e": 25994,
"s": 25979,
"text": "Returns: Panel"
},
{
"code": null,
"e": 26003,
"s": 25994,
"text": "Code #1:"
},
{
"code": "# importing pandas module import pandas as pd import numpy as np df1 = pd.DataFrame({'a': ['Geeks', 'For', 'geeks', 'for', 'real'], 'b': [11, 1.025, 333, 114.48, 1333]}) data = {'item1':df1, 'item2':df1} # creating Panel panel = pd.Panel.from_dict(data, orient ='minor') print(\"panel['b'] is - \\n\\n\", panel['b'], '\\n') print(\"\\nAdding panel['b'] with df1['b'] using add() method - \\n\") print(\"\\n\", panel['b'].add(df1['b'], axis = 0)) ",
"e": 26504,
"s": 26003,
"text": null
},
{
"code": null,
"e": 26513,
"s": 26504,
"text": "Output: "
},
{
"code": null,
"e": 26522,
"s": 26513,
"text": "Code #2:"
},
{
"code": "# importing pandas module import pandas as pd import numpy as np df1 = pd.DataFrame({'a': ['Geeks', 'For', 'geeks', 'for', 'real'], 'b': [11, 1.025, 333, 114.48, 1333]}) data = {'item1':df1, 'item2':df1} # creating Panel panel = pd.Panel.from_dict(data, orient ='minor') print(\"panel['b'] is - \\n\\n\", panel['b'], '\\n') # Create a 5 * 5 dataframe df2 = pd.DataFrame(np.random.rand(5, 2), columns =['item1', 'item2']) print(\"Newly create dataframe with random values is - \\n\\n\", df2) print(\"\\nAdding panel['b'] with df2 using add() method - \\n\") print(panel['b'].add(df2, axis = 0)) ",
"e": 27145,
"s": 26522,
"text": null
},
{
"code": null,
"e": 27154,
"s": 27145,
"text": "Output: "
},
{
"code": null,
"e": 27163,
"s": 27154,
"text": "Code #3:"
},
{
"code": "# importing pandas module import pandas as pd import numpy as np df1 = pd.DataFrame({'a': ['Geeks', 'For', 'geeks', 'real'], 'b': [-11, +1.025, -114.48, 1333]}) df2 = pd.DataFrame({'a': ['I', 'am', 'dataframe', 'two'], 'b': [100, 100, 100, 100]}) data = {'item1':df1, 'item2':df2} # creating Panel panel = pd.Panel.from_dict(data, orient ='minor') print(\"panel['b'] is - \\n\\n\", panel['b']) print(\"\\nAdding panel['b'] with df2['b'] using add() method - \\n\") print(\"\\n\", panel['b'].add(df2['b'], axis = 0)) ",
"e": 27740,
"s": 27163,
"text": null
},
{
"code": null,
"e": 27749,
"s": 27740,
"text": "Output: "
},
{
"code": null,
"e": 27769,
"s": 27749,
"text": "Python pandas-panel"
},
{
"code": null,
"e": 27797,
"s": 27769,
"text": "Python pandas-panel-methods"
},
{
"code": null,
"e": 27811,
"s": 27797,
"text": "Python-pandas"
},
{
"code": null,
"e": 27818,
"s": 27811,
"text": "Python"
},
{
"code": null,
"e": 27916,
"s": 27818,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27948,
"s": 27916,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27990,
"s": 27948,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28032,
"s": 27990,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28059,
"s": 28032,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28115,
"s": 28059,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28154,
"s": 28115,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28176,
"s": 28154,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28207,
"s": 28176,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28236,
"s": 28207,
"text": "Create a directory in Python"
}
] |
Commonly asked DBMS interview questions|Set 2
|
28 Jun, 2021
This article is extension of Commonly asked DBMS interview questions | Set 1.
Q. There is a table where only one row is fully repeated. Write a Query to find the Repeated row
In the above table, we can find duplicate row using below query.
SELECT name, section FROM tbl
GROUP BY name, section
HAVING COUNT(*) > 1
Q. Query to find 2nd highest salary of an employee?
SELECT max(salary) FROM EMPLOYEES WHERE salary IN
(SELECT salary FROM EMPLOYEEs MINUS SELECT max(salary)
FROM EMPLOYEES);
OR
SELECT max(salary) FROM EMPLOYEES WHERE
salary <> (SELECT max(salary) FROM EMPLOYEES);
Q.Consider the following Employee table. How many rows are there in the result of following query?
ID salary DeptName1 10000 EC2 40000 EC3 30000 CS4 40000 ME5 50000 ME6 60000 ME7 70000 CS
How many rows are there in the result of following query?
SELECT E.ID
FROM Employee E
WHERE EXISTS (SELECT E2.salary
FROM Employee E2
WHERE E2.DeptName = 'CS'
AND E.salary > E2.salary)
Following 5 rows will be result of query as 3000 is the minimum salary of CS Employees and all these rows are greater than 30000.
24567
Q. Write a trigger to update Emp table such that, If an updation is done in Dep table then salary of all employees of that department should be incremented by some amount (updation)
Assuming Table name are Dept and Emp, trigger can be written as –
CREATE OR REPLACE TRIGGER update_trig
AFTER UPDATE ON Dept
FOR EACH ROW
DECLARE
CURSOR emp_cur IS SELECT * FROM Emp;
BEGIN
FOR i IN emp_cur LOOP
IF i.dept_no = :NEW.dept_no THEN
DBMS_OUTPUT.PUT_LINE(i.emp_no); -- for printing those
UPDATE Emp -- emp number which are
SET sal = i.sal + 100 -- updated
WHERE emp_no = i.emp_no;
END IF;
END LOOP;
END;
Q. There is a table which contains two column Student and Marks, you need to find all the students, whose marks are greater than average marks i.e. list of above average students.
SELECT student, marks
FROM table
WHERE marks > SELECT AVG(marks) from table;
Q.Name the student who has secured third highest marks using sub queries.
SELECT Emp1.Name
FROM Employee Emp1
WHERE 2 = (SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary
)
*LOGIC- Number of people with salary higher than this person will be 2.
Q. Why we cannot use WHERE clause with aggregate functions like HAVING ?
The difference between the having and where clause in SQL is that the where clause canNOT be used with aggregates, but the having clause can. Please note : It is not a predefined rule but by and large you’ll see that in a good number of the SQL queries, we use WHERE prior to GROUP BY and HAVING after GROUP BY.
The Where clause acts as a pre filter where as Having as a post filter.
The where clause works on row’s data, not on aggregated data.
Let us consider below table ‘Marks’.
Student Course Score
a c1 40a c2 50b c3 60d c1 70e c2 80
Consider the query
SELECT Student, sum(Score) AS total
FROM Marks
This would select data row by row basis. The having clause works on aggregated data.
For example, output of below query
SELECT Student, sum(score) AS total FROM Marks
Student Totala 90b 60d 70e 80
When we apply having in above query, we get
SELECT Student, sum(score) AS total
FROM Marks having total > 70
Student Totala 90e 80
Q. Difference between primary key and unique key and why one should use unique key if it allows only one null ?
Primary key:
Only one in a row(tuple).
Never allows null value(only key field).
Unique key identifier and can not be null and must be unique.
Unique Key:
Can be more than one unique key in one row.
Unique key can have null values(only single null is allowed).
It can be a candidate key.
Unique key can be null and may not be unique.
Q. What’s the difference between materialized and dynamic view?
Materialized views
Disk based and are updated periodically based upon the query definition.
A materialized table is created or updated infrequently and it must be synchronized with its associated base tables.
Dynamic views
Virtual only and run the query definition each time they are accessed.
A dynamic view may be created every time that a specific view is requested by the user.
Q. What is embedded and dynamic SQL?
Static or Embedded SQL
SQL statements in an application that do not change at runtime and, therefore, can be hard-coded into the application.
Dynamic SQL
SQL statements that are constructed at runtime; for example, the application may allow users to enter their own queries.
Dynamic SQL is a programming technique that enables you to buildSQL statements dynamically at runtime. You can create more general purpose, flexible applications by using dynamic SQL because the full text of a SQL statement may be unknown at compilation.
http://docs.oracle.com/cd/A87860_01/doc/appdev.817/a76939/adg09dyn.htm
Q. What is the difference between CHAR and VARCHAR?
CHAR and VARCHAR are differ in storage and retrieval.
CHAR column length is fixed while VARCHAR length is variable.
The maximum no. of character CHAR data type can hold is 255 character while VARCHAR can hold up to 4000 character.
CHAR is 50% faster than VARCHAR.
CHAR uses static memory allocation while VARCHAR uses dynamic memory allocation.
You may also like:
Practice Quizzes on DBMS
Last Minute Notes – DBMS
DBMS Articles
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Data Preprocessing in Data Mining
Difference between DDL and DML in DBMS
Difference between SQL and NoSQL
Difference between DELETE, DROP and TRUNCATE
Indexing in Databases | Set 1
Third Normal Form (3NF)
Deadlock in DBMS
Second Normal Form (2NF)
|
[
{
"code": null,
"e": 25497,
"s": 25469,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25575,
"s": 25497,
"text": "This article is extension of Commonly asked DBMS interview questions | Set 1."
},
{
"code": null,
"e": 25672,
"s": 25575,
"text": "Q. There is a table where only one row is fully repeated. Write a Query to find the Repeated row"
},
{
"code": null,
"e": 25737,
"s": 25672,
"text": "In the above table, we can find duplicate row using below query."
},
{
"code": null,
"e": 25811,
"s": 25737,
"text": "SELECT name, section FROM tbl\nGROUP BY name, section\nHAVING COUNT(*) > 1\n"
},
{
"code": null,
"e": 25863,
"s": 25811,
"text": "Q. Query to find 2nd highest salary of an employee?"
},
{
"code": null,
"e": 25985,
"s": 25863,
"text": "SELECT max(salary) FROM EMPLOYEES WHERE salary IN\n(SELECT salary FROM EMPLOYEEs MINUS SELECT max(salary)\nFROM EMPLOYEES);"
},
{
"code": null,
"e": 25988,
"s": 25985,
"text": "OR"
},
{
"code": null,
"e": 26076,
"s": 25988,
"text": "SELECT max(salary) FROM EMPLOYEES WHERE \nsalary <> (SELECT max(salary) FROM EMPLOYEES);"
},
{
"code": null,
"e": 26175,
"s": 26076,
"text": "Q.Consider the following Employee table. How many rows are there in the result of following query?"
},
{
"code": null,
"e": 26324,
"s": 26175,
"text": "ID salary DeptName1 10000 EC2 40000 EC3 30000 CS4 40000 ME5 50000 ME6 60000 ME7 70000 CS"
},
{
"code": null,
"e": 26382,
"s": 26324,
"text": "How many rows are there in the result of following query?"
},
{
"code": null,
"e": 26514,
"s": 26382,
"text": "SELECT E.ID\nFROM Employee E\nWHERE EXISTS (SELECT E2.salary\nFROM Employee E2\nWHERE E2.DeptName = 'CS'\nAND E.salary > E2.salary)"
},
{
"code": null,
"e": 26644,
"s": 26514,
"text": "Following 5 rows will be result of query as 3000 is the minimum salary of CS Employees and all these rows are greater than 30000."
},
{
"code": null,
"e": 26650,
"s": 26644,
"text": "24567"
},
{
"code": null,
"e": 26832,
"s": 26650,
"text": "Q. Write a trigger to update Emp table such that, If an updation is done in Dep table then salary of all employees of that department should be incremented by some amount (updation)"
},
{
"code": null,
"e": 26898,
"s": 26832,
"text": "Assuming Table name are Dept and Emp, trigger can be written as –"
},
{
"code": null,
"e": 27279,
"s": 26898,
"text": "CREATE OR REPLACE TRIGGER update_trig\nAFTER UPDATE ON Dept\nFOR EACH ROW\nDECLARE\nCURSOR emp_cur IS SELECT * FROM Emp;\nBEGIN\nFOR i IN emp_cur LOOP\nIF i.dept_no = :NEW.dept_no THEN\nDBMS_OUTPUT.PUT_LINE(i.emp_no); -- for printing those\nUPDATE Emp -- emp number which are\nSET sal = i.sal + 100 -- updated\nWHERE emp_no = i.emp_no;\nEND IF;\nEND LOOP;\nEND;"
},
{
"code": null,
"e": 27459,
"s": 27279,
"text": "Q. There is a table which contains two column Student and Marks, you need to find all the students, whose marks are greater than average marks i.e. list of above average students."
},
{
"code": null,
"e": 27537,
"s": 27459,
"text": "SELECT student, marks \nFROM table\nWHERE marks > SELECT AVG(marks) from table;"
},
{
"code": null,
"e": 27611,
"s": 27537,
"text": "Q.Name the student who has secured third highest marks using sub queries."
},
{
"code": null,
"e": 27779,
"s": 27611,
"text": "SELECT Emp1.Name\nFROM Employee Emp1\nWHERE 2 = (SELECT COUNT(DISTINCT(Emp2.Salary))\n FROM Employee Emp2\n WHERE Emp2.Salary > Emp1.Salary\n )"
},
{
"code": null,
"e": 27851,
"s": 27779,
"text": "*LOGIC- Number of people with salary higher than this person will be 2."
},
{
"code": null,
"e": 27924,
"s": 27851,
"text": "Q. Why we cannot use WHERE clause with aggregate functions like HAVING ?"
},
{
"code": null,
"e": 28236,
"s": 27924,
"text": "The difference between the having and where clause in SQL is that the where clause canNOT be used with aggregates, but the having clause can. Please note : It is not a predefined rule but by and large you’ll see that in a good number of the SQL queries, we use WHERE prior to GROUP BY and HAVING after GROUP BY."
},
{
"code": null,
"e": 28308,
"s": 28236,
"text": "The Where clause acts as a pre filter where as Having as a post filter."
},
{
"code": null,
"e": 28370,
"s": 28308,
"text": "The where clause works on row’s data, not on aggregated data."
},
{
"code": null,
"e": 28407,
"s": 28370,
"text": "Let us consider below table ‘Marks’."
},
{
"code": null,
"e": 28439,
"s": 28407,
"text": "Student Course Score"
},
{
"code": null,
"e": 28610,
"s": 28439,
"text": "a c1 40a c2 50b c3 60d c1 70e c2 80"
},
{
"code": null,
"e": 28629,
"s": 28610,
"text": "Consider the query"
},
{
"code": null,
"e": 28677,
"s": 28629,
"text": "SELECT Student, sum(Score) AS total \nFROM Marks"
},
{
"code": null,
"e": 28762,
"s": 28677,
"text": "This would select data row by row basis. The having clause works on aggregated data."
},
{
"code": null,
"e": 28798,
"s": 28762,
"text": "For example, output of below query"
},
{
"code": null,
"e": 28845,
"s": 28798,
"text": "SELECT Student, sum(score) AS total FROM Marks"
},
{
"code": null,
"e": 28927,
"s": 28845,
"text": "Student Totala 90b 60d 70e 80"
},
{
"code": null,
"e": 28971,
"s": 28927,
"text": "When we apply having in above query, we get"
},
{
"code": null,
"e": 29036,
"s": 28971,
"text": "SELECT Student, sum(score) AS total\nFROM Marks having total > 70"
},
{
"code": null,
"e": 29074,
"s": 29036,
"text": "Student Totala 90e 80"
},
{
"code": null,
"e": 29186,
"s": 29074,
"text": "Q. Difference between primary key and unique key and why one should use unique key if it allows only one null ?"
},
{
"code": null,
"e": 29199,
"s": 29186,
"text": "Primary key:"
},
{
"code": null,
"e": 29225,
"s": 29199,
"text": "Only one in a row(tuple)."
},
{
"code": null,
"e": 29266,
"s": 29225,
"text": "Never allows null value(only key field)."
},
{
"code": null,
"e": 29328,
"s": 29266,
"text": "Unique key identifier and can not be null and must be unique."
},
{
"code": null,
"e": 29340,
"s": 29328,
"text": "Unique Key:"
},
{
"code": null,
"e": 29384,
"s": 29340,
"text": "Can be more than one unique key in one row."
},
{
"code": null,
"e": 29446,
"s": 29384,
"text": "Unique key can have null values(only single null is allowed)."
},
{
"code": null,
"e": 29473,
"s": 29446,
"text": "It can be a candidate key."
},
{
"code": null,
"e": 29519,
"s": 29473,
"text": "Unique key can be null and may not be unique."
},
{
"code": null,
"e": 29583,
"s": 29519,
"text": "Q. What’s the difference between materialized and dynamic view?"
},
{
"code": null,
"e": 29602,
"s": 29583,
"text": "Materialized views"
},
{
"code": null,
"e": 29675,
"s": 29602,
"text": "Disk based and are updated periodically based upon the query definition."
},
{
"code": null,
"e": 29792,
"s": 29675,
"text": "A materialized table is created or updated infrequently and it must be synchronized with its associated base tables."
},
{
"code": null,
"e": 29806,
"s": 29792,
"text": "Dynamic views"
},
{
"code": null,
"e": 29877,
"s": 29806,
"text": "Virtual only and run the query definition each time they are accessed."
},
{
"code": null,
"e": 29965,
"s": 29877,
"text": "A dynamic view may be created every time that a specific view is requested by the user."
},
{
"code": null,
"e": 30003,
"s": 29965,
"text": "Q. What is embedded and dynamic SQL? "
},
{
"code": null,
"e": 30026,
"s": 30003,
"text": "Static or Embedded SQL"
},
{
"code": null,
"e": 30145,
"s": 30026,
"text": "SQL statements in an application that do not change at runtime and, therefore, can be hard-coded into the application."
},
{
"code": null,
"e": 30157,
"s": 30145,
"text": "Dynamic SQL"
},
{
"code": null,
"e": 30278,
"s": 30157,
"text": "SQL statements that are constructed at runtime; for example, the application may allow users to enter their own queries."
},
{
"code": null,
"e": 30533,
"s": 30278,
"text": "Dynamic SQL is a programming technique that enables you to buildSQL statements dynamically at runtime. You can create more general purpose, flexible applications by using dynamic SQL because the full text of a SQL statement may be unknown at compilation."
},
{
"code": null,
"e": 30604,
"s": 30533,
"text": "http://docs.oracle.com/cd/A87860_01/doc/appdev.817/a76939/adg09dyn.htm"
},
{
"code": null,
"e": 30656,
"s": 30604,
"text": "Q. What is the difference between CHAR and VARCHAR?"
},
{
"code": null,
"e": 30710,
"s": 30656,
"text": "CHAR and VARCHAR are differ in storage and retrieval."
},
{
"code": null,
"e": 30772,
"s": 30710,
"text": "CHAR column length is fixed while VARCHAR length is variable."
},
{
"code": null,
"e": 30887,
"s": 30772,
"text": "The maximum no. of character CHAR data type can hold is 255 character while VARCHAR can hold up to 4000 character."
},
{
"code": null,
"e": 30920,
"s": 30887,
"text": "CHAR is 50% faster than VARCHAR."
},
{
"code": null,
"e": 31001,
"s": 30920,
"text": "CHAR uses static memory allocation while VARCHAR uses dynamic memory allocation."
},
{
"code": null,
"e": 31020,
"s": 31001,
"text": "You may also like:"
},
{
"code": null,
"e": 31045,
"s": 31020,
"text": "Practice Quizzes on DBMS"
},
{
"code": null,
"e": 31070,
"s": 31045,
"text": "Last Minute Notes – DBMS"
},
{
"code": null,
"e": 31084,
"s": 31070,
"text": "DBMS Articles"
},
{
"code": null,
"e": 31209,
"s": 31084,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31214,
"s": 31209,
"text": "DBMS"
},
{
"code": null,
"e": 31219,
"s": 31214,
"text": "DBMS"
},
{
"code": null,
"e": 31317,
"s": 31219,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31328,
"s": 31317,
"text": "CTE in SQL"
},
{
"code": null,
"e": 31381,
"s": 31328,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 31415,
"s": 31381,
"text": "Data Preprocessing in Data Mining"
},
{
"code": null,
"e": 31454,
"s": 31415,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 31487,
"s": 31454,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 31532,
"s": 31487,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 31562,
"s": 31532,
"text": "Indexing in Databases | Set 1"
},
{
"code": null,
"e": 31586,
"s": 31562,
"text": "Third Normal Form (3NF)"
},
{
"code": null,
"e": 31603,
"s": 31586,
"text": "Deadlock in DBMS"
}
] |
Practice Quiz for Sudo Placement - GeeksforGeeks
|
28 Dec, 2020
main()
{
char g[] = "geeksforgeeks";
printf("%s", g + g[6] - g[8]);
}
char g[] = “geeksforgeeks”;
// g now has the base address string “geeksforgeeks”
// g[6] is ‘o’ and g[1] is ‘e’.
// g[6] – g[1] = ASCII value of ‘o’ – ASCII value of ‘e’ = 8
// So the expression g + g[6] – g[8] becomes g + 8 which is
// base address of string “geeks”
printf(“%s”, g + g[6] – g[8]); // prints geeks
while (true) // infinite condition
{
A :____;
printf("%d", 1);
printf("%d", 1);
B:____;
}
while (true) // infinite condition
{
C:____;
printf("%d", 0);
printf("%d", 0);
D:____;
}
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
C Program For Finding Length Of A Linked List
How to calculate MOVING AVERAGE in a Pandas DataFrame?
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
How to Fix: KeyError in Pandas
C Program to read contents of Whole File
How to Append Pandas DataFrame to Existing CSV File?
How to Replace Values in a List in Python?
|
[
{
"code": null,
"e": 28855,
"s": 28827,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 28925,
"s": 28855,
"text": "main()\n{\nchar g[] = \"geeksforgeeks\";\nprintf(\"%s\", g + g[6] - g[8]);\n}"
},
{
"code": null,
"e": 29259,
"s": 28925,
"text": "char g[] = “geeksforgeeks”; \n\n// g now has the base address string “geeksforgeeks” \n\n// g[6] is ‘o’ and g[1] is ‘e’. \n\n// g[6] – g[1] = ASCII value of ‘o’ – ASCII value of ‘e’ = 8\n\n// So the expression g + g[6] – g[8] becomes g + 8 which is \n\n// base address of string “geeks” \n\nprintf(“%s”, g + g[6] – g[8]); // prints geeks "
},
{
"code": null,
"e": 29349,
"s": 29259,
"text": "while (true) // infinite condition\n{\nA :____;\nprintf(\"%d\", 1);\nprintf(\"%d\", 1);\nB:____;\n}"
},
{
"code": null,
"e": 29438,
"s": 29349,
"text": "while (true) // infinite condition\n{\nC:____;\nprintf(\"%d\", 0);\nprintf(\"%d\", 0);\nD:____;\n}"
},
{
"code": null,
"e": 29536,
"s": 29438,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 29589,
"s": 29536,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29635,
"s": 29589,
"text": "C Program For Finding Length Of A Linked List"
},
{
"code": null,
"e": 29690,
"s": 29635,
"text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?"
},
{
"code": null,
"e": 29748,
"s": 29690,
"text": "How to Convert Categorical Variable to Numeric in Pandas?"
},
{
"code": null,
"e": 29810,
"s": 29748,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29890,
"s": 29810,
"text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python"
},
{
"code": null,
"e": 29921,
"s": 29890,
"text": "How to Fix: KeyError in Pandas"
},
{
"code": null,
"e": 29962,
"s": 29921,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 30015,
"s": 29962,
"text": "How to Append Pandas DataFrame to Existing CSV File?"
}
] |
Node.js querystring.decode() Function - GeeksforGeeks
|
08 Mar, 2021
The querystring.decode() method is used to parse a URL query string into an object that contains the key and pair values of the query URL. The object returned does not inherit prototypes from the JavaScript object, therefore usual Object methods will not work. During parsing, the UTF-8 encoding format is assumed unless there is an alternative character encoding format. To decode alternative character encoding, the decodeURIComponent option has to be specified.
Syntax:
querystring.decode( str, sep, eq, options )
Parameters: This function accepts four parameters as mentioned above and described below:
str: String that specifies the URL query that has to be parsed.
sep: String that specifies the substring used to delimit the key and value pairs in the specified query string. The default value is “&”.
eq: String that specifies the substring used to delimit keys and values in the specified query string. The default value is “=”.
options: It is an object which can be used to modify the behavior of the method. It has the following parameters:decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape().maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”.
decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape().
maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”.
Return Value: It returns an object that has the key and value pairs parsed from the query string.
Example 1:
Javascript
const querystring = require('querystring'); let str = "user=pratik&isMale=true&role=Coder"; let output = querystring.decode(str); console.log("Output: ", output);
Output:
Example 2:
Javascript
const querystring = require('querystring'); let str = "user->pratik/isMale->true/role->Coder/role->Engineer"; let output = querystring.decode(str, '/', '->'); console.log("Output 1 : ", output); output = querystring.decode(str, '/', '->', {maxKeys: 2}); console.log("Output 2 : ", output);
Output:
Reference:https://nodejs.org/api/querystring.html#querystring_querystring_decode
NodeJS-function
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect Node.js with React.js ?
Node.js Export Module
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
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
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n08 Mar, 2021"
},
{
"code": null,
"e": 26732,
"s": 26267,
"text": "The querystring.decode() method is used to parse a URL query string into an object that contains the key and pair values of the query URL. The object returned does not inherit prototypes from the JavaScript object, therefore usual Object methods will not work. During parsing, the UTF-8 encoding format is assumed unless there is an alternative character encoding format. To decode alternative character encoding, the decodeURIComponent option has to be specified."
},
{
"code": null,
"e": 26742,
"s": 26732,
"text": "Syntax: "
},
{
"code": null,
"e": 26786,
"s": 26742,
"text": "querystring.decode( str, sep, eq, options )"
},
{
"code": null,
"e": 26878,
"s": 26786,
"text": "Parameters: This function accepts four parameters as mentioned above and described below: "
},
{
"code": null,
"e": 26942,
"s": 26878,
"text": "str: String that specifies the URL query that has to be parsed."
},
{
"code": null,
"e": 27080,
"s": 26942,
"text": "sep: String that specifies the substring used to delimit the key and value pairs in the specified query string. The default value is “&”."
},
{
"code": null,
"e": 27209,
"s": 27080,
"text": "eq: String that specifies the substring used to delimit keys and values in the specified query string. The default value is “=”."
},
{
"code": null,
"e": 27674,
"s": 27209,
"text": "options: It is an object which can be used to modify the behavior of the method. It has the following parameters:decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape().maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”."
},
{
"code": null,
"e": 27833,
"s": 27674,
"text": "decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape()."
},
{
"code": null,
"e": 28027,
"s": 27833,
"text": "maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”."
},
{
"code": null,
"e": 28125,
"s": 28027,
"text": "Return Value: It returns an object that has the key and value pairs parsed from the query string."
},
{
"code": null,
"e": 28136,
"s": 28125,
"text": "Example 1:"
},
{
"code": null,
"e": 28147,
"s": 28136,
"text": "Javascript"
},
{
"code": "const querystring = require('querystring'); let str = \"user=pratik&isMale=true&role=Coder\"; let output = querystring.decode(str); console.log(\"Output: \", output);",
"e": 28313,
"s": 28147,
"text": null
},
{
"code": null,
"e": 28321,
"s": 28313,
"text": "Output:"
},
{
"code": null,
"e": 28332,
"s": 28321,
"text": "Example 2:"
},
{
"code": null,
"e": 28343,
"s": 28332,
"text": "Javascript"
},
{
"code": "const querystring = require('querystring'); let str = \"user->pratik/isMale->true/role->Coder/role->Engineer\"; let output = querystring.decode(str, '/', '->'); console.log(\"Output 1 : \", output); output = querystring.decode(str, '/', '->', {maxKeys: 2}); console.log(\"Output 2 : \", output);",
"e": 28638,
"s": 28343,
"text": null
},
{
"code": null,
"e": 28646,
"s": 28638,
"text": "Output:"
},
{
"code": null,
"e": 28727,
"s": 28646,
"text": "Reference:https://nodejs.org/api/querystring.html#querystring_querystring_decode"
},
{
"code": null,
"e": 28743,
"s": 28727,
"text": "NodeJS-function"
},
{
"code": null,
"e": 28750,
"s": 28743,
"text": "Picked"
},
{
"code": null,
"e": 28758,
"s": 28750,
"text": "Node.js"
},
{
"code": null,
"e": 28775,
"s": 28758,
"text": "Web Technologies"
},
{
"code": null,
"e": 28873,
"s": 28775,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28912,
"s": 28873,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 28934,
"s": 28912,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 29004,
"s": 28934,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 29031,
"s": 29004,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 29056,
"s": 29031,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 29096,
"s": 29056,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29141,
"s": 29096,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29184,
"s": 29141,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29246,
"s": 29184,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Strict mode in JavaScript - GeeksforGeeks
|
20 Nov, 2021
Strict Mode was a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This strict context prevents certain actions from being taken and throws more exceptions. The statement “use strict”; instructs the browser to use the Strict mode, which is a reduced and safer feature set of JavaScript.
Benefits of using ‘use strict’: Strict mode makes several changes to normal JavaScript semantics.
Strict mode eliminates some JavaScript silent errors by changing them to throw errors.
Strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode.
Strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.
It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object).
It disables features that are confusing or poorly thought out.
Strict mode makes it easier to write “secure” JavaScript.
How to use strict mode: Strict mode can be used in two ways, remember strict mode doesn’t work with block statements enclosed in {} braces.
Used in global scope for the entire script.
It can be applied to individual functions.
Using Strict mode for the entire script: To invoke strict mode for an entire script, put the exact statement “use strict”; (or ‘use strict’;) before any other statements.
// Whole-script strict mode syntax
'use strict';
let v = "strict mode script!";
This syntax has a flow, it isn’t possible to blindly concatenate non-conflicting scripts. Consider concatenating a strict mode script with a non-strict mode script. The entire concatenation looks strict, the inverse is also true. The non-strict plus strict looks non-strict. The concatenation of strict mode scripts with each other is fine, and concatenation of non-strict mode scripts is fine. Only concatenating strict and non-strict scripts is problematic. It is thus recommended that you enable strict mode on a function-by-function basis (at least during the transition period).
Using Strict mode for a function: Likewise, to invoke strict mode for a function, put the exact statement “use strict”; (or ‘use strict’;) in the function’s body before any other statements.
function strict() {
// Function-level strict mode syntax
'use strict';
function nested() { return 'Javascript on GeeksforGeeks'; }
return "strict mode function! " + nested();
}
function notStrict() { return "non strict function"; }
Examples of using Strict mode:
Example: In normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
Javascript
// Using a variable, without declaring it, is not allowed:'use strict'; x = 3.14; // will throw an error
Output:
Example: Using strict mode, don’t allow to use a variable without declaring it.
Javascript
// Objects are variables too.// Using an object, without declaring it, is not allowed:'use strict'; // Will throw an error x = {p1:10, p2:20};
Output:
Example: Deleting a variable (or object) and a function is not allowed.
Javascript
'use strict'; let x = 3.14; // Deleting a function is also not allowed'use strict'; function x(p1, p2) {}; // Will throw an error delete x;
Output:
Example: Duplicating a parameter name is not allowed.
Javascript
'use strict'; // Will throw an error function x(p1, p1) {};
Output:
Example: Octal numeric literals are not allowed.
Javascript
'use strict'; // Will throw an error let x = 010;
Output:
Example: Escape characters are not allowed.
Javascript
'use strict'; // Will throw an error let x = \010;
Output:
Example: Writing to a read-only property is not allowed.
Javascript
'use strict'; let obj = {}; Object.defineProperty(obj, "x", {value:0, writable:false}); // Will throw an error obj.x = 3.14;
Output:
Example: Writing to a get-only property is not allowed.
Javascript
'use strict'; let obj = {get x() {return 0} }; // Will throw an error obj.x = 3.14;
Output:
Example: Deleting an undeletable property is not allowed.
Javascript
'use strict'; // Will throw an error delete Object.prototype;
Output:
Example: The string “eval” cannot be used as a variable.
Javascript
'use strict'; // Will throw an error let eval = 3.14;
Output:
Example: The string “arguments” cannot be used as a variable.
Javascript
'use strict'; // Will throw an error let arguments = 3.14;
Output:
Example: The with statement is not allowed.
Javascript
'use strict'; // Will throw an error with (Math){x = cos(2)};
Output:
Note: In function calls like f(), this value was the global object. In strict mode, it is now undefined. In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.
immukul
techblazes
binikumari804408
javascript-basics
secure-coding
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Node.js | fs.writeFileSync() Method
How to Use the JavaScript Fetch API to Get Data?
JavaScript | Promises
How to get character array from string in JavaScript?
Set the value of an input field in JavaScript
|
[
{
"code": null,
"e": 25767,
"s": 25739,
"text": "\n20 Nov, 2021"
},
{
"code": null,
"e": 26117,
"s": 25767,
"text": "Strict Mode was a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This strict context prevents certain actions from being taken and throws more exceptions. The statement “use strict”; instructs the browser to use the Strict mode, which is a reduced and safer feature set of JavaScript."
},
{
"code": null,
"e": 26216,
"s": 26117,
"text": "Benefits of using ‘use strict’: Strict mode makes several changes to normal JavaScript semantics. "
},
{
"code": null,
"e": 26303,
"s": 26216,
"text": "Strict mode eliminates some JavaScript silent errors by changing them to throw errors."
},
{
"code": null,
"e": 26499,
"s": 26303,
"text": "Strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode."
},
{
"code": null,
"e": 26588,
"s": 26499,
"text": "Strict mode prohibits some syntax likely to be defined in future versions of ECMAScript."
},
{
"code": null,
"e": 26709,
"s": 26588,
"text": "It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object)."
},
{
"code": null,
"e": 26772,
"s": 26709,
"text": "It disables features that are confusing or poorly thought out."
},
{
"code": null,
"e": 26830,
"s": 26772,
"text": "Strict mode makes it easier to write “secure” JavaScript."
},
{
"code": null,
"e": 26971,
"s": 26830,
"text": "How to use strict mode: Strict mode can be used in two ways, remember strict mode doesn’t work with block statements enclosed in {} braces. "
},
{
"code": null,
"e": 27015,
"s": 26971,
"text": "Used in global scope for the entire script."
},
{
"code": null,
"e": 27058,
"s": 27015,
"text": "It can be applied to individual functions."
},
{
"code": null,
"e": 27230,
"s": 27058,
"text": "Using Strict mode for the entire script: To invoke strict mode for an entire script, put the exact statement “use strict”; (or ‘use strict’;) before any other statements. "
},
{
"code": null,
"e": 27311,
"s": 27230,
"text": "// Whole-script strict mode syntax\n'use strict';\n let v = \"strict mode script!\";"
},
{
"code": null,
"e": 27895,
"s": 27311,
"text": "This syntax has a flow, it isn’t possible to blindly concatenate non-conflicting scripts. Consider concatenating a strict mode script with a non-strict mode script. The entire concatenation looks strict, the inverse is also true. The non-strict plus strict looks non-strict. The concatenation of strict mode scripts with each other is fine, and concatenation of non-strict mode scripts is fine. Only concatenating strict and non-strict scripts is problematic. It is thus recommended that you enable strict mode on a function-by-function basis (at least during the transition period)."
},
{
"code": null,
"e": 28086,
"s": 27895,
"text": "Using Strict mode for a function: Likewise, to invoke strict mode for a function, put the exact statement “use strict”; (or ‘use strict’;) in the function’s body before any other statements."
},
{
"code": null,
"e": 28330,
"s": 28086,
"text": "function strict() {\n\n // Function-level strict mode syntax\n 'use strict';\n\n function nested() { return 'Javascript on GeeksforGeeks'; }\n\n return \"strict mode function! \" + nested();\n}\nfunction notStrict() { return \"non strict function\"; }"
},
{
"code": null,
"e": 28362,
"s": 28330,
"text": "Examples of using Strict mode: "
},
{
"code": null,
"e": 28556,
"s": 28362,
"text": "Example: In normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable. "
},
{
"code": null,
"e": 28567,
"s": 28556,
"text": "Javascript"
},
{
"code": "// Using a variable, without declaring it, is not allowed:'use strict'; x = 3.14; // will throw an error",
"e": 28673,
"s": 28567,
"text": null
},
{
"code": null,
"e": 28682,
"s": 28673,
"text": "Output: "
},
{
"code": null,
"e": 28763,
"s": 28682,
"text": "Example: Using strict mode, don’t allow to use a variable without declaring it. "
},
{
"code": null,
"e": 28774,
"s": 28763,
"text": "Javascript"
},
{
"code": "// Objects are variables too.// Using an object, without declaring it, is not allowed:'use strict'; // Will throw an error x = {p1:10, p2:20};",
"e": 28920,
"s": 28774,
"text": null
},
{
"code": null,
"e": 28929,
"s": 28920,
"text": "Output: "
},
{
"code": null,
"e": 29002,
"s": 28929,
"text": "Example: Deleting a variable (or object) and a function is not allowed. "
},
{
"code": null,
"e": 29013,
"s": 29002,
"text": "Javascript"
},
{
"code": "'use strict'; let x = 3.14; // Deleting a function is also not allowed'use strict'; function x(p1, p2) {}; // Will throw an error delete x; ",
"e": 29159,
"s": 29013,
"text": null
},
{
"code": null,
"e": 29168,
"s": 29159,
"text": "Output: "
},
{
"code": null,
"e": 29223,
"s": 29168,
"text": "Example: Duplicating a parameter name is not allowed. "
},
{
"code": null,
"e": 29234,
"s": 29223,
"text": "Javascript"
},
{
"code": "'use strict'; // Will throw an error function x(p1, p1) {}; ",
"e": 29297,
"s": 29234,
"text": null
},
{
"code": null,
"e": 29306,
"s": 29297,
"text": "Output: "
},
{
"code": null,
"e": 29356,
"s": 29306,
"text": "Example: Octal numeric literals are not allowed. "
},
{
"code": null,
"e": 29367,
"s": 29356,
"text": "Javascript"
},
{
"code": "'use strict'; // Will throw an error let x = 010; ",
"e": 29424,
"s": 29367,
"text": null
},
{
"code": null,
"e": 29433,
"s": 29424,
"text": "Output: "
},
{
"code": null,
"e": 29478,
"s": 29433,
"text": "Example: Escape characters are not allowed. "
},
{
"code": null,
"e": 29489,
"s": 29478,
"text": "Javascript"
},
{
"code": "'use strict'; // Will throw an error let x = \\010; ",
"e": 29545,
"s": 29489,
"text": null
},
{
"code": null,
"e": 29554,
"s": 29545,
"text": "Output: "
},
{
"code": null,
"e": 29612,
"s": 29554,
"text": "Example: Writing to a read-only property is not allowed. "
},
{
"code": null,
"e": 29623,
"s": 29612,
"text": "Javascript"
},
{
"code": "'use strict'; let obj = {}; Object.defineProperty(obj, \"x\", {value:0, writable:false}); // Will throw an error obj.x = 3.14; ",
"e": 29752,
"s": 29623,
"text": null
},
{
"code": null,
"e": 29761,
"s": 29752,
"text": "Output: "
},
{
"code": null,
"e": 29818,
"s": 29761,
"text": "Example: Writing to a get-only property is not allowed. "
},
{
"code": null,
"e": 29829,
"s": 29818,
"text": "Javascript"
},
{
"code": "'use strict'; let obj = {get x() {return 0} }; // Will throw an error obj.x = 3.14; ",
"e": 29918,
"s": 29829,
"text": null
},
{
"code": null,
"e": 29927,
"s": 29918,
"text": "Output: "
},
{
"code": null,
"e": 29986,
"s": 29927,
"text": "Example: Deleting an undeletable property is not allowed. "
},
{
"code": null,
"e": 29997,
"s": 29986,
"text": "Javascript"
},
{
"code": "'use strict'; // Will throw an error delete Object.prototype;",
"e": 30060,
"s": 29997,
"text": null
},
{
"code": null,
"e": 30069,
"s": 30060,
"text": "Output: "
},
{
"code": null,
"e": 30127,
"s": 30069,
"text": "Example: The string “eval” cannot be used as a variable. "
},
{
"code": null,
"e": 30138,
"s": 30127,
"text": "Javascript"
},
{
"code": "'use strict'; // Will throw an error let eval = 3.14; ",
"e": 30194,
"s": 30138,
"text": null
},
{
"code": null,
"e": 30203,
"s": 30194,
"text": "Output: "
},
{
"code": null,
"e": 30266,
"s": 30203,
"text": "Example: The string “arguments” cannot be used as a variable. "
},
{
"code": null,
"e": 30277,
"s": 30266,
"text": "Javascript"
},
{
"code": "'use strict'; // Will throw an error let arguments = 3.14; ",
"e": 30340,
"s": 30277,
"text": null
},
{
"code": null,
"e": 30349,
"s": 30340,
"text": "Output: "
},
{
"code": null,
"e": 30394,
"s": 30349,
"text": "Example: The with statement is not allowed. "
},
{
"code": null,
"e": 30405,
"s": 30394,
"text": "Javascript"
},
{
"code": "'use strict'; // Will throw an error with (Math){x = cos(2)};",
"e": 30468,
"s": 30405,
"text": null
},
{
"code": null,
"e": 30477,
"s": 30468,
"text": "Output: "
},
{
"code": null,
"e": 30697,
"s": 30477,
"text": "Note: In function calls like f(), this value was the global object. In strict mode, it is now undefined. In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties."
},
{
"code": null,
"e": 30705,
"s": 30697,
"text": "immukul"
},
{
"code": null,
"e": 30716,
"s": 30705,
"text": "techblazes"
},
{
"code": null,
"e": 30733,
"s": 30716,
"text": "binikumari804408"
},
{
"code": null,
"e": 30751,
"s": 30733,
"text": "javascript-basics"
},
{
"code": null,
"e": 30765,
"s": 30751,
"text": "secure-coding"
},
{
"code": null,
"e": 30776,
"s": 30765,
"text": "JavaScript"
},
{
"code": null,
"e": 30874,
"s": 30776,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30914,
"s": 30874,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30959,
"s": 30914,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31020,
"s": 30959,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31092,
"s": 31020,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 31133,
"s": 31092,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 31169,
"s": 31133,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 31218,
"s": 31169,
"text": "How to Use the JavaScript Fetch API to Get Data?"
},
{
"code": null,
"e": 31240,
"s": 31218,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 31294,
"s": 31240,
"text": "How to get character array from string in JavaScript?"
}
] |
BigInt in JavaScript - GeeksforGeeks
|
25 Jun, 2020
BigInt is a built-in object in JavaScript that provides a way to represent whole numbers larger than 253-1. The largest number that JavaScript can reliably represent with the Number primitive is 253-1, which is represented by the MAX_SAFE_INTEGER constant. This has various uses where operations on large numbers are required.
Syntax:
BigInt( number )
or
Appending n to end of an integer literal
Parameters: It accepts a single integer literal as string that needs to represent as BigInt.
Return Type: This method returns the given value as BigInt data type.
Example: This example creating a BigInt using the BigInt() function.
javascript
// Parameter in decimal formatvar bigNum = BigInt( "123422222222222222222222222222222222222");console.log(bigNum); // Parameter in hexadecimal formatvar bigHex = BigInt("0x1ffffffeeeeeeeeef");console.log(bigHex); // Parameter in binary formatvar bigBin = BigInt( "0b1010101001010101001111111111111111");console.log(bigBin);
Output:
123422222222222222222222222222222222222n
36893488074118328047n
11430854655n
Example: This example creating a BigInt by appending n at the end of the number.
javascript
// Decimal formatvar bigNum = 123422222222222222222222222222222222222nconsole.log(bigNum) // Hexadecimal formatvar bigHex = 0x1ffffffeeeeeeeeefnconsole.log(bigHex) // Binary formatvar bigBin = 0b1010101001010101001111111111111111nconsole.log(bigBin)
Output:
123422222222222222222222222222222222222n
36893488074118328047n
11430854655n
Comparing BigInt other types: A BigInt is similar to a Number in some ways, however, it cannot be used with methods of the builtin Math object and cannot be mixed with instances of Number in operations.
Example: Comparing BigInt with a Number.
typeof 100n === 100 // Returns false
typeof 100n == 100 // Returns true due to coercion
typeof 100n === 'bigint' // Returns true
100n < 101 // Returns true due to coercion
Sorting: An array can hold both primitive data types and BigInts. This allows the sort() method to work when both normal Number and BigInt values are present in the array.
Example:
javascript
// Array consisting of both// Number and BigIntvar arr = [4, 2, 5n, 2n] // Sorting the arrayarr.sort() console.log(arr) // [2, 2n, 4, 5n]
Output:
[2, 2n, 4, 5n]
Usage Recommendation: The following applications are not recommended to be used with BigInt due to its implementation:
Coercion: Coercing between Number and BigInt can lead to loss of precision, it is recommended to only use BigInt when values greater than 253 are reasonably expected and not to coerce between the two types.Cryptography: The operations supported on BigInt are not constant time. BigInt is therefore unsuitable for use in cryptography.
Coercion: Coercing between Number and BigInt can lead to loss of precision, it is recommended to only use BigInt when values greater than 253 are reasonably expected and not to coerce between the two types.
Cryptography: The operations supported on BigInt are not constant time. BigInt is therefore unsuitable for use in cryptography.
Supported Browsers: The browsers supporting BigInt method are listed below:
Chrome
Edge
Firefox
Opera
Data Types
javascript-basics
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26021,
"s": 25993,
"text": "\n25 Jun, 2020"
},
{
"code": null,
"e": 26348,
"s": 26021,
"text": "BigInt is a built-in object in JavaScript that provides a way to represent whole numbers larger than 253-1. The largest number that JavaScript can reliably represent with the Number primitive is 253-1, which is represented by the MAX_SAFE_INTEGER constant. This has various uses where operations on large numbers are required."
},
{
"code": null,
"e": 26356,
"s": 26348,
"text": "Syntax:"
},
{
"code": null,
"e": 26419,
"s": 26356,
"text": "BigInt( number ) \nor\nAppending n to end of an integer literal\n"
},
{
"code": null,
"e": 26512,
"s": 26419,
"text": "Parameters: It accepts a single integer literal as string that needs to represent as BigInt."
},
{
"code": null,
"e": 26582,
"s": 26512,
"text": "Return Type: This method returns the given value as BigInt data type."
},
{
"code": null,
"e": 26651,
"s": 26582,
"text": "Example: This example creating a BigInt using the BigInt() function."
},
{
"code": null,
"e": 26662,
"s": 26651,
"text": "javascript"
},
{
"code": "// Parameter in decimal formatvar bigNum = BigInt( \"123422222222222222222222222222222222222\");console.log(bigNum); // Parameter in hexadecimal formatvar bigHex = BigInt(\"0x1ffffffeeeeeeeeef\");console.log(bigHex); // Parameter in binary formatvar bigBin = BigInt( \"0b1010101001010101001111111111111111\");console.log(bigBin);",
"e": 26990,
"s": 26662,
"text": null
},
{
"code": null,
"e": 26999,
"s": 26990,
"text": "Output: "
},
{
"code": null,
"e": 27076,
"s": 26999,
"text": "123422222222222222222222222222222222222n\n36893488074118328047n\n11430854655n\n"
},
{
"code": null,
"e": 27157,
"s": 27076,
"text": "Example: This example creating a BigInt by appending n at the end of the number."
},
{
"code": null,
"e": 27168,
"s": 27157,
"text": "javascript"
},
{
"code": "// Decimal formatvar bigNum = 123422222222222222222222222222222222222nconsole.log(bigNum) // Hexadecimal formatvar bigHex = 0x1ffffffeeeeeeeeefnconsole.log(bigHex) // Binary formatvar bigBin = 0b1010101001010101001111111111111111nconsole.log(bigBin)",
"e": 27420,
"s": 27168,
"text": null
},
{
"code": null,
"e": 27429,
"s": 27420,
"text": "Output: "
},
{
"code": null,
"e": 27506,
"s": 27429,
"text": "123422222222222222222222222222222222222n\n36893488074118328047n\n11430854655n\n"
},
{
"code": null,
"e": 27709,
"s": 27506,
"text": "Comparing BigInt other types: A BigInt is similar to a Number in some ways, however, it cannot be used with methods of the builtin Math object and cannot be mixed with instances of Number in operations."
},
{
"code": null,
"e": 27750,
"s": 27709,
"text": "Example: Comparing BigInt with a Number."
},
{
"code": null,
"e": 27956,
"s": 27750,
"text": "typeof 100n === 100 // Returns false\ntypeof 100n == 100 // Returns true due to coercion\ntypeof 100n === 'bigint' // Returns true\n100n < 101 // Returns true due to coercion\n"
},
{
"code": null,
"e": 28128,
"s": 27956,
"text": "Sorting: An array can hold both primitive data types and BigInts. This allows the sort() method to work when both normal Number and BigInt values are present in the array."
},
{
"code": null,
"e": 28137,
"s": 28128,
"text": "Example:"
},
{
"code": null,
"e": 28148,
"s": 28137,
"text": "javascript"
},
{
"code": "// Array consisting of both// Number and BigIntvar arr = [4, 2, 5n, 2n] // Sorting the arrayarr.sort() console.log(arr) // [2, 2n, 4, 5n]",
"e": 28289,
"s": 28148,
"text": null
},
{
"code": null,
"e": 28297,
"s": 28289,
"text": "Output:"
},
{
"code": null,
"e": 28312,
"s": 28297,
"text": "[2, 2n, 4, 5n]"
},
{
"code": null,
"e": 28431,
"s": 28312,
"text": "Usage Recommendation: The following applications are not recommended to be used with BigInt due to its implementation:"
},
{
"code": null,
"e": 28765,
"s": 28431,
"text": "Coercion: Coercing between Number and BigInt can lead to loss of precision, it is recommended to only use BigInt when values greater than 253 are reasonably expected and not to coerce between the two types.Cryptography: The operations supported on BigInt are not constant time. BigInt is therefore unsuitable for use in cryptography."
},
{
"code": null,
"e": 28972,
"s": 28765,
"text": "Coercion: Coercing between Number and BigInt can lead to loss of precision, it is recommended to only use BigInt when values greater than 253 are reasonably expected and not to coerce between the two types."
},
{
"code": null,
"e": 29100,
"s": 28972,
"text": "Cryptography: The operations supported on BigInt are not constant time. BigInt is therefore unsuitable for use in cryptography."
},
{
"code": null,
"e": 29176,
"s": 29100,
"text": "Supported Browsers: The browsers supporting BigInt method are listed below:"
},
{
"code": null,
"e": 29183,
"s": 29176,
"text": "Chrome"
},
{
"code": null,
"e": 29188,
"s": 29183,
"text": "Edge"
},
{
"code": null,
"e": 29196,
"s": 29188,
"text": "Firefox"
},
{
"code": null,
"e": 29202,
"s": 29196,
"text": "Opera"
},
{
"code": null,
"e": 29213,
"s": 29202,
"text": "Data Types"
},
{
"code": null,
"e": 29231,
"s": 29213,
"text": "javascript-basics"
},
{
"code": null,
"e": 29242,
"s": 29231,
"text": "JavaScript"
},
{
"code": null,
"e": 29259,
"s": 29242,
"text": "Web Technologies"
},
{
"code": null,
"e": 29357,
"s": 29259,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29397,
"s": 29357,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29442,
"s": 29397,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29503,
"s": 29442,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29575,
"s": 29503,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29627,
"s": 29575,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29667,
"s": 29627,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29700,
"s": 29667,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29745,
"s": 29700,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29788,
"s": 29745,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python OpenCV - waitKeyEx() Function - GeeksforGeeks
|
17 Oct, 2021
Python OpenCv waitKeyEx() method is similar to waitKey() method but it also returns the full key code. The key code which is returned is implementation-specific and depends on the used backend: QT/GTK/Win32/etc.
Syntax: cv2.waitKey(delay)
Parameters:
delay: The time in milliseconds after which windows needs to destroyed. If given 0 it waits for infinite till any key is pressed to destroy window.
Return : This method return the full key code of the key which is pressed. If no key is pressed it return -1.
In the below example we have implemented the waitKeyEx() method we have made a window that has an image named “gfg_logo.png” and then we display it and using waitKeyEx() method we delay the closing of the window and then press a key to close it. We store the returned value in the full_key_code variable and print it.
Python
# importing cv2 moduleimport cv2 # read the imageimg = cv2.imread("gfg_logo.png") # showing the imagecv2.imshow('gfg', img) # waiting using waitKeyEX method and storing# the returned value in full_key_codefull_key_code = cv2.waitKeyEx(0) # printing the variableprint("The key code is:"+str(full_key_code))
Output:
The key code is:13
In the output, the value of full_key_code will be printed according to the key pressed When we press enter the value that is printed is as follows.
Another Example we can see is where we don’t press any key and wait for the window to destroy automatically after the delay that is given. We will pass 5000 as a parameter to wait for 5 seconds and then a window will close automatically without the need of pressing any key. In this case the function will return -1 as no key was pressed.
Python
# importing cv2 moduleimport cv2 # read the imageimg = cv2.imread("gfg_logo.png") # showing the imagecv2.imshow('gfg', img) # waiting using waitKeyEX method and# storing the returned value in full_key_codefull_key_code = cv2.waitKeyEx(5000) # printing the variableprint("The key code is:"+str(full_key_code))
Output:
The key code is:-1
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n17 Oct, 2021"
},
{
"code": null,
"e": 25749,
"s": 25537,
"text": "Python OpenCv waitKeyEx() method is similar to waitKey() method but it also returns the full key code. The key code which is returned is implementation-specific and depends on the used backend: QT/GTK/Win32/etc."
},
{
"code": null,
"e": 25776,
"s": 25749,
"text": "Syntax: cv2.waitKey(delay)"
},
{
"code": null,
"e": 25788,
"s": 25776,
"text": "Parameters:"
},
{
"code": null,
"e": 25936,
"s": 25788,
"text": "delay: The time in milliseconds after which windows needs to destroyed. If given 0 it waits for infinite till any key is pressed to destroy window."
},
{
"code": null,
"e": 26046,
"s": 25936,
"text": "Return : This method return the full key code of the key which is pressed. If no key is pressed it return -1."
},
{
"code": null,
"e": 26364,
"s": 26046,
"text": "In the below example we have implemented the waitKeyEx() method we have made a window that has an image named “gfg_logo.png” and then we display it and using waitKeyEx() method we delay the closing of the window and then press a key to close it. We store the returned value in the full_key_code variable and print it."
},
{
"code": null,
"e": 26371,
"s": 26364,
"text": "Python"
},
{
"code": "# importing cv2 moduleimport cv2 # read the imageimg = cv2.imread(\"gfg_logo.png\") # showing the imagecv2.imshow('gfg', img) # waiting using waitKeyEX method and storing# the returned value in full_key_codefull_key_code = cv2.waitKeyEx(0) # printing the variableprint(\"The key code is:\"+str(full_key_code))",
"e": 26681,
"s": 26371,
"text": null
},
{
"code": null,
"e": 26689,
"s": 26681,
"text": "Output:"
},
{
"code": null,
"e": 26708,
"s": 26689,
"text": "The key code is:13"
},
{
"code": null,
"e": 26856,
"s": 26708,
"text": "In the output, the value of full_key_code will be printed according to the key pressed When we press enter the value that is printed is as follows."
},
{
"code": null,
"e": 27195,
"s": 26856,
"text": "Another Example we can see is where we don’t press any key and wait for the window to destroy automatically after the delay that is given. We will pass 5000 as a parameter to wait for 5 seconds and then a window will close automatically without the need of pressing any key. In this case the function will return -1 as no key was pressed."
},
{
"code": null,
"e": 27202,
"s": 27195,
"text": "Python"
},
{
"code": "# importing cv2 moduleimport cv2 # read the imageimg = cv2.imread(\"gfg_logo.png\") # showing the imagecv2.imshow('gfg', img) # waiting using waitKeyEX method and# storing the returned value in full_key_codefull_key_code = cv2.waitKeyEx(5000) # printing the variableprint(\"The key code is:\"+str(full_key_code))",
"e": 27515,
"s": 27202,
"text": null
},
{
"code": null,
"e": 27523,
"s": 27515,
"text": "Output:"
},
{
"code": null,
"e": 27542,
"s": 27523,
"text": "The key code is:-1"
},
{
"code": null,
"e": 27549,
"s": 27542,
"text": "Picked"
},
{
"code": null,
"e": 27563,
"s": 27549,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 27570,
"s": 27563,
"text": "Python"
},
{
"code": null,
"e": 27668,
"s": 27570,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27700,
"s": 27668,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27742,
"s": 27700,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27784,
"s": 27742,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27840,
"s": 27784,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27867,
"s": 27840,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27906,
"s": 27867,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27937,
"s": 27906,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27959,
"s": 27937,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27988,
"s": 27959,
"text": "Create a directory in Python"
}
] |
Pandigital number in a given base - GeeksforGeeks
|
10 Mar, 2022
Given an integer n and its base b. The task is to check if given number is Pandigital Number in the given base or not. A Pandigital number is an integer that has each digit of its base at least once.It may be assumed that base is smaller than or equal to 36. In base 36, digits are [0, 1, ...9. A, B, ...Z]Examples :
Input : n = "9651723480", b = 10
Output : Yes
Given number n has all digits from 0 to 9
Input : n = "23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",
b = 36
Output : No
Given number n doesn't have all digits in base
36. For example 1 is missing.
Make a boolean hash array of size equal to base of the number and initialize it with false. Now, iterate each digit of the number mark its corresponding index value as true in the hash array. In the end, check whether all the value in hash array are marked or not, if marked print “Yes” i.e Pandigital number else print “No”.Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if a number is pandigital// in given base.#include<bits/stdc++.h>using namespace std; // Return true if n is pandigit else return false.bool checkPandigital(int b, char n[]){ // Checking length is less than base if (strlen(n) < b) return false; bool hash[b]; memset(hash, false, sizeof(hash)); // Traversing each digit of the number. for (int i = 0; i < strlen(n); i++) { // If digit is integer if (n[i] >= '0' && n[i] <= '9') hash[n[i] - '0'] = true; // If digit is alphabet else if (n[i] - 'A' <= b - 11) hash[n[i] - 'A' + 10] = true; } // Checking hash array, if any index is // unmarked. for (int i = 0; i < b; i++) if (hash[i] == false) return false; return true;} // Driver Programint main(){ int b = 13; char n[] = "1298450376ABC"; (checkPandigital(b, n))? (cout << "Yes" << endl): (cout << "No" << endl); return 0;}
// Java program to check if a number// is pandigital in given base.import java.util.*; class GFG { // Return true if n is pandigit// else return false.static boolean checkPandigital(int b, String n) { // Checking length is less than base if (n.length() < b) return false; boolean hash[] = new boolean[b]; Arrays.fill(hash, false); // Traversing each digit of the number. for (int i = 0; i < n.length(); i++) { // If digit is integer if (n.charAt(i) >= '0' && n.charAt(i) <= '9') hash[n.charAt(i) - '0'] = true; // If digit is alphabet else if (n.charAt(i) - 'A' <= b - 11) hash[n.charAt(i) - 'A' + 10] = true; } // Checking hash array, if any // index is unmarked. for (int i = 0; i < b; i++) if (hash[i] == false) return false; return true;} // Driver codepublic static void main(String[] args){ int b = 13; String n = "1298450376ABC"; if (checkPandigital(b, n)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by Anant Agarwal.
# Python3 program to check if a number is# pandigital in given base. # Return true if n is pandigit else return false.def checkPandigital(b, n): # Checking length is less than base if (len(n) < b): return 0; hash = [0] * b; # Traversing each digit of the number. for i in range(len(n)): # If digit is integer if (n[i] >= '0' and n[i] <= '9'): hash[ord(n[i]) - ord('0')] = 1; # If digit is alphabet else if (ord(n[i]) - ord('A') <= b - 11): hash[ord(n[i]) - ord('A') + 10] = 1; # Checking hash array, if any index is # unmarked. for i in range(b): if (hash[i] == 0): return 0; return 1; # Driver Codeb = 13;n = "1298450376ABC"; if(checkPandigital(b, n)): print("Yes");else: print("No"); # This code is contributed by mits
// C# program to check if a number// is pandigital in given base.using System; class GFG { // Return true if n is pandigit// else return false.static bool checkPandigital(int b, string n) { // Checking length is less than base if (n.Length < b) return false; bool []hash = new bool[b]; for(int i = 0; i < b; i++) hash[i] = false; // Traversing each digit of the number. for (int i = 0; i < n.Length; i++) { // If digit is integer if (n[i] >= '0' && n[i] <= '9') hash[n[i] - '0'] = true; // If digit is alphabet else if (n[i] - 'A' <= b - 11) hash[n[i] - 'A' + 10] = true; } // Checking hash array, if any // index is unmarked. for (int i = 0; i < b; i++) if (hash[i] == false) return false; return true;} // Driver codepublic static void Main(){ int b = 13; String n = "1298450376ABC"; if (checkPandigital(b, n)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by nitin mittal.
<?php// php program to check if a number is pandigital// in given base. // Return true if n is pandigit else return false.function checkPandigital($b, $n){ // Checking length is less than base if (strlen($n) < $b) return 0; $hash = array(); for($i = 0; $i< $b; $i++) $hash[$i] = 0; // Traversing each digit of the number. for ($i = 0; $i < strlen($n); $i++) { // If digit is integer if ($n[$i] >= '0' && $n[$i] <= '9') $hash[$n[$i] - '0'] = 1; // If digit is alphabet else if (ord($n[$i]) - ord('A') <= $b - 11) $hash[ord($n[$i]) - ord('A') + 10] = 1; } // Checking hash array, if any index is // unmarked. for ($i = 0; $i < $b; $i++) if ($hash[$i] == 0) return 0; return 1;} // Driver Program$b = 13;$n = "1298450376ABC"; if(checkPandigital($b, $n)) echo "Yes";else echo "No"; // This code is contributed by Sam007.?>
<script> // Javascript program to check if a number is pandigital// in given base. // Return true if n is pandigit else return false.function checkPandigital(b, n){ // Checking length is less than base if (n.length < b) return 0; let hash = []; for(let i = 0; i< b; i++) hash[i] = 0; // Traversing each digit of the number. for (let i = 0; i < n.length; i++) { // If digit is integer if (n[i] >= '0' && n[i] <= '9') hash[n[i] - '0'] = 1; // If digit is alphabet else if (n.charCodeAt(i) - 'A'.charCodeAt(0) <= b - 11) hash[n.charCodeAt(i) - 'A'.charCodeAt(0) + 10] = 1; } // Checking hash array, if any index is // unmarked. for (let i = 0; i < b; i++) if (hash[i] == 0) return 0; return 1;} // Driver Programlet b = 13;let n = "1298450376ABC"; if(checkPandigital(b, n)) document.write("Yes");else document.write("No"); // This code is contributed by _saurabh_jaiswal.</script>
Output:
Yes
Reference: https://en.wikipedia.org/wiki/Pandigital_numberThis article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
Sam007
Mithun Kumar
_saurabh_jaiswal
bunnyram19
simmytarika5
large-numbers
number-digits
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Check if a number is Palindrome
Program to multiply two matrices
Merge two sorted arrays with O(1) extra space
Generate all permutation of a set in Python
Count ways to reach the n'th stair
|
[
{
"code": null,
"e": 25961,
"s": 25933,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 26280,
"s": 25961,
"text": "Given an integer n and its base b. The task is to check if given number is Pandigital Number in the given base or not. A Pandigital number is an integer that has each digit of its base at least once.It may be assumed that base is smaller than or equal to 36. In base 36, digits are [0, 1, ...9. A, B, ...Z]Examples : "
},
{
"code": null,
"e": 26524,
"s": 26280,
"text": "Input : n = \"9651723480\", b = 10\nOutput : Yes\nGiven number n has all digits from 0 to 9\n\nInput : n = \"23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\", \n b = 36\nOutput : No\nGiven number n doesn't have all digits in base\n36. For example 1 is missing."
},
{
"code": null,
"e": 26899,
"s": 26526,
"text": "Make a boolean hash array of size equal to base of the number and initialize it with false. Now, iterate each digit of the number mark its corresponding index value as true in the hash array. In the end, check whether all the value in hash array are marked or not, if marked print “Yes” i.e Pandigital number else print “No”.Below is the implementation of this approach: "
},
{
"code": null,
"e": 26903,
"s": 26899,
"text": "C++"
},
{
"code": null,
"e": 26908,
"s": 26903,
"text": "Java"
},
{
"code": null,
"e": 26916,
"s": 26908,
"text": "Python3"
},
{
"code": null,
"e": 26919,
"s": 26916,
"text": "C#"
},
{
"code": null,
"e": 26923,
"s": 26919,
"text": "PHP"
},
{
"code": null,
"e": 26934,
"s": 26923,
"text": "Javascript"
},
{
"code": "// C++ program to check if a number is pandigital// in given base.#include<bits/stdc++.h>using namespace std; // Return true if n is pandigit else return false.bool checkPandigital(int b, char n[]){ // Checking length is less than base if (strlen(n) < b) return false; bool hash[b]; memset(hash, false, sizeof(hash)); // Traversing each digit of the number. for (int i = 0; i < strlen(n); i++) { // If digit is integer if (n[i] >= '0' && n[i] <= '9') hash[n[i] - '0'] = true; // If digit is alphabet else if (n[i] - 'A' <= b - 11) hash[n[i] - 'A' + 10] = true; } // Checking hash array, if any index is // unmarked. for (int i = 0; i < b; i++) if (hash[i] == false) return false; return true;} // Driver Programint main(){ int b = 13; char n[] = \"1298450376ABC\"; (checkPandigital(b, n))? (cout << \"Yes\" << endl): (cout << \"No\" << endl); return 0;}",
"e": 27940,
"s": 26934,
"text": null
},
{
"code": "// Java program to check if a number// is pandigital in given base.import java.util.*; class GFG { // Return true if n is pandigit// else return false.static boolean checkPandigital(int b, String n) { // Checking length is less than base if (n.length() < b) return false; boolean hash[] = new boolean[b]; Arrays.fill(hash, false); // Traversing each digit of the number. for (int i = 0; i < n.length(); i++) { // If digit is integer if (n.charAt(i) >= '0' && n.charAt(i) <= '9') hash[n.charAt(i) - '0'] = true; // If digit is alphabet else if (n.charAt(i) - 'A' <= b - 11) hash[n.charAt(i) - 'A' + 10] = true; } // Checking hash array, if any // index is unmarked. for (int i = 0; i < b; i++) if (hash[i] == false) return false; return true;} // Driver codepublic static void main(String[] args){ int b = 13; String n = \"1298450376ABC\"; if (checkPandigital(b, n)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by Anant Agarwal.",
"e": 29024,
"s": 27940,
"text": null
},
{
"code": "# Python3 program to check if a number is# pandigital in given base. # Return true if n is pandigit else return false.def checkPandigital(b, n): # Checking length is less than base if (len(n) < b): return 0; hash = [0] * b; # Traversing each digit of the number. for i in range(len(n)): # If digit is integer if (n[i] >= '0' and n[i] <= '9'): hash[ord(n[i]) - ord('0')] = 1; # If digit is alphabet else if (ord(n[i]) - ord('A') <= b - 11): hash[ord(n[i]) - ord('A') + 10] = 1; # Checking hash array, if any index is # unmarked. for i in range(b): if (hash[i] == 0): return 0; return 1; # Driver Codeb = 13;n = \"1298450376ABC\"; if(checkPandigital(b, n)): print(\"Yes\");else: print(\"No\"); # This code is contributed by mits",
"e": 29888,
"s": 29024,
"text": null
},
{
"code": "// C# program to check if a number// is pandigital in given base.using System; class GFG { // Return true if n is pandigit// else return false.static bool checkPandigital(int b, string n) { // Checking length is less than base if (n.Length < b) return false; bool []hash = new bool[b]; for(int i = 0; i < b; i++) hash[i] = false; // Traversing each digit of the number. for (int i = 0; i < n.Length; i++) { // If digit is integer if (n[i] >= '0' && n[i] <= '9') hash[n[i] - '0'] = true; // If digit is alphabet else if (n[i] - 'A' <= b - 11) hash[n[i] - 'A' + 10] = true; } // Checking hash array, if any // index is unmarked. for (int i = 0; i < b; i++) if (hash[i] == false) return false; return true;} // Driver codepublic static void Main(){ int b = 13; String n = \"1298450376ABC\"; if (checkPandigital(b, n)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by nitin mittal.",
"e": 30914,
"s": 29888,
"text": null
},
{
"code": "<?php// php program to check if a number is pandigital// in given base. // Return true if n is pandigit else return false.function checkPandigital($b, $n){ // Checking length is less than base if (strlen($n) < $b) return 0; $hash = array(); for($i = 0; $i< $b; $i++) $hash[$i] = 0; // Traversing each digit of the number. for ($i = 0; $i < strlen($n); $i++) { // If digit is integer if ($n[$i] >= '0' && $n[$i] <= '9') $hash[$n[$i] - '0'] = 1; // If digit is alphabet else if (ord($n[$i]) - ord('A') <= $b - 11) $hash[ord($n[$i]) - ord('A') + 10] = 1; } // Checking hash array, if any index is // unmarked. for ($i = 0; $i < $b; $i++) if ($hash[$i] == 0) return 0; return 1;} // Driver Program$b = 13;$n = \"1298450376ABC\"; if(checkPandigital($b, $n)) echo \"Yes\";else echo \"No\"; // This code is contributed by Sam007.?>",
"e": 31888,
"s": 30914,
"text": null
},
{
"code": "<script> // Javascript program to check if a number is pandigital// in given base. // Return true if n is pandigit else return false.function checkPandigital(b, n){ // Checking length is less than base if (n.length < b) return 0; let hash = []; for(let i = 0; i< b; i++) hash[i] = 0; // Traversing each digit of the number. for (let i = 0; i < n.length; i++) { // If digit is integer if (n[i] >= '0' && n[i] <= '9') hash[n[i] - '0'] = 1; // If digit is alphabet else if (n.charCodeAt(i) - 'A'.charCodeAt(0) <= b - 11) hash[n.charCodeAt(i) - 'A'.charCodeAt(0) + 10] = 1; } // Checking hash array, if any index is // unmarked. for (let i = 0; i < b; i++) if (hash[i] == 0) return 0; return 1;} // Driver Programlet b = 13;let n = \"1298450376ABC\"; if(checkPandigital(b, n)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by _saurabh_jaiswal.</script>",
"e": 32924,
"s": 31888,
"text": null
},
{
"code": null,
"e": 32934,
"s": 32924,
"text": "Output: "
},
{
"code": null,
"e": 32938,
"s": 32934,
"text": "Yes"
},
{
"code": null,
"e": 33417,
"s": 32938,
"text": "Reference: https://en.wikipedia.org/wiki/Pandigital_numberThis article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 33430,
"s": 33417,
"text": "nitin mittal"
},
{
"code": null,
"e": 33437,
"s": 33430,
"text": "Sam007"
},
{
"code": null,
"e": 33450,
"s": 33437,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 33467,
"s": 33450,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 33478,
"s": 33467,
"text": "bunnyram19"
},
{
"code": null,
"e": 33491,
"s": 33478,
"text": "simmytarika5"
},
{
"code": null,
"e": 33505,
"s": 33491,
"text": "large-numbers"
},
{
"code": null,
"e": 33519,
"s": 33505,
"text": "number-digits"
},
{
"code": null,
"e": 33532,
"s": 33519,
"text": "Mathematical"
},
{
"code": null,
"e": 33545,
"s": 33532,
"text": "Mathematical"
},
{
"code": null,
"e": 33643,
"s": 33545,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33687,
"s": 33643,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 33729,
"s": 33687,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 33760,
"s": 33729,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 33831,
"s": 33760,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 33856,
"s": 33831,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 33888,
"s": 33856,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 33921,
"s": 33888,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 33967,
"s": 33921,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 34011,
"s": 33967,
"text": "Generate all permutation of a set in Python"
}
] |
fileinput.input() in Python - GeeksforGeeks
|
22 Apr, 2020
With the help of fileinput.input() method, we can get the file as input and to can be used to update and append the data in the file by using fileinput.input() method.
Syntax : fileinput.input(files)
Return : Return the data of the file.
Example #1 :In this example we can see that by using fileinput.input() method, we are able to get the data of the file line by line by using this method.
Input File –
# import fileinputimport fileinput # Using fileinput.input() methodfor line in fileinput.input(files ='gfg.txt'): print(line)
Output : Example #2 :
Input Files –
# import fileinputimport fileinput # Using fileinput.input() methodfor line in fileinput.input(files =('gfg.txt', 'gfg1.txt')): print(line)
Output :
Python fileinput-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
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25571,
"s": 25543,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 25739,
"s": 25571,
"text": "With the help of fileinput.input() method, we can get the file as input and to can be used to update and append the data in the file by using fileinput.input() method."
},
{
"code": null,
"e": 25771,
"s": 25739,
"text": "Syntax : fileinput.input(files)"
},
{
"code": null,
"e": 25809,
"s": 25771,
"text": "Return : Return the data of the file."
},
{
"code": null,
"e": 25963,
"s": 25809,
"text": "Example #1 :In this example we can see that by using fileinput.input() method, we are able to get the data of the file line by line by using this method."
},
{
"code": null,
"e": 25976,
"s": 25963,
"text": "Input File –"
},
{
"code": "# import fileinputimport fileinput # Using fileinput.input() methodfor line in fileinput.input(files ='gfg.txt'): print(line)",
"e": 26106,
"s": 25976,
"text": null
},
{
"code": null,
"e": 26128,
"s": 26106,
"text": "Output : Example #2 :"
},
{
"code": null,
"e": 26142,
"s": 26128,
"text": "Input Files –"
},
{
"code": "# import fileinputimport fileinput # Using fileinput.input() methodfor line in fileinput.input(files =('gfg.txt', 'gfg1.txt')): print(line)",
"e": 26286,
"s": 26142,
"text": null
},
{
"code": null,
"e": 26295,
"s": 26286,
"text": "Output :"
},
{
"code": null,
"e": 26320,
"s": 26295,
"text": "Python fileinput-library"
},
{
"code": null,
"e": 26327,
"s": 26320,
"text": "Python"
},
{
"code": null,
"e": 26425,
"s": 26327,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26443,
"s": 26425,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26475,
"s": 26443,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26497,
"s": 26475,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26539,
"s": 26497,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26569,
"s": 26539,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26595,
"s": 26569,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26624,
"s": 26595,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 26661,
"s": 26624,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26697,
"s": 26661,
"text": "Convert integer to string in Python"
}
] |
Style <input> elements with a "readonly" attribute with CSS
|
To select elements that are read-only, use the CSS :read-only selector.
You can try to run the following code to implement the :read-only selector
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
input:read-only {
background-color: blue;
color: white;
}
</style>
</head>
<body>
<form>
Subject: <input type = "text" name = "subject" value = "Maths"><br>
Student: <input type = "text" name = "student" readonly value = "Amit"><br>
</form>
</body>
</html>
|
[
{
"code": null,
"e": 1134,
"s": 1062,
"text": "To select elements that are read-only, use the CSS :read-only selector."
},
{
"code": null,
"e": 1209,
"s": 1134,
"text": "You can try to run the following code to implement the :read-only selector"
},
{
"code": null,
"e": 1219,
"s": 1209,
"text": "Live Demo"
},
{
"code": null,
"e": 1610,
"s": 1219,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n input:read-only {\n background-color: blue;\n color: white;\n }\n </style>\n </head>\n <body>\n <form>\n Subject: <input type = \"text\" name = \"subject\" value = \"Maths\"><br>\n Student: <input type = \"text\" name = \"student\" readonly value = \"Amit\"><br>\n </form>\n </body>\n</html>"
}
] |
What is $(document).ready() method in jQuery?
|
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ).ready() method will run once the page DOM is ready to execute JavaScript code.
You can try to run the following code to learn how to use $(document).ready() method in jQuery:
Live Demo
<html>
<head>
<title>jQuery Function</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function() {
alert("Hello, world!");
});
});
</script>
</head>
<body>
<div id = "mydiv">
Click on this to see a dialogue box.
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1275,
"s": 1062,
"text": "The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ).ready() method will run once the page DOM is ready to execute JavaScript code."
},
{
"code": null,
"e": 1371,
"s": 1275,
"text": "You can try to run the following code to learn how to use $(document).ready() method in jQuery:"
},
{
"code": null,
"e": 1381,
"s": 1371,
"text": "Live Demo"
},
{
"code": null,
"e": 1832,
"s": 1381,
"text": "<html>\n\n <head>\n <title>jQuery Function</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n\n <script>\n $(document).ready(function() {\n $(\"div\").click(function() {\n alert(\"Hello, world!\");\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"mydiv\">\n Click on this to see a dialogue box.\n </div>\n </body>\n</html>"
}
] |
Mahotas – Convolution of Image - GeeksforGeeks
|
29 Jul, 2021
In this article, we will see how we can do convolution of the image in mahotas. Convolution is a simple mathematical operation which is fundamental to many common image processing operators. Convolution provides a way of `multiplying together’ two arrays of numbers, generally of different sizes, but of the same dimensionality, to produce a third array of numbers of the same dimensionality.
In this tutorial, we will use “lena” image, below is the command to load it.
mahotas.demos.load('lena')
Below is the lena image
In order to do this we will use mahotas.convolve method
Syntax : mahotas.convolve(img, weight)
Argument : It takes image object and numpy nd array objectas argument
Return : It returns image object
Note : Input image should be filtered or should be loaded as grey
In order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this
image = image[:, :, 0]
Below is the implementation
Python3
# importing required librariesimport mahotasimport mahotas.demosfrom pylab import gray, imshow, showimport numpy as np # loading imageimg = mahotas.demos.load('lena') # filtering imageimg = img.max(2) # otsu methodT_otsu = mahotas.otsu(img) # image values should be greater than otsu valueimg = img > T_otsu print("Image threshold using Otsu Method") # showing imageimshow(img)show() # weightweight = np.ones((5, 5), float) # convolving imagenew_img = mahotas.convolve(img, weight) print("Convolved Image") # showing imageimshow(new_img)show()
Output :
Image threshold using Otsu Method
Convolved Image
Another example
Python3
# importing required librariesimport mahotasimport numpy as npfrom pylab import gray, imshow, showimport os # loading imageimg = mahotas.imread('dog_image.png') # filtering imageimg = img[:, :, 0] # otsu methodT_otsu = mahotas.otsu(img) # image values should be greater than otsu valueimg = img > T_otsu print("Image threshold using Otsu Method") # showing imageimshow(img)show() # weightweight = np.ones((5, 5), float) # convolving imagenew_img = mahotas.convolve(img, weight) print("Convolved Image") # showing imageimshow(new_img)show()
Output :
Image threshold using Otsu Method
Convolved Image
surinderdawra388
sweetyty
Python-Mahotas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 24693,
"s": 24665,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 25086,
"s": 24693,
"text": "In this article, we will see how we can do convolution of the image in mahotas. Convolution is a simple mathematical operation which is fundamental to many common image processing operators. Convolution provides a way of `multiplying together’ two arrays of numbers, generally of different sizes, but of the same dimensionality, to produce a third array of numbers of the same dimensionality."
},
{
"code": null,
"e": 25166,
"s": 25086,
"text": "In this tutorial, we will use “lena” image, below is the command to load it. "
},
{
"code": null,
"e": 25193,
"s": 25166,
"text": "mahotas.demos.load('lena')"
},
{
"code": null,
"e": 25218,
"s": 25193,
"text": "Below is the lena image "
},
{
"code": null,
"e": 25274,
"s": 25218,
"text": "In order to do this we will use mahotas.convolve method"
},
{
"code": null,
"e": 25313,
"s": 25274,
"text": "Syntax : mahotas.convolve(img, weight)"
},
{
"code": null,
"e": 25383,
"s": 25313,
"text": "Argument : It takes image object and numpy nd array objectas argument"
},
{
"code": null,
"e": 25416,
"s": 25383,
"text": "Return : It returns image object"
},
{
"code": null,
"e": 25482,
"s": 25416,
"text": "Note : Input image should be filtered or should be loaded as grey"
},
{
"code": null,
"e": 25638,
"s": 25482,
"text": "In order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this "
},
{
"code": null,
"e": 25661,
"s": 25638,
"text": "image = image[:, :, 0]"
},
{
"code": null,
"e": 25690,
"s": 25661,
"text": "Below is the implementation "
},
{
"code": null,
"e": 25698,
"s": 25690,
"text": "Python3"
},
{
"code": "# importing required librariesimport mahotasimport mahotas.demosfrom pylab import gray, imshow, showimport numpy as np # loading imageimg = mahotas.demos.load('lena') # filtering imageimg = img.max(2) # otsu methodT_otsu = mahotas.otsu(img) # image values should be greater than otsu valueimg = img > T_otsu print(\"Image threshold using Otsu Method\") # showing imageimshow(img)show() # weightweight = np.ones((5, 5), float) # convolving imagenew_img = mahotas.convolve(img, weight) print(\"Convolved Image\") # showing imageimshow(new_img)show()",
"e": 26257,
"s": 25698,
"text": null
},
{
"code": null,
"e": 26267,
"s": 26257,
"text": "Output : "
},
{
"code": null,
"e": 26301,
"s": 26267,
"text": "Image threshold using Otsu Method"
},
{
"code": null,
"e": 26317,
"s": 26301,
"text": "Convolved Image"
},
{
"code": null,
"e": 26335,
"s": 26317,
"text": "Another example "
},
{
"code": null,
"e": 26343,
"s": 26335,
"text": "Python3"
},
{
"code": "# importing required librariesimport mahotasimport numpy as npfrom pylab import gray, imshow, showimport os # loading imageimg = mahotas.imread('dog_image.png') # filtering imageimg = img[:, :, 0] # otsu methodT_otsu = mahotas.otsu(img) # image values should be greater than otsu valueimg = img > T_otsu print(\"Image threshold using Otsu Method\") # showing imageimshow(img)show() # weightweight = np.ones((5, 5), float) # convolving imagenew_img = mahotas.convolve(img, weight) print(\"Convolved Image\") # showing imageimshow(new_img)show()",
"e": 26898,
"s": 26343,
"text": null
},
{
"code": null,
"e": 26908,
"s": 26898,
"text": "Output : "
},
{
"code": null,
"e": 26943,
"s": 26908,
"text": "Image threshold using Otsu Method "
},
{
"code": null,
"e": 26959,
"s": 26943,
"text": "Convolved Image"
},
{
"code": null,
"e": 26978,
"s": 26961,
"text": "surinderdawra388"
},
{
"code": null,
"e": 26987,
"s": 26978,
"text": "sweetyty"
},
{
"code": null,
"e": 27002,
"s": 26987,
"text": "Python-Mahotas"
},
{
"code": null,
"e": 27009,
"s": 27002,
"text": "Python"
},
{
"code": null,
"e": 27107,
"s": 27009,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27116,
"s": 27107,
"text": "Comments"
},
{
"code": null,
"e": 27129,
"s": 27116,
"text": "Old Comments"
},
{
"code": null,
"e": 27147,
"s": 27129,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27182,
"s": 27147,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27204,
"s": 27182,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27236,
"s": 27204,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27266,
"s": 27236,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27308,
"s": 27266,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27351,
"s": 27308,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27377,
"s": 27351,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27421,
"s": 27377,
"text": "Reading and Writing to text files in Python"
}
] |
Using proptypes in React.js
|
Use of proptypes ensures the type safety of receiving props on the components and also helps in making correct calculation.
Example − If we are receiving name as string and age as number then it should be received with the same type. If we receive age in string then it can result into incorrect calculation.
To use proptypes we have to install below package.
npm install –save prop-types
This package is provided by React Team. To use it on component, we will import it first
import PropType from ‘prop-types’;
we can use it on any type of component (Stateful or stateless).
At the end of component before exporting it we write it as −
Player.propTypes={};
Note the propType on name of component as shown above.
Player.propTypes={
age:PropType.number,
name:PropType.string
}
With the JavaScript object we are specifying the name of prop and its valid data type. If we pass an incorrect data type we will receive a warning in browser console.
The available prop types are −
any => it can be of any type
Boolean
String
Number
func => means function
array
object
symbol
Showing a warning message in browser console if there is a mismatch in prop type will help the developer correct its mistake.
Though we can use the proptype on every component, but should be used if the component is going to be used by other developers and there is considerable use of data types.
We can manipulate the dom element by getting hold on to it using ref.
<input value={this.props.name}
ref={(myInput)=>{this.testInput=myInput}}/>
we can use it on componentDidMount
componentDidMount(){
this.testInput.focus();
}
The alternate latest approach to use Ref
Inside constructor we can create a ref
constructor(props){
super(props);
this.testInputRef=React.createRef();
}
We can use the created ref on input element like below −
<input value={this.props.name}
ref={this.testInputRef }/>
how to access this new way in componentDidMount
componentDidMount(){
this.testInputRef.current.focus();
}
We have to use the current on the ref element to make it work.
This way we can avoid the creation of anonymous function to create reference for inputs.
We can create ref using useRef
import React, { useRef} from ‘react’;
const myFunction=(props)=>{
const inputRef = useRef(null);// we can give some value to ref using its constructor
}
We can use the ref similar like created in stateful component earlier.
Note that this ref should not be used immediately as the jsx code will not be prepared by that time.
We can use the ref element inside useEffect. the useEffect function runs after the render of jsx code so that we can sure the ref variables are attached to the actual elements and are ready to use.
These refs will be accessed like above using current keyword.
This.inputRef.current.click();
With the creation of ref, we are keeping a mutable field in our component to handle it easily.
Note that change in ref does not trigger re-render. There is an useCallback method which can notify the changes and work asynchronously.
|
[
{
"code": null,
"e": 1186,
"s": 1062,
"text": "Use of proptypes ensures the type safety of receiving props on the components and also helps in making correct calculation."
},
{
"code": null,
"e": 1371,
"s": 1186,
"text": "Example − If we are receiving name as string and age as number then it should be received with the same type. If we receive age in string then it can result into incorrect calculation."
},
{
"code": null,
"e": 1422,
"s": 1371,
"text": "To use proptypes we have to install below package."
},
{
"code": null,
"e": 1451,
"s": 1422,
"text": "npm install –save prop-types"
},
{
"code": null,
"e": 1539,
"s": 1451,
"text": "This package is provided by React Team. To use it on component, we will import it first"
},
{
"code": null,
"e": 1574,
"s": 1539,
"text": "import PropType from ‘prop-types’;"
},
{
"code": null,
"e": 1638,
"s": 1574,
"text": "we can use it on any type of component (Stateful or stateless)."
},
{
"code": null,
"e": 1699,
"s": 1638,
"text": "At the end of component before exporting it we write it as −"
},
{
"code": null,
"e": 1844,
"s": 1699,
"text": "Player.propTypes={};\nNote the propType on name of component as shown above.\nPlayer.propTypes={\n age:PropType.number,\n name:PropType.string\n}"
},
{
"code": null,
"e": 2011,
"s": 1844,
"text": "With the JavaScript object we are specifying the name of prop and its valid data type. If we pass an incorrect data type we will receive a warning in browser console."
},
{
"code": null,
"e": 2042,
"s": 2011,
"text": "The available prop types are −"
},
{
"code": null,
"e": 2071,
"s": 2042,
"text": "any => it can be of any type"
},
{
"code": null,
"e": 2079,
"s": 2071,
"text": "Boolean"
},
{
"code": null,
"e": 2086,
"s": 2079,
"text": "String"
},
{
"code": null,
"e": 2093,
"s": 2086,
"text": "Number"
},
{
"code": null,
"e": 2116,
"s": 2093,
"text": "func => means function"
},
{
"code": null,
"e": 2122,
"s": 2116,
"text": "array"
},
{
"code": null,
"e": 2129,
"s": 2122,
"text": "object"
},
{
"code": null,
"e": 2136,
"s": 2129,
"text": "symbol"
},
{
"code": null,
"e": 2262,
"s": 2136,
"text": "Showing a warning message in browser console if there is a mismatch in prop type will help the developer correct its mistake."
},
{
"code": null,
"e": 2434,
"s": 2262,
"text": "Though we can use the proptype on every component, but should be used if the component is going to be used by other developers and there is considerable use of data types."
},
{
"code": null,
"e": 2504,
"s": 2434,
"text": "We can manipulate the dom element by getting hold on to it using ref."
},
{
"code": null,
"e": 2664,
"s": 2504,
"text": "<input value={this.props.name}\nref={(myInput)=>{this.testInput=myInput}}/>\nwe can use it on componentDidMount\ncomponentDidMount(){\n this.testInput.focus();\n}"
},
{
"code": null,
"e": 2705,
"s": 2664,
"text": "The alternate latest approach to use Ref"
},
{
"code": null,
"e": 2823,
"s": 2705,
"text": "Inside constructor we can create a ref\nconstructor(props){\n super(props);\n this.testInputRef=React.createRef();\n}"
},
{
"code": null,
"e": 2880,
"s": 2823,
"text": "We can use the created ref on input element like below −"
},
{
"code": null,
"e": 2938,
"s": 2880,
"text": "<input value={this.props.name}\nref={this.testInputRef }/>"
},
{
"code": null,
"e": 2986,
"s": 2938,
"text": "how to access this new way in componentDidMount"
},
{
"code": null,
"e": 3047,
"s": 2986,
"text": "componentDidMount(){\n this.testInputRef.current.focus();\n}"
},
{
"code": null,
"e": 3110,
"s": 3047,
"text": "We have to use the current on the ref element to make it work."
},
{
"code": null,
"e": 3199,
"s": 3110,
"text": "This way we can avoid the creation of anonymous function to create reference for inputs."
},
{
"code": null,
"e": 3386,
"s": 3199,
"text": "We can create ref using useRef\nimport React, { useRef} from ‘react’;\nconst myFunction=(props)=>{\n const inputRef = useRef(null);// we can give some value to ref using its constructor\n}"
},
{
"code": null,
"e": 3457,
"s": 3386,
"text": "We can use the ref similar like created in stateful component earlier."
},
{
"code": null,
"e": 3558,
"s": 3457,
"text": "Note that this ref should not be used immediately as the jsx code will not be prepared by that time."
},
{
"code": null,
"e": 3756,
"s": 3558,
"text": "We can use the ref element inside useEffect. the useEffect function runs after the render of jsx code so that we can sure the ref variables are attached to the actual elements and are ready to use."
},
{
"code": null,
"e": 3818,
"s": 3756,
"text": "These refs will be accessed like above using current keyword."
},
{
"code": null,
"e": 3849,
"s": 3818,
"text": "This.inputRef.current.click();"
},
{
"code": null,
"e": 3944,
"s": 3849,
"text": "With the creation of ref, we are keeping a mutable field in our component to handle it easily."
},
{
"code": null,
"e": 4081,
"s": 3944,
"text": "Note that change in ref does not trigger re-render. There is an useCallback method which can notify the changes and work asynchronously."
}
] |
Arden's Theorem and Challenging Applications | Set 2 - GeeksforGeeks
|
24 Sep, 2020
Having gained the knowledge of how to draw a basic Finite State Machine ( DFA, NFA or -NFA ). We head to deriving a Regular Expression from the provided state machine.
For certain examples provided below, it’s fairly simple to derive it.
But for the following example, it’s fairly hard to derive the Regular Expression by just observing the Finite State Machine. For this purpose, we make use of Arden’s Theorem to simplify our Individual State Equations and come up with our final state equation ( which may or may not be the simplified version )
Arden’s Theorem states that, if P & Q are two regular expressions over , and if P does not contain , then the following equation R given by R = Q + RP has a unique solution ; R = QP*
PROOF :-
R = Q + RP
R = Q + QP*P ( Substituting the value of R )
R = Q( + P*P)
R = QP *( P*P = , + = P* )
Let’s solve the provided automata above with the help of Arden’s Theorem.
We see, that on state C, there is a state transition coming from B when a is the input
C = Ba
On state B, There is a self loop on input b, a transition from A when input is a, a transition from state C when input is b
B = Bb + Cb + Aa
On state A, There is a transition ( being the start state, transition must be included), a self loop on input a, a transition from B when input is b.
A = + Aa + Bb
Putting (2) in (1), we get
C = Ba
C = (Aa + Bb + Cb)a
C = Aaa + Bba + Cba
Putting (1) in (2), we get
B = Bb + Cb + Aa
B = Aa + Bb + (Ba)b
B = Aa + B(b + ab)
B = Aa(b + ab)* (Using R = QP*)
Putting (2) in (3), we get
A = + Aa + Bb
A = + Aa + Aa(b + ab)*b
A = + A(a + a(b + ab)*b)
A = (a + a(b + ab)*b)*
A = (a + a(b + ab)*b)*
As a final step, Let’s combine all the simplified equations onto the final state C
C = Ba
C = Aa(b + ab)*a
C = (a + a(b + ab)*b)* a (b + ab)* a
Now this example corresponded to direct derivation from a provided NFA to a Regular Expression.
Let’s say, we are provided with a problem that goes like
Problem : Derive a regular expression to represent a language having even no. of a’s
For this case, it’s difficult to arrive at a regular expression with just trial and error methodology. We might come across sample solutions like :-
which might satisfy some cases, but also leads to unwanted cases and missing cases with alternate a’s and b’s. The best way to solve this problem is to first draw a finite state machine for the same, and then derive the regular expression from the same.
The figure below shows the DFA for the provided problem
Now that we have the DFA, let’s solve it using Arden’s Theorem of Individual State Equations.
We see that on state A, there is a self loop with input b and transition from B with input a
A = + Ab + Ba
We see that on state B, there is a self loop on input b and transition from A when input is a.
B = Aa + Bb
Taking equation for B, we can apply Arden’s theorem
B = Aa + Bb
B = Aab*
Substituting the value of B in A we get
A = + Ab + Ba
A = + Ab + (Aab*)a
A = ( b + ab*a )*
A = ( b + ab*a )*
Hence, the regular expression for the provided problem is RE : ( b + ab*a )*
We see that Arden’s theorem can be used as a powerful simplification tool to determine the Regular Expressions and also to design the desired Finite State Machine from the same.
Please refer for Set 1
subratochowdhury111
Technical Scripter 2018
GATE CS
Technical Scripter
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Clustered and Non-clustered index
Phases of a Compiler
Regular Expressions, Regular Grammar and Regular Languages
Preemptive and Non-Preemptive Scheduling
Introduction of Process Synchronization
Regular Expressions, Regular Grammar and Regular Languages
Difference between DFA and NFA
Introduction of Finite Automata
Difference between Mealy machine and Moore machine
Pumping Lemma in Theory of Computation
|
[
{
"code": null,
"e": 24376,
"s": 24348,
"text": "\n24 Sep, 2020"
},
{
"code": null,
"e": 24545,
"s": 24376,
"text": "Having gained the knowledge of how to draw a basic Finite State Machine ( DFA, NFA or -NFA ). We head to deriving a Regular Expression from the provided state machine. "
},
{
"code": null,
"e": 24617,
"s": 24545,
"text": "For certain examples provided below, it’s fairly simple to derive it. "
},
{
"code": null,
"e": 24928,
"s": 24617,
"text": "But for the following example, it’s fairly hard to derive the Regular Expression by just observing the Finite State Machine. For this purpose, we make use of Arden’s Theorem to simplify our Individual State Equations and come up with our final state equation ( which may or may not be the simplified version ) "
},
{
"code": null,
"e": 25115,
"s": 24930,
"text": "Arden’s Theorem states that, if P & Q are two regular expressions over , and if P does not contain , then the following equation R given by R = Q + RP has a unique solution ; R = QP* "
},
{
"code": null,
"e": 25229,
"s": 25115,
"text": "PROOF :- \nR = Q + RP\nR = Q + QP*P ( Substituting the value of R )\nR = Q( + P*P)\n\nR = QP *( P*P = , + = P* )\n"
},
{
"code": null,
"e": 25304,
"s": 25229,
"text": "Let’s solve the provided automata above with the help of Arden’s Theorem. "
},
{
"code": null,
"e": 25392,
"s": 25304,
"text": "We see, that on state C, there is a state transition coming from B when a is the input "
},
{
"code": null,
"e": 25405,
"s": 25394,
"text": " C = Ba \n"
},
{
"code": null,
"e": 25530,
"s": 25405,
"text": "On state B, There is a self loop on input b, a transition from A when input is a, a transition from state C when input is b "
},
{
"code": null,
"e": 25553,
"s": 25532,
"text": " B = Bb + Cb + Aa \n"
},
{
"code": null,
"e": 25707,
"s": 25553,
"text": "On state A, There is a transition ( being the start state, transition must be included), a self loop on input a, a transition from B when input is b. "
},
{
"code": null,
"e": 25729,
"s": 25709,
"text": " A = + Aa + Bb \n"
},
{
"code": null,
"e": 25758,
"s": 25729,
"text": "Putting (2) in (1), we get "
},
{
"code": null,
"e": 25806,
"s": 25758,
"text": "C = Ba\nC = (Aa + Bb + Cb)a\nC = Aaa + Bba + Cba\n"
},
{
"code": null,
"e": 25834,
"s": 25806,
"text": "Putting (1) in (2), we get "
},
{
"code": null,
"e": 25926,
"s": 25836,
"text": "B = Bb + Cb + Aa\nB = Aa + Bb + (Ba)b\nB = Aa + B(b + ab)\nB = Aa(b + ab)* (Using R = QP*)\n"
},
{
"code": null,
"e": 25954,
"s": 25926,
"text": "Putting (2) in (3), we get "
},
{
"code": null,
"e": 26070,
"s": 25956,
"text": "A = + Aa + Bb\nA = + Aa + Aa(b + ab)*b\nA = + A(a + a(b + ab)*b)\nA = (a + a(b + ab)*b)*\nA = (a + a(b + ab)*b)*\n"
},
{
"code": null,
"e": 26154,
"s": 26070,
"text": "As a final step, Let’s combine all the simplified equations onto the final state C "
},
{
"code": null,
"e": 26218,
"s": 26156,
"text": "C = Ba\nC = Aa(b + ab)*a\nC = (a + a(b + ab)*b)* a (b + ab)* a\n"
},
{
"code": null,
"e": 26315,
"s": 26218,
"text": "Now this example corresponded to direct derivation from a provided NFA to a Regular Expression. "
},
{
"code": null,
"e": 26373,
"s": 26315,
"text": "Let’s say, we are provided with a problem that goes like "
},
{
"code": null,
"e": 26459,
"s": 26373,
"text": "Problem : Derive a regular expression to represent a language having even no. of a’s "
},
{
"code": null,
"e": 26609,
"s": 26459,
"text": "For this case, it’s difficult to arrive at a regular expression with just trial and error methodology. We might come across sample solutions like :- "
},
{
"code": null,
"e": 26864,
"s": 26609,
"text": "which might satisfy some cases, but also leads to unwanted cases and missing cases with alternate a’s and b’s. The best way to solve this problem is to first draw a finite state machine for the same, and then derive the regular expression from the same. "
},
{
"code": null,
"e": 26922,
"s": 26864,
"text": "The figure below shows the DFA for the provided problem "
},
{
"code": null,
"e": 27017,
"s": 26922,
"text": "Now that we have the DFA, let’s solve it using Arden’s Theorem of Individual State Equations. "
},
{
"code": null,
"e": 27112,
"s": 27017,
"text": "We see that on state A, there is a self loop with input b and transition from B with input a "
},
{
"code": null,
"e": 27129,
"s": 27112,
"text": "A = + Ab + Ba \n"
},
{
"code": null,
"e": 27225,
"s": 27129,
"text": "We see that on state B, there is a self loop on input b and transition from A when input is a. "
},
{
"code": null,
"e": 27240,
"s": 27227,
"text": "B = Aa + Bb\n"
},
{
"code": null,
"e": 27294,
"s": 27240,
"text": "Taking equation for B, we can apply Arden’s theorem "
},
{
"code": null,
"e": 27316,
"s": 27294,
"text": "B = Aa + Bb\nB = Aab*\n"
},
{
"code": null,
"e": 27358,
"s": 27316,
"text": "Substituting the value of B in A we get "
},
{
"code": null,
"e": 27431,
"s": 27358,
"text": "A = + Ab + Ba\nA = + Ab + (Aab*)a\nA = ( b + ab*a )*\nA = ( b + ab*a )*\n"
},
{
"code": null,
"e": 27509,
"s": 27431,
"text": "Hence, the regular expression for the provided problem is RE : ( b + ab*a )* "
},
{
"code": null,
"e": 27688,
"s": 27509,
"text": "We see that Arden’s theorem can be used as a powerful simplification tool to determine the Regular Expressions and also to design the desired Finite State Machine from the same. "
},
{
"code": null,
"e": 27712,
"s": 27688,
"text": "Please refer for Set 1 "
},
{
"code": null,
"e": 27732,
"s": 27712,
"text": "subratochowdhury111"
},
{
"code": null,
"e": 27756,
"s": 27732,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 27764,
"s": 27756,
"text": "GATE CS"
},
{
"code": null,
"e": 27783,
"s": 27764,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27816,
"s": 27783,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 27914,
"s": 27816,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27923,
"s": 27914,
"text": "Comments"
},
{
"code": null,
"e": 27936,
"s": 27923,
"text": "Old Comments"
},
{
"code": null,
"e": 27989,
"s": 27936,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 28010,
"s": 27989,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 28069,
"s": 28010,
"text": "Regular Expressions, Regular Grammar and Regular Languages"
},
{
"code": null,
"e": 28110,
"s": 28069,
"text": "Preemptive and Non-Preemptive Scheduling"
},
{
"code": null,
"e": 28150,
"s": 28110,
"text": "Introduction of Process Synchronization"
},
{
"code": null,
"e": 28209,
"s": 28150,
"text": "Regular Expressions, Regular Grammar and Regular Languages"
},
{
"code": null,
"e": 28240,
"s": 28209,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 28272,
"s": 28240,
"text": "Introduction of Finite Automata"
},
{
"code": null,
"e": 28323,
"s": 28272,
"text": "Difference between Mealy machine and Moore machine"
}
] |
Perl gmtime Function
|
This function returns a list of values corresponding to the date and time as specified by EXPR, or date and time returned by the time function if EXPR is omitted, localized for the standard Greenwich mean time. The values returned are as follows −
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
All list elements are numeric, and come straight out of the C `struct tm'. $sec, $min, and $hour are the seconds, minutes, and hours of the specified time. $mday is the day of the month, and $mon is the month itself, in the range 0..11 with 0 indicating January and 11 indicating December. $year is the number of years since 1900. That is, $year is 123 in year 2023. $wday is the day of the week, with 0 indicating Sunday and 3 indicating Wednesday. $yday is the day of the year, in the range 0..364 (or 0..365 in leap years). $isdst is always 0 .
Following is the simple syntax for this function −
gmtime EXPR
gmtime
This function returns a string of the form: Thu Sep 21 14:52:52 2000 in scalar context and in list context the individual time component values (seconds, minutes, hours, day of month, month, year, day of week, day of year, daylight savings time).
Following is the example code showing its basic usage −
#!/usr/bin/perl
@weekday = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
$local_time = gmtime();
print "Local time = $local_time\n";
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
$year = $year + 1900;
print "Formated time = $mday/$mon/$year $hour:$min:$sec $weekday[$wday]\n";
When above code is executed, it produces the following result −
Local time = Sun Sep 1 09:06:41 2013
Formated time = 1/8/2013 9:6:41 Sun
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2468,
"s": 2220,
"text": "This function returns a list of values corresponding to the date and time as specified by EXPR, or date and time returned by the time function if EXPR is omitted, localized for the standard Greenwich mean time. The values returned are as follows −"
},
{
"code": null,
"e": 2538,
"s": 2468,
"text": "($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);"
},
{
"code": null,
"e": 3086,
"s": 2538,
"text": "All list elements are numeric, and come straight out of the C `struct tm'. $sec, $min, and $hour are the seconds, minutes, and hours of the specified time. $mday is the day of the month, and $mon is the month itself, in the range 0..11 with 0 indicating January and 11 indicating December. $year is the number of years since 1900. That is, $year is 123 in year 2023. $wday is the day of the week, with 0 indicating Sunday and 3 indicating Wednesday. $yday is the day of the year, in the range 0..364 (or 0..365 in leap years). $isdst is always 0 ."
},
{
"code": null,
"e": 3137,
"s": 3086,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 3158,
"s": 3137,
"text": "gmtime EXPR\n\ngmtime\n"
},
{
"code": null,
"e": 3405,
"s": 3158,
"text": "This function returns a string of the form: Thu Sep 21 14:52:52 2000 in scalar context and in list context the individual time component values (seconds, minutes, hours, day of month, month, year, day of week, day of year, daylight savings time)."
},
{
"code": null,
"e": 3461,
"s": 3405,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 3770,
"s": 3461,
"text": "#!/usr/bin/perl\n\n@weekday = (\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\");\n\n$local_time = gmtime();\n\nprint \"Local time = $local_time\\n\";\n($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);\n$year = $year + 1900;\nprint \"Formated time = $mday/$mon/$year $hour:$min:$sec $weekday[$wday]\\n\";"
},
{
"code": null,
"e": 3834,
"s": 3770,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3909,
"s": 3834,
"text": "Local time = Sun Sep 1 09:06:41 2013\nFormated time = 1/8/2013 9:6:41 Sun\n"
},
{
"code": null,
"e": 3944,
"s": 3909,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3958,
"s": 3944,
"text": " Devi Killada"
},
{
"code": null,
"e": 3993,
"s": 3958,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4013,
"s": 3993,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4046,
"s": 4013,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4062,
"s": 4046,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 4095,
"s": 4062,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4112,
"s": 4095,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 4145,
"s": 4112,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4168,
"s": 4145,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 4203,
"s": 4168,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4226,
"s": 4203,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 4233,
"s": 4226,
"text": " Print"
},
{
"code": null,
"e": 4244,
"s": 4233,
"text": " Add Notes"
}
] |
Kth Largest Element in an Array
|
From a set of data, this algorithm will find the largest element to kth largest element of the array.
This problem can be solved easily by sorting the array. We can sort them either in ascending order or in descending order. Solving it in descending order, we can get first k elements to find our result.
Input:
The elements of an array: {1, 23, 12, 9, 30, 2, 50, 63, 87, 12, 45, 21}, K = 4
Output:
4 largest elements are 87 63 50 45
kthLargestElement(array, n, k)
Input: The array, number of elements in the array, place k.
Output: Display largest element to kth largest elements of the array.
Begin
sort the array in descending order
for i := 0 to k-1, do
display array[i]
done
End
#include<iostream>
#include<algorithm>
using namespace std;
bool compare(int a, int b) {
return a>b;
}
void kthLargestElement(int array[], int n, int k) {
sort(array, array+n, compare);
for (int i = 0; i < k; i++) //largest to kth largest element
cout << array[i] << " ";
}
int main() {
int array[] = {1, 23, 12, 9, 30, 2, 50, 63, 87, 12, 45, 21};
int n = 12;
int k = 4;
kthLargestElement(array, n, k);
}
87 63 50 45
|
[
{
"code": null,
"e": 1164,
"s": 1062,
"text": "From a set of data, this algorithm will find the largest element to kth largest element of the array."
},
{
"code": null,
"e": 1367,
"s": 1164,
"text": "This problem can be solved easily by sorting the array. We can sort them either in ascending order or in descending order. Solving it in descending order, we can get first k elements to find our result."
},
{
"code": null,
"e": 1496,
"s": 1367,
"text": "Input:\nThe elements of an array: {1, 23, 12, 9, 30, 2, 50, 63, 87, 12, 45, 21}, K = 4\nOutput:\n4 largest elements are 87 63 50 45"
},
{
"code": null,
"e": 1527,
"s": 1496,
"text": "kthLargestElement(array, n, k)"
},
{
"code": null,
"e": 1587,
"s": 1527,
"text": "Input: The array, number of elements in the array, place k."
},
{
"code": null,
"e": 1657,
"s": 1587,
"text": "Output: Display largest element to kth largest elements of the array."
},
{
"code": null,
"e": 1761,
"s": 1657,
"text": "Begin\n sort the array in descending order\n for i := 0 to k-1, do\n display array[i]\n done\nEnd"
},
{
"code": null,
"e": 2200,
"s": 1761,
"text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\n\nbool compare(int a, int b) {\n return a>b;\n}\n\nvoid kthLargestElement(int array[], int n, int k) {\n sort(array, array+n, compare);\n\n for (int i = 0; i < k; i++) //largest to kth largest element\n cout << array[i] << \" \";\n}\n\nint main() {\n int array[] = {1, 23, 12, 9, 30, 2, 50, 63, 87, 12, 45, 21};\n int n = 12;\n int k = 4;\n kthLargestElement(array, n, k);\n}"
},
{
"code": null,
"e": 2212,
"s": 2200,
"text": "87 63 50 45"
}
] |
Simple steps to create custom colormaps in Python | by Guangyuan(Frank) Li | Towards Data Science
|
Imagine you find a pretty colormap that other people used in their publications, and you want to use that in your results as well. However, unfortunately, it is not a built-in colormap in matplotlib. Is there a solution around?
So today I am going to show you how I usually resolve this problem by creating my custom colormap based on any image.
The Github repository for the wrapper function can be found at: https://github.com/frankligy/scTriangulate/blob/main/image/colors_module/README.md
I encountered a nice-looking colormap in this Cell Paper, in their figure4, panel K, there’s a rainbow-like colormap that shows great contrasts and is also visually attractive. The first step we need to do is to take a screenshot of this colormap, shown below:
As you can see, it seems that it has 5 different color patches within each of them within which there’s also a gradient. To reproduce this colormap in python, we first need to know the colors of some of the anchor points, the more anchor points we supply, the closer our colormap will look toward the original one. To extract the color of anchor points, we used the free web app adobe color gradient.
The app asks us to upload the screenshot and then you can extract the RGB color (represented as the values from 0–255) for the arbitrary number of anchor points. Here we chose 6 because we assume there are 5 different color patches.
The RGB values I highlighted in the red box will help us to create the custom colormaps in the next steps.
The logic of building a custom colormap in matplotlib is a little bit confusing at the first glance, it requires us to first create a cdict dictionary with the specification of red , green and blue channels’ dynamic changes. Using a simpler example to explain the syntax:
As in the above example, we instructed the program how to linearly interpolate the R, G, and B channels on the continuum from 0 to 1. The key concept is to select breakpoints at which we express the intensity of the color channels. Another confusing point is that there are two values we need to put, one is the intensity left to the breakpoint whereas the other one is the intensity to the right. In a simple situation like the example I just showed, it is totally fine to use the same intensity for both left and right. For more detailed manipulation, we can make them different for the desirable effects. With that in mind, we can finally start our journey!
Step1 is to install and load necessary packages:
from matplotlib import colorsimport numpy as npimport osimport matplotlib.pyplot as pltfrom matplotlib import cm
We first build the cdict as illustrated above, here we define a function inter_from_256() to convert Adobe output values (0–255) to range (0,1).
def inter_from_256(x): return np.interp(x=x,xp=[0,255],fp=[0,1])
Now the custom colormap object can be instantiated:
new_cmap = colors.LinearSegmentedColormap('new_cmap',segmentdata=cdict)
We can test it by generating a color bar using our custom colormap:
fig,ax = plt.subplots()fig.colorbar(cm.ScalarMappable(norm=colors.Normalize(),cmap=new_cmap),ax=ax)
When I first encountered this problem a few months ago, I found repeating this process several times for new colormaps is a pain. So I started to write a module called “colors” in one of my developed python packages called scTriangulate. Let’s use the very handy function build_custom_continuous_cmap in the colors module to simplify the whole process down to one line of code:
As you can see, we just need to pass all the RGB values in the adobe web app to the function and don’t need to worry about the underlying processes anymore.
Now we test it again:
fig,ax = plt.subplots()fig.colorbar(cm.ScalarMappable(norm=colors.Normalize(),cmap=new_cmap),ax=ax)
Here’s the end, I hope you found this short tutorial helpful in your situations. Also, I’d like to refer you to the scTriangulate.colors modules for more convenient functions for python visualization. Part of the reason I wrote this tutorial is also to get your valuable feedback on what other tedious plotting processes in python that you hope to simplify? If you have any feature requests, please let me know so I can implement them and add them to the scTriangulate.colors modules to benefit other users.
That’s about it! I hope you find this article interesting and useful, thanks for reading! If you like this article, follow me on medium, thank you so much for your support. Connect me on my Twitter or LinkedIn, also please let me know if you have any questions or what kind of tutorials you would like to see In the future!
|
[
{
"code": null,
"e": 400,
"s": 172,
"text": "Imagine you find a pretty colormap that other people used in their publications, and you want to use that in your results as well. However, unfortunately, it is not a built-in colormap in matplotlib. Is there a solution around?"
},
{
"code": null,
"e": 518,
"s": 400,
"text": "So today I am going to show you how I usually resolve this problem by creating my custom colormap based on any image."
},
{
"code": null,
"e": 665,
"s": 518,
"text": "The Github repository for the wrapper function can be found at: https://github.com/frankligy/scTriangulate/blob/main/image/colors_module/README.md"
},
{
"code": null,
"e": 926,
"s": 665,
"text": "I encountered a nice-looking colormap in this Cell Paper, in their figure4, panel K, there’s a rainbow-like colormap that shows great contrasts and is also visually attractive. The first step we need to do is to take a screenshot of this colormap, shown below:"
},
{
"code": null,
"e": 1327,
"s": 926,
"text": "As you can see, it seems that it has 5 different color patches within each of them within which there’s also a gradient. To reproduce this colormap in python, we first need to know the colors of some of the anchor points, the more anchor points we supply, the closer our colormap will look toward the original one. To extract the color of anchor points, we used the free web app adobe color gradient."
},
{
"code": null,
"e": 1560,
"s": 1327,
"text": "The app asks us to upload the screenshot and then you can extract the RGB color (represented as the values from 0–255) for the arbitrary number of anchor points. Here we chose 6 because we assume there are 5 different color patches."
},
{
"code": null,
"e": 1667,
"s": 1560,
"text": "The RGB values I highlighted in the red box will help us to create the custom colormaps in the next steps."
},
{
"code": null,
"e": 1939,
"s": 1667,
"text": "The logic of building a custom colormap in matplotlib is a little bit confusing at the first glance, it requires us to first create a cdict dictionary with the specification of red , green and blue channels’ dynamic changes. Using a simpler example to explain the syntax:"
},
{
"code": null,
"e": 2600,
"s": 1939,
"text": "As in the above example, we instructed the program how to linearly interpolate the R, G, and B channels on the continuum from 0 to 1. The key concept is to select breakpoints at which we express the intensity of the color channels. Another confusing point is that there are two values we need to put, one is the intensity left to the breakpoint whereas the other one is the intensity to the right. In a simple situation like the example I just showed, it is totally fine to use the same intensity for both left and right. For more detailed manipulation, we can make them different for the desirable effects. With that in mind, we can finally start our journey!"
},
{
"code": null,
"e": 2649,
"s": 2600,
"text": "Step1 is to install and load necessary packages:"
},
{
"code": null,
"e": 2762,
"s": 2649,
"text": "from matplotlib import colorsimport numpy as npimport osimport matplotlib.pyplot as pltfrom matplotlib import cm"
},
{
"code": null,
"e": 2907,
"s": 2762,
"text": "We first build the cdict as illustrated above, here we define a function inter_from_256() to convert Adobe output values (0–255) to range (0,1)."
},
{
"code": null,
"e": 2975,
"s": 2907,
"text": "def inter_from_256(x): return np.interp(x=x,xp=[0,255],fp=[0,1])"
},
{
"code": null,
"e": 3027,
"s": 2975,
"text": "Now the custom colormap object can be instantiated:"
},
{
"code": null,
"e": 3099,
"s": 3027,
"text": "new_cmap = colors.LinearSegmentedColormap('new_cmap',segmentdata=cdict)"
},
{
"code": null,
"e": 3167,
"s": 3099,
"text": "We can test it by generating a color bar using our custom colormap:"
},
{
"code": null,
"e": 3267,
"s": 3167,
"text": "fig,ax = plt.subplots()fig.colorbar(cm.ScalarMappable(norm=colors.Normalize(),cmap=new_cmap),ax=ax)"
},
{
"code": null,
"e": 3645,
"s": 3267,
"text": "When I first encountered this problem a few months ago, I found repeating this process several times for new colormaps is a pain. So I started to write a module called “colors” in one of my developed python packages called scTriangulate. Let’s use the very handy function build_custom_continuous_cmap in the colors module to simplify the whole process down to one line of code:"
},
{
"code": null,
"e": 3802,
"s": 3645,
"text": "As you can see, we just need to pass all the RGB values in the adobe web app to the function and don’t need to worry about the underlying processes anymore."
},
{
"code": null,
"e": 3824,
"s": 3802,
"text": "Now we test it again:"
},
{
"code": null,
"e": 3924,
"s": 3824,
"text": "fig,ax = plt.subplots()fig.colorbar(cm.ScalarMappable(norm=colors.Normalize(),cmap=new_cmap),ax=ax)"
},
{
"code": null,
"e": 4432,
"s": 3924,
"text": "Here’s the end, I hope you found this short tutorial helpful in your situations. Also, I’d like to refer you to the scTriangulate.colors modules for more convenient functions for python visualization. Part of the reason I wrote this tutorial is also to get your valuable feedback on what other tedious plotting processes in python that you hope to simplify? If you have any feature requests, please let me know so I can implement them and add them to the scTriangulate.colors modules to benefit other users."
}
] |
Embeeding and clustering combining Knime and Python | Towards Data Science
|
Knime is a free and open-source data analytics, reporting and integration platform. KNIME integrates various components for machine learning and data mining through its modular data pipelining concept. For people like me, who do not have a strong coding background, Knime has been the open door to end to end data science experience. For the last two years working with Knime, I have been able to understand the global picture of data science, I left my fears behind and now I am stepping deeper and deeper in the challenging and amazing world of data science.
A few days ago I read an article in TowardsDataScience by Rosaria Silipo and Mischa Lisovyi showing a very nice Knime workflow involving t-SNE applied on MNIST dataset. I had done a similar workflow in the past with UMAP with nice results.
Encouraged by Rosaria Silipo in Linkedin I decided to publish my first story.
The raw material for this article is the MNIST dataset from OpenML of handwritten numbers from 0 to 9 by Yan LeCun. The dataset has 70000 handwritten numbers of 28x28 pixels of 0–255 grey scale levels. That is to say that we have 70000 vectors wich dimension is 784.
That data is fetched in a Python script within Knime and the UMAP algorithm for dimensional reduction is applied, also on that Python script, so we can map each image of the data set in a point on a lower dimensional space. For the aim of representing the results, logically, I used 2D and 3D as target dimensions.
After that, in order to have more fun, with the resulting UMAP embedded data ignoring lables, I applied a DBSCAN node within Knime for clustering results. We will check results later.
Uniform Manifold Approximation and Projection (UMAP) is a dimension reduction technique that can be used for visualisation similarly to t-SNE, but also for general non-linear dimension reduction. The algorithm is founded on three assumptions about the data
-The data is uniformly distributed on Riemannian manifold;
-The Riemannian metric is locally constant (or can be approximated as such);
-The manifold is locally connected.
What is a Riemannian manifold? Wait!! What is a manifold? A manifold is a topological object of n-dimension that locally, on the neighborhood of a point, behaves like an n-dimensional euclidean space. A good layman’s example would be the earth. A Rieamannian manifold is a smooth differentiable manifold in which notions like length, curves, angles, volumes, gradient of functions can be defined. For more information on manifolds or Riemannian manifolds, try here and here.
UMAP has some parameters to control its performance.
n_neighbors: The bigger the n_neighbors the bigger neighborhoods that will be sought by the algorithm and will be tending to global overall structures.The lower the n_neighbors, the more detailed structures that UMAP will be focused on.
minimum distance: Defines the minimum distance that the algorithm will consider to pack points together in the final reducted space. That means that low values of minimum distance will result in smaller cluster embeddings. On the other side, high values of minimum distance will lead UMAP algorithm to point to global structures.
metric: We can define the metric with which the algorithm will calculate the distance in the original space.
Hard to digest! I know. Nearly magic for engineers. Coming out of that darkness, specifically (and simply!!), UMAP models each high-dimensional object by a n-dimensional point (n being down to 2) in such a way that similar objects are modeled by nearby points and dissimilar objects are modeled by distant points with high probability.
DBSCAN, Density-based spatial clustering of applications with noise, is a clustering algorithm considered among unsupervised lerning methods. Based on three input parameters the algorithm is able to clusterized a set of data by grouping together points that are closely packed together (points with a certain number of nearby neighbors), marking as noise those points that lie alone and away in low-density regions (whose nearest neighbors are too far away).
As you can imagine, the parameters ruling the performance of the DBSCAN algorithm are related to the distance to decide whether a point is near or not to one another, epsilon, and are also related to the minimum number of nearby points, minimum points, necessary to considered one point is a “neighborhood” or core point. A cluster is the sum of all core points and their neighbors. Finally, in KNIME node for DBSCAN included in the Knime extension KNIME Distance Matrix, we can see that a metric input is needed so the algorithm has the necessary Distance model to calculate de distances between points on the dataset.
So summarizing:
epsilon: Specifies distance between points so they can be be considered a part of a cluster. Two points will be considered neighbors belonging to the same cluster if the distance between them is lower than epsilon.
minimum Points: Minimum number of points reachable from a point p so that p point can be considered a core point.
distance model: As said before, it is necessary to inform DBSCAN node with a distance model to evaluate distances between points in data set. To do that we use the Mumeric Distance node.
Significative advantages of of DBSCAN algorithm are:
DBSCAN does not need the user to specify the number of clusters.
DBSCAN manages noise concept and discards and marks noise points
Both Knime workflows are published and available in Knime Hub:
UMAP DBSCAN MNIST 2D Python. UMAP 2D dimension embedding
UMAP DBSCAN MNIST 3D Python. UMAP 3D dimension embedding
I will only focuse on 2D explanation since both workflows are virtually identical. However, I will show comparative results for both in the end.
Following you can see the whole workflow and later I will explain it block by block.
Following you can find a detail picture of the first block with which data is fetched and UMAP is calculated within the Python Source node from Knime Python extension.
Orange block in the center is the Python Source node that includes the script used to fetch data from OpenML and to perform UMAP technique. Two variable nodes, “Metric” and “Number of rows” are merged and passed like inputs for the UMAP algorithm. For the final results I used euclidean metrics and regarding the “Number of rows” Integer input node, I just used it to change to low numbers while testing. Just a matter of time. On the right, I use the Column Rename node to name columns with understandable names during the workflow.
Here you can find the code within the Python Source node:
from pandas import DataFramefrom sklearn.datasets import fetch_openmlimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns# Dimension reduction and clustering librariesimport umapin_batch = flow_variables[‘input_batch’]umap_metric = flow_variables[‘metric’]#Varias metricas posibles # mnist_784 # Fashion-MNISTmnist = fetch_openml(‘mnist_784’, version=1, as_frame=False)mnist.target = mnist.target.astype(int)standard_embedding = umap.UMAP( n_neighbors=30, min_dist=0.0, n_components=2, metric=umap_metric, random_state=42 ).fit_transform(mnist.data[:in_batch, 1:])#Añadimos los targetarray2D_1=standard_embeddingarray2D_2=mnist.target[:in_batch]array2D_2=np.reshape(array2D_2,(in_batch,1))array_to_save=np.concatenate((array2D_1,array2D_2),axis=1)# Output table for the nodeoutput_table = DataFrame(array_to_save)
After the UMAP algorithm is performed, we have a 2D mapping for the MNIST digits. I used two different approaches to plotting just to compare results.
UMAP output Scatter Plot (Plotly) combined with Color Manager
Scatter Plot from Plotly Knime extension is a very nice node. Result is interactive and output colors can be configured with the Color Manager node so dataset point within the reducted 2D space can be labelled according to the digit they were within the original space before being embedded.
Alternatively, in 3D, instead of Scatter Plot node we can use Scatter 3D and the result is the following.
Please note that the same ten clearly differentiate clusters have been detected and mapped both in 2D and in 3D by the UMAP algorithm.
UMAP output with Python View
Using a Python Source node and a piece of code, similar results can also be found.
Following you can find de pieces of code to do both plots within the Python view node of Knime.
For 2D
from io import BytesIOimport matplotlib as mpltimport matplotlib.pyplot as pltimport numpy as nplabel_array=input_table['Col2']colors = ['red', 'blue', 'green', 'yellow', 'orange', 'peru', 'lime', 'pink', 'steelblue', 'olive']plt.scatter(input_table['Col0'], input_table['Col1'], c=label_array, alpha=0.5, marker='o', cmap=mplt.colors.ListedColormap(colors), s=0.1, label="Label")plt.xlabel("X")plt.ylabel("Y")plt.legend(loc='best')buffer=BytesIO()plt.savefig(buffer,format="svg")output_image = buffer.getvalue()
For 3D:
from io import BytesIOimport matplotlib as mpltimport matplotlib.pyplot as pltimport numpy as npfrom mpl_toolkits.mplot3d import Axes3Dlabel=input_table['Col3']colors = ['red', 'blue', 'green', 'yellow', 'orange', 'peru', 'lime', 'pink', 'steelblue', 'olive']fig = plt.figure(figsize=(12,12))ax = fig.add_subplot(111, projection='3d')ax.scatter(input_table['Col0'],input_table['Col1'] ,input_table['Col2'], c=input_table['Col3'], cmap=mplt.colors.ListedColormap(colors), marker='o', s=1)ax.set_xlabel('X Label')ax.set_ylabel('Y Label')ax.set_zlabel('Z Label')buffer=BytesIO()plt.savefig(buffer,format="svg")output_image = buffer.getvalue()
So, up to this point we have a set of 2D (or 3D) points representing a set of 700000 written images. We know which original number corresponds to each point of the reducted space since original labels have been added to the UMAP output as you can see here:
But imagine we had not original label. We would have a mass of points with no further information like this:
It is time to use DBSCAN and try to find what is the structure lying beneath that scatter nonsense plot.
We drive the output of the UMAP to the DBSCAN node. Additionally we feed the rest of the DBSCAN inputs with variables although they coud be configured inside the node.
For 2D DBSCAN I used Epsilon=0.15 and Minimum points=50. Metric, within the Numeric Distances node, was configured to Euclidean.
The output, after some string manipulation, is a table with clustered data.
What will we find if we plot points within the reducted space in 2D or 3D labelled with the clustering resulting from DBSCAN?
Let’s see.
In the following images you can see that DBSCAN identified clusters are the same clusters that UMAP delivered according to original images. That is pretty satisfying and nice.
Are results of DBSCAN good enough related to original labels?
Accuracy of DBSCAN clustering related to original labels is 95,9%.
All this work has been done within Knime combining native Knime nodes and embedding Python code on its workflows showing, hence, the capabilities of Knime environement.
Next story I am thinking about, will be on how to to perform a similar analysis but reaching the embedded state with a neural autoencoder. Will keep you informed.
|
[
{
"code": null,
"e": 733,
"s": 172,
"text": "Knime is a free and open-source data analytics, reporting and integration platform. KNIME integrates various components for machine learning and data mining through its modular data pipelining concept. For people like me, who do not have a strong coding background, Knime has been the open door to end to end data science experience. For the last two years working with Knime, I have been able to understand the global picture of data science, I left my fears behind and now I am stepping deeper and deeper in the challenging and amazing world of data science."
},
{
"code": null,
"e": 973,
"s": 733,
"text": "A few days ago I read an article in TowardsDataScience by Rosaria Silipo and Mischa Lisovyi showing a very nice Knime workflow involving t-SNE applied on MNIST dataset. I had done a similar workflow in the past with UMAP with nice results."
},
{
"code": null,
"e": 1051,
"s": 973,
"text": "Encouraged by Rosaria Silipo in Linkedin I decided to publish my first story."
},
{
"code": null,
"e": 1318,
"s": 1051,
"text": "The raw material for this article is the MNIST dataset from OpenML of handwritten numbers from 0 to 9 by Yan LeCun. The dataset has 70000 handwritten numbers of 28x28 pixels of 0–255 grey scale levels. That is to say that we have 70000 vectors wich dimension is 784."
},
{
"code": null,
"e": 1633,
"s": 1318,
"text": "That data is fetched in a Python script within Knime and the UMAP algorithm for dimensional reduction is applied, also on that Python script, so we can map each image of the data set in a point on a lower dimensional space. For the aim of representing the results, logically, I used 2D and 3D as target dimensions."
},
{
"code": null,
"e": 1817,
"s": 1633,
"text": "After that, in order to have more fun, with the resulting UMAP embedded data ignoring lables, I applied a DBSCAN node within Knime for clustering results. We will check results later."
},
{
"code": null,
"e": 2074,
"s": 1817,
"text": "Uniform Manifold Approximation and Projection (UMAP) is a dimension reduction technique that can be used for visualisation similarly to t-SNE, but also for general non-linear dimension reduction. The algorithm is founded on three assumptions about the data"
},
{
"code": null,
"e": 2133,
"s": 2074,
"text": "-The data is uniformly distributed on Riemannian manifold;"
},
{
"code": null,
"e": 2210,
"s": 2133,
"text": "-The Riemannian metric is locally constant (or can be approximated as such);"
},
{
"code": null,
"e": 2246,
"s": 2210,
"text": "-The manifold is locally connected."
},
{
"code": null,
"e": 2721,
"s": 2246,
"text": "What is a Riemannian manifold? Wait!! What is a manifold? A manifold is a topological object of n-dimension that locally, on the neighborhood of a point, behaves like an n-dimensional euclidean space. A good layman’s example would be the earth. A Rieamannian manifold is a smooth differentiable manifold in which notions like length, curves, angles, volumes, gradient of functions can be defined. For more information on manifolds or Riemannian manifolds, try here and here."
},
{
"code": null,
"e": 2774,
"s": 2721,
"text": "UMAP has some parameters to control its performance."
},
{
"code": null,
"e": 3011,
"s": 2774,
"text": "n_neighbors: The bigger the n_neighbors the bigger neighborhoods that will be sought by the algorithm and will be tending to global overall structures.The lower the n_neighbors, the more detailed structures that UMAP will be focused on."
},
{
"code": null,
"e": 3341,
"s": 3011,
"text": "minimum distance: Defines the minimum distance that the algorithm will consider to pack points together in the final reducted space. That means that low values of minimum distance will result in smaller cluster embeddings. On the other side, high values of minimum distance will lead UMAP algorithm to point to global structures."
},
{
"code": null,
"e": 3450,
"s": 3341,
"text": "metric: We can define the metric with which the algorithm will calculate the distance in the original space."
},
{
"code": null,
"e": 3786,
"s": 3450,
"text": "Hard to digest! I know. Nearly magic for engineers. Coming out of that darkness, specifically (and simply!!), UMAP models each high-dimensional object by a n-dimensional point (n being down to 2) in such a way that similar objects are modeled by nearby points and dissimilar objects are modeled by distant points with high probability."
},
{
"code": null,
"e": 4245,
"s": 3786,
"text": "DBSCAN, Density-based spatial clustering of applications with noise, is a clustering algorithm considered among unsupervised lerning methods. Based on three input parameters the algorithm is able to clusterized a set of data by grouping together points that are closely packed together (points with a certain number of nearby neighbors), marking as noise those points that lie alone and away in low-density regions (whose nearest neighbors are too far away)."
},
{
"code": null,
"e": 4865,
"s": 4245,
"text": "As you can imagine, the parameters ruling the performance of the DBSCAN algorithm are related to the distance to decide whether a point is near or not to one another, epsilon, and are also related to the minimum number of nearby points, minimum points, necessary to considered one point is a “neighborhood” or core point. A cluster is the sum of all core points and their neighbors. Finally, in KNIME node for DBSCAN included in the Knime extension KNIME Distance Matrix, we can see that a metric input is needed so the algorithm has the necessary Distance model to calculate de distances between points on the dataset."
},
{
"code": null,
"e": 4881,
"s": 4865,
"text": "So summarizing:"
},
{
"code": null,
"e": 5096,
"s": 4881,
"text": "epsilon: Specifies distance between points so they can be be considered a part of a cluster. Two points will be considered neighbors belonging to the same cluster if the distance between them is lower than epsilon."
},
{
"code": null,
"e": 5210,
"s": 5096,
"text": "minimum Points: Minimum number of points reachable from a point p so that p point can be considered a core point."
},
{
"code": null,
"e": 5397,
"s": 5210,
"text": "distance model: As said before, it is necessary to inform DBSCAN node with a distance model to evaluate distances between points in data set. To do that we use the Mumeric Distance node."
},
{
"code": null,
"e": 5450,
"s": 5397,
"text": "Significative advantages of of DBSCAN algorithm are:"
},
{
"code": null,
"e": 5515,
"s": 5450,
"text": "DBSCAN does not need the user to specify the number of clusters."
},
{
"code": null,
"e": 5580,
"s": 5515,
"text": "DBSCAN manages noise concept and discards and marks noise points"
},
{
"code": null,
"e": 5643,
"s": 5580,
"text": "Both Knime workflows are published and available in Knime Hub:"
},
{
"code": null,
"e": 5700,
"s": 5643,
"text": "UMAP DBSCAN MNIST 2D Python. UMAP 2D dimension embedding"
},
{
"code": null,
"e": 5757,
"s": 5700,
"text": "UMAP DBSCAN MNIST 3D Python. UMAP 3D dimension embedding"
},
{
"code": null,
"e": 5902,
"s": 5757,
"text": "I will only focuse on 2D explanation since both workflows are virtually identical. However, I will show comparative results for both in the end."
},
{
"code": null,
"e": 5987,
"s": 5902,
"text": "Following you can see the whole workflow and later I will explain it block by block."
},
{
"code": null,
"e": 6155,
"s": 5987,
"text": "Following you can find a detail picture of the first block with which data is fetched and UMAP is calculated within the Python Source node from Knime Python extension."
},
{
"code": null,
"e": 6689,
"s": 6155,
"text": "Orange block in the center is the Python Source node that includes the script used to fetch data from OpenML and to perform UMAP technique. Two variable nodes, “Metric” and “Number of rows” are merged and passed like inputs for the UMAP algorithm. For the final results I used euclidean metrics and regarding the “Number of rows” Integer input node, I just used it to change to low numbers while testing. Just a matter of time. On the right, I use the Column Rename node to name columns with understandable names during the workflow."
},
{
"code": null,
"e": 6747,
"s": 6689,
"text": "Here you can find the code within the Python Source node:"
},
{
"code": null,
"e": 7580,
"s": 6747,
"text": "from pandas import DataFramefrom sklearn.datasets import fetch_openmlimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns# Dimension reduction and clustering librariesimport umapin_batch = flow_variables[‘input_batch’]umap_metric = flow_variables[‘metric’]#Varias metricas posibles # mnist_784 # Fashion-MNISTmnist = fetch_openml(‘mnist_784’, version=1, as_frame=False)mnist.target = mnist.target.astype(int)standard_embedding = umap.UMAP( n_neighbors=30, min_dist=0.0, n_components=2, metric=umap_metric, random_state=42 ).fit_transform(mnist.data[:in_batch, 1:])#Añadimos los targetarray2D_1=standard_embeddingarray2D_2=mnist.target[:in_batch]array2D_2=np.reshape(array2D_2,(in_batch,1))array_to_save=np.concatenate((array2D_1,array2D_2),axis=1)# Output table for the nodeoutput_table = DataFrame(array_to_save)"
},
{
"code": null,
"e": 7731,
"s": 7580,
"text": "After the UMAP algorithm is performed, we have a 2D mapping for the MNIST digits. I used two different approaches to plotting just to compare results."
},
{
"code": null,
"e": 7793,
"s": 7731,
"text": "UMAP output Scatter Plot (Plotly) combined with Color Manager"
},
{
"code": null,
"e": 8085,
"s": 7793,
"text": "Scatter Plot from Plotly Knime extension is a very nice node. Result is interactive and output colors can be configured with the Color Manager node so dataset point within the reducted 2D space can be labelled according to the digit they were within the original space before being embedded."
},
{
"code": null,
"e": 8191,
"s": 8085,
"text": "Alternatively, in 3D, instead of Scatter Plot node we can use Scatter 3D and the result is the following."
},
{
"code": null,
"e": 8326,
"s": 8191,
"text": "Please note that the same ten clearly differentiate clusters have been detected and mapped both in 2D and in 3D by the UMAP algorithm."
},
{
"code": null,
"e": 8355,
"s": 8326,
"text": "UMAP output with Python View"
},
{
"code": null,
"e": 8438,
"s": 8355,
"text": "Using a Python Source node and a piece of code, similar results can also be found."
},
{
"code": null,
"e": 8534,
"s": 8438,
"text": "Following you can find de pieces of code to do both plots within the Python view node of Knime."
},
{
"code": null,
"e": 8541,
"s": 8534,
"text": "For 2D"
},
{
"code": null,
"e": 9071,
"s": 8541,
"text": "from io import BytesIOimport matplotlib as mpltimport matplotlib.pyplot as pltimport numpy as nplabel_array=input_table['Col2']colors = ['red', 'blue', 'green', 'yellow', 'orange', 'peru', 'lime', 'pink', 'steelblue', 'olive']plt.scatter(input_table['Col0'], input_table['Col1'], c=label_array, alpha=0.5, marker='o', cmap=mplt.colors.ListedColormap(colors), s=0.1, label=\"Label\")plt.xlabel(\"X\")plt.ylabel(\"Y\")plt.legend(loc='best')buffer=BytesIO()plt.savefig(buffer,format=\"svg\")output_image = buffer.getvalue()"
},
{
"code": null,
"e": 9079,
"s": 9071,
"text": "For 3D:"
},
{
"code": null,
"e": 9759,
"s": 9079,
"text": "from io import BytesIOimport matplotlib as mpltimport matplotlib.pyplot as pltimport numpy as npfrom mpl_toolkits.mplot3d import Axes3Dlabel=input_table['Col3']colors = ['red', 'blue', 'green', 'yellow', 'orange', 'peru', 'lime', 'pink', 'steelblue', 'olive']fig = plt.figure(figsize=(12,12))ax = fig.add_subplot(111, projection='3d')ax.scatter(input_table['Col0'],input_table['Col1'] ,input_table['Col2'], c=input_table['Col3'], cmap=mplt.colors.ListedColormap(colors), marker='o', s=1)ax.set_xlabel('X Label')ax.set_ylabel('Y Label')ax.set_zlabel('Z Label')buffer=BytesIO()plt.savefig(buffer,format=\"svg\")output_image = buffer.getvalue()"
},
{
"code": null,
"e": 10016,
"s": 9759,
"text": "So, up to this point we have a set of 2D (or 3D) points representing a set of 700000 written images. We know which original number corresponds to each point of the reducted space since original labels have been added to the UMAP output as you can see here:"
},
{
"code": null,
"e": 10125,
"s": 10016,
"text": "But imagine we had not original label. We would have a mass of points with no further information like this:"
},
{
"code": null,
"e": 10230,
"s": 10125,
"text": "It is time to use DBSCAN and try to find what is the structure lying beneath that scatter nonsense plot."
},
{
"code": null,
"e": 10398,
"s": 10230,
"text": "We drive the output of the UMAP to the DBSCAN node. Additionally we feed the rest of the DBSCAN inputs with variables although they coud be configured inside the node."
},
{
"code": null,
"e": 10527,
"s": 10398,
"text": "For 2D DBSCAN I used Epsilon=0.15 and Minimum points=50. Metric, within the Numeric Distances node, was configured to Euclidean."
},
{
"code": null,
"e": 10603,
"s": 10527,
"text": "The output, after some string manipulation, is a table with clustered data."
},
{
"code": null,
"e": 10729,
"s": 10603,
"text": "What will we find if we plot points within the reducted space in 2D or 3D labelled with the clustering resulting from DBSCAN?"
},
{
"code": null,
"e": 10740,
"s": 10729,
"text": "Let’s see."
},
{
"code": null,
"e": 10916,
"s": 10740,
"text": "In the following images you can see that DBSCAN identified clusters are the same clusters that UMAP delivered according to original images. That is pretty satisfying and nice."
},
{
"code": null,
"e": 10978,
"s": 10916,
"text": "Are results of DBSCAN good enough related to original labels?"
},
{
"code": null,
"e": 11045,
"s": 10978,
"text": "Accuracy of DBSCAN clustering related to original labels is 95,9%."
},
{
"code": null,
"e": 11214,
"s": 11045,
"text": "All this work has been done within Knime combining native Knime nodes and embedding Python code on its workflows showing, hence, the capabilities of Knime environement."
}
] |
How to Rename Columns in Pandas - A Quick Guide | Towards Data Science
|
Ensuring that dataframe columns are appropriately named is essential to understand what data is contained within, especially when we pass our data on to others. In this short article, we will cover a number of ways to rename columns within a pandas dataframe.
But first, what is Pandas? Pandas is a powerful, fast, and commonly used python library for carrying out data analytics. The Pandas name itself stands for “Python Data Analysis Library”. According to Wikipedia, the name originates from the term “panel data”. It allows data to be loaded in from a number file formats (CSV, XLS, XLSX, Pickle, etc.) and stored within table-like structures. These tables (dataframes) can be manipulated, analyzed, and visualized using a variety of functions that are available within pandas
The first steps involve importing the pandas library and creating some dummy data that we can use to illustrate the process of column renaming.
import pandas as pd
We will create some dummy data to illustrate the various techniques. We can do this by calling upon the .DataFrame() Here we will create three columns with the names A, B, and C.
df = pd.DataFrame({'A':[1,2,3,4,5], 'B':[101,102,103,104,105], 'C':[42,42,42,42,42]})
An alternative method for creating the dataframe would be to load the data from an existing file, such as a csv or xlsx file. When we load the data, we can change the names of the columns using the names argument. When we do this, we need to make sure we drop the existing header row by using header=0.
df = pd.read_csv('data.csv', names=['ColA', 'ColB', 'ColC'], header=0)
The first method we will look at is the .rename() function. Here we can pass in a dictionary to the columns keyword argument. The dictionary allows us to provide a mapping between the old column name and the new one that we want.
We will also set the inplaceargument to True so that we are making the changes to the dataframe, df, directly as opposed to making a copy of it.
df.rename(columns= {'A':'Z', 'B':'Y', 'C':'X' }, inplace=True)
An alternative version of this is to specify the axis, however, it is less readable and may not be clear what this argument is doing compared to using the columns argument.
df.rename({'A':'Z', 'B':'Y', 'C':'X' }, inplace=True, axis=1)
When we call upon df, we now see that our columns have been renamed from A, B, and C to Z, Y, and X respectively.
If we want to rename specific columns, we can use the rename function again. Instead of providing a string for string mapping, we can use df.columns and select a column by providing a column index position in the square brackets. We then map this to a new column name string.
df.rename(columns={df.columns[0]:'New Name'}, inplace=True)
We can also specify a mapping between an existing column name and the new one.
df.rename(columns= {'X':'XX' }, inplace=True)
The next method is set_axis() which is used to set the axis (column: axis=1 or row: axis=0) of a dataframe.
We can use this method to rename the columns by first defining our list of names we want to replace the columns with and setting axis=1 or axis='columns'. Note that here the number of names needs to equal the total number of columns.
df.set_axis(['Column A', 'Column B', 'Column C'], axis='columns', inplace=True)
We can rename the columns directly by assigning a new list containing the names that we want to rename the columns to. This is achieved using the df.columns attribute of the dataframe.
This method requires the new list of names to be the same length as the number of columns in the dataframe. Therefore, if we only want to rename one or two columns this is probably not the best approach.
df.columns = ['1', '2', '3']
The final method we will look at is using str.replace(), which can be used to replace specific characters or entire column names.
In this example, we will replace column 1 with the letter Z.
df.columns = df.columns.str.replace('1', 'Z')
There are multiple methods for renaming columns within a pandas dataframe including pd.read_csv, .set_axis, df.rename and df.columns. This illustrates the great flexibility that is available within the pandas python library and makes it easy to ensure that columns within a dataframe are appropriately labeled.
Thanks for reading!
If you have found this article useful, feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub.
If you want to get in touch you can find me on LinkedIn or at my website.
Interested in learning more about python, petrophysics, or well log data petrophysics? Follow me on Medium or on YouTube.
|
[
{
"code": null,
"e": 432,
"s": 172,
"text": "Ensuring that dataframe columns are appropriately named is essential to understand what data is contained within, especially when we pass our data on to others. In this short article, we will cover a number of ways to rename columns within a pandas dataframe."
},
{
"code": null,
"e": 954,
"s": 432,
"text": "But first, what is Pandas? Pandas is a powerful, fast, and commonly used python library for carrying out data analytics. The Pandas name itself stands for “Python Data Analysis Library”. According to Wikipedia, the name originates from the term “panel data”. It allows data to be loaded in from a number file formats (CSV, XLS, XLSX, Pickle, etc.) and stored within table-like structures. These tables (dataframes) can be manipulated, analyzed, and visualized using a variety of functions that are available within pandas"
},
{
"code": null,
"e": 1098,
"s": 954,
"text": "The first steps involve importing the pandas library and creating some dummy data that we can use to illustrate the process of column renaming."
},
{
"code": null,
"e": 1118,
"s": 1098,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1297,
"s": 1118,
"text": "We will create some dummy data to illustrate the various techniques. We can do this by calling upon the .DataFrame() Here we will create three columns with the names A, B, and C."
},
{
"code": null,
"e": 1419,
"s": 1297,
"text": "df = pd.DataFrame({'A':[1,2,3,4,5], 'B':[101,102,103,104,105], 'C':[42,42,42,42,42]})"
},
{
"code": null,
"e": 1722,
"s": 1419,
"text": "An alternative method for creating the dataframe would be to load the data from an existing file, such as a csv or xlsx file. When we load the data, we can change the names of the columns using the names argument. When we do this, we need to make sure we drop the existing header row by using header=0."
},
{
"code": null,
"e": 1834,
"s": 1722,
"text": "df = pd.read_csv('data.csv', names=['ColA', 'ColB', 'ColC'], header=0)"
},
{
"code": null,
"e": 2064,
"s": 1834,
"text": "The first method we will look at is the .rename() function. Here we can pass in a dictionary to the columns keyword argument. The dictionary allows us to provide a mapping between the old column name and the new one that we want."
},
{
"code": null,
"e": 2209,
"s": 2064,
"text": "We will also set the inplaceargument to True so that we are making the changes to the dataframe, df, directly as opposed to making a copy of it."
},
{
"code": null,
"e": 2272,
"s": 2209,
"text": "df.rename(columns= {'A':'Z', 'B':'Y', 'C':'X' }, inplace=True)"
},
{
"code": null,
"e": 2445,
"s": 2272,
"text": "An alternative version of this is to specify the axis, however, it is less readable and may not be clear what this argument is doing compared to using the columns argument."
},
{
"code": null,
"e": 2507,
"s": 2445,
"text": "df.rename({'A':'Z', 'B':'Y', 'C':'X' }, inplace=True, axis=1)"
},
{
"code": null,
"e": 2621,
"s": 2507,
"text": "When we call upon df, we now see that our columns have been renamed from A, B, and C to Z, Y, and X respectively."
},
{
"code": null,
"e": 2897,
"s": 2621,
"text": "If we want to rename specific columns, we can use the rename function again. Instead of providing a string for string mapping, we can use df.columns and select a column by providing a column index position in the square brackets. We then map this to a new column name string."
},
{
"code": null,
"e": 2957,
"s": 2897,
"text": "df.rename(columns={df.columns[0]:'New Name'}, inplace=True)"
},
{
"code": null,
"e": 3036,
"s": 2957,
"text": "We can also specify a mapping between an existing column name and the new one."
},
{
"code": null,
"e": 3082,
"s": 3036,
"text": "df.rename(columns= {'X':'XX' }, inplace=True)"
},
{
"code": null,
"e": 3190,
"s": 3082,
"text": "The next method is set_axis() which is used to set the axis (column: axis=1 or row: axis=0) of a dataframe."
},
{
"code": null,
"e": 3424,
"s": 3190,
"text": "We can use this method to rename the columns by first defining our list of names we want to replace the columns with and setting axis=1 or axis='columns'. Note that here the number of names needs to equal the total number of columns."
},
{
"code": null,
"e": 3528,
"s": 3424,
"text": "df.set_axis(['Column A', 'Column B', 'Column C'], axis='columns', inplace=True)"
},
{
"code": null,
"e": 3713,
"s": 3528,
"text": "We can rename the columns directly by assigning a new list containing the names that we want to rename the columns to. This is achieved using the df.columns attribute of the dataframe."
},
{
"code": null,
"e": 3917,
"s": 3713,
"text": "This method requires the new list of names to be the same length as the number of columns in the dataframe. Therefore, if we only want to rename one or two columns this is probably not the best approach."
},
{
"code": null,
"e": 3946,
"s": 3917,
"text": "df.columns = ['1', '2', '3']"
},
{
"code": null,
"e": 4076,
"s": 3946,
"text": "The final method we will look at is using str.replace(), which can be used to replace specific characters or entire column names."
},
{
"code": null,
"e": 4137,
"s": 4076,
"text": "In this example, we will replace column 1 with the letter Z."
},
{
"code": null,
"e": 4183,
"s": 4137,
"text": "df.columns = df.columns.str.replace('1', 'Z')"
},
{
"code": null,
"e": 4494,
"s": 4183,
"text": "There are multiple methods for renaming columns within a pandas dataframe including pd.read_csv, .set_axis, df.rename and df.columns. This illustrates the great flexibility that is available within the pandas python library and makes it easy to ensure that columns within a dataframe are appropriately labeled."
},
{
"code": null,
"e": 4514,
"s": 4494,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 4719,
"s": 4514,
"text": "If you have found this article useful, feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub."
},
{
"code": null,
"e": 4793,
"s": 4719,
"text": "If you want to get in touch you can find me on LinkedIn or at my website."
}
] |
How to create a bold text using JavaScript?
|
To create a bold text using JavaScript, use the bold() text. This method causes a string to be displayed as bold as if it were in a <b> tag.
You can try to run the following code to create a bold text with JavaScript −
Live Demo
<html>
<head>
<title>JavaScript String bold() Method</title>
</head>
<body>
<script>
var str = new String("Demo Text");
document.write(str.bold());
alert(str.bold());
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "To create a bold text using JavaScript, use the bold() text. This method causes a string to be displayed as bold as if it were in a <b> tag."
},
{
"code": null,
"e": 1281,
"s": 1203,
"text": "You can try to run the following code to create a bold text with JavaScript −"
},
{
"code": null,
"e": 1291,
"s": 1281,
"text": "Live Demo"
},
{
"code": null,
"e": 1542,
"s": 1291,
"text": "<html>\n <head>\n <title>JavaScript String bold() Method</title>\n </head>\n\n <body>\n <script>\n var str = new String(\"Demo Text\");\n document.write(str.bold());\n alert(str.bold());\n </script>\n </body>\n</html>"
}
] |
Ensemble Learning: Stacking, Blending & Voting | by Fernando López | Towards Data Science
|
We have heard the phrase “unity is strength”, whose meaning can be transferred to different areas of life. Sometimes correct answers to a specific problem are supported by several sources and not just one. This is what Ensemble Learning tries to do, that is, to put together a group of ML models to improve solutions to specific problems.
Throughout this blog, we will learrn what Ensemble Learning is, what are the types of Ensembles that exist and we will specifically address Voting and Stacking Ensembles. Therefore, this blog will be divided into the following sections:
What is Ensemble Learning?
Stacking
Blending
Voting
I invite you to download the code and try it for yourself, it will be worth: https://github.com/FernandoLpz/Stacking-Blending-Voting-Ensembles
Ensemble Learning refers to the use of ML algorithms jointly to solve classification and/or regression problems mainly. These algorithms can be the same type (homogeneous Ensemble Learning) or different types (heterogeneous Ensemble Learning). Ensemble Learning performs a strategic combination of various experts or ML models in order to improve the effectiveness obtained using a single weak model [1, 2]. Figure 1 provides a visual overview regarding the comparison of a model that does not implement Ensemble Learning and a model that does implement Ensemble Learning.
There are different types of Ensemble Learning techniques which differ mainly by the type of models used (homogeneous or heterogeneous models), the data sampling (with or without replacement, k-fold, etc.) and the decision function (voting, average, meta model, etc). Therefore, Ensemble Learning techniques can be classified as:
Bagging
Boosting
Stacking
In addition to these three main categories, two important variations emerge: Voting (which is a complement of Bagging) and Blending (a subtype of Stacking). Although Voting and Blending are a complement and a subtype of Bagging and Stacking respectively, these techniques are often found as direct types of Ensemble Learning.
In this blog we will specifically address the Stacking, Blending and Voting techniques, let’s go for it!
Better known as Stacking Generalization, it is a method introduced by David H. Wolpert in 1992 [3] where the key is to reduce the generalization error of different generalizers (i.e. ML models). The general idea of the Stacking Generalization method is the generation of a Meta-Model. Such a Meta-Model is made up of the predictions of a set of ML base models (i.e. weak learners) through the k-fold cross validation technique. Finally, the Meta-Model is trained with an additional ML model (which is commonly known as the “final estimator” or “final learner”).
The Stacking Generalization method is commonly composed of 2 training stages, better known as “level 0” and “level 1”. It is important to mention that it can be added as many levels as necessary. However, in practice it is common to use only 2 levels. The aim of the first stage (level 0) is to generate the training data for the meta-model, this is carried out by implementing k-fold cross validation for each “weak learner” defined in the first stage. The predictions of each one of these“weak learners” are “stacked” in order to build such such “new training set” (the meta-model). The aim of the second stage (level 1) is to train the meta-model, such training is carried out through an already determined “final learner”.
In figure 2 we see a graphical description of an architecture of a Stacking Generalization Classifier that is composed of 3 base models (weak learners) and a final estimator.
Perfect, so far we already know how the Stacking Generalization technique works. Now let’s see a small example of how we would do this in code (it is important to mention that this technique can be implemented directly from scikit-learn, however, in order to make the explanation more demonstrative, let’s see how we do it from scratch).
Let’s analyze the key parts, in line 4 we are defining 5 classifiers (weak learners) that will be the base models of our stack (which are trained at level 0). In line 11 we define the final classifier (which is the meta-model classifier). Now, level 0 training begins with the for loop defined in line 17. As we can see, in line 19 we are receiving the predictions of k-fold cross validation and in line 26 we are “stacking” these predictions (the which are forming the training data of the meta-model). On line 22 we are receiving the predictions from the test set which are “stacked” on line 33 to form the meta-model test data. Finally, in line 45 we carry out the level 1 training, that is, the meta-model training.
I invite you to download the code and try it for yourself, it will be worth: https://github.com/FernandoLpz/Stacking-Blending-Voting-Ensembles
Well, so far we already know how the Stacking Generalization technique works. As we mentioned, one of the key parts of this method is the use of the k-fold cross validation for the generation of the meta-model training data. However, there is a variation, we can omit k-fold cross validation and only use “one-holdout set”, this small but significant variation is called “Blending”.
Let’s see how it works!
Blending is a technique derived from Stacking Generalization. The only difference is that in Blending, the k-fold cross validation technique is not used to generate the training data of the meta-model. Blending implements “one-holdout set”, that is, a small portion of the training data (validation) to make predictions which will be “stacked” to form the training data of the meta-model. Also, predictions are made from the test data to form the meta-model test data.
In figure 3 we can see a Blending architecture using 3 base models (weak learners) and a final classifier. The blue boxes represent that portion of the training data that is used to generate predictions (yellow boxes) to form the meta-model. The green boxes represent the test data which is used to generate predictions to form the meta-model test data (purple boxes).
Great, now that you’re familiar with the Blending architecture, let’s see how we do this in code:
Let’s analyze the key parts of this model. In line 4 we are defining the 5 base classifiers that we will use (weak learners), in line 11 we define the final classifier, as in the previous example, we will use Logistic Regression. Level 0 training begins on line 17. As we can see, on line 20 we are receiving the predictions of the validation set (which will form the training data of the meta-model) and the predictions of the test data (the which will form the meta-model test data). Also, on lines 24 and 31 we are “stacking” the predictions of each base classifier. Finally, on line 43 we are moving to level 1 training, and that is it!
I invite you to download the code and try it for yourself, it will be worth: https://github.com/FernandoLpz/Stacking-Blending-Voting-Ensembles
As we can see, the Blending architecture is slightly simpler and more compact than Stack Generalization. Omitting k-fold cross validation can make us optimize the processing time.
Great, by now you already know the Stacked Generalization architecture and how it works as well as the variation that arises from it (Blending). The million dollar question remains: which technique is better? When should I apply Stacking or Blending? Well, that will depend 100% on the task you are trying to solve, the amount of data you have as well as the computing power and memory available.
Finally, let’s talk about an Ensemble Learning technique that is simple, intuitive and that can sometimes be a good option, let’s talk about Voting!
This type of ensemble is one of the most intuitive and easy to understand. The Voting Classifier is a homogeneous and heterogeneous type of Ensemble Learning, that is, the base classifiers can be of the same or different type. As mentioned earlier, this type of ensemble also works as an extension of bagging (e.g. Random Forest).
The architecture of a Voting Classifier is made up of a number “n” of ML models, whose predictions are valued in two different ways: hard and soft. In hard mode, the winning prediction is the one with “the most votes”. In Figure 2 we see an example of how the Voting Classifier works in hard mode.
On the other hand, the Voting Classifier in soft mode considers the probabilities thrown by each ML model, these probabilities will be weighted and averaged, consequently the winning class will be the one with the highest weighted and averaged probability. In Figure 3 we see an example of how the Voting Classifier works in the soft mode.
Ok, now that we know how the Voiting Classifier works, let’s see how to do this in code. On this occasion, since it is a simple and intuitive ensemble technique (compared to Stacking or Blending), let’s make use of the function provided by scikit-learn for the implementation of Voting, let’s do it!
In the code above we are creating a class which will contain different classifiers which are: Decision Tree, K-Nearest Neighbors, Logistic Regression and Voting Classifier (lines 24, 32, 40 and 48 respectively). To compare the effectiveness between “weak classifiers” and the Ensemble, we will make use of the “breast_cancer” toy dataset (line 8). We will use each classifier with its default values.
Let’s go directly to what interests us, Voting Classifier. As we can see, in lines from 51 to 53 we are defining the weak classifiers that we are going to use and, in a simple way, we are going to pass these classifiers as parameters to the Voting Classifier (line 56), in this example, we are using the “hard” mode. Finally, on line 59 we train the Ensemble, this is what we get:
Decision Tree, Train accuracy: 1Decision Tree, Test accuracy: 0.958K-Nearest Neighbors, Train accuracy: 0.930K-Nearest Neighbors, Test accuracy: 0.946Logistic Regression, Train accuracy: 0.953Logistic Regression, Test accuracy: 0.951Voting Classifier, Train accuracy: 0.981Voting Classifier, Test accuracy: 0.965
As we can see, the Test accuracy of the Voting Classifier is slightly better than that of the weak classifiers. It is very important to mention that, although Voting Classifier is a great alternative to improve the accuracy of your models, it may not always be the best option due to various factors, including processing time.
I invite you to download the code and try it for yourself, it will be worth: https://github.com/FernandoLpz/Stacking-Blending-Voting-Ensembles
Congratulations, we have reached the end of this great journey to learn a little more about Ensemble Learning.
In this blog we have seen what Ensemble Learning is and its most common techniques. On the other hand, we have delved a little into Stacking, Blending and Voting techniques. Blending being a technique derived from Stacking.
In the end, there is a great diversity of techniques to reduce the error of our ML models as well as to increase their effectiveness, it will be up to each developer to choose the one that best suits their problem taking into account several factors such as the amount of data available, the type of learning to be carried out, the amount of computational processing available, etc.
|
[
{
"code": null,
"e": 511,
"s": 172,
"text": "We have heard the phrase “unity is strength”, whose meaning can be transferred to different areas of life. Sometimes correct answers to a specific problem are supported by several sources and not just one. This is what Ensemble Learning tries to do, that is, to put together a group of ML models to improve solutions to specific problems."
},
{
"code": null,
"e": 748,
"s": 511,
"text": "Throughout this blog, we will learrn what Ensemble Learning is, what are the types of Ensembles that exist and we will specifically address Voting and Stacking Ensembles. Therefore, this blog will be divided into the following sections:"
},
{
"code": null,
"e": 775,
"s": 748,
"text": "What is Ensemble Learning?"
},
{
"code": null,
"e": 784,
"s": 775,
"text": "Stacking"
},
{
"code": null,
"e": 793,
"s": 784,
"text": "Blending"
},
{
"code": null,
"e": 800,
"s": 793,
"text": "Voting"
},
{
"code": null,
"e": 943,
"s": 800,
"text": "I invite you to download the code and try it for yourself, it will be worth: https://github.com/FernandoLpz/Stacking-Blending-Voting-Ensembles"
},
{
"code": null,
"e": 1516,
"s": 943,
"text": "Ensemble Learning refers to the use of ML algorithms jointly to solve classification and/or regression problems mainly. These algorithms can be the same type (homogeneous Ensemble Learning) or different types (heterogeneous Ensemble Learning). Ensemble Learning performs a strategic combination of various experts or ML models in order to improve the effectiveness obtained using a single weak model [1, 2]. Figure 1 provides a visual overview regarding the comparison of a model that does not implement Ensemble Learning and a model that does implement Ensemble Learning."
},
{
"code": null,
"e": 1846,
"s": 1516,
"text": "There are different types of Ensemble Learning techniques which differ mainly by the type of models used (homogeneous or heterogeneous models), the data sampling (with or without replacement, k-fold, etc.) and the decision function (voting, average, meta model, etc). Therefore, Ensemble Learning techniques can be classified as:"
},
{
"code": null,
"e": 1854,
"s": 1846,
"text": "Bagging"
},
{
"code": null,
"e": 1863,
"s": 1854,
"text": "Boosting"
},
{
"code": null,
"e": 1872,
"s": 1863,
"text": "Stacking"
},
{
"code": null,
"e": 2198,
"s": 1872,
"text": "In addition to these three main categories, two important variations emerge: Voting (which is a complement of Bagging) and Blending (a subtype of Stacking). Although Voting and Blending are a complement and a subtype of Bagging and Stacking respectively, these techniques are often found as direct types of Ensemble Learning."
},
{
"code": null,
"e": 2303,
"s": 2198,
"text": "In this blog we will specifically address the Stacking, Blending and Voting techniques, let’s go for it!"
},
{
"code": null,
"e": 2865,
"s": 2303,
"text": "Better known as Stacking Generalization, it is a method introduced by David H. Wolpert in 1992 [3] where the key is to reduce the generalization error of different generalizers (i.e. ML models). The general idea of the Stacking Generalization method is the generation of a Meta-Model. Such a Meta-Model is made up of the predictions of a set of ML base models (i.e. weak learners) through the k-fold cross validation technique. Finally, the Meta-Model is trained with an additional ML model (which is commonly known as the “final estimator” or “final learner”)."
},
{
"code": null,
"e": 3592,
"s": 2865,
"text": "The Stacking Generalization method is commonly composed of 2 training stages, better known as “level 0” and “level 1”. It is important to mention that it can be added as many levels as necessary. However, in practice it is common to use only 2 levels. The aim of the first stage (level 0) is to generate the training data for the meta-model, this is carried out by implementing k-fold cross validation for each “weak learner” defined in the first stage. The predictions of each one of these“weak learners” are “stacked” in order to build such such “new training set” (the meta-model). The aim of the second stage (level 1) is to train the meta-model, such training is carried out through an already determined “final learner”."
},
{
"code": null,
"e": 3767,
"s": 3592,
"text": "In figure 2 we see a graphical description of an architecture of a Stacking Generalization Classifier that is composed of 3 base models (weak learners) and a final estimator."
},
{
"code": null,
"e": 4105,
"s": 3767,
"text": "Perfect, so far we already know how the Stacking Generalization technique works. Now let’s see a small example of how we would do this in code (it is important to mention that this technique can be implemented directly from scikit-learn, however, in order to make the explanation more demonstrative, let’s see how we do it from scratch)."
},
{
"code": null,
"e": 4825,
"s": 4105,
"text": "Let’s analyze the key parts, in line 4 we are defining 5 classifiers (weak learners) that will be the base models of our stack (which are trained at level 0). In line 11 we define the final classifier (which is the meta-model classifier). Now, level 0 training begins with the for loop defined in line 17. As we can see, in line 19 we are receiving the predictions of k-fold cross validation and in line 26 we are “stacking” these predictions (the which are forming the training data of the meta-model). On line 22 we are receiving the predictions from the test set which are “stacked” on line 33 to form the meta-model test data. Finally, in line 45 we carry out the level 1 training, that is, the meta-model training."
},
{
"code": null,
"e": 4968,
"s": 4825,
"text": "I invite you to download the code and try it for yourself, it will be worth: https://github.com/FernandoLpz/Stacking-Blending-Voting-Ensembles"
},
{
"code": null,
"e": 5351,
"s": 4968,
"text": "Well, so far we already know how the Stacking Generalization technique works. As we mentioned, one of the key parts of this method is the use of the k-fold cross validation for the generation of the meta-model training data. However, there is a variation, we can omit k-fold cross validation and only use “one-holdout set”, this small but significant variation is called “Blending”."
},
{
"code": null,
"e": 5375,
"s": 5351,
"text": "Let’s see how it works!"
},
{
"code": null,
"e": 5844,
"s": 5375,
"text": "Blending is a technique derived from Stacking Generalization. The only difference is that in Blending, the k-fold cross validation technique is not used to generate the training data of the meta-model. Blending implements “one-holdout set”, that is, a small portion of the training data (validation) to make predictions which will be “stacked” to form the training data of the meta-model. Also, predictions are made from the test data to form the meta-model test data."
},
{
"code": null,
"e": 6213,
"s": 5844,
"text": "In figure 3 we can see a Blending architecture using 3 base models (weak learners) and a final classifier. The blue boxes represent that portion of the training data that is used to generate predictions (yellow boxes) to form the meta-model. The green boxes represent the test data which is used to generate predictions to form the meta-model test data (purple boxes)."
},
{
"code": null,
"e": 6311,
"s": 6213,
"text": "Great, now that you’re familiar with the Blending architecture, let’s see how we do this in code:"
},
{
"code": null,
"e": 6952,
"s": 6311,
"text": "Let’s analyze the key parts of this model. In line 4 we are defining the 5 base classifiers that we will use (weak learners), in line 11 we define the final classifier, as in the previous example, we will use Logistic Regression. Level 0 training begins on line 17. As we can see, on line 20 we are receiving the predictions of the validation set (which will form the training data of the meta-model) and the predictions of the test data (the which will form the meta-model test data). Also, on lines 24 and 31 we are “stacking” the predictions of each base classifier. Finally, on line 43 we are moving to level 1 training, and that is it!"
},
{
"code": null,
"e": 7095,
"s": 6952,
"text": "I invite you to download the code and try it for yourself, it will be worth: https://github.com/FernandoLpz/Stacking-Blending-Voting-Ensembles"
},
{
"code": null,
"e": 7275,
"s": 7095,
"text": "As we can see, the Blending architecture is slightly simpler and more compact than Stack Generalization. Omitting k-fold cross validation can make us optimize the processing time."
},
{
"code": null,
"e": 7672,
"s": 7275,
"text": "Great, by now you already know the Stacked Generalization architecture and how it works as well as the variation that arises from it (Blending). The million dollar question remains: which technique is better? When should I apply Stacking or Blending? Well, that will depend 100% on the task you are trying to solve, the amount of data you have as well as the computing power and memory available."
},
{
"code": null,
"e": 7821,
"s": 7672,
"text": "Finally, let’s talk about an Ensemble Learning technique that is simple, intuitive and that can sometimes be a good option, let’s talk about Voting!"
},
{
"code": null,
"e": 8152,
"s": 7821,
"text": "This type of ensemble is one of the most intuitive and easy to understand. The Voting Classifier is a homogeneous and heterogeneous type of Ensemble Learning, that is, the base classifiers can be of the same or different type. As mentioned earlier, this type of ensemble also works as an extension of bagging (e.g. Random Forest)."
},
{
"code": null,
"e": 8450,
"s": 8152,
"text": "The architecture of a Voting Classifier is made up of a number “n” of ML models, whose predictions are valued in two different ways: hard and soft. In hard mode, the winning prediction is the one with “the most votes”. In Figure 2 we see an example of how the Voting Classifier works in hard mode."
},
{
"code": null,
"e": 8790,
"s": 8450,
"text": "On the other hand, the Voting Classifier in soft mode considers the probabilities thrown by each ML model, these probabilities will be weighted and averaged, consequently the winning class will be the one with the highest weighted and averaged probability. In Figure 3 we see an example of how the Voting Classifier works in the soft mode."
},
{
"code": null,
"e": 9090,
"s": 8790,
"text": "Ok, now that we know how the Voiting Classifier works, let’s see how to do this in code. On this occasion, since it is a simple and intuitive ensemble technique (compared to Stacking or Blending), let’s make use of the function provided by scikit-learn for the implementation of Voting, let’s do it!"
},
{
"code": null,
"e": 9491,
"s": 9090,
"text": "In the code above we are creating a class which will contain different classifiers which are: Decision Tree, K-Nearest Neighbors, Logistic Regression and Voting Classifier (lines 24, 32, 40 and 48 respectively). To compare the effectiveness between “weak classifiers” and the Ensemble, we will make use of the “breast_cancer” toy dataset (line 8). We will use each classifier with its default values."
},
{
"code": null,
"e": 9872,
"s": 9491,
"text": "Let’s go directly to what interests us, Voting Classifier. As we can see, in lines from 51 to 53 we are defining the weak classifiers that we are going to use and, in a simple way, we are going to pass these classifiers as parameters to the Voting Classifier (line 56), in this example, we are using the “hard” mode. Finally, on line 59 we train the Ensemble, this is what we get:"
},
{
"code": null,
"e": 10185,
"s": 9872,
"text": "Decision Tree, Train accuracy: 1Decision Tree, Test accuracy: 0.958K-Nearest Neighbors, Train accuracy: 0.930K-Nearest Neighbors, Test accuracy: 0.946Logistic Regression, Train accuracy: 0.953Logistic Regression, Test accuracy: 0.951Voting Classifier, Train accuracy: 0.981Voting Classifier, Test accuracy: 0.965"
},
{
"code": null,
"e": 10513,
"s": 10185,
"text": "As we can see, the Test accuracy of the Voting Classifier is slightly better than that of the weak classifiers. It is very important to mention that, although Voting Classifier is a great alternative to improve the accuracy of your models, it may not always be the best option due to various factors, including processing time."
},
{
"code": null,
"e": 10656,
"s": 10513,
"text": "I invite you to download the code and try it for yourself, it will be worth: https://github.com/FernandoLpz/Stacking-Blending-Voting-Ensembles"
},
{
"code": null,
"e": 10767,
"s": 10656,
"text": "Congratulations, we have reached the end of this great journey to learn a little more about Ensemble Learning."
},
{
"code": null,
"e": 10991,
"s": 10767,
"text": "In this blog we have seen what Ensemble Learning is and its most common techniques. On the other hand, we have delved a little into Stacking, Blending and Voting techniques. Blending being a technique derived from Stacking."
}
] |
Apache Flink - API Concepts
|
Flink has a rich set of APIs using which developers can perform transformations on both batch and real-time data. A variety of transformations includes mapping, filtering, sorting, joining, grouping and aggregating. These transformations by Apache Flink are performed on distributed data. Let us discuss the different APIs Apache Flink offers.
Dataset API in Apache Flink is used to perform batch operations on the data over a period. This API can be used in Java, Scala and Python. It can apply different kinds of transformations on the datasets like filtering, mapping, aggregating, joining and grouping.
Datasets are created from sources like local files or by reading a file from a particular sourse and the result data can be written on different sinks like distributed files or command line terminal. This API is supported by both Java and Scala programming languages.
Here is a Wordcount program of Dataset API −
public class WordCountProg {
public static void main(String[] args) throws Exception {
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<String> text = env.fromElements(
"Hello",
"My Dataset API Flink Program");
DataSet<Tuple2<String, Integer>> wordCounts = text
.flatMap(new LineSplitter())
.groupBy(0)
.sum(1);
wordCounts.print();
}
public static class LineSplitter implements FlatMapFunction<String, Tuple2<String, Integer>> {
@Override
public void flatMap(String line, Collector<Tuple2<String, Integer>> out) {
for (String word : line.split(" ")) {
out.collect(new Tuple2<String, Integer>(word, 1));
}
}
}
}
This API is used for handling data in continuous stream. You can perform various operations like filtering, mapping, windowing, aggregating on the stream data. There are various sources on this data stream like message queues, files, socket streams and the result data can be written on different sinks like command line terminal. Both Java and Scala programming languages support this API.
Here is a streaming Wordcount program of DataStream API, where you have continuous stream of word counts and the data is grouped in the second window.
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
public class WindowWordCountProg {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStream<Tuple2<String, Integer>> dataStream = env
.socketTextStream("localhost", 9999)
.flatMap(new Splitter())
.keyBy(0)
.timeWindow(Time.seconds(5))
.sum(1);
dataStream.print();
env.execute("Streaming WordCount Example");
}
public static class Splitter implements FlatMapFunction<String, Tuple2<String, Integer>> {
@Override
public void flatMap(String sentence, Collector<Tuple2<String, Integer>> out) throws Exception {
for (String word: sentence.split(" ")) {
out.collect(new Tuple2<String, Integer>(word, 1));
}
}
}
}
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2413,
"s": 2069,
"text": "Flink has a rich set of APIs using which developers can perform transformations on both batch and real-time data. A variety of transformations includes mapping, filtering, sorting, joining, grouping and aggregating. These transformations by Apache Flink are performed on distributed data. Let us discuss the different APIs Apache Flink offers."
},
{
"code": null,
"e": 2676,
"s": 2413,
"text": "Dataset API in Apache Flink is used to perform batch operations on the data over a period. This API can be used in Java, Scala and Python. It can apply different kinds of transformations on the datasets like filtering, mapping, aggregating, joining and grouping."
},
{
"code": null,
"e": 2944,
"s": 2676,
"text": "Datasets are created from sources like local files or by reading a file from a particular sourse and the result data can be written on different sinks like distributed files or command line terminal. This API is supported by both Java and Scala programming languages."
},
{
"code": null,
"e": 2989,
"s": 2944,
"text": "Here is a Wordcount program of Dataset API −"
},
{
"code": null,
"e": 3758,
"s": 2989,
"text": "public class WordCountProg {\n public static void main(String[] args) throws Exception {\n final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();\n\n DataSet<String> text = env.fromElements(\n \"Hello\",\n \"My Dataset API Flink Program\");\n\n DataSet<Tuple2<String, Integer>> wordCounts = text\n .flatMap(new LineSplitter())\n .groupBy(0)\n .sum(1);\n\n wordCounts.print();\n }\n\n public static class LineSplitter implements FlatMapFunction<String, Tuple2<String, Integer>> {\n @Override\n public void flatMap(String line, Collector<Tuple2<String, Integer>> out) {\n for (String word : line.split(\" \")) {\n out.collect(new Tuple2<String, Integer>(word, 1));\n }\n }\n }\n}"
},
{
"code": null,
"e": 4149,
"s": 3758,
"text": "This API is used for handling data in continuous stream. You can perform various operations like filtering, mapping, windowing, aggregating on the stream data. There are various sources on this data stream like message queues, files, socket streams and the result data can be written on different sinks like command line terminal. Both Java and Scala programming languages support this API."
},
{
"code": null,
"e": 4300,
"s": 4149,
"text": "Here is a streaming Wordcount program of DataStream API, where you have continuous stream of word counts and the data is grouped in the second window."
},
{
"code": null,
"e": 5467,
"s": 4300,
"text": "import org.apache.flink.api.common.functions.FlatMapFunction;\nimport org.apache.flink.api.java.tuple.Tuple2;\nimport org.apache.flink.streaming.api.datastream.DataStream;\nimport org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;\nimport org.apache.flink.streaming.api.windowing.time.Time;\nimport org.apache.flink.util.Collector;\npublic class WindowWordCountProg {\n public static void main(String[] args) throws Exception {\n StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();\n DataStream<Tuple2<String, Integer>> dataStream = env\n .socketTextStream(\"localhost\", 9999)\n .flatMap(new Splitter())\n .keyBy(0)\n .timeWindow(Time.seconds(5))\n .sum(1);\n dataStream.print();\n env.execute(\"Streaming WordCount Example\");\n }\n public static class Splitter implements FlatMapFunction<String, Tuple2<String, Integer>> {\n @Override\n public void flatMap(String sentence, Collector<Tuple2<String, Integer>> out) throws Exception {\n for (String word: sentence.split(\" \")) {\n out.collect(new Tuple2<String, Integer>(word, 1));\n }\n }\n }\n}"
},
{
"code": null,
"e": 5502,
"s": 5467,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5521,
"s": 5502,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5556,
"s": 5521,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5577,
"s": 5556,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 5610,
"s": 5577,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5623,
"s": 5610,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5658,
"s": 5623,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5676,
"s": 5658,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5709,
"s": 5676,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5727,
"s": 5709,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5760,
"s": 5727,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5778,
"s": 5760,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5785,
"s": 5778,
"text": " Print"
},
{
"code": null,
"e": 5796,
"s": 5785,
"text": " Add Notes"
}
] |
Building a Complete AI Based Search Engine with Elasticsearch, Kubeflow and Katib | by Will Fuks | Towards Data Science
|
Building search systems is hard. Preparing them to work with machine learning is really hard. Developing a complete search engine framework integrated with AI is really really hard.
So let’s make one. ✌️
In this post, we’ll build a search engine from scratch and discuss on how to further optimize results by adding a machine learning layer using Kubeflow and Katib. This new layer will be capable of retrieving results considering the context of users and is the main focus of this article.
As we’ll see, thanks to Kubeflow and Katib, final result is rather quite simple, efficient and easy to maintain.
To understand the concepts in practice, we’ll implement the system with hands-on experience. As it’s been built on top of Kubernetes, you can use any infrastructure you like (given appropriate adaptations). We’ll be using Google Cloud Platform (GCP) in this post.
We begin with a brief introduction to concepts and then move to the system implementation discussion.
So, with no further ado,
If you receive the challenge of building a search system for your company or want to build one for your own, you’ll soon realize that the initial steps tend to be somewhat straightforward.
First and foremost, the search engine must contain documents for retrieval. As we’ll be working with Elasticsearch, let’s use it as reference (for an introduction, please refer to their official docs)
Documents should be uploaded to Elasticsearch following a JSON format. If, for instance, we are building a search engine for a fashion eCommerce store, here’s an example of a document:
Then comes the retrieval step which in essence involves matching search queries with document fields:
The ranking phase applies some mathematical rules such as TF-IDF or BM25F to figure out how to properly rank, sorting documents from best to worst match. It’d be something like:
Further optimization could leverage on specific fields of documents containing performance metrics. For instance, in the previous example, we have that the Click Through Rate (CTR, i.e., reason between clicks and total impressions) of the t-shirt is CTR=0.36. Another retrieval layer could be added using this information and favoring documents with better CTR to show at the top (also known as “boosting”):
So far so good. But let’s see how to further optimize even more.
Consider that each user has a specific context. Let’s take our fashion online store as an example again. Some of the traffic may come from southern regions where it may be warmer than regions from the north. They’d probably rather be exposed to lighter clothing than to winter specific products.
More context can be added to the equation: we could distinguish customers based on their favorite brands, categories, colors, sizes, device used, average consuming ticket, profession, age and the list goes on and on...
Doing so requires some extra tools as well. Let’s dive a bit deeper into that.
Learn-to-rank (LTR) is a field of machine learning that studies algorithms whose main goal is to properly rank a list of documents.
It works essentially as any other learning algorithm: it requires a training dataset, suffers from problems such as bias-variance, each model has advantages over certain scenarios and so on.
What basically changes is that the cost function for the training process is designed to let the algorithm learn about ranking and the output of the model is a value for how good of a match a given document is for a given query.
Mathematically, it’s simply given by:
X in our case comprehends all features we’d like to use to add context to the search. They can be values such as region of the user, their age, favorite brand, correlation between queries and documents fields and so on.
f is the ranking model which is supposed to be trained and evaluated.
Finally, J extends for Judgment and for us it’s an integer value that ranges from 0 (meaning the document is not a good match for a query given features) up to 4 (document is a very good match). We arrange documents from best to worst by using the judgments.
Our main goal is to obtain f since it represents the ranking algorithm that adds the machine learning layer to the search results. And in order to obtain f, we need a dataset that already contains the values of the judgments otherwise we can’t train the models.
As it turns out, finding those values can be quite challenging. While the details of how to do so won’t be covered here, this post has a thorough discussion on the subject; in a nutshell, we use clickstream data of users interactions with search engines (their clicks and purchases) to fit models whose variables yield a proxy for the judgment value.
After computing the judgments, we are left with training the ranking models. Elasticsearch already offers a learn-to-rank plugin which we’ll use in this implementation. The plugin offers various ranking algorithms ranging from decision trees to neural networks.
This is an example of the required training file:
The idea is to register for each query (“women t-shirt”) all documents that were printed in the results page. For each, we compute their expected judgment and build the matrix of features X.
In practice, what will happen is that we’ll first prepare all this data and feed it to the Learn-To-Rank plugin of Elasticsearch which will result in a trained ranking model. It can then be used to add the personalization layer we are looking for.
Further details on building X will be discussed soon.
We are ready now to train the models. So far so good. But then, we still have a tricky problem: how to know if it’s working?
We could choose from several methods to check the performance of a ranking model. The one we’ll discuss here is the average rank metric based on what users either clicked or purchased (pySearchML focuses on purchase events only but clicks can be used interchangeably).
Mathematically, it’s given by:
The formula basically sums over each rank associated to each purchased (or clicked) item in reference to a complete list of documents. The denominator is simply the cardinality of how many items were summed over in the process (total items users either clicked or bought).
In practice, what will happen is that, after training a ranking model, we’ll loop through the validation dataset (which contains what users searched and what they purchased) and use each search term to send a query to Elasticsearch. We then compare the results with what users bought to compute the appropriate average ranking.
The image above illustrates the concept. For each user, we send their search term to Elasticsearch which already contains the just recently trained model. We then compare the search results with what the user purchased and compute the rank. In the previous example, the red t-shirt appears at position 2 out of the 3 retrieved items. As it’s just one item that was purchased then rank=66%.
We run the same computation to all users in the database and then average them all together for a final rank expression.
Notice that the final rank metric must be lower than 50% otherwise the algorithm is just performing as a random selector of documents.
This value is important as it’s used for selecting the best ranking model. That’s where we use Katib from Kubeflow.
Let’s see now how to put all these concepts together and build the search engine:
As discussed before, Kubeflow is the orchestrator for the pipeline processing. It has various responsibilities ranging from preparing data for Elasticsearch and for training to running the entire training process.
It works by defining components and their respective tasks. For pySearchML, here’s the complete pipeline that was implemented:
The pipeline is defined by receiving various input parameters such as the bucket and model_name and we’ll be able to change those values at execution time (as we’ll see soon).
Let’s see each component from the pipeline implementation and its purpose:
Here’s how prepare_env component is defined:
Image is a docker reference for the component to run in that step.
Arguments are input parameters sent to the script executed in the Docker’s image ENTRYPOINT.
pvolumes mounts the volume claim into \data.
Here’s all files in prepare_env:
run.py is responsible for running queries against BigQuery and preparing Elasticsearch. One of its input arguments is model_name which sets which folder to use as reference for processing data. lambdamart0 is an algorithm that has already implemented to work with Google Analytics(GA) public sample dataset.
Dockerfile bundles the whole code together and have as ENTRYPOINT the execution of the run.py script:
lambdamart0 is a folder dedicated to an implementation of an algorithm with this respective name. It’s been built to process GA public data and works as an example of the system. Here’s the files it contains:
ga_data.sql is a query responsible for retrieving documents from the GA public dataset and exporting it to Elasticsearch
es_mapping.json is an index definition for each field of the documents
features carries the value of X as discussed before. In lambdamart0 example, it uses the GA public data as reference for building the features.
Notice the feature called name.json:
Learn-To-Rank plugin requires that each feature be defined as a valid Elasticsearch query and score results are associated as to X.
In the previous example, it receives a parameter search_term and proceeds on matching it on the field name of each document returning the BM25 match, which effectively becomes our “X0”.
Using BM25 between query and name field is not enough to add personalization to results. Another feature that advances in the customization layer is the channel_group.json defined as follows:
It receives as input the parameter channel_group (channel that brought the user to our web store) and returns the CTR for that respective channel.
This effectively prepares the model to distinguish from users their origin and how to rank each group. Specifically, users coming from paid sources might behave differently than those coming in through organic channels for instance. If the training is good enough, the ranking algorithm should be prepared to handle these situations.
Still, this doesn’t tell much on how to personalize results by using intrinsic characteristics of each user. So, here’s one possibility for solving that. The feature avg_customer_price.json is defined as:
It receives as input the parameter customer_avg_ticket and returns for each document the log of the distance between the average user ticket and the price of the document.
Now the ranking model can learn in the training phase how to manage the rank of each item based on how distant its price is to the average spending of the user on the website.
With those three types of features we can add a complete personalization layer to a search system on top of Elasticsearch. Features can be anything as long as it can be abstracted into a valid search query and they must return some scoring metric eventually translated as our value X.
For what follows in prepare_env component:
Features are exported to Elasticsearch.
An index is created on Elasticsearch that defines documents fields.
Documents are queried from BigQuery and uploaded into Elasticsearch.
RankLib requirements are created (feature set store and so on).
For implementing a new model with new data and features, just create another folder inside prepare_env (something like modelname2) and set how it will query data and upload them to Elasticsearch.
This is a simple step. It consists of retrieving data from BigQuery containing what users searched, the context of the search and a list of products purchased.
Here’s the BigQuery query used for retrieving the data. It basically selects all users, their searches and purchases and then combines with their context. An example of the results:
search_keys can contain any available information that sets the context of customers. In the previous example, we’re using their channel group and average spending ticket on the website.
This data is what we feed into the validation framework when computing the average rank as discussed before.
Notice that the system builds three different validation datasets: one for the training period, another for the regular validation and finally the third is for the final testing step. The idea here is to analyze bias and variance for the trained models.
This is the component responsible for building the RankLib training file as discussed before. The complete script is actually quite simple. First, it downloads from BigQuery the input clickstream data which consists of users interactions on search pages. Here’s an example:
Notice that the keys associated to the search are aggregated together inside search_keys. Those values are the ones we send to Elasticsearch and replace appropriately each feature X as discussed in prepare_env. In the previous JSON example, we know that the user search context is:
Searched for drinkware.
Came to the store directly.
Spent on average $20 on the website.
judgment_keys combines users sessions composed of documents they saw on the search page and their interaction on a given document.
This information is then sent to pyClickModels which then process the data and evaluates the judgment for each query-document pair. Result is a newline delimited JSON document as follows:
Notice that the value of the key is search_term:bags|channel_group:organic|customer_avg_ticket:30.
As discussed before, we want our search engine to be aware of context and further optimize on top of that. As a consequence, judgments are extract based on the entire selected context, not just the search_term.
By doing so, we can differentiate documents for each context and we’d have scenarios where a product receives judgment 4 for customers coming from northern regions and judgment 0 otherwise, as an example.
Notice that the judgments values, as given by pyClickModels, ranges between 0 and 1. As the Learn-To-Rank Elasticsearch plugin is built on top of RankLib, this value is expected to range between integers 0 and 4, inclusive. What we do then is we transform the variables using their percentile as reference. Here’s the complete code for building the final judgment files:
Here’s an example of the output of this step:
This data needs to be transformed into the required training file for RankLib. This is where we combine the information of judgments, documents, queries context with the features X (here’s the code example for retrieving X from Elasticsearch).
Each JSON row from previous step containing search context and judgment keys is looped over and sent as a query against Elasticsearch with the input parameters of the search_keys. The result will be each value of X as already defined from previous prepare_env step.
End result is a training file that looks something like this:
For each query and for each document we have the estimated judgment as computed by pyClickModels, the id of the query and then a list of features X with their respective values.
With this file, we can train now the ranking algorithms.
Katib is a tool from Kubeflow that offers an interface for automatic hyperparameter optimization. It has several available methods; Bayesian Optimization is the one selected in pySearchML.
What Katib does is it selects for each hyperparameter a new value based on a trade-off between exploration-exploitation. It then tests the new model and observe results which are used for future steps.
For pySearchML, each parameter is an input of RankLib which sets how the model will be fit (such as how many trees to use, total leaf nodes, how many neurons in a net and so on).
Katib is defined through a Custom Resource of Kubernetes. We can run it by defining a YAML file and deploying it to the cluster, something like:
kubectl create -f katib_def.yaml
What Katib will do is read through the YAML file and start trials, each experimenting a specific value of hyperparameters. It can instantiate multiple pods running in parallel executing the code as specified in the experiment definition.
Here are the files in this step:
launch_katib.py is responsible for launching Katib from a Python script. It receives input arguments, builds an YAML definition and use Kubernetes APIs to start Katib from the script itself.
experiment.json works as a template for the definition of the experiment. Here’s its definition:
It essentially defines how many pods to run in parallel and which Docker image to run for each trial along with its input command. Notice that the total pods running in parallel as well as maximum trials are hard-coded in pySearchML. Best approach would be to receive those parameters from the pipeline execution and replace them accordingly.
launch_katib.py will read this template, build a final YAML definition and send it to Kubernetes which will start the Katib process.
One of the input parameters is the ranker which is the ranking algorithm to select from RankLib (such as lambdaMart, listNet and so on). Each ranker has its own set of parameters, here’s the example for LambdaMart algorithm as implemented in launch_katib.py:
Katib will select parameters from the domain defined above and run train.py where effectively RankLib is used to train the ranking models. An example of the command as implemented in Python:
This string is sent to a subprocess call (notice it requires Java because of RankLib) which starts the training process. The result is a newly trained ranking model that can be exported to Elasticsearch.
Just as the model is fit, validate.py is invoked for computing the expected rank. The steps that take place are:
The script loops through each JSON from the validation dataset.
Each row contains the search context which is then used to build an Elasticsearch query. Here’s the query used by the model lambdamart0 which we’ll use later on:
Given the recently built query, a request is sent to Elasticsearch.
A comparison happens between the search results and purchased documents.
Here’s the code responsible for building the Elasticsearch query:
Notice that the parameter rescore_query triggers the machine learning layer on Elasticsearch learn-to-rank plugin.
Finally, the function compute_rank puts it all together as shown below:
Katib instantiate sidecars pods which keeps reading through the stdout of the training pod. When it identifies the string Validation-rank=(...), it uses the value as the result for the optimization process.
A persistent volume is used in the process to save the definition of the best model trained by Katib which is used by our next component.
The most difficult parts are done already. Now what happens is the script simply goes after the definition of the best model as saved in a text file and uploads it to Elasticsearch.
Notice that one of the main advantages with this design is that this component could export the model to a production Elasticsearch while the whole optimization could happen on a staging replica engine.
Finally, as the best model is exported to Elasticsearch, the system has at its disposal the best optimized ranking model. In this step, a final validation is executed in order to verify not only that everything worked fine as well as for providing further information on whether the system is suffering from bias-variance.
That’s pretty much it! Let’s run some code now to see this whole framework in action.
Time to implement the whole architecture in practice! Complete code is available on pySearchML repository:
github.com
In this section, we’ll be using GCP for running the code with real data. Also, keep in mind that there will be costs (a few cents) associated to running this experiment.
For those new to GCP, there’s a $300 free credit gift that lasts for a year; just sign in and create a project for this tutorial (pysearchml for instance). You should end up with access to a dashboard that looks like this:
gcloud will be required for interacting with GCP through command line. Installing it is quite straightforward. After the initial setup, make sure you can login by running:
gcloud auth login
Now the rest is quite simple. Clone pySearchML to your local:
git clone pysearchml && cd pySearchML
Enable Kubernetes Engine in your platform. After that, just trigger the execution of cloudbuild which will be responsible for creating the whole required infrastructure (this step should take somewhere between 5~10 minutes).
Here’s how the build triggers the run:
You can choose appropriate values in the variable SUBSTITUTIONS. Notice that _VERSION sets the pipeline version to be exported to Kubeflow. After everything is set, just run the script:
./kubeflow/build/build.sh
Prepares secret keys to allow access and authorization into GCP tools.Prepares known_hosts in building machine.Clones pySearchML locally.The file create_k8.sh that runs in step 4 is responsible for creating the Kubernetes cluster on top of Google Kubernetes Engine (GKE) as well as deploying Elasticsearch, Kubeflow and Katib. In parallel, all Docker images required for the system is built and deployed to Google Container Registry (GCR) for later use in Kubeflow.Run several unittests. Those ended up being important to confirm the system was working as expected. Also, it compiles the Kubeflow pipeline in parallel.Finally, deploys the pipeline to the cluster.
Prepares secret keys to allow access and authorization into GCP tools.
Prepares known_hosts in building machine.
Clones pySearchML locally.
The file create_k8.sh that runs in step 4 is responsible for creating the Kubernetes cluster on top of Google Kubernetes Engine (GKE) as well as deploying Elasticsearch, Kubeflow and Katib. In parallel, all Docker images required for the system is built and deployed to Google Container Registry (GCR) for later use in Kubeflow.
Run several unittests. Those ended up being important to confirm the system was working as expected. Also, it compiles the Kubeflow pipeline in parallel.
Finally, deploys the pipeline to the cluster.
After it’s done, if you browse to your console and select “Kubernetes Engine”, you’ll see that it’s already up and running:
It’s a small cluster as we won’t be using much data, this helps to further save on costs.
Kubeflow and Katib have already been installed. In order to access it, first connect your gcloud to the cluster by running:
gcloud container clusters get-credentials pysearchml
After that, port-forward the service that deals with Kubeflow to your local by running:
kubectl port-forward -n kubeflow svc/ml-pipeline-ui 8080:80 1>/dev/null &
Now, if you access your localhost on port 8080, this is what you should see:
And the pipeline is ready for execution.
This experiment uses the public Google Analytics sample dataset and it consists of a small sample of customers browsing on Google Store. It spans from 20160801 up to 20170801 and contains what each user searched and how they interacted with the search results.
Select pysearchml_0.0.0 and then select “+Create Run”. You should see a screen with all possible input parameters as defined in the Python pipeline script. After choosing appropriate parameters, just run the code.
After execution, here’s the expected result:
Output of Katib component:
We can see a rank of 36.05%. Then, we can compare results from the test component:
Rank here is 40.16% which is a bit worse than validation dataset. It might indicate that the model suffers a bit of over fitting; more data or further parameters exploration might help to alleviate this problem.
And, pretty much, there you have it! Elasticsearch now has a fully trained new layer of machine learning to improve results based on context of customers.
If you want to navigate through the files created for each step, there’s an available deployment for that. In the pySearchML folder, just run:
kubectl apply -f kubeflow/disk-busybox.yaml
If you run kubectl -n kubeflow get pods you’ll see that the name of one of the pods is something like “nfs-busybox-(...)”. If you exec into it you’ll have access to the files:
kubectl -n kubeflow exec -it nfs-busybox-(...) sh
They should be located at /mnt/pysearchml.
There’s also a quick and dirty visualizer for the whole process as well. Just run:
kubectl port-forward service/front -n front 8088:8088 1>/dev/null &
And access your browser in localhost:8088. You should see this (quick and ugly) interface:
Example of results:
Not only does it allow to play around with results as well as give us a better sense if the optimization pipeline is working or not.
And that’s pretty much all it takes to have a complete search engine running with AI optimization ready to handle income traffic for any store.
Now, that was a challenge!
Building pySearchML was quite tough and I can safely say it was one of the most brutal challenges I’ve ever faced 😅. Countless and countless designs, architectures, infrastructures were considered but most failed.
The realization of integrating the whole process on top of Kubeflow and Katib came only later on when several alternatives had already been tested.
The advantage of this design is how simple and direct the final code becomes. It’s fully modular, each component is responsible for a simple task and Kubeflow orchestrates the whole execution. On top of that, we can focus mainly in the code development and let Katib do the hard work of finding best parameters.
The development process was not straightforward. Several lessons had to be learned including concepts from Kubernetes and its available resources. Still, it was all well worth it. As a result, an entire search engine could be built from scratch with a few lines of code, ready to handle real traffic.
As next steps, one could probably consider replacing RankLib with some Deep Learning algorithm which would further extract context from data. One of the main challenges for doing so is that the response time of the system could increase as well as the costs (pros and cons have to be evaluated).
Regardless of the ranking algorithm used, the architecture remains the same for the most part.
Hopefully, that was a useful post for those working in this field. Now it’s time for us to take some rest, meditate on the lessons learned and prepare ourselves for the next adventure :).
As for this post, it certainly deserves being concluded with the mission accomplished soundtrack.
And, as always,
See you in the next mission ;)!
|
[
{
"code": null,
"e": 354,
"s": 172,
"text": "Building search systems is hard. Preparing them to work with machine learning is really hard. Developing a complete search engine framework integrated with AI is really really hard."
},
{
"code": null,
"e": 376,
"s": 354,
"text": "So let’s make one. ✌️"
},
{
"code": null,
"e": 664,
"s": 376,
"text": "In this post, we’ll build a search engine from scratch and discuss on how to further optimize results by adding a machine learning layer using Kubeflow and Katib. This new layer will be capable of retrieving results considering the context of users and is the main focus of this article."
},
{
"code": null,
"e": 777,
"s": 664,
"text": "As we’ll see, thanks to Kubeflow and Katib, final result is rather quite simple, efficient and easy to maintain."
},
{
"code": null,
"e": 1041,
"s": 777,
"text": "To understand the concepts in practice, we’ll implement the system with hands-on experience. As it’s been built on top of Kubernetes, you can use any infrastructure you like (given appropriate adaptations). We’ll be using Google Cloud Platform (GCP) in this post."
},
{
"code": null,
"e": 1143,
"s": 1041,
"text": "We begin with a brief introduction to concepts and then move to the system implementation discussion."
},
{
"code": null,
"e": 1168,
"s": 1143,
"text": "So, with no further ado,"
},
{
"code": null,
"e": 1357,
"s": 1168,
"text": "If you receive the challenge of building a search system for your company or want to build one for your own, you’ll soon realize that the initial steps tend to be somewhat straightforward."
},
{
"code": null,
"e": 1558,
"s": 1357,
"text": "First and foremost, the search engine must contain documents for retrieval. As we’ll be working with Elasticsearch, let’s use it as reference (for an introduction, please refer to their official docs)"
},
{
"code": null,
"e": 1743,
"s": 1558,
"text": "Documents should be uploaded to Elasticsearch following a JSON format. If, for instance, we are building a search engine for a fashion eCommerce store, here’s an example of a document:"
},
{
"code": null,
"e": 1845,
"s": 1743,
"text": "Then comes the retrieval step which in essence involves matching search queries with document fields:"
},
{
"code": null,
"e": 2023,
"s": 1845,
"text": "The ranking phase applies some mathematical rules such as TF-IDF or BM25F to figure out how to properly rank, sorting documents from best to worst match. It’d be something like:"
},
{
"code": null,
"e": 2431,
"s": 2023,
"text": "Further optimization could leverage on specific fields of documents containing performance metrics. For instance, in the previous example, we have that the Click Through Rate (CTR, i.e., reason between clicks and total impressions) of the t-shirt is CTR=0.36. Another retrieval layer could be added using this information and favoring documents with better CTR to show at the top (also known as “boosting”):"
},
{
"code": null,
"e": 2496,
"s": 2431,
"text": "So far so good. But let’s see how to further optimize even more."
},
{
"code": null,
"e": 2792,
"s": 2496,
"text": "Consider that each user has a specific context. Let’s take our fashion online store as an example again. Some of the traffic may come from southern regions where it may be warmer than regions from the north. They’d probably rather be exposed to lighter clothing than to winter specific products."
},
{
"code": null,
"e": 3011,
"s": 2792,
"text": "More context can be added to the equation: we could distinguish customers based on their favorite brands, categories, colors, sizes, device used, average consuming ticket, profession, age and the list goes on and on..."
},
{
"code": null,
"e": 3090,
"s": 3011,
"text": "Doing so requires some extra tools as well. Let’s dive a bit deeper into that."
},
{
"code": null,
"e": 3222,
"s": 3090,
"text": "Learn-to-rank (LTR) is a field of machine learning that studies algorithms whose main goal is to properly rank a list of documents."
},
{
"code": null,
"e": 3413,
"s": 3222,
"text": "It works essentially as any other learning algorithm: it requires a training dataset, suffers from problems such as bias-variance, each model has advantages over certain scenarios and so on."
},
{
"code": null,
"e": 3642,
"s": 3413,
"text": "What basically changes is that the cost function for the training process is designed to let the algorithm learn about ranking and the output of the model is a value for how good of a match a given document is for a given query."
},
{
"code": null,
"e": 3680,
"s": 3642,
"text": "Mathematically, it’s simply given by:"
},
{
"code": null,
"e": 3900,
"s": 3680,
"text": "X in our case comprehends all features we’d like to use to add context to the search. They can be values such as region of the user, their age, favorite brand, correlation between queries and documents fields and so on."
},
{
"code": null,
"e": 3970,
"s": 3900,
"text": "f is the ranking model which is supposed to be trained and evaluated."
},
{
"code": null,
"e": 4229,
"s": 3970,
"text": "Finally, J extends for Judgment and for us it’s an integer value that ranges from 0 (meaning the document is not a good match for a query given features) up to 4 (document is a very good match). We arrange documents from best to worst by using the judgments."
},
{
"code": null,
"e": 4491,
"s": 4229,
"text": "Our main goal is to obtain f since it represents the ranking algorithm that adds the machine learning layer to the search results. And in order to obtain f, we need a dataset that already contains the values of the judgments otherwise we can’t train the models."
},
{
"code": null,
"e": 4842,
"s": 4491,
"text": "As it turns out, finding those values can be quite challenging. While the details of how to do so won’t be covered here, this post has a thorough discussion on the subject; in a nutshell, we use clickstream data of users interactions with search engines (their clicks and purchases) to fit models whose variables yield a proxy for the judgment value."
},
{
"code": null,
"e": 5104,
"s": 4842,
"text": "After computing the judgments, we are left with training the ranking models. Elasticsearch already offers a learn-to-rank plugin which we’ll use in this implementation. The plugin offers various ranking algorithms ranging from decision trees to neural networks."
},
{
"code": null,
"e": 5154,
"s": 5104,
"text": "This is an example of the required training file:"
},
{
"code": null,
"e": 5345,
"s": 5154,
"text": "The idea is to register for each query (“women t-shirt”) all documents that were printed in the results page. For each, we compute their expected judgment and build the matrix of features X."
},
{
"code": null,
"e": 5593,
"s": 5345,
"text": "In practice, what will happen is that we’ll first prepare all this data and feed it to the Learn-To-Rank plugin of Elasticsearch which will result in a trained ranking model. It can then be used to add the personalization layer we are looking for."
},
{
"code": null,
"e": 5647,
"s": 5593,
"text": "Further details on building X will be discussed soon."
},
{
"code": null,
"e": 5772,
"s": 5647,
"text": "We are ready now to train the models. So far so good. But then, we still have a tricky problem: how to know if it’s working?"
},
{
"code": null,
"e": 6041,
"s": 5772,
"text": "We could choose from several methods to check the performance of a ranking model. The one we’ll discuss here is the average rank metric based on what users either clicked or purchased (pySearchML focuses on purchase events only but clicks can be used interchangeably)."
},
{
"code": null,
"e": 6072,
"s": 6041,
"text": "Mathematically, it’s given by:"
},
{
"code": null,
"e": 6345,
"s": 6072,
"text": "The formula basically sums over each rank associated to each purchased (or clicked) item in reference to a complete list of documents. The denominator is simply the cardinality of how many items were summed over in the process (total items users either clicked or bought)."
},
{
"code": null,
"e": 6673,
"s": 6345,
"text": "In practice, what will happen is that, after training a ranking model, we’ll loop through the validation dataset (which contains what users searched and what they purchased) and use each search term to send a query to Elasticsearch. We then compare the results with what users bought to compute the appropriate average ranking."
},
{
"code": null,
"e": 7063,
"s": 6673,
"text": "The image above illustrates the concept. For each user, we send their search term to Elasticsearch which already contains the just recently trained model. We then compare the search results with what the user purchased and compute the rank. In the previous example, the red t-shirt appears at position 2 out of the 3 retrieved items. As it’s just one item that was purchased then rank=66%."
},
{
"code": null,
"e": 7184,
"s": 7063,
"text": "We run the same computation to all users in the database and then average them all together for a final rank expression."
},
{
"code": null,
"e": 7319,
"s": 7184,
"text": "Notice that the final rank metric must be lower than 50% otherwise the algorithm is just performing as a random selector of documents."
},
{
"code": null,
"e": 7435,
"s": 7319,
"text": "This value is important as it’s used for selecting the best ranking model. That’s where we use Katib from Kubeflow."
},
{
"code": null,
"e": 7517,
"s": 7435,
"text": "Let’s see now how to put all these concepts together and build the search engine:"
},
{
"code": null,
"e": 7731,
"s": 7517,
"text": "As discussed before, Kubeflow is the orchestrator for the pipeline processing. It has various responsibilities ranging from preparing data for Elasticsearch and for training to running the entire training process."
},
{
"code": null,
"e": 7858,
"s": 7731,
"text": "It works by defining components and their respective tasks. For pySearchML, here’s the complete pipeline that was implemented:"
},
{
"code": null,
"e": 8034,
"s": 7858,
"text": "The pipeline is defined by receiving various input parameters such as the bucket and model_name and we’ll be able to change those values at execution time (as we’ll see soon)."
},
{
"code": null,
"e": 8109,
"s": 8034,
"text": "Let’s see each component from the pipeline implementation and its purpose:"
},
{
"code": null,
"e": 8154,
"s": 8109,
"text": "Here’s how prepare_env component is defined:"
},
{
"code": null,
"e": 8221,
"s": 8154,
"text": "Image is a docker reference for the component to run in that step."
},
{
"code": null,
"e": 8314,
"s": 8221,
"text": "Arguments are input parameters sent to the script executed in the Docker’s image ENTRYPOINT."
},
{
"code": null,
"e": 8359,
"s": 8314,
"text": "pvolumes mounts the volume claim into \\data."
},
{
"code": null,
"e": 8392,
"s": 8359,
"text": "Here’s all files in prepare_env:"
},
{
"code": null,
"e": 8700,
"s": 8392,
"text": "run.py is responsible for running queries against BigQuery and preparing Elasticsearch. One of its input arguments is model_name which sets which folder to use as reference for processing data. lambdamart0 is an algorithm that has already implemented to work with Google Analytics(GA) public sample dataset."
},
{
"code": null,
"e": 8802,
"s": 8700,
"text": "Dockerfile bundles the whole code together and have as ENTRYPOINT the execution of the run.py script:"
},
{
"code": null,
"e": 9011,
"s": 8802,
"text": "lambdamart0 is a folder dedicated to an implementation of an algorithm with this respective name. It’s been built to process GA public data and works as an example of the system. Here’s the files it contains:"
},
{
"code": null,
"e": 9132,
"s": 9011,
"text": "ga_data.sql is a query responsible for retrieving documents from the GA public dataset and exporting it to Elasticsearch"
},
{
"code": null,
"e": 9203,
"s": 9132,
"text": "es_mapping.json is an index definition for each field of the documents"
},
{
"code": null,
"e": 9347,
"s": 9203,
"text": "features carries the value of X as discussed before. In lambdamart0 example, it uses the GA public data as reference for building the features."
},
{
"code": null,
"e": 9384,
"s": 9347,
"text": "Notice the feature called name.json:"
},
{
"code": null,
"e": 9516,
"s": 9384,
"text": "Learn-To-Rank plugin requires that each feature be defined as a valid Elasticsearch query and score results are associated as to X."
},
{
"code": null,
"e": 9702,
"s": 9516,
"text": "In the previous example, it receives a parameter search_term and proceeds on matching it on the field name of each document returning the BM25 match, which effectively becomes our “X0”."
},
{
"code": null,
"e": 9894,
"s": 9702,
"text": "Using BM25 between query and name field is not enough to add personalization to results. Another feature that advances in the customization layer is the channel_group.json defined as follows:"
},
{
"code": null,
"e": 10041,
"s": 9894,
"text": "It receives as input the parameter channel_group (channel that brought the user to our web store) and returns the CTR for that respective channel."
},
{
"code": null,
"e": 10375,
"s": 10041,
"text": "This effectively prepares the model to distinguish from users their origin and how to rank each group. Specifically, users coming from paid sources might behave differently than those coming in through organic channels for instance. If the training is good enough, the ranking algorithm should be prepared to handle these situations."
},
{
"code": null,
"e": 10580,
"s": 10375,
"text": "Still, this doesn’t tell much on how to personalize results by using intrinsic characteristics of each user. So, here’s one possibility for solving that. The feature avg_customer_price.json is defined as:"
},
{
"code": null,
"e": 10752,
"s": 10580,
"text": "It receives as input the parameter customer_avg_ticket and returns for each document the log of the distance between the average user ticket and the price of the document."
},
{
"code": null,
"e": 10928,
"s": 10752,
"text": "Now the ranking model can learn in the training phase how to manage the rank of each item based on how distant its price is to the average spending of the user on the website."
},
{
"code": null,
"e": 11213,
"s": 10928,
"text": "With those three types of features we can add a complete personalization layer to a search system on top of Elasticsearch. Features can be anything as long as it can be abstracted into a valid search query and they must return some scoring metric eventually translated as our value X."
},
{
"code": null,
"e": 11256,
"s": 11213,
"text": "For what follows in prepare_env component:"
},
{
"code": null,
"e": 11296,
"s": 11256,
"text": "Features are exported to Elasticsearch."
},
{
"code": null,
"e": 11364,
"s": 11296,
"text": "An index is created on Elasticsearch that defines documents fields."
},
{
"code": null,
"e": 11433,
"s": 11364,
"text": "Documents are queried from BigQuery and uploaded into Elasticsearch."
},
{
"code": null,
"e": 11497,
"s": 11433,
"text": "RankLib requirements are created (feature set store and so on)."
},
{
"code": null,
"e": 11693,
"s": 11497,
"text": "For implementing a new model with new data and features, just create another folder inside prepare_env (something like modelname2) and set how it will query data and upload them to Elasticsearch."
},
{
"code": null,
"e": 11853,
"s": 11693,
"text": "This is a simple step. It consists of retrieving data from BigQuery containing what users searched, the context of the search and a list of products purchased."
},
{
"code": null,
"e": 12035,
"s": 11853,
"text": "Here’s the BigQuery query used for retrieving the data. It basically selects all users, their searches and purchases and then combines with their context. An example of the results:"
},
{
"code": null,
"e": 12222,
"s": 12035,
"text": "search_keys can contain any available information that sets the context of customers. In the previous example, we’re using their channel group and average spending ticket on the website."
},
{
"code": null,
"e": 12331,
"s": 12222,
"text": "This data is what we feed into the validation framework when computing the average rank as discussed before."
},
{
"code": null,
"e": 12585,
"s": 12331,
"text": "Notice that the system builds three different validation datasets: one for the training period, another for the regular validation and finally the third is for the final testing step. The idea here is to analyze bias and variance for the trained models."
},
{
"code": null,
"e": 12859,
"s": 12585,
"text": "This is the component responsible for building the RankLib training file as discussed before. The complete script is actually quite simple. First, it downloads from BigQuery the input clickstream data which consists of users interactions on search pages. Here’s an example:"
},
{
"code": null,
"e": 13141,
"s": 12859,
"text": "Notice that the keys associated to the search are aggregated together inside search_keys. Those values are the ones we send to Elasticsearch and replace appropriately each feature X as discussed in prepare_env. In the previous JSON example, we know that the user search context is:"
},
{
"code": null,
"e": 13165,
"s": 13141,
"text": "Searched for drinkware."
},
{
"code": null,
"e": 13193,
"s": 13165,
"text": "Came to the store directly."
},
{
"code": null,
"e": 13230,
"s": 13193,
"text": "Spent on average $20 on the website."
},
{
"code": null,
"e": 13361,
"s": 13230,
"text": "judgment_keys combines users sessions composed of documents they saw on the search page and their interaction on a given document."
},
{
"code": null,
"e": 13549,
"s": 13361,
"text": "This information is then sent to pyClickModels which then process the data and evaluates the judgment for each query-document pair. Result is a newline delimited JSON document as follows:"
},
{
"code": null,
"e": 13648,
"s": 13549,
"text": "Notice that the value of the key is search_term:bags|channel_group:organic|customer_avg_ticket:30."
},
{
"code": null,
"e": 13859,
"s": 13648,
"text": "As discussed before, we want our search engine to be aware of context and further optimize on top of that. As a consequence, judgments are extract based on the entire selected context, not just the search_term."
},
{
"code": null,
"e": 14064,
"s": 13859,
"text": "By doing so, we can differentiate documents for each context and we’d have scenarios where a product receives judgment 4 for customers coming from northern regions and judgment 0 otherwise, as an example."
},
{
"code": null,
"e": 14435,
"s": 14064,
"text": "Notice that the judgments values, as given by pyClickModels, ranges between 0 and 1. As the Learn-To-Rank Elasticsearch plugin is built on top of RankLib, this value is expected to range between integers 0 and 4, inclusive. What we do then is we transform the variables using their percentile as reference. Here’s the complete code for building the final judgment files:"
},
{
"code": null,
"e": 14481,
"s": 14435,
"text": "Here’s an example of the output of this step:"
},
{
"code": null,
"e": 14725,
"s": 14481,
"text": "This data needs to be transformed into the required training file for RankLib. This is where we combine the information of judgments, documents, queries context with the features X (here’s the code example for retrieving X from Elasticsearch)."
},
{
"code": null,
"e": 14991,
"s": 14725,
"text": "Each JSON row from previous step containing search context and judgment keys is looped over and sent as a query against Elasticsearch with the input parameters of the search_keys. The result will be each value of X as already defined from previous prepare_env step."
},
{
"code": null,
"e": 15053,
"s": 14991,
"text": "End result is a training file that looks something like this:"
},
{
"code": null,
"e": 15231,
"s": 15053,
"text": "For each query and for each document we have the estimated judgment as computed by pyClickModels, the id of the query and then a list of features X with their respective values."
},
{
"code": null,
"e": 15288,
"s": 15231,
"text": "With this file, we can train now the ranking algorithms."
},
{
"code": null,
"e": 15477,
"s": 15288,
"text": "Katib is a tool from Kubeflow that offers an interface for automatic hyperparameter optimization. It has several available methods; Bayesian Optimization is the one selected in pySearchML."
},
{
"code": null,
"e": 15679,
"s": 15477,
"text": "What Katib does is it selects for each hyperparameter a new value based on a trade-off between exploration-exploitation. It then tests the new model and observe results which are used for future steps."
},
{
"code": null,
"e": 15858,
"s": 15679,
"text": "For pySearchML, each parameter is an input of RankLib which sets how the model will be fit (such as how many trees to use, total leaf nodes, how many neurons in a net and so on)."
},
{
"code": null,
"e": 16003,
"s": 15858,
"text": "Katib is defined through a Custom Resource of Kubernetes. We can run it by defining a YAML file and deploying it to the cluster, something like:"
},
{
"code": null,
"e": 16036,
"s": 16003,
"text": "kubectl create -f katib_def.yaml"
},
{
"code": null,
"e": 16274,
"s": 16036,
"text": "What Katib will do is read through the YAML file and start trials, each experimenting a specific value of hyperparameters. It can instantiate multiple pods running in parallel executing the code as specified in the experiment definition."
},
{
"code": null,
"e": 16307,
"s": 16274,
"text": "Here are the files in this step:"
},
{
"code": null,
"e": 16498,
"s": 16307,
"text": "launch_katib.py is responsible for launching Katib from a Python script. It receives input arguments, builds an YAML definition and use Kubernetes APIs to start Katib from the script itself."
},
{
"code": null,
"e": 16595,
"s": 16498,
"text": "experiment.json works as a template for the definition of the experiment. Here’s its definition:"
},
{
"code": null,
"e": 16938,
"s": 16595,
"text": "It essentially defines how many pods to run in parallel and which Docker image to run for each trial along with its input command. Notice that the total pods running in parallel as well as maximum trials are hard-coded in pySearchML. Best approach would be to receive those parameters from the pipeline execution and replace them accordingly."
},
{
"code": null,
"e": 17071,
"s": 16938,
"text": "launch_katib.py will read this template, build a final YAML definition and send it to Kubernetes which will start the Katib process."
},
{
"code": null,
"e": 17330,
"s": 17071,
"text": "One of the input parameters is the ranker which is the ranking algorithm to select from RankLib (such as lambdaMart, listNet and so on). Each ranker has its own set of parameters, here’s the example for LambdaMart algorithm as implemented in launch_katib.py:"
},
{
"code": null,
"e": 17521,
"s": 17330,
"text": "Katib will select parameters from the domain defined above and run train.py where effectively RankLib is used to train the ranking models. An example of the command as implemented in Python:"
},
{
"code": null,
"e": 17725,
"s": 17521,
"text": "This string is sent to a subprocess call (notice it requires Java because of RankLib) which starts the training process. The result is a newly trained ranking model that can be exported to Elasticsearch."
},
{
"code": null,
"e": 17838,
"s": 17725,
"text": "Just as the model is fit, validate.py is invoked for computing the expected rank. The steps that take place are:"
},
{
"code": null,
"e": 17902,
"s": 17838,
"text": "The script loops through each JSON from the validation dataset."
},
{
"code": null,
"e": 18064,
"s": 17902,
"text": "Each row contains the search context which is then used to build an Elasticsearch query. Here’s the query used by the model lambdamart0 which we’ll use later on:"
},
{
"code": null,
"e": 18132,
"s": 18064,
"text": "Given the recently built query, a request is sent to Elasticsearch."
},
{
"code": null,
"e": 18205,
"s": 18132,
"text": "A comparison happens between the search results and purchased documents."
},
{
"code": null,
"e": 18271,
"s": 18205,
"text": "Here’s the code responsible for building the Elasticsearch query:"
},
{
"code": null,
"e": 18386,
"s": 18271,
"text": "Notice that the parameter rescore_query triggers the machine learning layer on Elasticsearch learn-to-rank plugin."
},
{
"code": null,
"e": 18458,
"s": 18386,
"text": "Finally, the function compute_rank puts it all together as shown below:"
},
{
"code": null,
"e": 18665,
"s": 18458,
"text": "Katib instantiate sidecars pods which keeps reading through the stdout of the training pod. When it identifies the string Validation-rank=(...), it uses the value as the result for the optimization process."
},
{
"code": null,
"e": 18803,
"s": 18665,
"text": "A persistent volume is used in the process to save the definition of the best model trained by Katib which is used by our next component."
},
{
"code": null,
"e": 18985,
"s": 18803,
"text": "The most difficult parts are done already. Now what happens is the script simply goes after the definition of the best model as saved in a text file and uploads it to Elasticsearch."
},
{
"code": null,
"e": 19188,
"s": 18985,
"text": "Notice that one of the main advantages with this design is that this component could export the model to a production Elasticsearch while the whole optimization could happen on a staging replica engine."
},
{
"code": null,
"e": 19511,
"s": 19188,
"text": "Finally, as the best model is exported to Elasticsearch, the system has at its disposal the best optimized ranking model. In this step, a final validation is executed in order to verify not only that everything worked fine as well as for providing further information on whether the system is suffering from bias-variance."
},
{
"code": null,
"e": 19597,
"s": 19511,
"text": "That’s pretty much it! Let’s run some code now to see this whole framework in action."
},
{
"code": null,
"e": 19704,
"s": 19597,
"text": "Time to implement the whole architecture in practice! Complete code is available on pySearchML repository:"
},
{
"code": null,
"e": 19715,
"s": 19704,
"text": "github.com"
},
{
"code": null,
"e": 19885,
"s": 19715,
"text": "In this section, we’ll be using GCP for running the code with real data. Also, keep in mind that there will be costs (a few cents) associated to running this experiment."
},
{
"code": null,
"e": 20108,
"s": 19885,
"text": "For those new to GCP, there’s a $300 free credit gift that lasts for a year; just sign in and create a project for this tutorial (pysearchml for instance). You should end up with access to a dashboard that looks like this:"
},
{
"code": null,
"e": 20280,
"s": 20108,
"text": "gcloud will be required for interacting with GCP through command line. Installing it is quite straightforward. After the initial setup, make sure you can login by running:"
},
{
"code": null,
"e": 20298,
"s": 20280,
"text": "gcloud auth login"
},
{
"code": null,
"e": 20360,
"s": 20298,
"text": "Now the rest is quite simple. Clone pySearchML to your local:"
},
{
"code": null,
"e": 20398,
"s": 20360,
"text": "git clone pysearchml && cd pySearchML"
},
{
"code": null,
"e": 20623,
"s": 20398,
"text": "Enable Kubernetes Engine in your platform. After that, just trigger the execution of cloudbuild which will be responsible for creating the whole required infrastructure (this step should take somewhere between 5~10 minutes)."
},
{
"code": null,
"e": 20662,
"s": 20623,
"text": "Here’s how the build triggers the run:"
},
{
"code": null,
"e": 20848,
"s": 20662,
"text": "You can choose appropriate values in the variable SUBSTITUTIONS. Notice that _VERSION sets the pipeline version to be exported to Kubeflow. After everything is set, just run the script:"
},
{
"code": null,
"e": 20874,
"s": 20848,
"text": "./kubeflow/build/build.sh"
},
{
"code": null,
"e": 21538,
"s": 20874,
"text": "Prepares secret keys to allow access and authorization into GCP tools.Prepares known_hosts in building machine.Clones pySearchML locally.The file create_k8.sh that runs in step 4 is responsible for creating the Kubernetes cluster on top of Google Kubernetes Engine (GKE) as well as deploying Elasticsearch, Kubeflow and Katib. In parallel, all Docker images required for the system is built and deployed to Google Container Registry (GCR) for later use in Kubeflow.Run several unittests. Those ended up being important to confirm the system was working as expected. Also, it compiles the Kubeflow pipeline in parallel.Finally, deploys the pipeline to the cluster."
},
{
"code": null,
"e": 21609,
"s": 21538,
"text": "Prepares secret keys to allow access and authorization into GCP tools."
},
{
"code": null,
"e": 21651,
"s": 21609,
"text": "Prepares known_hosts in building machine."
},
{
"code": null,
"e": 21678,
"s": 21651,
"text": "Clones pySearchML locally."
},
{
"code": null,
"e": 22007,
"s": 21678,
"text": "The file create_k8.sh that runs in step 4 is responsible for creating the Kubernetes cluster on top of Google Kubernetes Engine (GKE) as well as deploying Elasticsearch, Kubeflow and Katib. In parallel, all Docker images required for the system is built and deployed to Google Container Registry (GCR) for later use in Kubeflow."
},
{
"code": null,
"e": 22161,
"s": 22007,
"text": "Run several unittests. Those ended up being important to confirm the system was working as expected. Also, it compiles the Kubeflow pipeline in parallel."
},
{
"code": null,
"e": 22207,
"s": 22161,
"text": "Finally, deploys the pipeline to the cluster."
},
{
"code": null,
"e": 22331,
"s": 22207,
"text": "After it’s done, if you browse to your console and select “Kubernetes Engine”, you’ll see that it’s already up and running:"
},
{
"code": null,
"e": 22421,
"s": 22331,
"text": "It’s a small cluster as we won’t be using much data, this helps to further save on costs."
},
{
"code": null,
"e": 22545,
"s": 22421,
"text": "Kubeflow and Katib have already been installed. In order to access it, first connect your gcloud to the cluster by running:"
},
{
"code": null,
"e": 22598,
"s": 22545,
"text": "gcloud container clusters get-credentials pysearchml"
},
{
"code": null,
"e": 22686,
"s": 22598,
"text": "After that, port-forward the service that deals with Kubeflow to your local by running:"
},
{
"code": null,
"e": 22760,
"s": 22686,
"text": "kubectl port-forward -n kubeflow svc/ml-pipeline-ui 8080:80 1>/dev/null &"
},
{
"code": null,
"e": 22837,
"s": 22760,
"text": "Now, if you access your localhost on port 8080, this is what you should see:"
},
{
"code": null,
"e": 22878,
"s": 22837,
"text": "And the pipeline is ready for execution."
},
{
"code": null,
"e": 23139,
"s": 22878,
"text": "This experiment uses the public Google Analytics sample dataset and it consists of a small sample of customers browsing on Google Store. It spans from 20160801 up to 20170801 and contains what each user searched and how they interacted with the search results."
},
{
"code": null,
"e": 23353,
"s": 23139,
"text": "Select pysearchml_0.0.0 and then select “+Create Run”. You should see a screen with all possible input parameters as defined in the Python pipeline script. After choosing appropriate parameters, just run the code."
},
{
"code": null,
"e": 23398,
"s": 23353,
"text": "After execution, here’s the expected result:"
},
{
"code": null,
"e": 23425,
"s": 23398,
"text": "Output of Katib component:"
},
{
"code": null,
"e": 23508,
"s": 23425,
"text": "We can see a rank of 36.05%. Then, we can compare results from the test component:"
},
{
"code": null,
"e": 23720,
"s": 23508,
"text": "Rank here is 40.16% which is a bit worse than validation dataset. It might indicate that the model suffers a bit of over fitting; more data or further parameters exploration might help to alleviate this problem."
},
{
"code": null,
"e": 23875,
"s": 23720,
"text": "And, pretty much, there you have it! Elasticsearch now has a fully trained new layer of machine learning to improve results based on context of customers."
},
{
"code": null,
"e": 24018,
"s": 23875,
"text": "If you want to navigate through the files created for each step, there’s an available deployment for that. In the pySearchML folder, just run:"
},
{
"code": null,
"e": 24062,
"s": 24018,
"text": "kubectl apply -f kubeflow/disk-busybox.yaml"
},
{
"code": null,
"e": 24238,
"s": 24062,
"text": "If you run kubectl -n kubeflow get pods you’ll see that the name of one of the pods is something like “nfs-busybox-(...)”. If you exec into it you’ll have access to the files:"
},
{
"code": null,
"e": 24288,
"s": 24238,
"text": "kubectl -n kubeflow exec -it nfs-busybox-(...) sh"
},
{
"code": null,
"e": 24331,
"s": 24288,
"text": "They should be located at /mnt/pysearchml."
},
{
"code": null,
"e": 24414,
"s": 24331,
"text": "There’s also a quick and dirty visualizer for the whole process as well. Just run:"
},
{
"code": null,
"e": 24482,
"s": 24414,
"text": "kubectl port-forward service/front -n front 8088:8088 1>/dev/null &"
},
{
"code": null,
"e": 24573,
"s": 24482,
"text": "And access your browser in localhost:8088. You should see this (quick and ugly) interface:"
},
{
"code": null,
"e": 24593,
"s": 24573,
"text": "Example of results:"
},
{
"code": null,
"e": 24726,
"s": 24593,
"text": "Not only does it allow to play around with results as well as give us a better sense if the optimization pipeline is working or not."
},
{
"code": null,
"e": 24870,
"s": 24726,
"text": "And that’s pretty much all it takes to have a complete search engine running with AI optimization ready to handle income traffic for any store."
},
{
"code": null,
"e": 24897,
"s": 24870,
"text": "Now, that was a challenge!"
},
{
"code": null,
"e": 25111,
"s": 24897,
"text": "Building pySearchML was quite tough and I can safely say it was one of the most brutal challenges I’ve ever faced 😅. Countless and countless designs, architectures, infrastructures were considered but most failed."
},
{
"code": null,
"e": 25259,
"s": 25111,
"text": "The realization of integrating the whole process on top of Kubeflow and Katib came only later on when several alternatives had already been tested."
},
{
"code": null,
"e": 25571,
"s": 25259,
"text": "The advantage of this design is how simple and direct the final code becomes. It’s fully modular, each component is responsible for a simple task and Kubeflow orchestrates the whole execution. On top of that, we can focus mainly in the code development and let Katib do the hard work of finding best parameters."
},
{
"code": null,
"e": 25872,
"s": 25571,
"text": "The development process was not straightforward. Several lessons had to be learned including concepts from Kubernetes and its available resources. Still, it was all well worth it. As a result, an entire search engine could be built from scratch with a few lines of code, ready to handle real traffic."
},
{
"code": null,
"e": 26168,
"s": 25872,
"text": "As next steps, one could probably consider replacing RankLib with some Deep Learning algorithm which would further extract context from data. One of the main challenges for doing so is that the response time of the system could increase as well as the costs (pros and cons have to be evaluated)."
},
{
"code": null,
"e": 26263,
"s": 26168,
"text": "Regardless of the ranking algorithm used, the architecture remains the same for the most part."
},
{
"code": null,
"e": 26451,
"s": 26263,
"text": "Hopefully, that was a useful post for those working in this field. Now it’s time for us to take some rest, meditate on the lessons learned and prepare ourselves for the next adventure :)."
},
{
"code": null,
"e": 26549,
"s": 26451,
"text": "As for this post, it certainly deserves being concluded with the mission accomplished soundtrack."
},
{
"code": null,
"e": 26565,
"s": 26549,
"text": "And, as always,"
}
] |
Flip Card Animation in Android - GeeksforGeeks
|
25 Aug, 2021
In this article, we are going to see how to build a Flip Card Animation app in Android Studio. Animation makes our app more attractive, convincing, and user-friendly. A sample GIF is given below to get an idea about what we are going to do in this article. Please note that we will be using Kotlin as the programming language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
Go to res > layout > activity_main.xml file and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><!--We are going to use Constraintlayout--><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Add a textView for front part of the card--> <TextView android:id="@+id/card_back" android:layout_width="300dp" android:layout_height="300dp" android:textAlignment="center" android:gravity="center" android:text="Back Card" android:textSize="22sp" android:background="#BF3030" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!--Add a textview for back part of the card--> <TextView android:id="@+id/card_front" android:layout_width="300dp" android:layout_height="300dp" android:textAlignment="center" android:gravity="center" android:text="Front Card" android:textSize="22sp" android:background="#326314" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!--Add a Button that will apply flip on the card--> <Button android:id="@+id/flip_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Flip Me" tools:ignore="MissingConstraints" android:layout_marginTop="380dp" tools:layout_editor_absoluteX="142dp" tools:layout_editor_absoluteY="559dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Create a New Directory
Create a new directory with the name animator where we will deal with the card’s front and back animation part. To create a new directory please follow the images given below.
Step 4: Create a New Animator Resource File
Create a New Animator Resource File with the name front_animator.xml that will handle the flip card’s front animation. To create a new Animator Resource File follow the images given below.
Step 5: Working with the front_animator.xml file
Navigate to res > animator > front_animator.xml and add the below code to that file. Here we will be using objectAnimator tag for animation of the front part of the flipping card. Below is the code for the front_animator.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <objectAnimator android:valueFrom="0" android:valueTo="180" android:propertyName="rotationY" android:duration="1000" /> <objectAnimator android:valueFrom="1.0" android:valueTo="0.0" android:propertyName="alpha" android:startOffset="500" android:duration="1" /></set>
Step 6: Again Create a New Animator Resource File
Again Create a New Animator Resource File with the name back_animator.xml that will be handling animation of the back part of the flip card. To create a new Animator Resource File follow the same images as shown earlier for creating the front_animator.xml file.
Step 7: Working with the back_animator.xml file
Navigate to res > animator > back_animator.xml and add the below code to that file. Here we will be using the objectAnimator tag for animation of the front part of the flipping card. Below is the code for the back_animator.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <objectAnimator android:valueFrom="1.0" android:valueTo="0.0" android:propertyName="alpha" android:duration="0" /> <objectAnimator android:valueFrom="180" android:valueTo="0" android:propertyName="rotationY" android:repeatMode="reverse" android:duration="1000" /> <objectAnimator android:valueFrom="0.0" android:valueTo="1.0" android:propertyName="alpha" android:startOffset="500" android:duration="0" /> </set>
Step 8: Working with the MainActivity.kt file
Go to MainActivity.kt file and add the code below to that file. Below is the code for MainActivity.kt file. Here we will see how to operate the front and back animation part of the flip card. Comments are added inside the code to understand the code in more detail.
Kotlin
package com.example.flippingcard import android.animation.AnimatorInflaterimport android.animation.AnimatorSetimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.TextView class MainActivity : AppCompatActivity() { lateinit var front_anim:AnimatorSet lateinit var back_anim: AnimatorSet var isFront =true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Now Create Animator Object // For this we add animator folder inside res // Now we will add the animator to our card // we now need to modify the camera scale var scale = applicationContext.resources.displayMetrics.density val front = findViewById<TextView>(R.id.card_front) as TextView val back =findViewById<TextView>(R.id.card_back) as TextView val flip = findViewById<Button>(R.id.flip_btn) as Button front.cameraDistance = 8000 * scale back.cameraDistance = 8000 * scale // Now we will set the front animation front_animation = AnimatorInflater.loadAnimator(applicationContext, R.animator.front_animator) as AnimatorSet back_animation = AnimatorInflater.loadAnimator(applicationContext, R.animator.back_animator) as AnimatorSet // Now we will set the event listener flip.setOnClickListener{ if(isFront) { front_animation.setTarget(front); back_animation.setTarget(back); front_animation.start() back_animation.start() isFront = false } else { front_animation.setTarget(back) back_animation.setTarget(front) back_animation.start() front_animation.start() isFront =true } } }}
Output:
You can get the source code of the project from this link: Click Here
Android-Animation
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Flexbox-Layout in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters
|
[
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 26709,
"s": 26381,
"text": "In this article, we are going to see how to build a Flip Card Animation app in Android Studio. Animation makes our app more attractive, convincing, and user-friendly. A sample GIF is given below to get an idea about what we are going to do in this article. Please note that we will be using Kotlin as the programming language. "
},
{
"code": null,
"e": 26738,
"s": 26709,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26900,
"s": 26738,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 26948,
"s": 26900,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 27153,
"s": 26948,
"text": "Go to res > layout > activity_main.xml file and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 27157,
"s": 27153,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--We are going to use Constraintlayout--><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Add a textView for front part of the card--> <TextView android:id=\"@+id/card_back\" android:layout_width=\"300dp\" android:layout_height=\"300dp\" android:textAlignment=\"center\" android:gravity=\"center\" android:text=\"Back Card\" android:textSize=\"22sp\" android:background=\"#BF3030\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <!--Add a textview for back part of the card--> <TextView android:id=\"@+id/card_front\" android:layout_width=\"300dp\" android:layout_height=\"300dp\" android:textAlignment=\"center\" android:gravity=\"center\" android:text=\"Front Card\" android:textSize=\"22sp\" android:background=\"#326314\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <!--Add a Button that will apply flip on the card--> <Button android:id=\"@+id/flip_btn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Flip Me\" tools:ignore=\"MissingConstraints\" android:layout_marginTop=\"380dp\" tools:layout_editor_absoluteX=\"142dp\" tools:layout_editor_absoluteY=\"559dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"/> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 29340,
"s": 27157,
"text": null
},
{
"code": null,
"e": 29371,
"s": 29340,
"text": "Step 3: Create a New Directory"
},
{
"code": null,
"e": 29547,
"s": 29371,
"text": "Create a new directory with the name animator where we will deal with the card’s front and back animation part. To create a new directory please follow the images given below."
},
{
"code": null,
"e": 29591,
"s": 29547,
"text": "Step 4: Create a New Animator Resource File"
},
{
"code": null,
"e": 29780,
"s": 29591,
"text": "Create a New Animator Resource File with the name front_animator.xml that will handle the flip card’s front animation. To create a new Animator Resource File follow the images given below."
},
{
"code": null,
"e": 29829,
"s": 29780,
"text": "Step 5: Working with the front_animator.xml file"
},
{
"code": null,
"e": 30061,
"s": 29829,
"text": "Navigate to res > animator > front_animator.xml and add the below code to that file. Here we will be using objectAnimator tag for animation of the front part of the flipping card. Below is the code for the front_animator.xml file. "
},
{
"code": null,
"e": 30065,
"s": 30061,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <objectAnimator android:valueFrom=\"0\" android:valueTo=\"180\" android:propertyName=\"rotationY\" android:duration=\"1000\" /> <objectAnimator android:valueFrom=\"1.0\" android:valueTo=\"0.0\" android:propertyName=\"alpha\" android:startOffset=\"500\" android:duration=\"1\" /></set>",
"e": 30518,
"s": 30065,
"text": null
},
{
"code": null,
"e": 30568,
"s": 30518,
"text": "Step 6: Again Create a New Animator Resource File"
},
{
"code": null,
"e": 30832,
"s": 30568,
"text": "Again Create a New Animator Resource File with the name back_animator.xml that will be handling animation of the back part of the flip card. To create a new Animator Resource File follow the same images as shown earlier for creating the front_animator.xml file. "
},
{
"code": null,
"e": 30880,
"s": 30832,
"text": "Step 7: Working with the back_animator.xml file"
},
{
"code": null,
"e": 31114,
"s": 30880,
"text": "Navigate to res > animator > back_animator.xml and add the below code to that file. Here we will be using the objectAnimator tag for animation of the front part of the flipping card. Below is the code for the back_animator.xml file. "
},
{
"code": null,
"e": 31118,
"s": 31114,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <objectAnimator android:valueFrom=\"1.0\" android:valueTo=\"0.0\" android:propertyName=\"alpha\" android:duration=\"0\" /> <objectAnimator android:valueFrom=\"180\" android:valueTo=\"0\" android:propertyName=\"rotationY\" android:repeatMode=\"reverse\" android:duration=\"1000\" /> <objectAnimator android:valueFrom=\"0.0\" android:valueTo=\"1.0\" android:propertyName=\"alpha\" android:startOffset=\"500\" android:duration=\"0\" /> </set>",
"e": 31764,
"s": 31118,
"text": null
},
{
"code": null,
"e": 31810,
"s": 31764,
"text": "Step 8: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 32076,
"s": 31810,
"text": "Go to MainActivity.kt file and add the code below to that file. Below is the code for MainActivity.kt file. Here we will see how to operate the front and back animation part of the flip card. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 32083,
"s": 32076,
"text": "Kotlin"
},
{
"code": "package com.example.flippingcard import android.animation.AnimatorInflaterimport android.animation.AnimatorSetimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.TextView class MainActivity : AppCompatActivity() { lateinit var front_anim:AnimatorSet lateinit var back_anim: AnimatorSet var isFront =true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Now Create Animator Object // For this we add animator folder inside res // Now we will add the animator to our card // we now need to modify the camera scale var scale = applicationContext.resources.displayMetrics.density val front = findViewById<TextView>(R.id.card_front) as TextView val back =findViewById<TextView>(R.id.card_back) as TextView val flip = findViewById<Button>(R.id.flip_btn) as Button front.cameraDistance = 8000 * scale back.cameraDistance = 8000 * scale // Now we will set the front animation front_animation = AnimatorInflater.loadAnimator(applicationContext, R.animator.front_animator) as AnimatorSet back_animation = AnimatorInflater.loadAnimator(applicationContext, R.animator.back_animator) as AnimatorSet // Now we will set the event listener flip.setOnClickListener{ if(isFront) { front_animation.setTarget(front); back_animation.setTarget(back); front_animation.start() back_animation.start() isFront = false } else { front_animation.setTarget(back) back_animation.setTarget(front) back_animation.start() front_animation.start() isFront =true } } }}",
"e": 34045,
"s": 32083,
"text": null
},
{
"code": null,
"e": 34053,
"s": 34045,
"text": "Output:"
},
{
"code": null,
"e": 34123,
"s": 34053,
"text": "You can get the source code of the project from this link: Click Here"
},
{
"code": null,
"e": 34141,
"s": 34123,
"text": "Android-Animation"
},
{
"code": null,
"e": 34149,
"s": 34141,
"text": "Android"
},
{
"code": null,
"e": 34156,
"s": 34149,
"text": "Kotlin"
},
{
"code": null,
"e": 34164,
"s": 34156,
"text": "Android"
},
{
"code": null,
"e": 34262,
"s": 34164,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34300,
"s": 34262,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 34339,
"s": 34300,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 34389,
"s": 34339,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 34440,
"s": 34389,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 34466,
"s": 34440,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 34485,
"s": 34466,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 34498,
"s": 34485,
"text": "Kotlin Array"
},
{
"code": null,
"e": 34540,
"s": 34498,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 34580,
"s": 34540,
"text": "How to Get Current Location in Android?"
}
] |
Python Program to find the factorial of a number without recursion
|
When it is required to find the factorial of a number without using recursion, the ‘while’ loop can be used.
Below is a demonstration for the same −
Live Demo
my_num = int(input("Enter a number :"))
my_factorial = 1
while(my_num>0):
my_factorial = my_factorial*my_num
my_num=my_num-1
print("The factorial of the number is : ")
print(my_factorial)
Enter a number :7
The factorial of the number is :
5040
The input number is takne from the user.
A variable is assigned to 1.
It is checked to see for being 0.
If not, it is multiplied by the previous value in the variable.
It is assigned to the same variable.
This is done until the number reaches 0.
It is then displayed as output on the console.
|
[
{
"code": null,
"e": 1171,
"s": 1062,
"text": "When it is required to find the factorial of a number without using recursion, the ‘while’ loop can be used."
},
{
"code": null,
"e": 1211,
"s": 1171,
"text": "Below is a demonstration for the same −"
},
{
"code": null,
"e": 1222,
"s": 1211,
"text": " Live Demo"
},
{
"code": null,
"e": 1416,
"s": 1222,
"text": "my_num = int(input(\"Enter a number :\"))\nmy_factorial = 1\nwhile(my_num>0):\n my_factorial = my_factorial*my_num\n my_num=my_num-1\nprint(\"The factorial of the number is : \")\nprint(my_factorial)"
},
{
"code": null,
"e": 1472,
"s": 1416,
"text": "Enter a number :7\nThe factorial of the number is :\n5040"
},
{
"code": null,
"e": 1513,
"s": 1472,
"text": "The input number is takne from the user."
},
{
"code": null,
"e": 1542,
"s": 1513,
"text": "A variable is assigned to 1."
},
{
"code": null,
"e": 1576,
"s": 1542,
"text": "It is checked to see for being 0."
},
{
"code": null,
"e": 1640,
"s": 1576,
"text": "If not, it is multiplied by the previous value in the variable."
},
{
"code": null,
"e": 1677,
"s": 1640,
"text": "It is assigned to the same variable."
},
{
"code": null,
"e": 1718,
"s": 1677,
"text": "This is done until the number reaches 0."
},
{
"code": null,
"e": 1765,
"s": 1718,
"text": "It is then displayed as output on the console."
}
] |
Keras - Regression Prediction using MPL
|
In this chapter, let us write a simple MPL based ANN to do regression prediction. Till now, we have only done the classification based prediction. Now, we will try to predict the next possible value by analyzing the previous (continuous) values and its influencing factors.
The Regression MPL can be represented as below −
The core features of the model are as follows −
Input layer consists of (13,) values.
Input layer consists of (13,) values.
First layer, Dense consists of 64 units and ‘relu’ activation function with ‘normal’ kernel initializer.
First layer, Dense consists of 64 units and ‘relu’ activation function with ‘normal’ kernel initializer.
Second layer, Dense consists of 64 units and ‘relu’ activation function.
Second layer, Dense consists of 64 units and ‘relu’ activation function.
Output layer, Dense consists of 1 unit.
Output layer, Dense consists of 1 unit.
Use mse as loss function.
Use mse as loss function.
Use RMSprop as Optimizer.
Use RMSprop as Optimizer.
Use accuracy as metrics.
Use accuracy as metrics.
Use 128 as batch size.
Use 128 as batch size.
Use 500 as epochs.
Use 500 as epochs.
Step 1 − Import the modules
Let us import the necessary modules.
import keras
from keras.datasets import boston_housing
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import RMSprop
from keras.callbacks import EarlyStopping
from sklearn import preprocessing
from sklearn.preprocessing import scale
Step 2 − Load data
Let us import the Boston housing dataset.
(x_train, y_train), (x_test, y_test) = boston_housing.load_data()
Here,
boston_housing is a dataset provided by Keras. It represents a collection of housing information in Boston area, each having 13 features.
Step 3 − Process the data
Let us change the dataset according to our model, so that, we can feed into our model. The data can be changed using below code −
x_train_scaled = preprocessing.scale(x_train)
scaler = preprocessing.StandardScaler().fit(x_train)
x_test_scaled = scaler.transform(x_test)
Here, we have normalized the training data using sklearn.preprocessing.scale function. preprocessing.StandardScaler().fit function returns a scalar with the normalized mean and standard deviation of the training data, which we can apply to the test data using scalar.transform function. This will normalize the test data as well with the same setting as that of training data.
Step 4 − Create the model
Let us create the actual model.
model = Sequential()
model.add(Dense(64, kernel_initializer = 'normal', activation = 'relu',
input_shape = (13,)))
model.add(Dense(64, activation = 'relu')) model.add(Dense(1))
Step 5 − Compile the model
Let us compile the model using selected loss function, optimizer and metrics.
model.compile(
loss = 'mse',
optimizer = RMSprop(),
metrics = ['mean_absolute_error']
)
Step 6 − Train the model
Let us train the model using fit() method.
history = model.fit(
x_train_scaled, y_train,
batch_size=128,
epochs = 500,
verbose = 1,
validation_split = 0.2,
callbacks = [EarlyStopping(monitor = 'val_loss', patience = 20)]
)
Here, we have used callback function, EarlyStopping. The purpose of this callback is to monitor the loss value during each epoch and compare it with previous epoch loss value to find the improvement in the training. If there is no improvement for the patience times, then the whole process will be stopped.
Executing the application will give the below information as output −
Train on 323 samples, validate on 81 samples Epoch 1/500 2019-09-24 01:07:03.889046: I
tensorflow/core/platform/cpu_feature_guard.cc:142]
Your CPU supports instructions that this
TensorFlow binary was not co mpiled to use: AVX2 323/323
[==============================] - 0s 515us/step - loss: 562.3129
- mean_absolute_error: 21.8575 - val_loss: 621.6523 - val_mean_absolute_erro
r: 23.1730 Epoch 2/500
323/323 [==============================] - 0s 11us/step - loss: 545.1666
- mean_absolute_error: 21.4887 - val_loss: 605.1341 - val_mean_absolute_error
: 22.8293 Epoch 3/500
323/323 [==============================] - 0s 12us/step - loss: 528.9944
- mean_absolute_error: 21.1328 - val_loss: 588.6594 - val_mean_absolute_error
: 22.4799 Epoch 4/500
323/323 [==============================] - 0s 12us/step - loss: 512.2739
- mean_absolute_error: 20.7658 - val_loss: 570.3772 - val_mean_absolute_error
: 22.0853 Epoch 5/500
323/323 [==============================] - 0s 9us/step - loss: 493.9775
- mean_absolute_error: 20.3506 - val_loss: 550.9548 - val_mean_absolute_error: 21.6547
..........
..........
..........
Epoch 143/500
323/323 [==============================] - 0s 15us/step - loss: 8.1004
- mean_absolute_error: 2.0002 - val_loss: 14.6286 - val_mean_absolute_error:
2. 5904 Epoch 144/500
323/323 [==============================] - 0s 19us/step - loss: 8.0300
- mean_absolute_error: 1.9683 - val_loss: 14.5949 - val_mean_absolute_error:
2. 5843 Epoch 145/500
323/323 [==============================] - 0s 12us/step - loss: 7.8704
- mean_absolute_error: 1.9313 - val_loss: 14.3770 - val_mean_absolute_error: 2. 4996
Step 7 − Evaluate the model
Let us evaluate the model using test data.
score = model.evaluate(x_test_scaled, y_test, verbose = 0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
Executing the above code will output the below information −
Test loss: 21.928471583946077 Test accuracy: 2.9599233234629914
Step 8 − Predict
Finally, predict using test data as below −
prediction = model.predict(x_test_scaled)
print(prediction.flatten())
print(y_test)
The output of the above application is as follows −
[ 7.5612316 17.583357 21.09344 31.859276 25.055613 18.673872 26.600405 22.403967 19.060272 22.264952
17.4191 17.00466 15.58924 41.624374 20.220217 18.985565 26.419338 19.837091 19.946192 36.43445
12.278508 16.330965 20.701359 14.345301 21.741161 25.050423 31.046402 27.738455 9.959419 20.93039
20.069063 14.518344 33.20235 24.735163 18.7274 9.148898 15.781284 18.556862 18.692865 26.045074
27.954073 28.106823 15.272034 40.879818 29.33896 23.714525 26.427515 16.483374 22.518442 22.425386
33.94826 18.831465 13.2501955 15.537227 34.639984 27.468002 13.474407 48.134598 34.39617
22.8503124.042334 17.747198 14.7837715 18.187277 23.655672 22.364983 13.858193 22.710032 14.371148
7.1272087 35.960033 28.247292 25.3014 14.477208 25.306196 17.891165 20.193708 23.585173 34.690193
12.200583 20.102983 38.45882 14.741723 14.408362 17.67158 18.418497 21.151712 21.157492 22.693687
29.809034 19.366991 20.072294 25.880817 40.814568 34.64087 19.43741 36.2591 50.73806 26.968863 43.91787
32.54908 20.248306 ] [ 7.2 18.8 19. 27. 22.2 24.5 31.2 22.9 20.5 23.2 18.6 14.5 17.8 50. 20.8 24.3 24.2
19.8 19.1 22.7 12. 10.2 20. 18.5 20.9 23. 27.5 30.1 9.5 22. 21.2 14.1 33.1 23.4 20.1 7.4 15.4 23.8 20.1
24.5 33. 28.4 14.1 46.7 32.5 29.6 28.4 19.8 20.2 25. 35.4 20.3 9.7 14.5 34.9 26.6 7.2 50. 32.4 21.6 29.8
13.1 27.5 21.2 23.1 21.9 13. 23.2 8.1 5.6 21.7 29.6 19.6 7. 26.4 18.9 20.9 28.1 35.4 10.2 24.3 43.1 17.6
15.4 16.2 27.1 21.4 21.5 22.4 25. 16.6 18.6 22. 42.8 35.1 21.5 36. 21.9 24.1 50. 26.7 25. ]
The output of both array have around 10-30% difference and it indicate our model predicts with reasonable range.
87 Lectures
11 hours
Abhilash Nelson
61 Lectures
9 hours
Abhishek And Pukhraj
57 Lectures
7 hours
Abhishek And Pukhraj
52 Lectures
7 hours
Abhishek And Pukhraj
52 Lectures
6 hours
Abhishek And Pukhraj
68 Lectures
2 hours
Mike West
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2325,
"s": 2051,
"text": "In this chapter, let us write a simple MPL based ANN to do regression prediction. Till now, we have only done the classification based prediction. Now, we will try to predict the next possible value by analyzing the previous (continuous) values and its influencing factors."
},
{
"code": null,
"e": 2374,
"s": 2325,
"text": "The Regression MPL can be represented as below −"
},
{
"code": null,
"e": 2422,
"s": 2374,
"text": "The core features of the model are as follows −"
},
{
"code": null,
"e": 2460,
"s": 2422,
"text": "Input layer consists of (13,) values."
},
{
"code": null,
"e": 2498,
"s": 2460,
"text": "Input layer consists of (13,) values."
},
{
"code": null,
"e": 2603,
"s": 2498,
"text": "First layer, Dense consists of 64 units and ‘relu’ activation function with ‘normal’ kernel initializer."
},
{
"code": null,
"e": 2708,
"s": 2603,
"text": "First layer, Dense consists of 64 units and ‘relu’ activation function with ‘normal’ kernel initializer."
},
{
"code": null,
"e": 2781,
"s": 2708,
"text": "Second layer, Dense consists of 64 units and ‘relu’ activation function."
},
{
"code": null,
"e": 2854,
"s": 2781,
"text": "Second layer, Dense consists of 64 units and ‘relu’ activation function."
},
{
"code": null,
"e": 2894,
"s": 2854,
"text": "Output layer, Dense consists of 1 unit."
},
{
"code": null,
"e": 2934,
"s": 2894,
"text": "Output layer, Dense consists of 1 unit."
},
{
"code": null,
"e": 2960,
"s": 2934,
"text": "Use mse as loss function."
},
{
"code": null,
"e": 2986,
"s": 2960,
"text": "Use mse as loss function."
},
{
"code": null,
"e": 3012,
"s": 2986,
"text": "Use RMSprop as Optimizer."
},
{
"code": null,
"e": 3038,
"s": 3012,
"text": "Use RMSprop as Optimizer."
},
{
"code": null,
"e": 3063,
"s": 3038,
"text": "Use accuracy as metrics."
},
{
"code": null,
"e": 3088,
"s": 3063,
"text": "Use accuracy as metrics."
},
{
"code": null,
"e": 3111,
"s": 3088,
"text": "Use 128 as batch size."
},
{
"code": null,
"e": 3134,
"s": 3111,
"text": "Use 128 as batch size."
},
{
"code": null,
"e": 3153,
"s": 3134,
"text": "Use 500 as epochs."
},
{
"code": null,
"e": 3172,
"s": 3153,
"text": "Use 500 as epochs."
},
{
"code": null,
"e": 3200,
"s": 3172,
"text": "Step 1 − Import the modules"
},
{
"code": null,
"e": 3237,
"s": 3200,
"text": "Let us import the necessary modules."
},
{
"code": null,
"e": 3520,
"s": 3237,
"text": "import keras \n\nfrom keras.datasets import boston_housing \nfrom keras.models import Sequential \nfrom keras.layers import Dense \nfrom keras.optimizers import RMSprop \nfrom keras.callbacks import EarlyStopping \nfrom sklearn import preprocessing \nfrom sklearn.preprocessing import scale"
},
{
"code": null,
"e": 3539,
"s": 3520,
"text": "Step 2 − Load data"
},
{
"code": null,
"e": 3581,
"s": 3539,
"text": "Let us import the Boston housing dataset."
},
{
"code": null,
"e": 3648,
"s": 3581,
"text": "(x_train, y_train), (x_test, y_test) = boston_housing.load_data()\n"
},
{
"code": null,
"e": 3654,
"s": 3648,
"text": "Here,"
},
{
"code": null,
"e": 3792,
"s": 3654,
"text": "boston_housing is a dataset provided by Keras. It represents a collection of housing information in Boston area, each having 13 features."
},
{
"code": null,
"e": 3818,
"s": 3792,
"text": "Step 3 − Process the data"
},
{
"code": null,
"e": 3948,
"s": 3818,
"text": "Let us change the dataset according to our model, so that, we can feed into our model. The data can be changed using below code −"
},
{
"code": null,
"e": 4090,
"s": 3948,
"text": "x_train_scaled = preprocessing.scale(x_train) \nscaler = preprocessing.StandardScaler().fit(x_train) \nx_test_scaled = scaler.transform(x_test)"
},
{
"code": null,
"e": 4467,
"s": 4090,
"text": "Here, we have normalized the training data using sklearn.preprocessing.scale function. preprocessing.StandardScaler().fit function returns a scalar with the normalized mean and standard deviation of the training data, which we can apply to the test data using scalar.transform function. This will normalize the test data as well with the same setting as that of training data."
},
{
"code": null,
"e": 4493,
"s": 4467,
"text": "Step 4 − Create the model"
},
{
"code": null,
"e": 4525,
"s": 4493,
"text": "Let us create the actual model."
},
{
"code": null,
"e": 4704,
"s": 4525,
"text": "model = Sequential() \nmodel.add(Dense(64, kernel_initializer = 'normal', activation = 'relu',\ninput_shape = (13,))) \nmodel.add(Dense(64, activation = 'relu')) model.add(Dense(1))"
},
{
"code": null,
"e": 4731,
"s": 4704,
"text": "Step 5 − Compile the model"
},
{
"code": null,
"e": 4809,
"s": 4731,
"text": "Let us compile the model using selected loss function, optimizer and metrics."
},
{
"code": null,
"e": 4908,
"s": 4809,
"text": "model.compile(\n loss = 'mse', \n optimizer = RMSprop(), \n metrics = ['mean_absolute_error']\n)"
},
{
"code": null,
"e": 4933,
"s": 4908,
"text": "Step 6 − Train the model"
},
{
"code": null,
"e": 4976,
"s": 4933,
"text": "Let us train the model using fit() method."
},
{
"code": null,
"e": 5182,
"s": 4976,
"text": "history = model.fit(\n x_train_scaled, y_train, \n batch_size=128, \n epochs = 500, \n verbose = 1, \n validation_split = 0.2, \n callbacks = [EarlyStopping(monitor = 'val_loss', patience = 20)]\n)"
},
{
"code": null,
"e": 5489,
"s": 5182,
"text": "Here, we have used callback function, EarlyStopping. The purpose of this callback is to monitor the loss value during each epoch and compare it with previous epoch loss value to find the improvement in the training. If there is no improvement for the patience times, then the whole process will be stopped."
},
{
"code": null,
"e": 5559,
"s": 5489,
"text": "Executing the application will give the below information as output −"
},
{
"code": null,
"e": 7211,
"s": 5559,
"text": "Train on 323 samples, validate on 81 samples Epoch 1/500 2019-09-24 01:07:03.889046: I \ntensorflow/core/platform/cpu_feature_guard.cc:142] \nYour CPU supports instructions that this \nTensorFlow binary was not co mpiled to use: AVX2 323/323 \n[==============================] - 0s 515us/step - loss: 562.3129 \n- mean_absolute_error: 21.8575 - val_loss: 621.6523 - val_mean_absolute_erro \nr: 23.1730 Epoch 2/500 \n323/323 [==============================] - 0s 11us/step - loss: 545.1666 \n- mean_absolute_error: 21.4887 - val_loss: 605.1341 - val_mean_absolute_error \n: 22.8293 Epoch 3/500 \n323/323 [==============================] - 0s 12us/step - loss: 528.9944 \n- mean_absolute_error: 21.1328 - val_loss: 588.6594 - val_mean_absolute_error \n: 22.4799 Epoch 4/500 \n323/323 [==============================] - 0s 12us/step - loss: 512.2739 \n- mean_absolute_error: 20.7658 - val_loss: 570.3772 - val_mean_absolute_error \n: 22.0853 Epoch 5/500\n323/323 [==============================] - 0s 9us/step - loss: 493.9775 \n- mean_absolute_error: 20.3506 - val_loss: 550.9548 - val_mean_absolute_error: 21.6547 \n.......... \n.......... \n.......... \nEpoch 143/500 \n323/323 [==============================] - 0s 15us/step - loss: 8.1004 \n- mean_absolute_error: 2.0002 - val_loss: 14.6286 - val_mean_absolute_error: \n2. 5904 Epoch 144/500 \n323/323 [==============================] - 0s 19us/step - loss: 8.0300 \n- mean_absolute_error: 1.9683 - val_loss: 14.5949 - val_mean_absolute_error: \n2. 5843 Epoch 145/500 \n323/323 [==============================] - 0s 12us/step - loss: 7.8704 \n- mean_absolute_error: 1.9313 - val_loss: 14.3770 - val_mean_absolute_error: 2. 4996\n"
},
{
"code": null,
"e": 7239,
"s": 7211,
"text": "Step 7 − Evaluate the model"
},
{
"code": null,
"e": 7282,
"s": 7239,
"text": "Let us evaluate the model using test data."
},
{
"code": null,
"e": 7407,
"s": 7282,
"text": "score = model.evaluate(x_test_scaled, y_test, verbose = 0) \nprint('Test loss:', score[0]) \nprint('Test accuracy:', score[1])"
},
{
"code": null,
"e": 7468,
"s": 7407,
"text": "Executing the above code will output the below information −"
},
{
"code": null,
"e": 7533,
"s": 7468,
"text": "Test loss: 21.928471583946077 Test accuracy: 2.9599233234629914\n"
},
{
"code": null,
"e": 7550,
"s": 7533,
"text": "Step 8 − Predict"
},
{
"code": null,
"e": 7594,
"s": 7550,
"text": "Finally, predict using test data as below −"
},
{
"code": null,
"e": 7680,
"s": 7594,
"text": "prediction = model.predict(x_test_scaled) \nprint(prediction.flatten()) \nprint(y_test)"
},
{
"code": null,
"e": 7732,
"s": 7680,
"text": "The output of the above application is as follows −"
},
{
"code": null,
"e": 9234,
"s": 7732,
"text": "[ 7.5612316 17.583357 21.09344 31.859276 25.055613 18.673872 26.600405 22.403967 19.060272 22.264952 \n17.4191 17.00466 15.58924 41.624374 20.220217 18.985565 26.419338 19.837091 19.946192 36.43445 \n12.278508 16.330965 20.701359 14.345301 21.741161 25.050423 31.046402 27.738455 9.959419 20.93039 \n20.069063 14.518344 33.20235 24.735163 18.7274 9.148898 15.781284 18.556862 18.692865 26.045074 \n27.954073 28.106823 15.272034 40.879818 29.33896 23.714525 26.427515 16.483374 22.518442 22.425386 \n33.94826 18.831465 13.2501955 15.537227 34.639984 27.468002 13.474407 48.134598 34.39617 \n22.8503124.042334 17.747198 14.7837715 18.187277 23.655672 22.364983 13.858193 22.710032 14.371148 \n7.1272087 35.960033 28.247292 25.3014 14.477208 25.306196 17.891165 20.193708 23.585173 34.690193 \n12.200583 20.102983 38.45882 14.741723 14.408362 17.67158 18.418497 21.151712 21.157492 22.693687 \n29.809034 19.366991 20.072294 25.880817 40.814568 34.64087 19.43741 36.2591 50.73806 26.968863 43.91787 \n32.54908 20.248306 ] [ 7.2 18.8 19. 27. 22.2 24.5 31.2 22.9 20.5 23.2 18.6 14.5 17.8 50. 20.8 24.3 24.2 \n19.8 19.1 22.7 12. 10.2 20. 18.5 20.9 23. 27.5 30.1 9.5 22. 21.2 14.1 33.1 23.4 20.1 7.4 15.4 23.8 20.1 \n24.5 33. 28.4 14.1 46.7 32.5 29.6 28.4 19.8 20.2 25. 35.4 20.3 9.7 14.5 34.9 26.6 7.2 50. 32.4 21.6 29.8 \n13.1 27.5 21.2 23.1 21.9 13. 23.2 8.1 5.6 21.7 29.6 19.6 7. 26.4 18.9 20.9 28.1 35.4 10.2 24.3 43.1 17.6 \n15.4 16.2 27.1 21.4 21.5 22.4 25. 16.6 18.6 22. 42.8 35.1 21.5 36. 21.9 24.1 50. 26.7 25. ]\n"
},
{
"code": null,
"e": 9347,
"s": 9234,
"text": "The output of both array have around 10-30% difference and it indicate our model predicts with reasonable range."
},
{
"code": null,
"e": 9381,
"s": 9347,
"text": "\n 87 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 9398,
"s": 9381,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9431,
"s": 9398,
"text": "\n 61 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 9453,
"s": 9431,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 9486,
"s": 9453,
"text": "\n 57 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 9508,
"s": 9486,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 9541,
"s": 9508,
"text": "\n 52 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 9563,
"s": 9541,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 9596,
"s": 9563,
"text": "\n 52 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9618,
"s": 9596,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 9651,
"s": 9618,
"text": "\n 68 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9662,
"s": 9651,
"text": " Mike West"
},
{
"code": null,
"e": 9669,
"s": 9662,
"text": " Print"
},
{
"code": null,
"e": 9680,
"s": 9669,
"text": " Add Notes"
}
] |
RequireJS - Dojo
|
Dojo is a JavaScript toolkit which is based on the AMD module architecture that provides additional modules to add extra functionality to the web application and also saves time and scale in the web application development process.
The following example shows the usage of Dojo along with RequireJS. Create an html file with the name index.html and place the following code in it −
<!DOCTYPE html>
<html>
<head>
<title>RequireJS Dojo</title>
<script data-main="app" src="lib/require.js"></script>
</head>
<body>
<h2>RequireJS Dojo</h2>
<p>
Hello... ...
</p>
</body>
</html>
Create a js file with the name app.js and add the following code in it −
require ({
//You can configure loading modules from the lib directory
baseUrl: 'lib',
paths: {
//mapping of package
dojo: 'http://sfoster.dojotoolkit.org/dojobox/1.7-branch/dojo'
}
}, [
//modules which we are using here
'dojo/dom'
], function(dom) {
//using the 'byId' method from dom module
var mydojo = dom.byId('dojo_val')
mydojo.innerHTML = "The text is displaying via dojo/dom";
}
);
Open the HTML file in a browser; you will receive the following output −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2074,
"s": 1842,
"text": "Dojo is a JavaScript toolkit which is based on the AMD module architecture that provides additional modules to add extra functionality to the web application and also saves time and scale in the web application development process."
},
{
"code": null,
"e": 2224,
"s": 2074,
"text": "The following example shows the usage of Dojo along with RequireJS. Create an html file with the name index.html and place the following code in it −"
},
{
"code": null,
"e": 2472,
"s": 2224,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>RequireJS Dojo</title>\n <script data-main=\"app\" src=\"lib/require.js\"></script>\n </head>\n \n <body>\n <h2>RequireJS Dojo</h2>\n <p>\n Hello... ...\n </p>\n </body>\n</html>"
},
{
"code": null,
"e": 2545,
"s": 2472,
"text": "Create a js file with the name app.js and add the following code in it −"
},
{
"code": null,
"e": 3010,
"s": 2545,
"text": "require ({\n //You can configure loading modules from the lib directory\n baseUrl: 'lib',\n \n paths: {\n //mapping of package\n dojo: 'http://sfoster.dojotoolkit.org/dojobox/1.7-branch/dojo'\n }\n \n}, [\n //modules which we are using here\n 'dojo/dom'\n ], function(dom) { \n \n //using the 'byId' method from dom module\n var mydojo = dom.byId('dojo_val')\n mydojo.innerHTML = \"The text is displaying via dojo/dom\"; \n }\n);"
},
{
"code": null,
"e": 3083,
"s": 3010,
"text": "Open the HTML file in a browser; you will receive the following output −"
},
{
"code": null,
"e": 3090,
"s": 3083,
"text": " Print"
},
{
"code": null,
"e": 3101,
"s": 3090,
"text": " Add Notes"
}
] |
EM Algorithm. Mathematical Background and Example | by Mengsay Loem | Towards Data Science
|
Working with a stochastic approach based-machine learning, we consider the information origin as a type of probability distribution. Once we estimate the distribution, it is straightforward to classifier unknown data as well as to predict future generated data. There are two phases to estimate a probability distribution. 1) Decide a model to define the distribution, for example, the form of probability density function (Gaussian distribution, Multinomial distribution...). Here, consider the Gaussian Mixture Model (GMM) as an example. The form of probability density function can be defined by
where w_k is the ratio data generated from the k-th Gaussian distribution.
2) After deciding a form of probability density function, we estimate its parameters from observed data. For example, in the case of Gaussian distribution, mean and variance are parameters to estimate.
Our current known knowledge is observed data set D and the form of generative distribution (unknown parameter Gaussian distributions). However, to solve 2) we need the information on which Gaussian distribution each observed data is generated from, and this information is not directly shown in the observed data.
In this case, the variables which represent the information that cannot be obtained directly from the observed data set are called Latent Variables. In the above example, w_k is a latent variable.
Therefore, in GMM, it is necessary to estimate the latent variable first. And next, we use the estimated latent variable to estimate the parameters of each Gaussian distribution.
An effective method to estimate parameters in a model with latent variables is the Expectation and Maximization algorithm (EM algorithm).
Let’s prepare the symbols used in this part.
D={x_i | i=1,2,3,...,N} : Observed data set of stochastic variable x : where x_i is a d-dimension vector.
z : Latent variable. z_i corresponds with x_i.
theta: Set of parameters to be estimated
Our purpose is to estimate theta from the observed data set D with EM algorithm.
In the case that observed data is i.i.d, the log-likehood function is
We can rewrite our purpose in the following form.
The probability shown in log-likelihood function p(x,z|theta) can be represented with the probability of latent variable z as the following form. The third relation is the result of marginal distribution on the latent variable z
Now, our goal is to determine the parameter theta which maximizes the log-likelihood function log p(x|theta). However, it is not possible to directly maximize this value from the above relation. Therefore, we decide a process to update the parameter theta while maximizing the log p(x|theta). We consider theta be the optimal parameter to be defined, theta(t) be the t-th step value of parameter theta. In the following process, we tend to define an update rule to increase log p(x|theta(t)) compare to log p(x|theta).
Here, we represent q(z) by conditional probability given recent parameter theta and observed data.
Hence, log p(x|theta) can be written as
We start by focusing on the change of log p(x|theta)-log p(x|theta(t)) when update theta(t). We try to define rule which lead to decrease the amount of log p(x|theta)-log p(x|theta(t)).
Rewrite this relation, we get the following form. Equation (1):
Now, we need to evaluate the right-hand side to find a rule in updating parameter theta. To do this, consider a well-known mathematical relationlog x ≤ x-1. Using this relation, we can obtain the following inequality.
Therefore, the 3rd term of Equation(1) is
The first and second term of Equation(1) is non-negative. It is true because, when we replace theta by theta(t), term1-term2=0 then by maximizing the first term, term1-term2 becomes larger or equal to 0.
Consider this relation, log p(x|theta)-log p(x|theta(t))≥0. Therefore, to maximize the left-hand side of Equation(1), we just update theta(t) with a value of theta(t) which maximizes the first term of the right-hand side of Equation(1).
Let the subject of argmax of the above update rule be function Q(theta).
We can translate this relation as an expectation value of log p(x,z|theta) when theta=theta(t).
From this update, we can summary the process of EM algorithm as the following E step and M step.
Let’s take a 2-dimension Gaussian Mixture Model as an example.
Random variable: x_n (d-dimension vector) Latent variable: z_mMixture ratio: w_kMean : mu_k (d-dimension vector)Variance-covariance matrix: Sigma_k (dxd matrix)
Here, if an observed data x is generated from m-th Gaussian distribution, then z_m = 1, else z_m = 0. The distribution of latent variable z, therefore can be written as
The probability density function of m-th Gaussian distribution is given by
Therefore, the probability which data x belongs to m-th distribution is p(z_m=1|x) which is calculated by
Randomly initialize mu, Sigma and w. t = 1.
Calculate p(z|x,theta(t))
Using theta(t) to calculate the expectation value of latent variable z.
Therefore, if z_nm is the latent variable of x_n, N_m is the number of observed data in m-th distribution, the following relation is true.
Update parameter
Our goal in this step is to define w_m, mu_m, Sigma_m which maximize Q(theta|theta(t)).
Solve this equation, the update of mu is
Solve this equation, the update of Sigma is
To derivate the update relation of w, we use Lagrange method to maximize Q(theta|theta(t)) subject to w_1+w_2+...+w_M=1.
Solving this equation for lambda and use the restraint relation, the update rule for w_m is
All Parameters Updates:
n1=150; n2=250; n3=300n = n1+n2+n3x = []x.append(np.dot(np.random.randn(n1,2),np.sqrt(np.diag([1,4]))))x.append(np.random.randn(n2,2)+np.dot(np.asarray([[1.]*n2]).T,np.asarray([[8.0,4.0]])))x.append(np.dot(np.random.randn(n3,2),np.sqrt(np.asarray([[2.45,1],[1,4]])))+16.0)X = np.concatenate((x[0],x[1],x[2]),axis=0)
def genSigma(): A = np.random.rand(2,2)+np.eye(2,2) #A = np.eye(2,2)*np.random.rand(1) S = np.dot(A.T,A) #S = np.diag(np.diag(S)) return Sdef genMu(m): mu = np.zeros((2,m)) mu[0] = np.linspace(np.min(X,axis=0)[0],np.max(X,axis=0)[0],m) mu[1] = np.linspace(np.min(X,axis=0)[1],np.max(X,axis=0)[1],m) return mu.TSigma = np.zeros((m,2,2)) for i in range(m): Sigma[i] = (genSigma())Mu = genMu(m) W = np.asarray([1.]*m) W = W/sum(W) L = -float('inf')iteration = 0
while True: if iteration >=100: break iteration+=1# E step wN = np.zeros((n,m)) for j in range(m): for i in range(n): wN[i,j]=W[j]*gauss(X[i],Sigma[j],Mu[j])sum_wN = np.sum(wN,axis=1) Lnew = np.sum(np.log(sum_wN)) if (Lnew-L) < 0.00001: print("Model Converged") break L = Lnewprint("iter#",iteration," Lnew:",Lnew) iters.append(iteration) Log.append(Lnew)# M stepeta = np.zeros((n,m)) for i in range(n): eta[i,:]=wN[i]/sum_wN[i]sum_eta = np.sum(eta,axis=0) W = sum_eta/nfor j in range(m): tmp = np.zeros((2,)) for i in range(n): tmp += eta[i,j]*X[i] Mu[j]=tmp/sum_eta[j]for j in range(m): tmp = np.zeros((2,2)) for i in range(n): xmu = (X[i]-Mu[j]).reshape(2,1) tmp1 = np.dot(xmu,xmu.T)*eta[i][j] tmp += tmp1 Sigma[j]=tmp/sum_eta[j]
import numpy as npimport randomfrom scipy.interpolate import griddatafrom scipy.stats import multivariate_normalimport numpy.ma as mafrom numpy.random import uniform, seedfrom matplotlib import cmfrom scipy.special import softmaximport matplotlib.pyplot as plt# Gaussian pdf def gauss(x,sigma,mu): n = multivariate_normal(mu,sigma) return n.pdf(x)# Visualizedef plot_countour(sigma,mu): xy_range = np.zeros((2,2)) xy_range[0] = np.linspace(mu[0]-2*sigma[0,0],mu[0]+2*sigma[0,0],2) xy_range[1] = np.linspace(mu[1]-2*sigma[1,1],mu[1]+2*sigma[1,1],2) x, y = np.mgrid[xy_range[0][0]:xy_range[0][1]:.01, xy_range[1][0]:xy_range[1][1]:.01] pos = np.dstack((x, y)) rv = multivariate_normal(mu, sigma) z = rv.pdf(pos) levels = np.linspace(np.min(z),np.max(z),5) plt.contour(x, y, z,linewidths=1.0,colors='black',levels=levels) #plt.contourf(x,y,z,15,cmap=plt.cm.jet) plt.xlim([-5,25])
From the result, with the EM algorithm, the log-likelihood function always converged after repeat the update rules on parameters. However, since the EM algorithm is an iterative calculation, it easily falls into local optimal state. As saw in the result(1),(2) differences in M value(number of mixture model) and initializations offer different changes in Log-likelihood convergence and estimate distribution. To solve this problem, a simple method is to repeat the algorithm with several initialization states and choose the best state from those works.
|
[
{
"code": null,
"e": 771,
"s": 172,
"text": "Working with a stochastic approach based-machine learning, we consider the information origin as a type of probability distribution. Once we estimate the distribution, it is straightforward to classifier unknown data as well as to predict future generated data. There are two phases to estimate a probability distribution. 1) Decide a model to define the distribution, for example, the form of probability density function (Gaussian distribution, Multinomial distribution...). Here, consider the Gaussian Mixture Model (GMM) as an example. The form of probability density function can be defined by"
},
{
"code": null,
"e": 846,
"s": 771,
"text": "where w_k is the ratio data generated from the k-th Gaussian distribution."
},
{
"code": null,
"e": 1048,
"s": 846,
"text": "2) After deciding a form of probability density function, we estimate its parameters from observed data. For example, in the case of Gaussian distribution, mean and variance are parameters to estimate."
},
{
"code": null,
"e": 1362,
"s": 1048,
"text": "Our current known knowledge is observed data set D and the form of generative distribution (unknown parameter Gaussian distributions). However, to solve 2) we need the information on which Gaussian distribution each observed data is generated from, and this information is not directly shown in the observed data."
},
{
"code": null,
"e": 1559,
"s": 1362,
"text": "In this case, the variables which represent the information that cannot be obtained directly from the observed data set are called Latent Variables. In the above example, w_k is a latent variable."
},
{
"code": null,
"e": 1738,
"s": 1559,
"text": "Therefore, in GMM, it is necessary to estimate the latent variable first. And next, we use the estimated latent variable to estimate the parameters of each Gaussian distribution."
},
{
"code": null,
"e": 1876,
"s": 1738,
"text": "An effective method to estimate parameters in a model with latent variables is the Expectation and Maximization algorithm (EM algorithm)."
},
{
"code": null,
"e": 1921,
"s": 1876,
"text": "Let’s prepare the symbols used in this part."
},
{
"code": null,
"e": 2027,
"s": 1921,
"text": "D={x_i | i=1,2,3,...,N} : Observed data set of stochastic variable x : where x_i is a d-dimension vector."
},
{
"code": null,
"e": 2074,
"s": 2027,
"text": "z : Latent variable. z_i corresponds with x_i."
},
{
"code": null,
"e": 2115,
"s": 2074,
"text": "theta: Set of parameters to be estimated"
},
{
"code": null,
"e": 2196,
"s": 2115,
"text": "Our purpose is to estimate theta from the observed data set D with EM algorithm."
},
{
"code": null,
"e": 2266,
"s": 2196,
"text": "In the case that observed data is i.i.d, the log-likehood function is"
},
{
"code": null,
"e": 2316,
"s": 2266,
"text": "We can rewrite our purpose in the following form."
},
{
"code": null,
"e": 2545,
"s": 2316,
"text": "The probability shown in log-likelihood function p(x,z|theta) can be represented with the probability of latent variable z as the following form. The third relation is the result of marginal distribution on the latent variable z"
},
{
"code": null,
"e": 3064,
"s": 2545,
"text": "Now, our goal is to determine the parameter theta which maximizes the log-likelihood function log p(x|theta). However, it is not possible to directly maximize this value from the above relation. Therefore, we decide a process to update the parameter theta while maximizing the log p(x|theta). We consider theta be the optimal parameter to be defined, theta(t) be the t-th step value of parameter theta. In the following process, we tend to define an update rule to increase log p(x|theta(t)) compare to log p(x|theta)."
},
{
"code": null,
"e": 3163,
"s": 3064,
"text": "Here, we represent q(z) by conditional probability given recent parameter theta and observed data."
},
{
"code": null,
"e": 3203,
"s": 3163,
"text": "Hence, log p(x|theta) can be written as"
},
{
"code": null,
"e": 3389,
"s": 3203,
"text": "We start by focusing on the change of log p(x|theta)-log p(x|theta(t)) when update theta(t). We try to define rule which lead to decrease the amount of log p(x|theta)-log p(x|theta(t))."
},
{
"code": null,
"e": 3453,
"s": 3389,
"text": "Rewrite this relation, we get the following form. Equation (1):"
},
{
"code": null,
"e": 3671,
"s": 3453,
"text": "Now, we need to evaluate the right-hand side to find a rule in updating parameter theta. To do this, consider a well-known mathematical relationlog x ≤ x-1. Using this relation, we can obtain the following inequality."
},
{
"code": null,
"e": 3713,
"s": 3671,
"text": "Therefore, the 3rd term of Equation(1) is"
},
{
"code": null,
"e": 3917,
"s": 3713,
"text": "The first and second term of Equation(1) is non-negative. It is true because, when we replace theta by theta(t), term1-term2=0 then by maximizing the first term, term1-term2 becomes larger or equal to 0."
},
{
"code": null,
"e": 4154,
"s": 3917,
"text": "Consider this relation, log p(x|theta)-log p(x|theta(t))≥0. Therefore, to maximize the left-hand side of Equation(1), we just update theta(t) with a value of theta(t) which maximizes the first term of the right-hand side of Equation(1)."
},
{
"code": null,
"e": 4227,
"s": 4154,
"text": "Let the subject of argmax of the above update rule be function Q(theta)."
},
{
"code": null,
"e": 4323,
"s": 4227,
"text": "We can translate this relation as an expectation value of log p(x,z|theta) when theta=theta(t)."
},
{
"code": null,
"e": 4420,
"s": 4323,
"text": "From this update, we can summary the process of EM algorithm as the following E step and M step."
},
{
"code": null,
"e": 4483,
"s": 4420,
"text": "Let’s take a 2-dimension Gaussian Mixture Model as an example."
},
{
"code": null,
"e": 4644,
"s": 4483,
"text": "Random variable: x_n (d-dimension vector) Latent variable: z_mMixture ratio: w_kMean : mu_k (d-dimension vector)Variance-covariance matrix: Sigma_k (dxd matrix)"
},
{
"code": null,
"e": 4813,
"s": 4644,
"text": "Here, if an observed data x is generated from m-th Gaussian distribution, then z_m = 1, else z_m = 0. The distribution of latent variable z, therefore can be written as"
},
{
"code": null,
"e": 4888,
"s": 4813,
"text": "The probability density function of m-th Gaussian distribution is given by"
},
{
"code": null,
"e": 4994,
"s": 4888,
"text": "Therefore, the probability which data x belongs to m-th distribution is p(z_m=1|x) which is calculated by"
},
{
"code": null,
"e": 5038,
"s": 4994,
"text": "Randomly initialize mu, Sigma and w. t = 1."
},
{
"code": null,
"e": 5064,
"s": 5038,
"text": "Calculate p(z|x,theta(t))"
},
{
"code": null,
"e": 5136,
"s": 5064,
"text": "Using theta(t) to calculate the expectation value of latent variable z."
},
{
"code": null,
"e": 5275,
"s": 5136,
"text": "Therefore, if z_nm is the latent variable of x_n, N_m is the number of observed data in m-th distribution, the following relation is true."
},
{
"code": null,
"e": 5292,
"s": 5275,
"text": "Update parameter"
},
{
"code": null,
"e": 5380,
"s": 5292,
"text": "Our goal in this step is to define w_m, mu_m, Sigma_m which maximize Q(theta|theta(t))."
},
{
"code": null,
"e": 5421,
"s": 5380,
"text": "Solve this equation, the update of mu is"
},
{
"code": null,
"e": 5465,
"s": 5421,
"text": "Solve this equation, the update of Sigma is"
},
{
"code": null,
"e": 5586,
"s": 5465,
"text": "To derivate the update relation of w, we use Lagrange method to maximize Q(theta|theta(t)) subject to w_1+w_2+...+w_M=1."
},
{
"code": null,
"e": 5678,
"s": 5586,
"text": "Solving this equation for lambda and use the restraint relation, the update rule for w_m is"
},
{
"code": null,
"e": 5702,
"s": 5678,
"text": "All Parameters Updates:"
},
{
"code": null,
"e": 6018,
"s": 5702,
"text": "n1=150; n2=250; n3=300n = n1+n2+n3x = []x.append(np.dot(np.random.randn(n1,2),np.sqrt(np.diag([1,4]))))x.append(np.random.randn(n2,2)+np.dot(np.asarray([[1.]*n2]).T,np.asarray([[8.0,4.0]])))x.append(np.dot(np.random.randn(n3,2),np.sqrt(np.asarray([[2.45,1],[1,4]])))+16.0)X = np.concatenate((x[0],x[1],x[2]),axis=0)"
},
{
"code": null,
"e": 6527,
"s": 6018,
"text": "def genSigma(): A = np.random.rand(2,2)+np.eye(2,2) #A = np.eye(2,2)*np.random.rand(1) S = np.dot(A.T,A) #S = np.diag(np.diag(S)) return Sdef genMu(m): mu = np.zeros((2,m)) mu[0] = np.linspace(np.min(X,axis=0)[0],np.max(X,axis=0)[0],m) mu[1] = np.linspace(np.min(X,axis=0)[1],np.max(X,axis=0)[1],m) return mu.TSigma = np.zeros((m,2,2)) for i in range(m): Sigma[i] = (genSigma())Mu = genMu(m) W = np.asarray([1.]*m) W = W/sum(W) L = -float('inf')iteration = 0"
},
{
"code": null,
"e": 7533,
"s": 6527,
"text": "while True: if iteration >=100: break iteration+=1# E step wN = np.zeros((n,m)) for j in range(m): for i in range(n): wN[i,j]=W[j]*gauss(X[i],Sigma[j],Mu[j])sum_wN = np.sum(wN,axis=1) Lnew = np.sum(np.log(sum_wN)) if (Lnew-L) < 0.00001: print(\"Model Converged\") break L = Lnewprint(\"iter#\",iteration,\" Lnew:\",Lnew) iters.append(iteration) Log.append(Lnew)# M stepeta = np.zeros((n,m)) for i in range(n): eta[i,:]=wN[i]/sum_wN[i]sum_eta = np.sum(eta,axis=0) W = sum_eta/nfor j in range(m): tmp = np.zeros((2,)) for i in range(n): tmp += eta[i,j]*X[i] Mu[j]=tmp/sum_eta[j]for j in range(m): tmp = np.zeros((2,2)) for i in range(n): xmu = (X[i]-Mu[j]).reshape(2,1) tmp1 = np.dot(xmu,xmu.T)*eta[i][j] tmp += tmp1 Sigma[j]=tmp/sum_eta[j]"
},
{
"code": null,
"e": 8449,
"s": 7533,
"text": "import numpy as npimport randomfrom scipy.interpolate import griddatafrom scipy.stats import multivariate_normalimport numpy.ma as mafrom numpy.random import uniform, seedfrom matplotlib import cmfrom scipy.special import softmaximport matplotlib.pyplot as plt# Gaussian pdf def gauss(x,sigma,mu): n = multivariate_normal(mu,sigma) return n.pdf(x)# Visualizedef plot_countour(sigma,mu): xy_range = np.zeros((2,2)) xy_range[0] = np.linspace(mu[0]-2*sigma[0,0],mu[0]+2*sigma[0,0],2) xy_range[1] = np.linspace(mu[1]-2*sigma[1,1],mu[1]+2*sigma[1,1],2) x, y = np.mgrid[xy_range[0][0]:xy_range[0][1]:.01, xy_range[1][0]:xy_range[1][1]:.01] pos = np.dstack((x, y)) rv = multivariate_normal(mu, sigma) z = rv.pdf(pos) levels = np.linspace(np.min(z),np.max(z),5) plt.contour(x, y, z,linewidths=1.0,colors='black',levels=levels) #plt.contourf(x,y,z,15,cmap=plt.cm.jet) plt.xlim([-5,25])"
}
] |
ONNX for image processing from scratch | by Maurits Kaptein | Towards Data Science
|
ONNX has been around for a while, and it is becoming a successful intermediate format to move, often heavy, trained neural networks from one training tool to another (e.g., move between pyTorch and Tensorflow), or to deploy models in the cloud using the ONNX runtime. However, ONNX can be put to a much more versatile use: ONNX can easily be used to manually specify AI/ML processing pipelines, including all the pre- and post-processing that is often necessary for real-world deployments. In this tutorial we will show how to use the onnx helper tools in Python to create a ONNX image processing pipeline from scratch and deploy it efficiently.
In this tutorial we will not introduce ONNX again; please see our previous post on creating ONNX from scratch for a general introduction. In this tutorial we will show how to easily use ONNX to specify image processing pipelines. We will cover the following steps:
Pipeline “training”: We will explain the image recognition task we are facing and our general approach.ONNX creation: We will detail, step-by-step, how we create the ONNX pipeline to carry out the desired image processing.Testing within python: We will demonstrate how to test our pipeline in Python using the ONNX runtime.Deployment using WebAssembly: We will demonstrate how to convert our image processing pipeline to WebAssembly for efficient deployment in the browser, in the cloud, or on embedded devices.
Pipeline “training”: We will explain the image recognition task we are facing and our general approach.
ONNX creation: We will detail, step-by-step, how we create the ONNX pipeline to carry out the desired image processing.
Testing within python: We will demonstrate how to test our pipeline in Python using the ONNX runtime.
Deployment using WebAssembly: We will demonstrate how to convert our image processing pipeline to WebAssembly for efficient deployment in the browser, in the cloud, or on embedded devices.
Note that the main aim of this tutorial is to show the ease with which ONNX can be used to specify data processing tasks (in this case image processing) that would often not be regarded as AI/ML, but are still extremely useful. Hopefully this helps to open up the use of ONNX far beyond the simple storing of trained neural networks.
It is hard to really call the steps below model training, but we start by setting up the problem including the processing we need for the classification algorithm that we will implement in ONNX. In this toy example, we are faced with a total of 14 images of a small container which is either empty or full. Our goal is to create an ONNX pipeline (and deploy it) which, given an input image, detects whether or not the container is filled. Here is one of the examples:
Our approach is simple: we first compute the average of all the empty images to use as a reference. Next, for each new image we simply subtract the new image from the reference image and see if it deviates (too much) from it: if it does, it must not be an empty image.
Note that the image processing approach we implement in this tutorial is very rudimentary; it is not very robust to changes in (e.g.,) the lighting of the image, nor would it work well with different containers. However, the example does go to show the ease with which processing pipelines can be created in ONNX.
Using Pillow and Numpy our “training” stage is relatively simple: we simply open up all the empty containers and compute their average:
import numpy as npfrom PIL import Image## Setup:image_folder = “images/”empty_containers = [2,3,5,8,9,12,13]full_containers = [1,4,6,7,10,11,14]all_containers = empty_containers+full_containers# Get number of images, image width, and image height:n_empty = len(empty_containers)image_width, image_height=Image.open(image_folder + str(empty_containers[0])+”.JPG”).size# Create a numpy array of ints to store the average (assume RGB images)av_arr=np.zeros((image_height,image_width,3),np.int64)# Build up average pixel intensities, casting each image as an array of intsfor i in empty_containers: im_arr=np.array(Image.open(image_folder + str(empty_containers[0])+”.JPG”),dtype=np.int64) av_arr=av_arr+im_arr/n_empty# Round values in array and cast as 8-bit integerav_arr=np.array(np.round(av_arr),dtype=np.uint8)# Generate and save the average empty container imageout=Image.fromarray(avarr,mode=”RGB”)out.save(image_folder+”empty-average.JPG”)out.show()
The empty-average.JPG will be used as our reference. It looks like this:
We will use ONNX from scratch using the onnx.helper tools in Python to implement our image processing pipeline. Conceptually the steps are simple:
We subtract the empty-average.JPG from a given image that we would like to classify.We compute the absolute value of the remaining difference.We sum the array of image (absolute) color values in the difference to a single number.We check if the number is larger than some threshold.
We subtract the empty-average.JPG from a given image that we would like to classify.
We compute the absolute value of the remaining difference.
We sum the array of image (absolute) color values in the difference to a single number.
We check if the number is larger than some threshold.
Thus, the logic of this implementation is simple: compared to the (average) empty image, an image of an empty container should be relatively similar, i.e., its absolute difference should be small. If however the container is full, the image is different, and thus its summed absolute difference compared to the reference image should be large.
The python code to implement this pipeline is as follows:
# The imports used in this blockfrom onnx import helper as hfrom onnx import TensorProto as tpfrom onnx import checkerfrom onnx import save# 1. We start by opening the reference image and creating the necessary ONNX constants:# The baseline empty container image (average of the 7 empty images)reference_image=np.array(Image.open(image_folder+”empty-average.JPG”),dtype=np.int64)# The baseline image as ONNX constant:c_base = h.make_node(‘Constant’, inputs=[], outputs=[‘c_base’], name=”c_base_node”, value=h.make_tensor(name=”c_base_value”, data_type=tp.INT64, dims=reference_image.shape, vals=reference_image.flatten()))# The threshold value as ONNX constant; here we select an average of 25 points difference (3000000=300*400*25)image_threshold = numpy.array([3000000]).astype(numpy.int64)c_cut = h.make_node(‘Constant’, inputs=[], outputs=[‘c_cut’], name=”c_cut_node”, value=h.make_tensor(name=”c1v”, data_type=tp.INT64, dims=image_threshold.shape, vals=image_threshold.flatten()))# 2. Next, we declare the functional ONNX nodes in order of appearance:# Subtract input xin from baselinen1 = h.make_node(‘Sub’, inputs=[‘xin’, ‘c_base’], outputs=[‘min’], name=’n1')# Compute absolute values of the remaining differencen2 = h.make_node(‘Abs’, inputs=[‘min’], outputs=[‘abs’], name=”n2")# Sum all the absolute differencesn3 = h.make_node(‘ReduceSum’, inputs=[‘abs’], outputs=[‘sum’], name=”n3", keepdims=0)# See if the sum is less than image_threshold; if it is the image is emptyn4 = h.make_node(‘Less’, inputs=[‘sum’,’c_cut’], outputs=[‘out’], name=”n4")# 3. Finally, we create the resulting ONNX graph# Create the graphg1 = h.make_graph([c_base, c_cut, n1,n2,n3,n4], ‘convert_image’, [h.make_tensor_value_info(‘xin’, tp.INT64, target.shape)], [h.make_tensor_value_info(‘out’, tp.BOOL, [1])])# Create the model and checkm1 = h.make_model(g1, producer_name=’scailable-demo’)checker.check_model(m1)# Save the modelsave(m1, ‘empty-container.onnx’)
With Netron we can inspect the resulting ONNX pipeline:
Before detailing how this pipeline can be used on (e.g.,) a small ESP32 device for actual image processing “in the field”, we first want to see its performance. In total we have 14 test images, 7 empty, and 7 full. The following python code uses the `onnxruntime` to check each of the images and print whether or not our processing pipeline thinks it is empty:
import onnxruntime as rt# Open the model:sess = rt.InferenceSession(“empty-container.onnx”)# Test all the empty imagesprint(“Iterating through all images”)for i in all_containers: # Get whether in reality the container is empty true_empty = i in empty_containers # Check image using the ONNX pipeline target=numpy.array(Image.open(image_folder + str(i)+".JPG"),dtype=numpy.int64) out = sess.run(["out"], {"xin": target.astype(numpy.int64)}) print("Container {} is empty {}, and it is classified as empty {}.".format(i, true_empty, out[0].flatten()))
Running the code shows that all the example images are correctly “classified”. See this notebook for a fully working version.
Up until this point we hope this tutorial has shown how simple it is to create a rudimentary image processing pipeline using ONNX. Thus, ONNX can be used to not only store complex AI/ML models, it is also a very useful tool to express pre- and post-processing in a general data pipeline.
However, ONNX, in our view, is not very well suited to subsequently deploy the resulting pipeline. Although in the cloud the onnxruntime works well, it is quite bloated (one needs > 200Mb to just install the runtime itself). On (I)IoT and/or Edge devices, where simple image processing tasks such as the one described in this tutorial are common, there is no way you will be able to deploy the full ONNX runtime.
Does that mean ONNX is useless for deployment on embedded devices? Nope, not at all! Because of the level of detail of an ONNX graph, it is possible to automatically convert an ONNX graph to a lower level representation (for example, to LLVM IR). Actually, it is possible to go from ONNX directly to c to embed the pipeline on extremely small devices. Or, the option that we prefer, we compile from c to WebAssembly: by compiling to WebAssembly we can now take the specified ONNX pipeline and run it without difficulties on virtually any device; here the WebAssembly runtime will take care of the differences in Chipsets (e.g., Intel vs. Arm, 32 vs. 64 bits, etc.) that we often face on Edge devices.
Using the tools offered by Scailable (you can sign up for a free account here), the conversion from ONNX to WebAssembly is out-of-the box. The automatic conversion above provides us with a .wasm binary adhering to the interface standards described here. Subsequently, it is easy to embed this binary in e.g., a simple c project:
// Note: c code this time, not Python:int main(int argc, char *argv[]) {// ...// 1. Read WASM into runtime. sclbl_core_wasm_read(wasm_path);// 2. Initialize runtime. sclbl_core_wasm_init();// 3. Generate JSON formatted runtime input string. char *input_string = sclbl_util_bmp_to_json(bmp_path);// 4. Run Sclbl inference. char *output_string = sclbl_core_exec(input_string);// 5. Do something with the output string. printf("%s\n", output_string);// 6. Clean up. sclbl_core_finalize();}char *sclbl_util_bmp_to_json(char *imgPath) {// ...// read bmp file sclbl_read_bmp(imgPath, &pixels, &width, &height, &bytes_per_pixel); enc = sclbl_b64_encode((const unsigned char *) bytes_per_pixel, width * height * bytes_per_pixel * sizeof(float)); free(bytes_per_pixel); // wrap in json json = sclbl_raw_input_wrapper(enc); free(enc); return json;}
The code above, with some changes to interact with the integrated camera, allowed us to run the ONNX pipeline above on an ESP32 device with only 4Mb of memory.
Pretty cool.
Note, the code above requires the Scailable c runtime which is available after signing up for an account. It is a general WebAssembly runtime which makes the I/O to Scailable binaries easy and enables modular deployment.
We hope to have shown that it is relatively easy to use ONNX as a tool to specify data processing pipelines. Although many other tools exists (e.g., openCV), one of the nice things of ONNX is that its versatility, combined with its specificity, jointly allow for the specification of complex pre-processing, inference, and post-processing tasks that can be embedded on tiny devices (by converting to WebAssembly).
Let us know if you have any questions using ONNX / WebAssembly!
It’s good to note my own involvement here: I am a professor of Data Science at the Jheronimus Academy of Data Science and one of the cofounders of Scailable. Thus, no doubt, I have a vested interest in Scailable; I have an interest in making it grow such that we can finally bring AI to production and deliver on its promises. The opinions expressed here are my own.
|
[
{
"code": null,
"e": 817,
"s": 171,
"text": "ONNX has been around for a while, and it is becoming a successful intermediate format to move, often heavy, trained neural networks from one training tool to another (e.g., move between pyTorch and Tensorflow), or to deploy models in the cloud using the ONNX runtime. However, ONNX can be put to a much more versatile use: ONNX can easily be used to manually specify AI/ML processing pipelines, including all the pre- and post-processing that is often necessary for real-world deployments. In this tutorial we will show how to use the onnx helper tools in Python to create a ONNX image processing pipeline from scratch and deploy it efficiently."
},
{
"code": null,
"e": 1082,
"s": 817,
"text": "In this tutorial we will not introduce ONNX again; please see our previous post on creating ONNX from scratch for a general introduction. In this tutorial we will show how to easily use ONNX to specify image processing pipelines. We will cover the following steps:"
},
{
"code": null,
"e": 1594,
"s": 1082,
"text": "Pipeline “training”: We will explain the image recognition task we are facing and our general approach.ONNX creation: We will detail, step-by-step, how we create the ONNX pipeline to carry out the desired image processing.Testing within python: We will demonstrate how to test our pipeline in Python using the ONNX runtime.Deployment using WebAssembly: We will demonstrate how to convert our image processing pipeline to WebAssembly for efficient deployment in the browser, in the cloud, or on embedded devices."
},
{
"code": null,
"e": 1698,
"s": 1594,
"text": "Pipeline “training”: We will explain the image recognition task we are facing and our general approach."
},
{
"code": null,
"e": 1818,
"s": 1698,
"text": "ONNX creation: We will detail, step-by-step, how we create the ONNX pipeline to carry out the desired image processing."
},
{
"code": null,
"e": 1920,
"s": 1818,
"text": "Testing within python: We will demonstrate how to test our pipeline in Python using the ONNX runtime."
},
{
"code": null,
"e": 2109,
"s": 1920,
"text": "Deployment using WebAssembly: We will demonstrate how to convert our image processing pipeline to WebAssembly for efficient deployment in the browser, in the cloud, or on embedded devices."
},
{
"code": null,
"e": 2443,
"s": 2109,
"text": "Note that the main aim of this tutorial is to show the ease with which ONNX can be used to specify data processing tasks (in this case image processing) that would often not be regarded as AI/ML, but are still extremely useful. Hopefully this helps to open up the use of ONNX far beyond the simple storing of trained neural networks."
},
{
"code": null,
"e": 2911,
"s": 2443,
"text": "It is hard to really call the steps below model training, but we start by setting up the problem including the processing we need for the classification algorithm that we will implement in ONNX. In this toy example, we are faced with a total of 14 images of a small container which is either empty or full. Our goal is to create an ONNX pipeline (and deploy it) which, given an input image, detects whether or not the container is filled. Here is one of the examples:"
},
{
"code": null,
"e": 3180,
"s": 2911,
"text": "Our approach is simple: we first compute the average of all the empty images to use as a reference. Next, for each new image we simply subtract the new image from the reference image and see if it deviates (too much) from it: if it does, it must not be an empty image."
},
{
"code": null,
"e": 3494,
"s": 3180,
"text": "Note that the image processing approach we implement in this tutorial is very rudimentary; it is not very robust to changes in (e.g.,) the lighting of the image, nor would it work well with different containers. However, the example does go to show the ease with which processing pipelines can be created in ONNX."
},
{
"code": null,
"e": 3630,
"s": 3494,
"text": "Using Pillow and Numpy our “training” stage is relatively simple: we simply open up all the empty containers and compute their average:"
},
{
"code": null,
"e": 4584,
"s": 3630,
"text": "import numpy as npfrom PIL import Image## Setup:image_folder = “images/”empty_containers = [2,3,5,8,9,12,13]full_containers = [1,4,6,7,10,11,14]all_containers = empty_containers+full_containers# Get number of images, image width, and image height:n_empty = len(empty_containers)image_width, image_height=Image.open(image_folder + str(empty_containers[0])+”.JPG”).size# Create a numpy array of ints to store the average (assume RGB images)av_arr=np.zeros((image_height,image_width,3),np.int64)# Build up average pixel intensities, casting each image as an array of intsfor i in empty_containers: im_arr=np.array(Image.open(image_folder + str(empty_containers[0])+”.JPG”),dtype=np.int64) av_arr=av_arr+im_arr/n_empty# Round values in array and cast as 8-bit integerav_arr=np.array(np.round(av_arr),dtype=np.uint8)# Generate and save the average empty container imageout=Image.fromarray(avarr,mode=”RGB”)out.save(image_folder+”empty-average.JPG”)out.show()"
},
{
"code": null,
"e": 4657,
"s": 4584,
"text": "The empty-average.JPG will be used as our reference. It looks like this:"
},
{
"code": null,
"e": 4804,
"s": 4657,
"text": "We will use ONNX from scratch using the onnx.helper tools in Python to implement our image processing pipeline. Conceptually the steps are simple:"
},
{
"code": null,
"e": 5087,
"s": 4804,
"text": "We subtract the empty-average.JPG from a given image that we would like to classify.We compute the absolute value of the remaining difference.We sum the array of image (absolute) color values in the difference to a single number.We check if the number is larger than some threshold."
},
{
"code": null,
"e": 5172,
"s": 5087,
"text": "We subtract the empty-average.JPG from a given image that we would like to classify."
},
{
"code": null,
"e": 5231,
"s": 5172,
"text": "We compute the absolute value of the remaining difference."
},
{
"code": null,
"e": 5319,
"s": 5231,
"text": "We sum the array of image (absolute) color values in the difference to a single number."
},
{
"code": null,
"e": 5373,
"s": 5319,
"text": "We check if the number is larger than some threshold."
},
{
"code": null,
"e": 5717,
"s": 5373,
"text": "Thus, the logic of this implementation is simple: compared to the (average) empty image, an image of an empty container should be relatively similar, i.e., its absolute difference should be small. If however the container is full, the image is different, and thus its summed absolute difference compared to the reference image should be large."
},
{
"code": null,
"e": 5775,
"s": 5717,
"text": "The python code to implement this pipeline is as follows:"
},
{
"code": null,
"e": 7728,
"s": 5775,
"text": "# The imports used in this blockfrom onnx import helper as hfrom onnx import TensorProto as tpfrom onnx import checkerfrom onnx import save# 1. We start by opening the reference image and creating the necessary ONNX constants:# The baseline empty container image (average of the 7 empty images)reference_image=np.array(Image.open(image_folder+”empty-average.JPG”),dtype=np.int64)# The baseline image as ONNX constant:c_base = h.make_node(‘Constant’, inputs=[], outputs=[‘c_base’], name=”c_base_node”, value=h.make_tensor(name=”c_base_value”, data_type=tp.INT64, dims=reference_image.shape, vals=reference_image.flatten()))# The threshold value as ONNX constant; here we select an average of 25 points difference (3000000=300*400*25)image_threshold = numpy.array([3000000]).astype(numpy.int64)c_cut = h.make_node(‘Constant’, inputs=[], outputs=[‘c_cut’], name=”c_cut_node”, value=h.make_tensor(name=”c1v”, data_type=tp.INT64, dims=image_threshold.shape, vals=image_threshold.flatten()))# 2. Next, we declare the functional ONNX nodes in order of appearance:# Subtract input xin from baselinen1 = h.make_node(‘Sub’, inputs=[‘xin’, ‘c_base’], outputs=[‘min’], name=’n1')# Compute absolute values of the remaining differencen2 = h.make_node(‘Abs’, inputs=[‘min’], outputs=[‘abs’], name=”n2\")# Sum all the absolute differencesn3 = h.make_node(‘ReduceSum’, inputs=[‘abs’], outputs=[‘sum’], name=”n3\", keepdims=0)# See if the sum is less than image_threshold; if it is the image is emptyn4 = h.make_node(‘Less’, inputs=[‘sum’,’c_cut’], outputs=[‘out’], name=”n4\")# 3. Finally, we create the resulting ONNX graph# Create the graphg1 = h.make_graph([c_base, c_cut, n1,n2,n3,n4], ‘convert_image’, [h.make_tensor_value_info(‘xin’, tp.INT64, target.shape)], [h.make_tensor_value_info(‘out’, tp.BOOL, [1])])# Create the model and checkm1 = h.make_model(g1, producer_name=’scailable-demo’)checker.check_model(m1)# Save the modelsave(m1, ‘empty-container.onnx’)"
},
{
"code": null,
"e": 7784,
"s": 7728,
"text": "With Netron we can inspect the resulting ONNX pipeline:"
},
{
"code": null,
"e": 8145,
"s": 7784,
"text": "Before detailing how this pipeline can be used on (e.g.,) a small ESP32 device for actual image processing “in the field”, we first want to see its performance. In total we have 14 test images, 7 empty, and 7 full. The following python code uses the `onnxruntime` to check each of the images and print whether or not our processing pipeline thinks it is empty:"
},
{
"code": null,
"e": 8727,
"s": 8145,
"text": "import onnxruntime as rt# Open the model:sess = rt.InferenceSession(“empty-container.onnx”)# Test all the empty imagesprint(“Iterating through all images”)for i in all_containers: # Get whether in reality the container is empty true_empty = i in empty_containers # Check image using the ONNX pipeline target=numpy.array(Image.open(image_folder + str(i)+\".JPG\"),dtype=numpy.int64) out = sess.run([\"out\"], {\"xin\": target.astype(numpy.int64)}) print(\"Container {} is empty {}, and it is classified as empty {}.\".format(i, true_empty, out[0].flatten()))"
},
{
"code": null,
"e": 8853,
"s": 8727,
"text": "Running the code shows that all the example images are correctly “classified”. See this notebook for a fully working version."
},
{
"code": null,
"e": 9141,
"s": 8853,
"text": "Up until this point we hope this tutorial has shown how simple it is to create a rudimentary image processing pipeline using ONNX. Thus, ONNX can be used to not only store complex AI/ML models, it is also a very useful tool to express pre- and post-processing in a general data pipeline."
},
{
"code": null,
"e": 9554,
"s": 9141,
"text": "However, ONNX, in our view, is not very well suited to subsequently deploy the resulting pipeline. Although in the cloud the onnxruntime works well, it is quite bloated (one needs > 200Mb to just install the runtime itself). On (I)IoT and/or Edge devices, where simple image processing tasks such as the one described in this tutorial are common, there is no way you will be able to deploy the full ONNX runtime."
},
{
"code": null,
"e": 10255,
"s": 9554,
"text": "Does that mean ONNX is useless for deployment on embedded devices? Nope, not at all! Because of the level of detail of an ONNX graph, it is possible to automatically convert an ONNX graph to a lower level representation (for example, to LLVM IR). Actually, it is possible to go from ONNX directly to c to embed the pipeline on extremely small devices. Or, the option that we prefer, we compile from c to WebAssembly: by compiling to WebAssembly we can now take the specified ONNX pipeline and run it without difficulties on virtually any device; here the WebAssembly runtime will take care of the differences in Chipsets (e.g., Intel vs. Arm, 32 vs. 64 bits, etc.) that we often face on Edge devices."
},
{
"code": null,
"e": 10584,
"s": 10255,
"text": "Using the tools offered by Scailable (you can sign up for a free account here), the conversion from ONNX to WebAssembly is out-of-the box. The automatic conversion above provides us with a .wasm binary adhering to the interface standards described here. Subsequently, it is easy to embed this binary in e.g., a simple c project:"
},
{
"code": null,
"e": 11424,
"s": 10584,
"text": "// Note: c code this time, not Python:int main(int argc, char *argv[]) {// ...// 1. Read WASM into runtime. sclbl_core_wasm_read(wasm_path);// 2. Initialize runtime. sclbl_core_wasm_init();// 3. Generate JSON formatted runtime input string. char *input_string = sclbl_util_bmp_to_json(bmp_path);// 4. Run Sclbl inference. char *output_string = sclbl_core_exec(input_string);// 5. Do something with the output string. printf(\"%s\\n\", output_string);// 6. Clean up. sclbl_core_finalize();}char *sclbl_util_bmp_to_json(char *imgPath) {// ...// read bmp file sclbl_read_bmp(imgPath, &pixels, &width, &height, &bytes_per_pixel); enc = sclbl_b64_encode((const unsigned char *) bytes_per_pixel, width * height * bytes_per_pixel * sizeof(float)); free(bytes_per_pixel); // wrap in json json = sclbl_raw_input_wrapper(enc); free(enc); return json;}"
},
{
"code": null,
"e": 11584,
"s": 11424,
"text": "The code above, with some changes to interact with the integrated camera, allowed us to run the ONNX pipeline above on an ESP32 device with only 4Mb of memory."
},
{
"code": null,
"e": 11597,
"s": 11584,
"text": "Pretty cool."
},
{
"code": null,
"e": 11818,
"s": 11597,
"text": "Note, the code above requires the Scailable c runtime which is available after signing up for an account. It is a general WebAssembly runtime which makes the I/O to Scailable binaries easy and enables modular deployment."
},
{
"code": null,
"e": 12232,
"s": 11818,
"text": "We hope to have shown that it is relatively easy to use ONNX as a tool to specify data processing pipelines. Although many other tools exists (e.g., openCV), one of the nice things of ONNX is that its versatility, combined with its specificity, jointly allow for the specification of complex pre-processing, inference, and post-processing tasks that can be embedded on tiny devices (by converting to WebAssembly)."
},
{
"code": null,
"e": 12296,
"s": 12232,
"text": "Let us know if you have any questions using ONNX / WebAssembly!"
}
] |
TypeScript - Bitwise Operators Examples
|
Assume variable A = 2 and B = 3
var a:number = 2; // Bit presentation 10
var b:number = 3; // Bit presentation 11
var result;
result = (a & b);
console.log("(a & b) => ",result)
result = (a | b);
console.log("(a | b) => ",result)
result = (a ^ b);
console.log("(a ^ b) => ",result);
result = (~b);
console.log("(~b) => ",result);
result = (a << b);
console.log("(a << b) => ",result);
result = (a >> b);
console.log("(a >> b) => ",result);
On compiling, it will generate the following JavaScript code −
//Generated by typescript 1.8.10
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var result;
result = (a & b);
console.log("(a & b) => ", result);
result = (a | b);
console.log("(a | b) => ", result);
result = (a ^ b);
console.log("(a ^ b) => ", result);
result = (~b);
console.log("(~b) => ", result);
result = (a << b);
console.log("(a << b) => ", result);
result = (a >> b);
console.log("(a >> b) => ", result);
The output of the above program is given below −
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2080,
"s": 2048,
"text": "Assume variable A = 2 and B = 3"
},
{
"code": null,
"e": 2549,
"s": 2080,
"text": "var a:number = 2; // Bit presentation 10 \nvar b:number = 3; // Bit presentation 11\n \nvar result; \n \nresult = (a & b); \nconsole.log(\"(a & b) => \",result)\n \nresult = (a | b); \nconsole.log(\"(a | b) => \",result) \n \nresult = (a ^ b); \nconsole.log(\"(a ^ b) => \",result);\n \nresult = (~b); \nconsole.log(\"(~b) => \",result);\n\nresult = (a << b); \nconsole.log(\"(a << b) => \",result); \n\nresult = (a >> b); \nconsole.log(\"(a >> b) => \",result);\n"
},
{
"code": null,
"e": 2612,
"s": 2549,
"text": "On compiling, it will generate the following JavaScript code −"
},
{
"code": null,
"e": 3058,
"s": 2612,
"text": "//Generated by typescript 1.8.10\nvar a = 2; // Bit presentation 10\nvar b = 3; // Bit presentation 11\nvar result;\n\nresult = (a & b);\nconsole.log(\"(a & b) => \", result);\n\nresult = (a | b);\nconsole.log(\"(a | b) => \", result);\n\nresult = (a ^ b);\nconsole.log(\"(a ^ b) => \", result);\n\nresult = (~b);\nconsole.log(\"(~b) => \", result);\n\nresult = (a << b);\nconsole.log(\"(a << b) => \", result);\n\nresult = (a >> b);\nconsole.log(\"(a >> b) => \", result);\n"
},
{
"code": null,
"e": 3107,
"s": 3058,
"text": "The output of the above program is given below −"
},
{
"code": null,
"e": 3198,
"s": 3107,
"text": "(a & b) => 2 \n(a | b) => 3 \n(a ^ b) => 1 \n(~b) => -4 \n(a << b) => 16 \n(a >> b) => 0\n"
},
{
"code": null,
"e": 3231,
"s": 3198,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3245,
"s": 3231,
"text": " Antonio Papa"
},
{
"code": null,
"e": 3278,
"s": 3245,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3292,
"s": 3278,
"text": " Haider Malik"
},
{
"code": null,
"e": 3327,
"s": 3292,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3347,
"s": 3327,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 3380,
"s": 3347,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3394,
"s": 3380,
"text": " Sean Bradley"
},
{
"code": null,
"e": 3429,
"s": 3394,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3445,
"s": 3429,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3478,
"s": 3445,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3498,
"s": 3478,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 3505,
"s": 3498,
"text": " Print"
},
{
"code": null,
"e": 3516,
"s": 3505,
"text": " Add Notes"
}
] |
How to Rotate image in image view by an angle in Android?
|
This example demonstrates how to Rotate image in image view by an angle.
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"
android:id="@+id/parent"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:src="@mipmap/ic_launcher"
android:layout_width=" wrap_content"
android:layout_height=" wrap_content" />
<TextView
android:id="@+id/textChanger"
android:layout_margin="20dp"
android:textAlignment="center"
android:text="Initial text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken Image view and text view. When a user clicks on Text view, Image will rotate to the 20-degree angle.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
TextView textChanger;
ImageView imageView;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
textChanger = findViewById(R.id.textChanger);
imageView=findViewById(R.id.imageView);
textChanger.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
roateImage(imageView);
}
});
}
private void roateImage(ImageView imageView) {
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);
imageView.setImageMatrix(matrix);
}
}
In the above code, we have to used roateImage() and passed imageview as shown below -
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);
imageView.setImageMatrix(matrix);
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above code, it is a default screen. When user click on "initial text" text view, it will rotate 20 degrees as shown below -
Click here to download the project code
|
[
{
"code": null,
"e": 1135,
"s": 1062,
"text": "This example demonstrates how to Rotate image in image view by an angle."
},
{
"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": 2131,
"s": 1329,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/parent\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:gravity=\"center\"\n android:orientation=\"vertical\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:src=\"@mipmap/ic_launcher\"\n android:layout_width=\" wrap_content\"\n android:layout_height=\" wrap_content\" />\n <TextView\n android:id=\"@+id/textChanger\"\n android:layout_margin=\"20dp\"\n android:textAlignment=\"center\"\n android:text=\"Initial text\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2265,
"s": 2131,
"text": "In the above code, we have taken Image view and text view. When a user clicks on Text view, Image will rotate to the 20-degree angle."
},
{
"code": null,
"e": 2322,
"s": 2265,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3645,
"s": 2322,
"text": "package com.example.andy.myapplication;\nimport android.graphics.Bitmap;\nimport android.graphics.Matrix;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ImageView;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n TextView textChanger;\n ImageView imageView;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n textChanger = findViewById(R.id.textChanger);\n imageView=findViewById(R.id.imageView);\n textChanger.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n roateImage(imageView);\n }\n });\n }\n private void roateImage(ImageView imageView) {\n Matrix matrix = new Matrix();\n imageView.setScaleType(ImageView.ScaleType.MATRIX); //required\n matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);\n imageView.setImageMatrix(matrix);\n }\n}"
},
{
"code": null,
"e": 3731,
"s": 3645,
"text": "In the above code, we have to used roateImage() and passed imageview as shown below -"
},
{
"code": null,
"e": 3984,
"s": 3731,
"text": "Matrix matrix = new Matrix();\nimageView.setScaleType(ImageView.ScaleType.MATRIX); //required\nmatrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);\nimageView.setImageMatrix(matrix);"
},
{
"code": null,
"e": 4335,
"s": 3984,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4466,
"s": 4335,
"text": "In the above code, it is a default screen. When user click on \"initial text\" text view, it will rotate 20 degrees as shown below -"
},
{
"code": null,
"e": 4506,
"s": 4466,
"text": "Click here to download the project code"
}
] |
C++ program to demonstrate exception handling
|
Suppose there is a function that calculates some serious complex mathematical operations. But during the operations, some exceptions can occur. We have to handle the different types of exceptions that can occur and perform the following.
If the computer is unable to allocate the memory for computation, we have to print 'Memory Low!'
If any other C++-related exception occurs, we have to print 'Exception:' then the exception.
If something else happens, we print 'Unhandled exception'.
We are given an array that contains a pair of values, and we pass it to the function. If any exception occurs, we handle it, or otherwise, we print the output value.
We only have to handle the exceptions disregarding the mechanisms of the function generating the exceptions.
So, if the input is like arr = {{361643035132, 2297873642249}, {-17, 15}};, then the output will be −
Memory Low!
Exception: val1 is negative
The first pair of values is too large to be handled, so 'Memory low' is printed. The first value of the second pair is negative. The function provided cannot work with that so it generates/throws an exception 'val1 is negative',
To solve this, we will follow these steps −
for initialize i := 0, when i < t, update (increase i by 1), do −val1 := values[i, 0]val2 := values[i, 1]try,print(foo(val1, val2))if the memory can not be allocated (bad_alloc exception is caught), thenprint("Memory Low!")otherwise, if any other standard C++ exception e is caught, thenprint("Exception: ")print details of the exceptionotherwise if any other exception is caught, thenprint("Unhandled Exception")
val1 := values[i, 0]
val2 := values[i, 1]
try,print(foo(val1, val2))
print(foo(val1, val2))
if the memory can not be allocated (bad_alloc exception is caught), thenprint("Memory Low!")
print("Memory Low!")
otherwise, if any other standard C++ exception e is caught, thenprint("Exception: ")print details of the exception
print("Exception: ")
print details of the exception
otherwise if any other exception is caught, thenprint("Unhandled Exception")
print("Unhandled Exception")
Let us see the following implementation to get better understanding −
#include <iostream>
#include <exception>
#include <string>
#include <stdexcept>
#include <vector>
#include <cmath>
using namespace std;
class Solution {
private:
static int value;
public:
static int foo(long long val1, long long val2) {
value += 1;
if(val1 < 0) {
throw std::invalid_argument("val1 is negative");
}
vector<int> vectorList(val1, 0);
int r = -1, c = sqrt(-1);
if(val2 == 0) throw 0;
r = (val1 / val2) * r;
int ans = vectorList.at(val2);
return r + val1 - val2 * ans;
}
static int getVal() {
return value;
}
};
int Solution::value = 0;
void solve(int t, long int values[][2]) {
for (int i = 0; i < t; i++) {
long long val1, val2;
val1 = values[i][0];
val2 = values[i][1];
try {
cout << Solution::foo(val1, val2) << '\n';
}
catch (const std::bad_alloc&) {
cout << "Memory Low!\n";
}
catch (const std::exception& e) {
cout << "Exception: " << e.what() << '\n';
}
catch (...) {
cout << "Unhandled Exception\n";
}
}
}
int main() {
long int arr[][2] = {{361643035132, 2297873642249}, {-17, 15}};
solve(2, arr);
}
long int arr[][2] = {{361643035132, 2297873642249}, {-17, 15}};
solve(2, arr);
Memory Low!
Exception: val1 is negative
|
[
{
"code": null,
"e": 1300,
"s": 1062,
"text": "Suppose there is a function that calculates some serious complex mathematical operations. But during the operations, some exceptions can occur. We have to handle the different types of exceptions that can occur and perform the following."
},
{
"code": null,
"e": 1397,
"s": 1300,
"text": "If the computer is unable to allocate the memory for computation, we have to print 'Memory Low!'"
},
{
"code": null,
"e": 1490,
"s": 1397,
"text": "If any other C++-related exception occurs, we have to print 'Exception:' then the exception."
},
{
"code": null,
"e": 1549,
"s": 1490,
"text": "If something else happens, we print 'Unhandled exception'."
},
{
"code": null,
"e": 1715,
"s": 1549,
"text": "We are given an array that contains a pair of values, and we pass it to the function. If any exception occurs, we handle it, or otherwise, we print the output value."
},
{
"code": null,
"e": 1824,
"s": 1715,
"text": "We only have to handle the exceptions disregarding the mechanisms of the function generating the exceptions."
},
{
"code": null,
"e": 1926,
"s": 1824,
"text": "So, if the input is like arr = {{361643035132, 2297873642249}, {-17, 15}};, then the output will be −"
},
{
"code": null,
"e": 1966,
"s": 1926,
"text": "Memory Low!\nException: val1 is negative"
},
{
"code": null,
"e": 2195,
"s": 1966,
"text": "The first pair of values is too large to be handled, so 'Memory low' is printed. The first value of the second pair is negative. The function provided cannot work with that so it generates/throws an exception 'val1 is negative',"
},
{
"code": null,
"e": 2239,
"s": 2195,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 2653,
"s": 2239,
"text": "for initialize i := 0, when i < t, update (increase i by 1), do −val1 := values[i, 0]val2 := values[i, 1]try,print(foo(val1, val2))if the memory can not be allocated (bad_alloc exception is caught), thenprint(\"Memory Low!\")otherwise, if any other standard C++ exception e is caught, thenprint(\"Exception: \")print details of the exceptionotherwise if any other exception is caught, thenprint(\"Unhandled Exception\")"
},
{
"code": null,
"e": 2674,
"s": 2653,
"text": "val1 := values[i, 0]"
},
{
"code": null,
"e": 2695,
"s": 2674,
"text": "val2 := values[i, 1]"
},
{
"code": null,
"e": 2722,
"s": 2695,
"text": "try,print(foo(val1, val2))"
},
{
"code": null,
"e": 2745,
"s": 2722,
"text": "print(foo(val1, val2))"
},
{
"code": null,
"e": 2838,
"s": 2745,
"text": "if the memory can not be allocated (bad_alloc exception is caught), thenprint(\"Memory Low!\")"
},
{
"code": null,
"e": 2859,
"s": 2838,
"text": "print(\"Memory Low!\")"
},
{
"code": null,
"e": 2974,
"s": 2859,
"text": "otherwise, if any other standard C++ exception e is caught, thenprint(\"Exception: \")print details of the exception"
},
{
"code": null,
"e": 2995,
"s": 2974,
"text": "print(\"Exception: \")"
},
{
"code": null,
"e": 3026,
"s": 2995,
"text": "print details of the exception"
},
{
"code": null,
"e": 3103,
"s": 3026,
"text": "otherwise if any other exception is caught, thenprint(\"Unhandled Exception\")"
},
{
"code": null,
"e": 3132,
"s": 3103,
"text": "print(\"Unhandled Exception\")"
},
{
"code": null,
"e": 3202,
"s": 3132,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 4423,
"s": 3202,
"text": "#include <iostream>\n#include <exception>\n#include <string>\n#include <stdexcept>\n#include <vector>\n#include <cmath>\nusing namespace std;\n\nclass Solution {\nprivate:\n static int value;\npublic:\n static int foo(long long val1, long long val2) {\n value += 1;\n if(val1 < 0) {\n throw std::invalid_argument(\"val1 is negative\");\n }\n vector<int> vectorList(val1, 0);\n int r = -1, c = sqrt(-1);\n if(val2 == 0) throw 0;\n r = (val1 / val2) * r;\n int ans = vectorList.at(val2);\n return r + val1 - val2 * ans;\n }\n static int getVal() {\n return value;\n }\n};\nint Solution::value = 0;\n\nvoid solve(int t, long int values[][2]) {\n for (int i = 0; i < t; i++) {\n long long val1, val2;\n val1 = values[i][0];\n val2 = values[i][1];\n try {\n cout << Solution::foo(val1, val2) << '\\n';\n }\n catch (const std::bad_alloc&) {\n cout << \"Memory Low!\\n\";\n }\n catch (const std::exception& e) {\n cout << \"Exception: \" << e.what() << '\\n';\n }\n catch (...) {\n cout << \"Unhandled Exception\\n\";\n }\n }\n}\nint main() {\n long int arr[][2] = {{361643035132, 2297873642249}, {-17, 15}};\n solve(2, arr);\n}"
},
{
"code": null,
"e": 4502,
"s": 4423,
"text": "long int arr[][2] = {{361643035132, 2297873642249}, {-17, 15}};\nsolve(2, arr);"
},
{
"code": null,
"e": 4542,
"s": 4502,
"text": "Memory Low!\nException: val1 is negative"
}
] |
How to filter object array based on attributes in jQuery?
|
To filter object array based on attributes in jQuery, use the map() method with JSON.
You can try to run the following code to learn how to filter object array based on attributes in jQuery,
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).ready(function(){
var json ={"DEPARTMENT": [
{
"id":"1",
"deptemp":"840",
"shares":"1100",
},
{
"id":"2",
"deptemp":"1010",
"shares":"1900",
}, {
"id":"1",
"deptemp":"350",
"shares":"510",
},
{
"id":"2",
"deptemp":"575",
"shares":"1900",
}]};
json.DEPARTMENT = $.map(json.DEPARTMENT,function(val,key) {
if(Number(val.deptemp) <= 500 && Number(val.shares) >= 500) return val;
});
for(var i in json.DEPARTMENT)
$("p").html("Department Employees: "+json.DEPARTMENT[i].deptemp+" , Shares:"+json.DEPARTMENT[i].shares)
});
});
</script>
</head>
<body>
<p></p>
<div></div>
</body>
</html>
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "To filter object array based on attributes in jQuery, use the map() method with JSON."
},
{
"code": null,
"e": 1253,
"s": 1148,
"text": "You can try to run the following code to learn how to filter object array based on attributes in jQuery,"
},
{
"code": null,
"e": 1263,
"s": 1253,
"text": "Live Demo"
},
{
"code": null,
"e": 2377,
"s": 1263,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(document).ready(function(){\n var json ={\"DEPARTMENT\": [\n {\n \"id\":\"1\",\n \"deptemp\":\"840\",\n \"shares\":\"1100\",\n \n },\n {\n \"id\":\"2\",\n \"deptemp\":\"1010\",\n \"shares\":\"1900\", \n }, {\n \"id\":\"1\",\n \"deptemp\":\"350\",\n \"shares\":\"510\",\n },\n {\n \"id\":\"2\",\n \"deptemp\":\"575\",\n \"shares\":\"1900\",\n }]};\n\n json.DEPARTMENT = $.map(json.DEPARTMENT,function(val,key) {\n if(Number(val.deptemp) <= 500 && Number(val.shares) >= 500) return val;\n });\n \n for(var i in json.DEPARTMENT)\n $(\"p\").html(\"Department Employees: \"+json.DEPARTMENT[i].deptemp+\" , Shares:\"+json.DEPARTMENT[i].shares)\n });\n});\n</script>\n</head>\n<body>\n\n<p></p>\n<div></div>\n\n</body>\n</html>"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.