title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Collect.js contains() Method - GeeksforGeeks | 29 Jul, 2020
The contains() method is used to determines whether the collection contains a given item or not. If it contains the item then it returns true otherwise false. The JavaScript array is first transformed into a collection and then the function is applied to the collection.
Syntax:
collect(array).contains(item)
Parameters: This method accepts single parameter i.e. converted into the collection and then contains() function take an item to be searched.
Return Value: Returns a boolean value.
Below examples illustrate the contains() method in Collect.js:
Example 1: Here collect = require(‘collect.js’) is used to import the collect.js library into the file.
Javascript
const collect = require('collect.js'); let arr = [1, 2, 3]; // Convert array into collection const collection = collect(arr); // item to searchedlet item = 3; let newObject = collection.contains(item); console.log("Result : ", newObject);
Output:
Result : true
Example 2:
Javascript
const collect = require('collect.js'); let arr = [1, 2, 3] // Convert array into collection const collection = collect(arr); // concate the arraylet concatarr = collection.concat(['a', 'b', 'c']); // concate the objectconcatarr = concatarr.concat({ first : "GeeksforGeeks", second : "Collect.js"}); // item to searchedlet item = "GeeksforGeek"; let newObject = collection.contains(item); console.log("Result : ", newObject);
Output:
Result : false
Reference: https://collect.js.org/api/contains.html
Collect.js
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 calculate the number of days between two dates in 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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 24869,
"s": 24841,
"text": "\n29 Jul, 2020"
},
{
"code": null,
"e": 25140,
"s": 24869,
"text": "The contains() method is used to determines whether the collection contains a given item or not. If it contains the item then it returns true otherwise false. The JavaScript array is first transformed into a collection and then the function is applied to the collection."
},
{
"code": null,
"e": 25150,
"s": 25140,
"text": "Syntax: "
},
{
"code": null,
"e": 25180,
"s": 25150,
"text": "collect(array).contains(item)"
},
{
"code": null,
"e": 25322,
"s": 25180,
"text": "Parameters: This method accepts single parameter i.e. converted into the collection and then contains() function take an item to be searched."
},
{
"code": null,
"e": 25361,
"s": 25322,
"text": "Return Value: Returns a boolean value."
},
{
"code": null,
"e": 25424,
"s": 25361,
"text": "Below examples illustrate the contains() method in Collect.js:"
},
{
"code": null,
"e": 25528,
"s": 25424,
"text": "Example 1: Here collect = require(‘collect.js’) is used to import the collect.js library into the file."
},
{
"code": null,
"e": 25539,
"s": 25528,
"text": "Javascript"
},
{
"code": "const collect = require('collect.js'); let arr = [1, 2, 3]; // Convert array into collection const collection = collect(arr); // item to searchedlet item = 3; let newObject = collection.contains(item); console.log(\"Result : \", newObject);",
"e": 25802,
"s": 25539,
"text": null
},
{
"code": null,
"e": 25810,
"s": 25802,
"text": "Output:"
},
{
"code": null,
"e": 25825,
"s": 25810,
"text": "Result : true"
},
{
"code": null,
"e": 25836,
"s": 25825,
"text": "Example 2:"
},
{
"code": null,
"e": 25847,
"s": 25836,
"text": "Javascript"
},
{
"code": "const collect = require('collect.js'); let arr = [1, 2, 3] // Convert array into collection const collection = collect(arr); // concate the arraylet concatarr = collection.concat(['a', 'b', 'c']); // concate the objectconcatarr = concatarr.concat({ first : \"GeeksforGeeks\", second : \"Collect.js\"}); // item to searchedlet item = \"GeeksforGeek\"; let newObject = collection.contains(item); console.log(\"Result : \", newObject);",
"e": 26306,
"s": 25847,
"text": null
},
{
"code": null,
"e": 26314,
"s": 26306,
"text": "Output:"
},
{
"code": null,
"e": 26329,
"s": 26314,
"text": "Result : false"
},
{
"code": null,
"e": 26381,
"s": 26329,
"text": "Reference: https://collect.js.org/api/contains.html"
},
{
"code": null,
"e": 26392,
"s": 26381,
"text": "Collect.js"
},
{
"code": null,
"e": 26403,
"s": 26392,
"text": "JavaScript"
},
{
"code": null,
"e": 26420,
"s": 26403,
"text": "Web Technologies"
},
{
"code": null,
"e": 26518,
"s": 26420,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26558,
"s": 26518,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26603,
"s": 26558,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26664,
"s": 26603,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26736,
"s": 26664,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26805,
"s": 26736,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 26845,
"s": 26805,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26878,
"s": 26845,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26923,
"s": 26878,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26966,
"s": 26923,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Replace Inf with NA in Dataframe in R - GeeksforGeeks | 27 Sep, 2021
In this article, we will discuss how to replace Inf (Infinity) with NA in Dataframe in R Programming Language.
Create a dataframe with for demonstration:
R
# create a dataframe with 3 columns and 5 rowsdata=data.frame(column1 = c(Inf, 2, 3, 4, 5), column2 = c(1, Inf, 1, Inf, 1), column3 = c(1,2,3,Inf,Inf)) # display dataframeprint(data)
Output:
So we can replace Inf with NA by using lapply() function, we have to create our own function to replace Inf with NA and then pass that function to lapply() through do.call method.
Function Syntax:
function(value)
replace(value, is.infinite(value),
NA)
Where value is the input value and replace() is used to replace the value to NA if it is infinite.
R
# create a dataframe with 3 columns and 5 rowsdata=data.frame(column1 = c(Inf, 2, 3, 4, 5), column2= c(1, Inf, 1, Inf, 1), column3=c(1,2,3,Inf,Inf)) # actual dataframeprint(data) # replace inf with NAfinal=do.call(data.frame, lapply (data, function(value) replace (value, is.infinite(value),NA))) # displayprint(final)
Output:
R
# create a dataframe with 5 columns and 5 rowsdata=data.frame(column1 = c(Inf, 2, 3, 4, 5), column2= c(1, Inf, 1, Inf, 1), column3=c(1,2,3,Inf,Inf), column4=c(Inf,Inf,Inf,3,4), column5=c(1,2,3,4,Inf)) # actual dataframeprint(data) # replace inf with NAfinal=do.call(data.frame,lapply (data, function(value) replace (value, is.infinite(value),NA))) # displayprint(final)
Output:
anikakapoor
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R | [
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 24962,
"s": 24851,
"text": "In this article, we will discuss how to replace Inf (Infinity) with NA in Dataframe in R Programming Language."
},
{
"code": null,
"e": 25005,
"s": 24962,
"text": "Create a dataframe with for demonstration:"
},
{
"code": null,
"e": 25007,
"s": 25005,
"text": "R"
},
{
"code": "# create a dataframe with 3 columns and 5 rowsdata=data.frame(column1 = c(Inf, 2, 3, 4, 5), column2 = c(1, Inf, 1, Inf, 1), column3 = c(1,2,3,Inf,Inf)) # display dataframeprint(data)",
"e": 25221,
"s": 25007,
"text": null
},
{
"code": null,
"e": 25229,
"s": 25221,
"text": "Output:"
},
{
"code": null,
"e": 25409,
"s": 25229,
"text": "So we can replace Inf with NA by using lapply() function, we have to create our own function to replace Inf with NA and then pass that function to lapply() through do.call method."
},
{
"code": null,
"e": 25426,
"s": 25409,
"text": "Function Syntax:"
},
{
"code": null,
"e": 25483,
"s": 25426,
"text": "function(value) \nreplace(value, is.infinite(value), \nNA)"
},
{
"code": null,
"e": 25582,
"s": 25483,
"text": "Where value is the input value and replace() is used to replace the value to NA if it is infinite."
},
{
"code": null,
"e": 25584,
"s": 25582,
"text": "R"
},
{
"code": "# create a dataframe with 3 columns and 5 rowsdata=data.frame(column1 = c(Inf, 2, 3, 4, 5), column2= c(1, Inf, 1, Inf, 1), column3=c(1,2,3,Inf,Inf)) # actual dataframeprint(data) # replace inf with NAfinal=do.call(data.frame, lapply (data, function(value) replace (value, is.infinite(value),NA))) # displayprint(final)",
"e": 25960,
"s": 25584,
"text": null
},
{
"code": null,
"e": 25968,
"s": 25960,
"text": "Output:"
},
{
"code": null,
"e": 25970,
"s": 25968,
"text": "R"
},
{
"code": "# create a dataframe with 5 columns and 5 rowsdata=data.frame(column1 = c(Inf, 2, 3, 4, 5), column2= c(1, Inf, 1, Inf, 1), column3=c(1,2,3,Inf,Inf), column4=c(Inf,Inf,Inf,3,4), column5=c(1,2,3,4,Inf)) # actual dataframeprint(data) # replace inf with NAfinal=do.call(data.frame,lapply (data, function(value) replace (value, is.infinite(value),NA))) # displayprint(final)",
"e": 26427,
"s": 25970,
"text": null
},
{
"code": null,
"e": 26435,
"s": 26427,
"text": "Output:"
},
{
"code": null,
"e": 26447,
"s": 26435,
"text": "anikakapoor"
},
{
"code": null,
"e": 26454,
"s": 26447,
"text": "Picked"
},
{
"code": null,
"e": 26475,
"s": 26454,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 26487,
"s": 26475,
"text": "R-DataFrame"
},
{
"code": null,
"e": 26498,
"s": 26487,
"text": "R Language"
},
{
"code": null,
"e": 26509,
"s": 26498,
"text": "R Programs"
},
{
"code": null,
"e": 26607,
"s": 26509,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26616,
"s": 26607,
"text": "Comments"
},
{
"code": null,
"e": 26629,
"s": 26616,
"text": "Old Comments"
},
{
"code": null,
"e": 26681,
"s": 26629,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26719,
"s": 26681,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26754,
"s": 26719,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26812,
"s": 26754,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 26861,
"s": 26812,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 26919,
"s": 26861,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 26968,
"s": 26919,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27011,
"s": 26968,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27061,
"s": 27011,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
The Beginner’s Guide to Acing SQL Interviews for Data Scientists | by Pedram Ataee, PhD | Towards Data Science | At most data science interviews, your SQL skill will be examined in some way. You must write some SQL queries in your technical interviews and many of them in your day-to-day job. It does not matter whether you work at a small or a big company, SQL programming is an important tool in your toolbox. You can use SQL programming to work with small and huge datasets especially with advanced query engines such as Spark SQL.
Spark (an open-source unified analytics engine for large-scale data processing) has a module named Spark SQL (a distributed SQL query engine) that lets you manage SQL queries in big data efficiently. Databricks, one of the top growing enterprise software to manage data warehouses, has a user-friendly environment to set up Spark SQL engines. So be prepared to learn SQL programming soon in your career.
A data science interview usually has three technical steps: SQL programming, ML development, and an onsite technical interview. The SQL programming and ML development steps are pretty standard these days. The onsite interview varies across different companies. In this article, I aim to help you ace the SQL programming interview.
If you find this article useful, you can subscribe through the link below. This will help me to create high-quality content for you.
pedram-ataee.medium.com
The structure of this article is as follows:
What are the basics of SQL coding?
A simple example of a SQL problem
A useful technique: “parametrized query”
Last Words
Let’s start.
You should learn the basics of SQL programming from any resource that you are comfortable with. I learned a lot from w3school website, and I highly recommend it check it out later.
The SELECT statement is used to extract data from a database as follows SELECT column1_name FROM table_name. You can also use * after SELECT if you want to extract everything in the database. The SELECT DISTINCT statement can be used to extract unique values. A column often contains many duplicate values, and sometimes you only need to extract the unique or distinct values.
The WHERE statement is used to filter records from a database as follows SELECT column1_name FROM table_name WHERE condition;It returns only those records that fulfill the condition written after that. You can use various operators in the condition such as: >, =, IN , LIKE , or BETWEEN . You can also combine several conditions with AND, OR, and NOT operators to narrow down the filter.
The ORDER BY statement is used to sort the result in ascending ASC or descending DESC order. By default, it sorts the records in ascending order though. You can try the following code to extract everything from a table ordered by column1_name and column2_name : SELECT * FROM table_name ORDER BY column1_name ASC, columne2_name DESC
The COUNT() function returns the number of rows that matches a specified criterion as follows: SELECT COUNT(column_name) FROM table_name WHERE condition; You can try other SQL functions, instead of COUNT, such as AVG or SUM to return the average value or the total sum of a numeric column.
The GROUP BY statement extracts rows that have the same values in a column and groups them into summary rows, like "find the number of students in each school". The GROUP BY statement is often used with aggregate functions such as COUNT(), MAX(), MIN(), SUM(), AVG() to group the results. You can check the code below.
SELECT column_name(s)FROM table_nameWHERE conditionGROUP BY column_name(s)ORDER BY column_name(s);
There are more SQL commands that you can learn from w3school such as JOIN or CASE . A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Or, the CASE statement goes through several conditions and returns a value when the first condition is met exactly similar to if-then-else statement in other programming languages.
The problem below is taken from Leetcode, a fantastic website where you can practice your coding skills. You can find many more problems on that website.
Problem: We have a table named Activity that contains 4 fields from a series of gamers: palyer_id, device_id, event_date and games_played. Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using the same device. Write an SQL query that reports the first login date for each player.
Solution: As you can see, the solution uses commands that you learn above.
SELECT player_id MIN(event_date) AS first_loginFROM ActivityGROUP BY player_id
When you must write a large number of similar queries, you can use a technique called “parameterized query”. This will help you write more efficient code and also show your expertise in programming. Here, I describe how to write parameterized SQL queries using Python.
Let’s say you want to write a COUNT query that can be used with different fields and tables. In this case, you can save part 1 in the code below under, for example, count.txt . Then, you must parse (load and fill) the parameterized query in Python using part 2, the code coming right after.
------------------------------------------------------# PART 1 (SQL) - PARAMETRIZED QUERY saved as count.txt------------------------------------------------------SELECT {var}, count({var}) as countFROM {table_name}GROUP BY {var}ORDER BY count DESC---------------------------------# PART 2 (PYTHON) - QUERY PARSER ---------------------------------class Query: def __init__(self, table_name, var): self.table_name = table_name self.var = var self.parsed = None def parser(self): file_path_query = os.path.join(FILE_DIR, 'count.txt') with open(file_path_query, 'r') as file: template = file.read().replace('\n', ' ') self.parsed = template.format(table_name=self.table_name, var=self.var)
towardsdatascience.com
A SQL programming interview can be live or offline. If it is offline, you will be evaluated based on whether your code is executable or not. Otherwise, you will be evaluated based on the code quality in general and how well you can communicate. Let’s dig into each of them.
The interviewers will judge your code quality (and, certainly not you!) based on several angles. First, they want to see whether the code is executable without any syntax error. Then, they check whether your code is clean and concise. Third, the interviewer checks whether you considered edge cases. If you can not write clean code or consider edge cases in a timebox, make sure to be aware of the best practices and share them with your interviewer. In the end, they check whether your solution is optimized in terms of efficiency. For example, you could get the same result using one Join or using three Join. The former is more optimized.
In every interview, it is important to have effective communication with your interviewer. What does effective communication mean though? The first step in effective communication is to clearly share your thought process with your interviewer before diving into coding. Plus, you must be able to elaborate your reasoning for each choice of yours. I can not emphasize more how important is the power of sharing thought processes and elaboration on reasoning. I can work with a person whose code is not executable in the coding interview but can not work with whom fail on communication.
If you like this post and want to support me...
Follow me on Medium!
Check out my books on Amazon!
Become a member on Medium!
Connect on Linkedin!
Follow me on Twitter! | [
{
"code": null,
"e": 468,
"s": 46,
"text": "At most data science interviews, your SQL skill will be examined in some way. You must write some SQL queries in your technical interviews and many of them in your day-to-day job. It does not matter whether you work at a small or a big company, SQL programming is an important tool in your toolbox. You can use SQL programming to work with small and huge datasets especially with advanced query engines such as Spark SQL."
},
{
"code": null,
"e": 872,
"s": 468,
"text": "Spark (an open-source unified analytics engine for large-scale data processing) has a module named Spark SQL (a distributed SQL query engine) that lets you manage SQL queries in big data efficiently. Databricks, one of the top growing enterprise software to manage data warehouses, has a user-friendly environment to set up Spark SQL engines. So be prepared to learn SQL programming soon in your career."
},
{
"code": null,
"e": 1203,
"s": 872,
"text": "A data science interview usually has three technical steps: SQL programming, ML development, and an onsite technical interview. The SQL programming and ML development steps are pretty standard these days. The onsite interview varies across different companies. In this article, I aim to help you ace the SQL programming interview."
},
{
"code": null,
"e": 1336,
"s": 1203,
"text": "If you find this article useful, you can subscribe through the link below. This will help me to create high-quality content for you."
},
{
"code": null,
"e": 1360,
"s": 1336,
"text": "pedram-ataee.medium.com"
},
{
"code": null,
"e": 1405,
"s": 1360,
"text": "The structure of this article is as follows:"
},
{
"code": null,
"e": 1440,
"s": 1405,
"text": "What are the basics of SQL coding?"
},
{
"code": null,
"e": 1474,
"s": 1440,
"text": "A simple example of a SQL problem"
},
{
"code": null,
"e": 1515,
"s": 1474,
"text": "A useful technique: “parametrized query”"
},
{
"code": null,
"e": 1526,
"s": 1515,
"text": "Last Words"
},
{
"code": null,
"e": 1539,
"s": 1526,
"text": "Let’s start."
},
{
"code": null,
"e": 1720,
"s": 1539,
"text": "You should learn the basics of SQL programming from any resource that you are comfortable with. I learned a lot from w3school website, and I highly recommend it check it out later."
},
{
"code": null,
"e": 2097,
"s": 1720,
"text": "The SELECT statement is used to extract data from a database as follows SELECT column1_name FROM table_name. You can also use * after SELECT if you want to extract everything in the database. The SELECT DISTINCT statement can be used to extract unique values. A column often contains many duplicate values, and sometimes you only need to extract the unique or distinct values."
},
{
"code": null,
"e": 2485,
"s": 2097,
"text": "The WHERE statement is used to filter records from a database as follows SELECT column1_name FROM table_name WHERE condition;It returns only those records that fulfill the condition written after that. You can use various operators in the condition such as: >, =, IN , LIKE , or BETWEEN . You can also combine several conditions with AND, OR, and NOT operators to narrow down the filter."
},
{
"code": null,
"e": 2818,
"s": 2485,
"text": "The ORDER BY statement is used to sort the result in ascending ASC or descending DESC order. By default, it sorts the records in ascending order though. You can try the following code to extract everything from a table ordered by column1_name and column2_name : SELECT * FROM table_name ORDER BY column1_name ASC, columne2_name DESC"
},
{
"code": null,
"e": 3108,
"s": 2818,
"text": "The COUNT() function returns the number of rows that matches a specified criterion as follows: SELECT COUNT(column_name) FROM table_name WHERE condition; You can try other SQL functions, instead of COUNT, such as AVG or SUM to return the average value or the total sum of a numeric column."
},
{
"code": null,
"e": 3427,
"s": 3108,
"text": "The GROUP BY statement extracts rows that have the same values in a column and groups them into summary rows, like \"find the number of students in each school\". The GROUP BY statement is often used with aggregate functions such as COUNT(), MAX(), MIN(), SUM(), AVG() to group the results. You can check the code below."
},
{
"code": null,
"e": 3526,
"s": 3427,
"text": "SELECT column_name(s)FROM table_nameWHERE conditionGROUP BY column_name(s)ORDER BY column_name(s);"
},
{
"code": null,
"e": 3894,
"s": 3526,
"text": "There are more SQL commands that you can learn from w3school such as JOIN or CASE . A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Or, the CASE statement goes through several conditions and returns a value when the first condition is met exactly similar to if-then-else statement in other programming languages."
},
{
"code": null,
"e": 4048,
"s": 3894,
"text": "The problem below is taken from Leetcode, a fantastic website where you can practice your coding skills. You can find many more problems on that website."
},
{
"code": null,
"e": 4399,
"s": 4048,
"text": "Problem: We have a table named Activity that contains 4 fields from a series of gamers: palyer_id, device_id, event_date and games_played. Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using the same device. Write an SQL query that reports the first login date for each player."
},
{
"code": null,
"e": 4474,
"s": 4399,
"text": "Solution: As you can see, the solution uses commands that you learn above."
},
{
"code": null,
"e": 4560,
"s": 4474,
"text": "SELECT player_id MIN(event_date) AS first_loginFROM ActivityGROUP BY player_id"
},
{
"code": null,
"e": 4829,
"s": 4560,
"text": "When you must write a large number of similar queries, you can use a technique called “parameterized query”. This will help you write more efficient code and also show your expertise in programming. Here, I describe how to write parameterized SQL queries using Python."
},
{
"code": null,
"e": 5120,
"s": 4829,
"text": "Let’s say you want to write a COUNT query that can be used with different fields and tables. In this case, you can save part 1 in the code below under, for example, count.txt . Then, you must parse (load and fill) the parameterized query in Python using part 2, the code coming right after."
},
{
"code": null,
"e": 5902,
"s": 5120,
"text": "------------------------------------------------------# PART 1 (SQL) - PARAMETRIZED QUERY saved as count.txt------------------------------------------------------SELECT {var}, count({var}) as countFROM {table_name}GROUP BY {var}ORDER BY count DESC---------------------------------# PART 2 (PYTHON) - QUERY PARSER ---------------------------------class Query: def __init__(self, table_name, var): self.table_name = table_name self.var = var self.parsed = None def parser(self): file_path_query = os.path.join(FILE_DIR, 'count.txt') with open(file_path_query, 'r') as file: template = file.read().replace('\\n', ' ') self.parsed = template.format(table_name=self.table_name, var=self.var)"
},
{
"code": null,
"e": 5925,
"s": 5902,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6199,
"s": 5925,
"text": "A SQL programming interview can be live or offline. If it is offline, you will be evaluated based on whether your code is executable or not. Otherwise, you will be evaluated based on the code quality in general and how well you can communicate. Let’s dig into each of them."
},
{
"code": null,
"e": 6841,
"s": 6199,
"text": "The interviewers will judge your code quality (and, certainly not you!) based on several angles. First, they want to see whether the code is executable without any syntax error. Then, they check whether your code is clean and concise. Third, the interviewer checks whether you considered edge cases. If you can not write clean code or consider edge cases in a timebox, make sure to be aware of the best practices and share them with your interviewer. In the end, they check whether your solution is optimized in terms of efficiency. For example, you could get the same result using one Join or using three Join. The former is more optimized."
},
{
"code": null,
"e": 7427,
"s": 6841,
"text": "In every interview, it is important to have effective communication with your interviewer. What does effective communication mean though? The first step in effective communication is to clearly share your thought process with your interviewer before diving into coding. Plus, you must be able to elaborate your reasoning for each choice of yours. I can not emphasize more how important is the power of sharing thought processes and elaboration on reasoning. I can work with a person whose code is not executable in the coding interview but can not work with whom fail on communication."
},
{
"code": null,
"e": 7475,
"s": 7427,
"text": "If you like this post and want to support me..."
},
{
"code": null,
"e": 7496,
"s": 7475,
"text": "Follow me on Medium!"
},
{
"code": null,
"e": 7526,
"s": 7496,
"text": "Check out my books on Amazon!"
},
{
"code": null,
"e": 7553,
"s": 7526,
"text": "Become a member on Medium!"
},
{
"code": null,
"e": 7574,
"s": 7553,
"text": "Connect on Linkedin!"
}
] |
Arduino - Advanced I/O Function | In this chapter, we will learn some advanced Input and Output Functions.
Configures the reference voltage used for analog input (i.e. the value used as the top of the input range). The options are −
DEFAULT − The default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)
DEFAULT − The default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)
INTERNAL − An built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega)
INTERNAL − An built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega)
INTERNAL1V1 − A built-in 1.1V reference (Arduino Mega only)
INTERNAL1V1 − A built-in 1.1V reference (Arduino Mega only)
INTERNAL2V56 − A built-in 2.56V reference (Arduino Mega only)
INTERNAL2V56 − A built-in 2.56V reference (Arduino Mega only)
EXTERNAL − The voltage applied to the AREF pin (0 to 5V only) is used as the reference
EXTERNAL − The voltage applied to the AREF pin (0 to 5V only) is used as the reference
analogReference (type);
type − can use any type of the follow (DEFAULT, INTERNAL, INTERNAL1V1, INTERNAL2V56, EXTERNAL)
Do not use anything less than 0V or more than 5V for external reference voltage on the AREF pin. If you are using an external reference on the AREF pin, you must set the analog reference to EXTERNAL before calling the analogRead() function. Otherwise, you will short the active reference voltage (internally generated) and the AREF pin, possibly damaging the microcontroller on your Arduino board.
Alternatively, you can connect the external reference voltage to the AREF pin through a 5K resistor, allowing you to switch between external and internal reference voltages.
Note that the resistor will alter the voltage that is used as the reference because there is an internal 32K resistor on the AREF pin. The two act as a voltage divider. For example, 2.5V applied through the resistor will yield 2.5 * 32 / (32 + 5) = ~2.2V at the AREF pin.
Example
int analogPin = 3;// potentiometer wiper (middle terminal) connected to analog pin 3
int val = 0; // variable to store the read value
void setup() {
Serial.begin(9600); // setup serial
analogReference(EXTERNAL); // the voltage applied to the AREF pin (0 to 5V only)
// is used as the reference.
}
void loop() {
val = analogRead(analogPin); // read the input pin
Serial.println(val); // debug value
}
65 Lectures
6.5 hours
Amit Rana
43 Lectures
3 hours
Amit Rana
20 Lectures
2 hours
Ashraf Said
19 Lectures
1.5 hours
Ashraf Said
11 Lectures
47 mins
Ashraf Said
9 Lectures
41 mins
Ashraf Said
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2943,
"s": 2870,
"text": "In this chapter, we will learn some advanced Input and Output Functions."
},
{
"code": null,
"e": 3069,
"s": 2943,
"text": "Configures the reference voltage used for analog input (i.e. the value used as the top of the input range). The options are −"
},
{
"code": null,
"e": 3180,
"s": 3069,
"text": "DEFAULT − The default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)"
},
{
"code": null,
"e": 3291,
"s": 3180,
"text": "DEFAULT − The default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)"
},
{
"code": null,
"e": 3440,
"s": 3291,
"text": "INTERNAL − An built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega)"
},
{
"code": null,
"e": 3589,
"s": 3440,
"text": "INTERNAL − An built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega)"
},
{
"code": null,
"e": 3649,
"s": 3589,
"text": "INTERNAL1V1 − A built-in 1.1V reference (Arduino Mega only)"
},
{
"code": null,
"e": 3709,
"s": 3649,
"text": "INTERNAL1V1 − A built-in 1.1V reference (Arduino Mega only)"
},
{
"code": null,
"e": 3771,
"s": 3709,
"text": "INTERNAL2V56 − A built-in 2.56V reference (Arduino Mega only)"
},
{
"code": null,
"e": 3833,
"s": 3771,
"text": "INTERNAL2V56 − A built-in 2.56V reference (Arduino Mega only)"
},
{
"code": null,
"e": 3920,
"s": 3833,
"text": "EXTERNAL − The voltage applied to the AREF pin (0 to 5V only) is used as the reference"
},
{
"code": null,
"e": 4007,
"s": 3920,
"text": "EXTERNAL − The voltage applied to the AREF pin (0 to 5V only) is used as the reference"
},
{
"code": null,
"e": 4032,
"s": 4007,
"text": "analogReference (type);\n"
},
{
"code": null,
"e": 4127,
"s": 4032,
"text": "type − can use any type of the follow (DEFAULT, INTERNAL, INTERNAL1V1, INTERNAL2V56, EXTERNAL)"
},
{
"code": null,
"e": 4525,
"s": 4127,
"text": "Do not use anything less than 0V or more than 5V for external reference voltage on the AREF pin. If you are using an external reference on the AREF pin, you must set the analog reference to EXTERNAL before calling the analogRead() function. Otherwise, you will short the active reference voltage (internally generated) and the AREF pin, possibly damaging the microcontroller on your Arduino board."
},
{
"code": null,
"e": 4699,
"s": 4525,
"text": "Alternatively, you can connect the external reference voltage to the AREF pin through a 5K resistor, allowing you to switch between external and internal reference voltages."
},
{
"code": null,
"e": 4971,
"s": 4699,
"text": "Note that the resistor will alter the voltage that is used as the reference because there is an internal 32K resistor on the AREF pin. The two act as a voltage divider. For example, 2.5V applied through the resistor will yield 2.5 * 32 / (32 + 5) = ~2.2V at the AREF pin."
},
{
"code": null,
"e": 4979,
"s": 4971,
"text": "Example"
},
{
"code": null,
"e": 5401,
"s": 4979,
"text": "int analogPin = 3;// potentiometer wiper (middle terminal) connected to analog pin 3 \nint val = 0; // variable to store the read value\n\nvoid setup() {\n Serial.begin(9600); // setup serial\n analogReference(EXTERNAL); // the voltage applied to the AREF pin (0 to 5V only) \n // is used as the reference.\n}\n\nvoid loop() {\n val = analogRead(analogPin); // read the input pin\n Serial.println(val); // debug value\n}"
},
{
"code": null,
"e": 5436,
"s": 5401,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5447,
"s": 5436,
"text": " Amit Rana"
},
{
"code": null,
"e": 5480,
"s": 5447,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5491,
"s": 5480,
"text": " Amit Rana"
},
{
"code": null,
"e": 5524,
"s": 5491,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5537,
"s": 5524,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5572,
"s": 5537,
"text": "\n 19 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5585,
"s": 5572,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5617,
"s": 5585,
"text": "\n 11 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 5630,
"s": 5617,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5661,
"s": 5630,
"text": "\n 9 Lectures \n 41 mins\n"
},
{
"code": null,
"e": 5674,
"s": 5661,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5681,
"s": 5674,
"text": " Print"
},
{
"code": null,
"e": 5692,
"s": 5681,
"text": " Add Notes"
}
] |
Angular 8 - Reactive Programming | Reactive programming is a programming paradigm dealing with data streams and the propagation of changes. Data streams may be static or dynamic. An example of static data stream is an array or collection of data. It will have an initial quantity and it will not change. An example for dynamic data stream is event emitters. Event emitters emit the data whenever the event happens. Initially, there may be no events but as the time moves on, events happens and it will gets emitted.
Reactive programming enables the data stream to be emitted from one source called Observable and the emitted data stream to be caught by other sources called Observer through a process called subscription. This Observable / Observer pattern or simple Observer pattern greatly simplifies complex change detection and necessary updating in the context of the programming.
JavaScript does not have the built-in support for Reactive Programming. RxJs is a JavaScript Library which enables reactive programming in JavaScript. Angular uses RxJs library extensively to do below mentioned advanced concepts −
Data transfer between components.
HTTP client.
Router.
Reactive forms.
Let us learn reactive programming using RxJs library in this chapter.
As learn earlier, Observable are data sources and they may be static or dynamic. Rxjs provides lot of method to create Observable from common JavaScript Objects. Let us see some of the common methods.
of − Emit any number of values in a sequence and finally emit a complete notification.
const numbers$ = of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Here,
numbers$ is an Observable object, which when subscribed will emit 1 to 10 in a sequence.
numbers$ is an Observable object, which when subscribed will emit 1 to 10 in a sequence.
Dollar sign ($) at the end of the variable is to identify that the variable is Observable.
Dollar sign ($) at the end of the variable is to identify that the variable is Observable.
range − Emit a range of number in sequence.
const numbers$ = range(1,10)
from − Emit array, promise or iterable.
const numbers$ = from([1,2,3,4,5,6,7,8,9,10]);
ajax − Fetch a url through AJAX and then emit the response.
const api$ = ajax({ url: 'https://httpbin.org/delay/1', method: 'POST', headers: { 'Content-Type': 'application/text' }, body: "Hello" });
Here,
https://httpbin.org is a free REST API service which will return the supplied body content in the JSON format as specified below −
{
"args": {},
"data": "Hello",
"files": {},
"form": {},
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
"Host": "httpbin.org", "Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36",
"X-Amzn-Trace-Id": "Root=1-5eeef468-015d8f0c228367109234953c"
},
"origin": "ip address",
"url": "https://httpbin.org/delay/1"
}
fromEvent − Listen to an HTML element’s event and then emit the event and its property whenever the listened event fires.
const clickEvent$ = fromEvent(document.getElementById('counter'), 'click');
Angular internally uses the concept extensively to provide data transfer between components and for reactive forms.
Subscribing to an Observable is quite easy. Every Observable object will have a method, subscribe for the subscription process. Observer need to implement three callback function to subscribe to the Observable object. They are as follows −
next − Receive and process the value emitted from the Observable
next − Receive and process the value emitted from the Observable
error − Error handling callback
error − Error handling callback
complete − Callback function called when all data from Observable are emitted.
complete − Callback function called when all data from Observable are emitted.
Once the three callback functions are defined, Observable’s subscribe method has to be called as specified below −
const numbers$ = from([1,2,3,4,5,6,7,8,9,10]);
// observer
const observer = {
next: (num: number) => { this.numbers.push(num); this.val1 += num },
error: (err: any) => console.log(err),
complete: () => console.log("Observation completed")
};
numbers$.subscribe(observer);
Here,
next − method get the emitted number and then push it into the local variable, this.numbers.
next − method get the emitted number and then push it into the local variable, this.numbers.
next − method also adding the number to local variable, this.val1.
next − method also adding the number to local variable, this.val1.
error − method just writes the error message to console.
error − method just writes the error message to console.
complete − method also writes the completion message to console.
complete − method also writes the completion message to console.
We can skip error and complete method and write only the next method as shown below −
number$.subscribe((num: number) => { this.numbers.push(num); this.val1 += num; });
Rxjs library provides some of the operators to process the data stream. Some of the important operators are as follows −
filter − Enable to filter the data stream using callback function.
const filterFn = filter( (num : number) => num > 5 );
const filteredNumbers$ = filterFn(numbers$);
filteredNumbers$.subscribe( (num : number) => {
this.filteredNumbers.push(num); this.val2 += num } );
map − Enables to map the data stream using callback function and to change the data stream itself.
const mapFn = map( (num : number) => num + num ); const mappedNumbers$ = mappedFn(numbers$);
pipe − Enable two or more operators to be combined.
const filterFn = filter( (num : number) => num > 5 );
const mapFn = map( (num : number) => num + num ); const processedNumbers$ = numbers$.pipe(filterFn, mapFn);
processedNumbers$.subscribe( (num : number) => { this.processedNumbers.push(num); this.val3 += num } );
Let us create a sample application to try out the reaction programming concept learned in this chapter.
Create a new application, reactive using below command −
ng new reactive
Change the directory to our newly created application.
cd reactive
Run the application.
ng serve
Change the AppComponent component code (src/app/app.component.ts) as specified below −
import { Component, OnInit } from '@angular/core'; import { Observable, of, range, from, fromEvent } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { filter, map, catchError } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Reactive programming concept';
numbers : number[] = [];
val1 : number = 0;
filteredNumbers : number[] = [];
val2 : number = 0;
processedNumbers : number[] = [];
val3 : number = 0;
apiMessage : string;
counter : number = 0;
ngOnInit() {
// Observable stream of data Observable<number>
// const numbers$ = of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// const numbers$ = range(1,10);
const numbers$ = from([1,2,3,4,5,6,7,8,9,10]);
// observer
const observer = {
next: (num: number) => {this.numbers.push(num); this.val1 += num },
error: (err: any) => console.log(err),
complete: () => console.log("Observation completed")
};
numbers$.subscribe(observer);
const filterFn = filter( (num : number) => num > 5 );
const filteredNumbers = filterFn(numbers$);
filteredNumbers.subscribe( (num : number) => {this.filteredNumbers.push(num); this.val2 += num } );
const mapFn = map( (num : number) => num + num );
const processedNumbers$ = numbers$.pipe(filterFn, mapFn);
processedNumbers$.subscribe( (num : number) => {this.processedNumbers.push(num); this.val3 += num } );
const api$ = ajax({
url: 'https://httpbin.org/delay/1',
method: 'POST',
headers: {'Content-Type': 'application/text' },
body: "Hello"
});
api$.subscribe(res => this.apiMessage = res.response.data );
const clickEvent$ = fromEvent(document.getElementById('counter'), 'click');
clickEvent$.subscribe( () => this.counter++ );
}
}
Here,
Used of, range, from, ajax and fromEvent methods to created Observable.
Used filter, map and pipe operator methods to process the data stream.
Callback functions catch the emitted data, process it and then store it in component’s local variables.
Change the AppComponent template (src/app/app.component.html) as specified below −
<h1>{{ title }}</h1>
<div>
The summation of numbers ( <span *ngFor="let num of numbers"> {{ num }} </span> ) is {{ val1 }}
</div>
<div>
The summation of filtered numbers ( <span *ngFor="let num of filteredNumbers"> {{ num }} </span> ) is {{ val2 }}
</div>
<div>
The summation of processed numbers ( <span *ngFor="let num of processedNumbers"> {{ num }} </span> ) is {{ val3 }}
</div>
<div>
The response from the API is <em>{{ apiMessage }}</em> </div>
<div>
<a id="counter" href="#">Click here</a> to increment the counter value. The current counter value is {{ counter }}
<div>
Here,
Shown all the local variable processed by Observer callback functions.
Open the browser, http://localhost:4200.
Click the Click here link for five times. For each event, the event will be emitted and forward to the Observer. Observer callback function will be called. The callback function increment the counter for every click and the final result will be as shown below −
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2869,
"s": 2388,
"text": "Reactive programming is a programming paradigm dealing with data streams and the propagation of changes. Data streams may be static or dynamic. An example of static data stream is an array or collection of data. It will have an initial quantity and it will not change. An example for dynamic data stream is event emitters. Event emitters emit the data whenever the event happens. Initially, there may be no events but as the time moves on, events happens and it will gets emitted."
},
{
"code": null,
"e": 3239,
"s": 2869,
"text": "Reactive programming enables the data stream to be emitted from one source called Observable and the emitted data stream to be caught by other sources called Observer through a process called subscription. This Observable / Observer pattern or simple Observer pattern greatly simplifies complex change detection and necessary updating in the context of the programming."
},
{
"code": null,
"e": 3470,
"s": 3239,
"text": "JavaScript does not have the built-in support for Reactive Programming. RxJs is a JavaScript Library which enables reactive programming in JavaScript. Angular uses RxJs library extensively to do below mentioned advanced concepts −"
},
{
"code": null,
"e": 3504,
"s": 3470,
"text": "Data transfer between components."
},
{
"code": null,
"e": 3517,
"s": 3504,
"text": "HTTP client."
},
{
"code": null,
"e": 3525,
"s": 3517,
"text": "Router."
},
{
"code": null,
"e": 3541,
"s": 3525,
"text": "Reactive forms."
},
{
"code": null,
"e": 3611,
"s": 3541,
"text": "Let us learn reactive programming using RxJs library in this chapter."
},
{
"code": null,
"e": 3812,
"s": 3611,
"text": "As learn earlier, Observable are data sources and they may be static or dynamic. Rxjs provides lot of method to create Observable from common JavaScript Objects. Let us see some of the common methods."
},
{
"code": null,
"e": 3899,
"s": 3812,
"text": "of − Emit any number of values in a sequence and finally emit a complete notification."
},
{
"code": null,
"e": 3952,
"s": 3899,
"text": "const numbers$ = of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);\n"
},
{
"code": null,
"e": 3958,
"s": 3952,
"text": "Here,"
},
{
"code": null,
"e": 4047,
"s": 3958,
"text": "numbers$ is an Observable object, which when subscribed will emit 1 to 10 in a sequence."
},
{
"code": null,
"e": 4136,
"s": 4047,
"text": "numbers$ is an Observable object, which when subscribed will emit 1 to 10 in a sequence."
},
{
"code": null,
"e": 4227,
"s": 4136,
"text": "Dollar sign ($) at the end of the variable is to identify that the variable is Observable."
},
{
"code": null,
"e": 4318,
"s": 4227,
"text": "Dollar sign ($) at the end of the variable is to identify that the variable is Observable."
},
{
"code": null,
"e": 4362,
"s": 4318,
"text": "range − Emit a range of number in sequence."
},
{
"code": null,
"e": 4392,
"s": 4362,
"text": "const numbers$ = range(1,10)\n"
},
{
"code": null,
"e": 4432,
"s": 4392,
"text": "from − Emit array, promise or iterable."
},
{
"code": null,
"e": 4480,
"s": 4432,
"text": "const numbers$ = from([1,2,3,4,5,6,7,8,9,10]);\n"
},
{
"code": null,
"e": 4540,
"s": 4480,
"text": "ajax − Fetch a url through AJAX and then emit the response."
},
{
"code": null,
"e": 4680,
"s": 4540,
"text": "const api$ = ajax({ url: 'https://httpbin.org/delay/1', method: 'POST', headers: { 'Content-Type': 'application/text' }, body: \"Hello\" });\n"
},
{
"code": null,
"e": 4686,
"s": 4680,
"text": "Here,"
},
{
"code": null,
"e": 4817,
"s": 4686,
"text": "https://httpbin.org is a free REST API service which will return the supplied body content in the JSON format as specified below −"
},
{
"code": null,
"e": 5602,
"s": 4817,
"text": "{ \n \"args\": {}, \n \"data\": \"Hello\", \n \"files\": {}, \n \"form\": {}, \n \"headers\": { \n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\", \n \"Accept-Encoding\": \"gzip, deflate, br\", \n \"Accept-Language\": \"en-US,en;q=0.9\", \n \"Host\": \"httpbin.org\", \"Sec-Fetch-Dest\": \"document\", \n \"Sec-Fetch-Mode\": \"navigate\", \n \"Sec-Fetch-Site\": \"none\", \n \"Upgrade-Insecure-Requests\": \"1\", \n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36\", \n \"X-Amzn-Trace-Id\": \"Root=1-5eeef468-015d8f0c228367109234953c\" \n }, \n \"origin\": \"ip address\", \n \"url\": \"https://httpbin.org/delay/1\" \n}\n"
},
{
"code": null,
"e": 5724,
"s": 5602,
"text": "fromEvent − Listen to an HTML element’s event and then emit the event and its property whenever the listened event fires."
},
{
"code": null,
"e": 5801,
"s": 5724,
"text": "const clickEvent$ = fromEvent(document.getElementById('counter'), 'click');\n"
},
{
"code": null,
"e": 5917,
"s": 5801,
"text": "Angular internally uses the concept extensively to provide data transfer between components and for reactive forms."
},
{
"code": null,
"e": 6157,
"s": 5917,
"text": "Subscribing to an Observable is quite easy. Every Observable object will have a method, subscribe for the subscription process. Observer need to implement three callback function to subscribe to the Observable object. They are as follows −"
},
{
"code": null,
"e": 6222,
"s": 6157,
"text": "next − Receive and process the value emitted from the Observable"
},
{
"code": null,
"e": 6287,
"s": 6222,
"text": "next − Receive and process the value emitted from the Observable"
},
{
"code": null,
"e": 6319,
"s": 6287,
"text": "error − Error handling callback"
},
{
"code": null,
"e": 6351,
"s": 6319,
"text": "error − Error handling callback"
},
{
"code": null,
"e": 6430,
"s": 6351,
"text": "complete − Callback function called when all data from Observable are emitted."
},
{
"code": null,
"e": 6509,
"s": 6430,
"text": "complete − Callback function called when all data from Observable are emitted."
},
{
"code": null,
"e": 6624,
"s": 6509,
"text": "Once the three callback functions are defined, Observable’s subscribe method has to be called as specified below −"
},
{
"code": null,
"e": 6924,
"s": 6624,
"text": "const numbers$ = from([1,2,3,4,5,6,7,8,9,10]); \n// observer \nconst observer = { \n next: (num: number) => { this.numbers.push(num); this.val1 += num }, \n error: (err: any) => console.log(err), \n complete: () => console.log(\"Observation completed\") \n}; \nnumbers$.subscribe(observer);\n"
},
{
"code": null,
"e": 6930,
"s": 6924,
"text": "Here,"
},
{
"code": null,
"e": 7023,
"s": 6930,
"text": "next − method get the emitted number and then push it into the local variable, this.numbers."
},
{
"code": null,
"e": 7116,
"s": 7023,
"text": "next − method get the emitted number and then push it into the local variable, this.numbers."
},
{
"code": null,
"e": 7183,
"s": 7116,
"text": "next − method also adding the number to local variable, this.val1."
},
{
"code": null,
"e": 7250,
"s": 7183,
"text": "next − method also adding the number to local variable, this.val1."
},
{
"code": null,
"e": 7307,
"s": 7250,
"text": "error − method just writes the error message to console."
},
{
"code": null,
"e": 7364,
"s": 7307,
"text": "error − method just writes the error message to console."
},
{
"code": null,
"e": 7429,
"s": 7364,
"text": "complete − method also writes the completion message to console."
},
{
"code": null,
"e": 7494,
"s": 7429,
"text": "complete − method also writes the completion message to console."
},
{
"code": null,
"e": 7580,
"s": 7494,
"text": "We can skip error and complete method and write only the next method as shown below −"
},
{
"code": null,
"e": 7664,
"s": 7580,
"text": "number$.subscribe((num: number) => { this.numbers.push(num); this.val1 += num; });\n"
},
{
"code": null,
"e": 7785,
"s": 7664,
"text": "Rxjs library provides some of the operators to process the data stream. Some of the important operators are as follows −"
},
{
"code": null,
"e": 7852,
"s": 7785,
"text": "filter − Enable to filter the data stream using callback function."
},
{
"code": null,
"e": 8057,
"s": 7852,
"text": "const filterFn = filter( (num : number) => num > 5 ); \nconst filteredNumbers$ = filterFn(numbers$); \nfilteredNumbers$.subscribe( (num : number) => { \nthis.filteredNumbers.push(num); this.val2 += num } );\n"
},
{
"code": null,
"e": 8156,
"s": 8057,
"text": "map − Enables to map the data stream using callback function and to change the data stream itself."
},
{
"code": null,
"e": 8250,
"s": 8156,
"text": "const mapFn = map( (num : number) => num + num ); const mappedNumbers$ = mappedFn(numbers$);\n"
},
{
"code": null,
"e": 8302,
"s": 8250,
"text": "pipe − Enable two or more operators to be combined."
},
{
"code": null,
"e": 8571,
"s": 8302,
"text": "const filterFn = filter( (num : number) => num > 5 ); \nconst mapFn = map( (num : number) => num + num ); const processedNumbers$ = numbers$.pipe(filterFn, mapFn); \nprocessedNumbers$.subscribe( (num : number) => { this.processedNumbers.push(num); this.val3 += num } );\n"
},
{
"code": null,
"e": 8675,
"s": 8571,
"text": "Let us create a sample application to try out the reaction programming concept learned in this chapter."
},
{
"code": null,
"e": 8732,
"s": 8675,
"text": "Create a new application, reactive using below command −"
},
{
"code": null,
"e": 8749,
"s": 8732,
"text": "ng new reactive\n"
},
{
"code": null,
"e": 8804,
"s": 8749,
"text": "Change the directory to our newly created application."
},
{
"code": null,
"e": 8817,
"s": 8804,
"text": "cd reactive\n"
},
{
"code": null,
"e": 8838,
"s": 8817,
"text": "Run the application."
},
{
"code": null,
"e": 8848,
"s": 8838,
"text": "ng serve\n"
},
{
"code": null,
"e": 8935,
"s": 8848,
"text": "Change the AppComponent component code (src/app/app.component.ts) as specified below −"
},
{
"code": null,
"e": 10948,
"s": 8935,
"text": "import { Component, OnInit } from '@angular/core'; import { Observable, of, range, from, fromEvent } from 'rxjs'; \nimport { ajax } from 'rxjs/ajax'; \nimport { filter, map, catchError } from 'rxjs/operators'; \n@Component({ \n selector: 'app-root', \n templateUrl: './app.component.html', \n styleUrls: ['./app.component.css'] \n}) \nexport class AppComponent implements OnInit { \n title = 'Reactive programming concept'; \n numbers : number[] = []; \n val1 : number = 0; \n filteredNumbers : number[] = []; \n val2 : number = 0; \n processedNumbers : number[] = []; \n val3 : number = 0; \n apiMessage : string; \n counter : number = 0; \n ngOnInit() { \n // Observable stream of data Observable<number>\n // const numbers$ = of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); \n // const numbers$ = range(1,10); \n const numbers$ = from([1,2,3,4,5,6,7,8,9,10]); \n // observer \n const observer = { \n next: (num: number) => {this.numbers.push(num); this.val1 += num }, \n error: (err: any) => console.log(err), \n complete: () => console.log(\"Observation completed\") \n }; \n numbers$.subscribe(observer); \n const filterFn = filter( (num : number) => num > 5 ); \n const filteredNumbers = filterFn(numbers$); \n filteredNumbers.subscribe( (num : number) => {this.filteredNumbers.push(num); this.val2 += num } ); \n const mapFn = map( (num : number) => num + num ); \n const processedNumbers$ = numbers$.pipe(filterFn, mapFn); \n processedNumbers$.subscribe( (num : number) => {this.processedNumbers.push(num); this.val3 += num } ); \n const api$ = ajax({ \n url: 'https://httpbin.org/delay/1', \n method: 'POST', \n headers: {'Content-Type': 'application/text' }, \n body: \"Hello\" \n }); \n api$.subscribe(res => this.apiMessage = res.response.data ); \n const clickEvent$ = fromEvent(document.getElementById('counter'), 'click'); \n clickEvent$.subscribe( () => this.counter++ ); \n } \n}"
},
{
"code": null,
"e": 10954,
"s": 10948,
"text": "Here,"
},
{
"code": null,
"e": 11026,
"s": 10954,
"text": "Used of, range, from, ajax and fromEvent methods to created Observable."
},
{
"code": null,
"e": 11097,
"s": 11026,
"text": "Used filter, map and pipe operator methods to process the data stream."
},
{
"code": null,
"e": 11201,
"s": 11097,
"text": "Callback functions catch the emitted data, process it and then store it in component’s local variables."
},
{
"code": null,
"e": 11284,
"s": 11201,
"text": "Change the AppComponent template (src/app/app.component.html) as specified below −"
},
{
"code": null,
"e": 11892,
"s": 11284,
"text": "<h1>{{ title }}</h1> \n<div> \n The summation of numbers ( <span *ngFor=\"let num of numbers\"> {{ num }} </span> ) is {{ val1 }} \n</div> \n<div> \n The summation of filtered numbers ( <span *ngFor=\"let num of filteredNumbers\"> {{ num }} </span> ) is {{ val2 }} \n</div> \n<div> \n The summation of processed numbers ( <span *ngFor=\"let num of processedNumbers\"> {{ num }} </span> ) is {{ val3 }} \n</div> \n<div> \n The response from the API is <em>{{ apiMessage }}</em> </div> \n<div> \n <a id=\"counter\" href=\"#\">Click here</a> to increment the counter value. The current counter value is {{ counter }} \n<div>"
},
{
"code": null,
"e": 11898,
"s": 11892,
"text": "Here,"
},
{
"code": null,
"e": 11969,
"s": 11898,
"text": "Shown all the local variable processed by Observer callback functions."
},
{
"code": null,
"e": 12010,
"s": 11969,
"text": "Open the browser, http://localhost:4200."
},
{
"code": null,
"e": 12272,
"s": 12010,
"text": "Click the Click here link for five times. For each event, the event will be emitted and forward to the Observer. Observer callback function will be called. The callback function increment the counter for every click and the final result will be as shown below −"
},
{
"code": null,
"e": 12307,
"s": 12272,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12321,
"s": 12307,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 12356,
"s": 12321,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12370,
"s": 12356,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 12405,
"s": 12370,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 12425,
"s": 12405,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 12460,
"s": 12425,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12477,
"s": 12460,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12510,
"s": 12477,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 12522,
"s": 12510,
"text": " Senol Atac"
},
{
"code": null,
"e": 12557,
"s": 12522,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 12569,
"s": 12557,
"text": " Senol Atac"
},
{
"code": null,
"e": 12576,
"s": 12569,
"text": " Print"
},
{
"code": null,
"e": 12587,
"s": 12576,
"text": " Add Notes"
}
] |
Check if a HashMap is empty in Java | Use the isEmpty() method to check of a HashMap is empty or not. Let us first create the HashMap −
HashMap hm = new HashMap();
Now, add some elements −
hm.put("Bag", new Integer(1100));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
Since, we added elements above, therefore, the HashMap isn’t empty. Let us check −
set.isEmpty()
The following is an example to check if a HashMap is empty or not −
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Bag", new Integer(1100));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
System.out.println("Is the HashMap with empty elements? "+set.isEmpty());
}
}
Belt: 600
Wallet: 700
Bag: 1100
Is the HashMap with empty elements? False | [
{
"code": null,
"e": 1160,
"s": 1062,
"text": "Use the isEmpty() method to check of a HashMap is empty or not. Let us first create the HashMap −"
},
{
"code": null,
"e": 1188,
"s": 1160,
"text": "HashMap hm = new HashMap();"
},
{
"code": null,
"e": 1213,
"s": 1188,
"text": "Now, add some elements −"
},
{
"code": null,
"e": 1317,
"s": 1213,
"text": "hm.put(\"Bag\", new Integer(1100));\nhm.put(\"Wallet\", new Integer(700));\nhm.put(\"Belt\", new Integer(600));"
},
{
"code": null,
"e": 1400,
"s": 1317,
"text": "Since, we added elements above, therefore, the HashMap isn’t empty. Let us check −"
},
{
"code": null,
"e": 1414,
"s": 1400,
"text": "set.isEmpty()"
},
{
"code": null,
"e": 1482,
"s": 1414,
"text": "The following is an example to check if a HashMap is empty or not −"
},
{
"code": null,
"e": 1493,
"s": 1482,
"text": " Live Demo"
},
{
"code": null,
"e": 2230,
"s": 1493,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n // Create a hash map\n HashMap hm = new HashMap();\n // Put elements to the map\n hm.put(\"Bag\", new Integer(1100));\n hm.put(\"Wallet\", new Integer(700));\n hm.put(\"Belt\", new Integer(600));\n // Get a set of the entries\n Set set = hm.entrySet();\n // Get an iterator\n Iterator i = set.iterator();\n // Display elements\n while(i.hasNext()) {\n Map.Entry me = (Map.Entry)i.next();\n System.out.print(me.getKey() + \": \");\n System.out.println(me.getValue());\n }\n System.out.println();\n System.out.println(\"Is the HashMap with empty elements? \"+set.isEmpty());\n }\n}"
},
{
"code": null,
"e": 2304,
"s": 2230,
"text": "Belt: 600\nWallet: 700\nBag: 1100\nIs the HashMap with empty elements? False"
}
] |
How to Create Shrink Header on Scroll using HTML, CSS and JavaScript ? - GeeksforGeeks | 09 Feb, 2022
Shrink Navigation bar works when the user scrolls down the page. In this article, we will use HTML, CSS, and JavaScript to design shrink navigation bar. HTML is used to create the structure, CSS is used to set the style on HTML structure to make it looks good. This kind of shrinking navbar looks attractive on a site. By using JavaScript you can easily make the navigation bar shrinkable when the user scrolls down.Creating Structure: In this section, we will create a basic website structure for the shrinkable navbar and when the user scrolls down the page it will display the effect.
HTML code to create structure:
html
<!DOCTYPE html><html> <head> <meta name="viewport" content ="width=device-width, initial-scale=1"> <title> How to Create Shrink Header on Scroll using HTML, CSS and JavaScript ? </title></head> <body> <!-- Navlist of header --> <div id="navlist"> <a href="#default" id="logo"> GeeksforGeeks </a> <div id="navlist-right"> <a href="#home">Home</a> <a href="#about">Our Products</a> <a href="#about">Careers</a> <a href="#contact">Contact US</a> <a href="#about">About US</a> </div> </div> <!-- Page Content --> <div class="content"> <b> A Computer Science Portal for Geeks </b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </div></body> </html>
Designing Structure: In the previous section, we have created the structure of the basic website. In this section, we will design the structure of navigation bar and then scroll down effect on the navbar using JavaScript.
CSS code to add style on HTML structure:
CSS
<style> * { box-sizing: border-box; } body { margin: 0; } /* Navlist designing */ #navlist { overflow: hidden; background-color: #0074D9; padding: 90px 10px; transition: 0.4s; position: fixed; width: 100%; top: 0; z-index: 1; } #navlist a { float: left; color: white; text-align: center; padding: 12px; text-decoration: none; font-size: 18px; line-height: 25px; border-radius: 4px; } #navlist #logo { font-size: 35px; font-weight: bold; transition: 0.4s; } #navlist a:hover { color: #01FE06; } #navlist-right { float: right; } /* Content design */ .content { margin-top:220px; padding:15px 15px 1800px; font-size:22px; }</style>
JavaScript code for animation on menu:
jscript
<script> // Scrolls down 90px from the top of // the document, to resize the navlist // padding and the title font-size window.onscroll = function() { scrollFunction() }; function scrollFunction() { if (document.body.scrollTop > 90 || document.documentElement.scrollTop > 90) { document.getElementById("navlist") .style.padding = "25px 10px"; document.getElementById("logo") .style.fontSize = "24px"; } else { document.getElementById("navlist") .style.padding = "90px 10px"; document.getElementById("logo") .style.fontSize = "35px"; } }</script>
Example: In this example, we will combine HTML, CSS and JavaScript code to make shrink header navigation-bar.
html
<!DOCTYPE html><html> <head> <meta name="viewport" content ="width=device-width, initial-scale=1"> <title> How to Create Shrink Header on Scroll using HTML, CSS and JavaScript ? </title> <style> * { box-sizing: border-box; } body { margin: 0; } /* Navlist designing */ #navlist { overflow: hidden; background-color: #0074D9; padding: 90px 10px; transition: 0.4s; position: fixed; width: 100%; top: 0; z-index: 1; } #navlist a { float: left; color: white; text-align: center; padding: 12px; text-decoration: none; font-size: 18px; line-height: 25px; border-radius: 4px; } #navlist #logo { font-size: 35px; font-weight: bold; transition: 0.4s; } #navlist a:hover { color: #01FE06; } #navlist-right { float: right; } /* Content design */ .content { margin-top:220px; padding:15px 15px 1800px; font-size:22px; } </style></head> <body> <!-- Navlist of header --> <div id="navlist"> <a href="#default" id="logo"> GeeksforGeeks </a> <div id="navlist-right"> <a href="#home">Home</a> <a href="#about">Our Products</a> <a href="#about">Careers</a> <a href="#contact">Contact US</a> <a href="#about">About US</a> </div> </div> <!-- Page Content --> <div class="content"> <b> A Computer Science Portal for Geeks </b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </div> <script> // Scrolls down 90px from the top of // the document, to resize the navlist // padding and the title font-size window.onscroll = function() { scrollFunction() }; function scrollFunction() { if (document.body.scrollTop > 90 || document.documentElement.scrollTop > 90) { document.getElementById("navlist") .style.padding = "25px 10px"; document.getElementById("logo") .style.fontSize = "24px"; } else { document.getElementById("navlist") .style.padding = "90px 10px"; document.getElementById("logo") .style.fontSize = "35px"; } } </script></body> </html>
Output:
rkbhola5
simranarora5sos
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
Hide or show elements in HTML using display property
REST API (Introduction) | [
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 25965,
"s": 25376,
"text": "Shrink Navigation bar works when the user scrolls down the page. In this article, we will use HTML, CSS, and JavaScript to design shrink navigation bar. HTML is used to create the structure, CSS is used to set the style on HTML structure to make it looks good. This kind of shrinking navbar looks attractive on a site. By using JavaScript you can easily make the navigation bar shrinkable when the user scrolls down.Creating Structure: In this section, we will create a basic website structure for the shrinkable navbar and when the user scrolls down the page it will display the effect. "
},
{
"code": null,
"e": 25996,
"s": 25965,
"text": "HTML code to create structure:"
},
{
"code": null,
"e": 26001,
"s": 25996,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content =\"width=device-width, initial-scale=1\"> <title> How to Create Shrink Header on Scroll using HTML, CSS and JavaScript ? </title></head> <body> <!-- Navlist of header --> <div id=\"navlist\"> <a href=\"#default\" id=\"logo\"> GeeksforGeeks </a> <div id=\"navlist-right\"> <a href=\"#home\">Home</a> <a href=\"#about\">Our Products</a> <a href=\"#about\">Careers</a> <a href=\"#contact\">Contact US</a> <a href=\"#about\">About US</a> </div> </div> <!-- Page Content --> <div class=\"content\"> <b> A Computer Science Portal for Geeks </b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </div></body> </html>",
"e": 27160,
"s": 26001,
"text": null
},
{
"code": null,
"e": 27382,
"s": 27160,
"text": "Designing Structure: In the previous section, we have created the structure of the basic website. In this section, we will design the structure of navigation bar and then scroll down effect on the navbar using JavaScript."
},
{
"code": null,
"e": 27423,
"s": 27382,
"text": "CSS code to add style on HTML structure:"
},
{
"code": null,
"e": 27427,
"s": 27423,
"text": "CSS"
},
{
"code": "<style> * { box-sizing: border-box; } body { margin: 0; } /* Navlist designing */ #navlist { overflow: hidden; background-color: #0074D9; padding: 90px 10px; transition: 0.4s; position: fixed; width: 100%; top: 0; z-index: 1; } #navlist a { float: left; color: white; text-align: center; padding: 12px; text-decoration: none; font-size: 18px; line-height: 25px; border-radius: 4px; } #navlist #logo { font-size: 35px; font-weight: bold; transition: 0.4s; } #navlist a:hover { color: #01FE06; } #navlist-right { float: right; } /* Content design */ .content { margin-top:220px; padding:15px 15px 1800px; font-size:22px; }</style>",
"e": 28309,
"s": 27427,
"text": null
},
{
"code": null,
"e": 28348,
"s": 28309,
"text": "JavaScript code for animation on menu:"
},
{
"code": null,
"e": 28356,
"s": 28348,
"text": "jscript"
},
{
"code": "<script> // Scrolls down 90px from the top of // the document, to resize the navlist // padding and the title font-size window.onscroll = function() { scrollFunction() }; function scrollFunction() { if (document.body.scrollTop > 90 || document.documentElement.scrollTop > 90) { document.getElementById(\"navlist\") .style.padding = \"25px 10px\"; document.getElementById(\"logo\") .style.fontSize = \"24px\"; } else { document.getElementById(\"navlist\") .style.padding = \"90px 10px\"; document.getElementById(\"logo\") .style.fontSize = \"35px\"; } }</script>",
"e": 29164,
"s": 28356,
"text": null
},
{
"code": null,
"e": 29275,
"s": 29164,
"text": "Example: In this example, we will combine HTML, CSS and JavaScript code to make shrink header navigation-bar. "
},
{
"code": null,
"e": 29280,
"s": 29275,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content =\"width=device-width, initial-scale=1\"> <title> How to Create Shrink Header on Scroll using HTML, CSS and JavaScript ? </title> <style> * { box-sizing: border-box; } body { margin: 0; } /* Navlist designing */ #navlist { overflow: hidden; background-color: #0074D9; padding: 90px 10px; transition: 0.4s; position: fixed; width: 100%; top: 0; z-index: 1; } #navlist a { float: left; color: white; text-align: center; padding: 12px; text-decoration: none; font-size: 18px; line-height: 25px; border-radius: 4px; } #navlist #logo { font-size: 35px; font-weight: bold; transition: 0.4s; } #navlist a:hover { color: #01FE06; } #navlist-right { float: right; } /* Content design */ .content { margin-top:220px; padding:15px 15px 1800px; font-size:22px; } </style></head> <body> <!-- Navlist of header --> <div id=\"navlist\"> <a href=\"#default\" id=\"logo\"> GeeksforGeeks </a> <div id=\"navlist-right\"> <a href=\"#home\">Home</a> <a href=\"#about\">Our Products</a> <a href=\"#about\">Careers</a> <a href=\"#contact\">Contact US</a> <a href=\"#about\">About US</a> </div> </div> <!-- Page Content --> <div class=\"content\"> <b> A Computer Science Portal for Geeks </b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </div> <script> // Scrolls down 90px from the top of // the document, to resize the navlist // padding and the title font-size window.onscroll = function() { scrollFunction() }; function scrollFunction() { if (document.body.scrollTop > 90 || document.documentElement.scrollTop > 90) { document.getElementById(\"navlist\") .style.padding = \"25px 10px\"; document.getElementById(\"logo\") .style.fontSize = \"24px\"; } else { document.getElementById(\"navlist\") .style.padding = \"90px 10px\"; document.getElementById(\"logo\") .style.fontSize = \"35px\"; } } </script></body> </html>",
"e": 32444,
"s": 29280,
"text": null
},
{
"code": null,
"e": 32453,
"s": 32444,
"text": "Output: "
},
{
"code": null,
"e": 32462,
"s": 32453,
"text": "rkbhola5"
},
{
"code": null,
"e": 32478,
"s": 32462,
"text": "simranarora5sos"
},
{
"code": null,
"e": 32487,
"s": 32478,
"text": "CSS-Misc"
},
{
"code": null,
"e": 32497,
"s": 32487,
"text": "HTML-Misc"
},
{
"code": null,
"e": 32513,
"s": 32497,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 32517,
"s": 32513,
"text": "CSS"
},
{
"code": null,
"e": 32522,
"s": 32517,
"text": "HTML"
},
{
"code": null,
"e": 32533,
"s": 32522,
"text": "JavaScript"
},
{
"code": null,
"e": 32550,
"s": 32533,
"text": "Web Technologies"
},
{
"code": null,
"e": 32577,
"s": 32550,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 32582,
"s": 32577,
"text": "HTML"
},
{
"code": null,
"e": 32680,
"s": 32582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32689,
"s": 32680,
"text": "Comments"
},
{
"code": null,
"e": 32702,
"s": 32689,
"text": "Old Comments"
},
{
"code": null,
"e": 32739,
"s": 32702,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32768,
"s": 32739,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32807,
"s": 32768,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 32849,
"s": 32807,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 32896,
"s": 32849,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 32956,
"s": 32896,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 33017,
"s": 32956,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 33067,
"s": 33017,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 33120,
"s": 33067,
"text": "Hide or show elements in HTML using display property"
}
] |
C# Program to Demonstrate Abstract Class with Multiple-level Inheritance - GeeksforGeeks | 01 Nov, 2021
Abstract Class is the way to achieve abstraction. It is a special class that never be instantiated directly. This class should contain at least one abstract method in it and mark by abstract keyword in the class definition. The main purpose of this class is to give a blueprint for derived classes and set some rules what the derived classes must implement when they inherit an abstract class. An abstract class can be used as a base class and all derived classes must implement the abstract definitions.
Syntax:
abstract class classname
{
// Method Declaration in abstract class
}
Here, the classname is the name of an abstract class. We can declare any number of methods inside it
Multiple-level Inheritance is a type of inheritance in which a derived class will inherit a base class and the derived class also behave like the base class to other class. For example, we have three classes named class1, class2, and class3. Here, class3 is derived from class2, and class2 is derived from class1.
Syntax:
class GFG : Abstract_Class
{
// Method definition for abstract method
}
Given an abstract class, our task is to implement the abstract class into the parent class and then implement the multilevel inheritance. So, let us understand with the help of an example.
class GFG : Abstract_class
{
// Method definition for abstract method
}
// First child class extends parent
class GFG2 : GFG
{
// Method definition
}
// Second child class extends first child class
class GFG3 : GFG2
{
// Method definition
}
Here, GFG is the parent class and GFG2 and GFG3 are the child class that extends the parent class.
Example:
C#
// C# program to illustrate abstract class // with multiple-level Inheritanceusing System; // Abstract classabstract class Abstract_class{ // Method declaration for abstract class public abstract void abstract_method();} // Parent classclass GFG : Abstract_class{ // Method definition for abstract method public override void abstract_method() { Console.WriteLine("Abstract method is called"); }} // First child class extends parentclass GFG2 : GFG{ // Method definition public void Mymethod1() { Console.WriteLine("Method from GFG2 class"); }} // Second child class extends first child classclass GFG3 : GFG2{ // Method definition public void Mymethod2() { Console.WriteLine("Method from GFG3 class"); }} class Geeks{ // Driver codepublic static void Main(String[] args){ // Creating an object of GFG3 class GFG3 obj = new GFG3(); // Call the methods using GFG3 class obj.abstract_method(); obj.Mymethod1(); obj.Mymethod2();}}
Output:
Abstract method is called
Method from GFG2 class
Method from GFG3 class
Explanation: In this example, we created an Abstract class named “Abstract_class” and declared a method named “abstract_method” inside it. Then we created a parent class named “GFG” by overriding the method of an abstract class. After that, we created the first child class named “GFG2” that inherits the parent class and defined a method named “Mymethod1” inside it. Then created a second child class named “GFG3” that inherits the first child class and defined a method “Mymethod2” inside it. Finally, we created the main class that includes the main method, then created an object(named “obj”) for the second child class and called all the methods that are declared and get the output on the screen.
CSharp-Inheritance
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Switch Statement in C#
C# | Generics - Introduction
Lambda Expressions in C#
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Convert String to Character Array in C# | [
{
"code": null,
"e": 24400,
"s": 24372,
"text": "\n01 Nov, 2021"
},
{
"code": null,
"e": 24906,
"s": 24400,
"text": "Abstract Class is the way to achieve abstraction. It is a special class that never be instantiated directly. This class should contain at least one abstract method in it and mark by abstract keyword in the class definition. The main purpose of this class is to give a blueprint for derived classes and set some rules what the derived classes must implement when they inherit an abstract class. An abstract class can be used as a base class and all derived classes must implement the abstract definitions. "
},
{
"code": null,
"e": 24914,
"s": 24906,
"text": "Syntax:"
},
{
"code": null,
"e": 24987,
"s": 24914,
"text": "abstract class classname\n{\n // Method Declaration in abstract class\n}"
},
{
"code": null,
"e": 25088,
"s": 24987,
"text": "Here, the classname is the name of an abstract class. We can declare any number of methods inside it"
},
{
"code": null,
"e": 25402,
"s": 25088,
"text": "Multiple-level Inheritance is a type of inheritance in which a derived class will inherit a base class and the derived class also behave like the base class to other class. For example, we have three classes named class1, class2, and class3. Here, class3 is derived from class2, and class2 is derived from class1."
},
{
"code": null,
"e": 25410,
"s": 25402,
"text": "Syntax:"
},
{
"code": null,
"e": 25486,
"s": 25410,
"text": "class GFG : Abstract_Class\n{\n // Method definition for abstract method\n}"
},
{
"code": null,
"e": 25675,
"s": 25486,
"text": "Given an abstract class, our task is to implement the abstract class into the parent class and then implement the multilevel inheritance. So, let us understand with the help of an example."
},
{
"code": null,
"e": 25929,
"s": 25675,
"text": "class GFG : Abstract_class\n{\n // Method definition for abstract method\n}\n\n// First child class extends parent\nclass GFG2 : GFG\n{\n // Method definition\n}\n\n// Second child class extends first child class\nclass GFG3 : GFG2\n{\n // Method definition\n}"
},
{
"code": null,
"e": 26028,
"s": 25929,
"text": "Here, GFG is the parent class and GFG2 and GFG3 are the child class that extends the parent class."
},
{
"code": null,
"e": 26037,
"s": 26028,
"text": "Example:"
},
{
"code": null,
"e": 26040,
"s": 26037,
"text": "C#"
},
{
"code": "// C# program to illustrate abstract class // with multiple-level Inheritanceusing System; // Abstract classabstract class Abstract_class{ // Method declaration for abstract class public abstract void abstract_method();} // Parent classclass GFG : Abstract_class{ // Method definition for abstract method public override void abstract_method() { Console.WriteLine(\"Abstract method is called\"); }} // First child class extends parentclass GFG2 : GFG{ // Method definition public void Mymethod1() { Console.WriteLine(\"Method from GFG2 class\"); }} // Second child class extends first child classclass GFG3 : GFG2{ // Method definition public void Mymethod2() { Console.WriteLine(\"Method from GFG3 class\"); }} class Geeks{ // Driver codepublic static void Main(String[] args){ // Creating an object of GFG3 class GFG3 obj = new GFG3(); // Call the methods using GFG3 class obj.abstract_method(); obj.Mymethod1(); obj.Mymethod2();}}",
"e": 27095,
"s": 26040,
"text": null
},
{
"code": null,
"e": 27103,
"s": 27095,
"text": "Output:"
},
{
"code": null,
"e": 27175,
"s": 27103,
"text": "Abstract method is called\nMethod from GFG2 class\nMethod from GFG3 class"
},
{
"code": null,
"e": 27878,
"s": 27175,
"text": "Explanation: In this example, we created an Abstract class named “Abstract_class” and declared a method named “abstract_method” inside it. Then we created a parent class named “GFG” by overriding the method of an abstract class. After that, we created the first child class named “GFG2” that inherits the parent class and defined a method named “Mymethod1” inside it. Then created a second child class named “GFG3” that inherits the first child class and defined a method “Mymethod2” inside it. Finally, we created the main class that includes the main method, then created an object(named “obj”) for the second child class and called all the methods that are declared and get the output on the screen."
},
{
"code": null,
"e": 27897,
"s": 27878,
"text": "CSharp-Inheritance"
},
{
"code": null,
"e": 27913,
"s": 27897,
"text": "CSharp-programs"
},
{
"code": null,
"e": 27920,
"s": 27913,
"text": "Picked"
},
{
"code": null,
"e": 27923,
"s": 27920,
"text": "C#"
},
{
"code": null,
"e": 28021,
"s": 27923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28044,
"s": 28021,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28072,
"s": 28044,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28094,
"s": 28072,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28111,
"s": 28094,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28134,
"s": 28111,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 28163,
"s": 28134,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 28188,
"s": 28163,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 28228,
"s": 28188,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28271,
"s": 28228,
"text": "C# | How to insert an element in an Array?"
}
] |
Find Cube root of a number using Log function - GeeksforGeeks | 17 Mar, 2021
Given number N, the task is to find the cube root using log function.Examples:
Input: N = 8 Output: 2.000000Input: N = 27 Output: 3.000000
Approach: To solve the problem mentioned above we will use log() function, according to the following formula:
Let cube root of N be d. => ∛N = d => N(1/3) = d Now, apply log on both sides: log3 (N(1/3)) = log3 (d) => log3 (d) = 1/3 * log3 (N) => d = 3(1/3 * log3 (N))
Below is the implementation of above problem:
C++
Java
Python3
C#
Javascript
// C++ program to Find Cube root// of a number using Logarithm #include <bits/stdc++.h> // Function to find the cube rootdouble cubeRoot(double n){ // calculate the cube root double ans = pow(3, (1.0 / 3) * (log(n) / log(3))); // Return the final answer return ans;} // Driver codeint main(){ double N = 8; printf("%.2lf ", cubeRoot(N)); return 0;}
// Java program to Find Cube root// of a number using Logarithmclass GFG{ // Function to find the cube rootstatic double cubeRoot(double n){ // Calculate the cube root double ans = Math.pow(3, ((1.0 / 3) * (Math.log(n) / Math.log(3)))); // Return the final answer return ans;} // Driver codepublic static void main(String[] args){ double N = 8; System.out.printf("%.2f", cubeRoot(N));}} // This code is contributed by Rajput-Ji
# Python3 program to find cube root# of a number using logarithmimport numpy as np # Function to find the cube rootdef cubeRoot(n): # Calculate the cube root ans = pow(3, (1.0 / 3) * (np.log(n) / np.log(3))) # Return the final answer return ans # Driver codeN = 8 print("%.2f" % cubeRoot(N)) # This code is contributed by PratikBasu
// C# program to find cube root// of a number using logarithmusing System; class GFG{ // Function to find the cube rootstatic double cubeRoot(double n){ // Calculate the cube root double ans = Math.Pow(3, ((1.0 / 3) * (Math.Log(n) / Math.Log(3)))); // Return the readonly answer return ans;} // Driver codepublic static void Main(String[] args){ double N = 8; Console.Write("{0:F2}", cubeRoot(N));}} // This code is contributed by sapnasingh4991
<script>// javascript program to Find Cube root// of a number using Logarithm // Function to find the cube rootfunction cubeRoot( n){ // calculate the cube root let ans = Math.pow(3, (1.0 / 3) * (Math.log(n) / Math.log(3))); // Return the final answer return ans;} // Driver codelet N = 8;document.write( cubeRoot(N).toFixed(2)); // This code is contributed by todaysgaurav </script>
2.00
Rajput-Ji
PratikBasu
sapnasingh4991
todaysgaurav
maths-cube
root
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Modular multiplicative inverse
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 24692,
"s": 24664,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 24772,
"s": 24692,
"text": "Given number N, the task is to find the cube root using log function.Examples: "
},
{
"code": null,
"e": 24834,
"s": 24772,
"text": "Input: N = 8 Output: 2.000000Input: N = 27 Output: 3.000000 "
},
{
"code": null,
"e": 24948,
"s": 24836,
"text": "Approach: To solve the problem mentioned above we will use log() function, according to the following formula: "
},
{
"code": null,
"e": 25108,
"s": 24948,
"text": "Let cube root of N be d. => ∛N = d => N(1/3) = d Now, apply log on both sides: log3 (N(1/3)) = log3 (d) => log3 (d) = 1/3 * log3 (N) => d = 3(1/3 * log3 (N)) "
},
{
"code": null,
"e": 25156,
"s": 25108,
"text": "Below is the implementation of above problem: "
},
{
"code": null,
"e": 25160,
"s": 25156,
"text": "C++"
},
{
"code": null,
"e": 25165,
"s": 25160,
"text": "Java"
},
{
"code": null,
"e": 25173,
"s": 25165,
"text": "Python3"
},
{
"code": null,
"e": 25176,
"s": 25173,
"text": "C#"
},
{
"code": null,
"e": 25187,
"s": 25176,
"text": "Javascript"
},
{
"code": "// C++ program to Find Cube root// of a number using Logarithm #include <bits/stdc++.h> // Function to find the cube rootdouble cubeRoot(double n){ // calculate the cube root double ans = pow(3, (1.0 / 3) * (log(n) / log(3))); // Return the final answer return ans;} // Driver codeint main(){ double N = 8; printf(\"%.2lf \", cubeRoot(N)); return 0;}",
"e": 25587,
"s": 25187,
"text": null
},
{
"code": "// Java program to Find Cube root// of a number using Logarithmclass GFG{ // Function to find the cube rootstatic double cubeRoot(double n){ // Calculate the cube root double ans = Math.pow(3, ((1.0 / 3) * (Math.log(n) / Math.log(3)))); // Return the final answer return ans;} // Driver codepublic static void main(String[] args){ double N = 8; System.out.printf(\"%.2f\", cubeRoot(N));}} // This code is contributed by Rajput-Ji",
"e": 26102,
"s": 25587,
"text": null
},
{
"code": "# Python3 program to find cube root# of a number using logarithmimport numpy as np # Function to find the cube rootdef cubeRoot(n): # Calculate the cube root ans = pow(3, (1.0 / 3) * (np.log(n) / np.log(3))) # Return the final answer return ans # Driver codeN = 8 print(\"%.2f\" % cubeRoot(N)) # This code is contributed by PratikBasu",
"e": 26478,
"s": 26102,
"text": null
},
{
"code": "// C# program to find cube root// of a number using logarithmusing System; class GFG{ // Function to find the cube rootstatic double cubeRoot(double n){ // Calculate the cube root double ans = Math.Pow(3, ((1.0 / 3) * (Math.Log(n) / Math.Log(3)))); // Return the readonly answer return ans;} // Driver codepublic static void Main(String[] args){ double N = 8; Console.Write(\"{0:F2}\", cubeRoot(N));}} // This code is contributed by sapnasingh4991",
"e": 27016,
"s": 26478,
"text": null
},
{
"code": "<script>// javascript program to Find Cube root// of a number using Logarithm // Function to find the cube rootfunction cubeRoot( n){ // calculate the cube root let ans = Math.pow(3, (1.0 / 3) * (Math.log(n) / Math.log(3))); // Return the final answer return ans;} // Driver codelet N = 8;document.write( cubeRoot(N).toFixed(2)); // This code is contributed by todaysgaurav </script>",
"e": 27447,
"s": 27016,
"text": null
},
{
"code": null,
"e": 27452,
"s": 27447,
"text": "2.00"
},
{
"code": null,
"e": 27464,
"s": 27454,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 27475,
"s": 27464,
"text": "PratikBasu"
},
{
"code": null,
"e": 27490,
"s": 27475,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 27503,
"s": 27490,
"text": "todaysgaurav"
},
{
"code": null,
"e": 27514,
"s": 27503,
"text": "maths-cube"
},
{
"code": null,
"e": 27519,
"s": 27514,
"text": "root"
},
{
"code": null,
"e": 27532,
"s": 27519,
"text": "Mathematical"
},
{
"code": null,
"e": 27551,
"s": 27532,
"text": "School Programming"
},
{
"code": null,
"e": 27564,
"s": 27551,
"text": "Mathematical"
},
{
"code": null,
"e": 27662,
"s": 27564,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27694,
"s": 27662,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 27738,
"s": 27694,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 27763,
"s": 27738,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 27796,
"s": 27763,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 27827,
"s": 27796,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 27845,
"s": 27827,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27861,
"s": 27845,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 27880,
"s": 27861,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27905,
"s": 27880,
"text": "Reverse a string in Java"
}
] |
Zip Code validation using Java Regular Expressions | The zip code can be validated using the java.util.regex.Pattern.matches() method. This method matches the regular expression for the zip code and the given input zip code and returns true if they match and false otherwise.
A program that demonstrates this is given as follows:
Live Demo
public class Demo {
public static void main(String args[]) {
String zipCode = "83592-1537";
String regex = "\\d{5}(-\\d{4})?";
System.out.println("The zip code is: " + zipCode);
System.out.println("Is the above zip code valid? " + zipCode.matches(regex));
}
}
The zip code is: 83592-1537
Is the above zip code valid? true
Now let us understand the above program.
The zip code is printed. The Pattern.matches() method matches the regular expression for the zip code and the given input zip code and the result is printed. A code snippet which demonstrates this is as follows:
String zipCode = "83592-1537";
String regex = "\\d{5}(-\\d{4})?";
System.out.println("The zip code is: " + zipCode);
System.out.println("Is the above zip code valid? " + zipCode.matches(regex)); | [
{
"code": null,
"e": 1285,
"s": 1062,
"text": "The zip code can be validated using the java.util.regex.Pattern.matches() method. This method matches the regular expression for the zip code and the given input zip code and returns true if they match and false otherwise."
},
{
"code": null,
"e": 1339,
"s": 1285,
"text": "A program that demonstrates this is given as follows:"
},
{
"code": null,
"e": 1350,
"s": 1339,
"text": " Live Demo"
},
{
"code": null,
"e": 1640,
"s": 1350,
"text": "public class Demo {\n public static void main(String args[]) {\n String zipCode = \"83592-1537\";\n String regex = \"\\\\d{5}(-\\\\d{4})?\";\n System.out.println(\"The zip code is: \" + zipCode);\n System.out.println(\"Is the above zip code valid? \" + zipCode.matches(regex));\n }\n}"
},
{
"code": null,
"e": 1702,
"s": 1640,
"text": "The zip code is: 83592-1537\nIs the above zip code valid? true"
},
{
"code": null,
"e": 1743,
"s": 1702,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 1955,
"s": 1743,
"text": "The zip code is printed. The Pattern.matches() method matches the regular expression for the zip code and the given input zip code and the result is printed. A code snippet which demonstrates this is as follows:"
},
{
"code": null,
"e": 2151,
"s": 1955,
"text": "String zipCode = \"83592-1537\";\nString regex = \"\\\\d{5}(-\\\\d{4})?\";\n\nSystem.out.println(\"The zip code is: \" + zipCode);\nSystem.out.println(\"Is the above zip code valid? \" + zipCode.matches(regex));"
}
] |
How to deal with error “Error in shapiro.test(...) : sample size must be between 3 and 5000” in R? | The shapiro.test has a restriction in R that it can be applied only up to a sample of size 5000 and the least sample size must be 3. Therefore, we have an alternative hypothesis test called Anderson Darling normality test. To perform this test, we need load nortest package and use the ad.test function as shown in the below examples.
Consider the below data frame −
Live Demo
x<-rnorm(1000000)
df1<-data.frame(x)
head(df1,20)
x
1 1.27305105
2 1.79910461
3 -1.05456918
4 0.27247323
5 -1.22709375
6 1.87211271
7 -0.98918543
8 -0.98504275
9 0.55901414
10 1.17920161
11 -0.16612397
12 -0.89614357
13 -0.70229748
14 1.16583130
15 -0.17427556
16 0.05428080
17 1.26193927
18 0.63517470
19 -0.02052002
20 -1.23316924
Performing shapiro.test on x −
shapiro.test(df1$x)
Error in shapiro.test(df1$x) : sample size must be between 3 and 5000
Loading nortest package and performing Anderson Darling test on x −
library(nortest)
ad.test(df1$x)
Anderson-Darling normality test
data: df1$x
A = 0.21458, p-value = 0.8496
Live Demo
y<-sample(0:9,500000,replace=TRUE)
df2<-data.frame(y)
head(df2,20)
y
1 8
2 9
3 7
4 0
5 3
6 4
7 9
8 3
9 1
10 5
11 9
12 4
13 5
14 9
15 5
16 7
17 1
18 0
19 4
20 4
Performing Anderson Darling test on y −
ad.test(df2$y)
Anderson-Darling normality test
data: df2$y
A = 8634.6, p-value < 2.2e-16 | [
{
"code": null,
"e": 1397,
"s": 1062,
"text": "The shapiro.test has a restriction in R that it can be applied only up to a sample of size 5000 and the least sample size must be 3. Therefore, we have an alternative hypothesis test called Anderson Darling normality test. To perform this test, we need load nortest package and use the ad.test function as shown in the below examples."
},
{
"code": null,
"e": 1429,
"s": 1397,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1440,
"s": 1429,
"text": " Live Demo"
},
{
"code": null,
"e": 1490,
"s": 1440,
"text": "x<-rnorm(1000000)\ndf1<-data.frame(x)\nhead(df1,20)"
},
{
"code": null,
"e": 1817,
"s": 1490,
"text": " x\n1 1.27305105\n2 1.79910461\n3 -1.05456918\n4 0.27247323\n5 -1.22709375\n6 1.87211271\n7 -0.98918543\n8 -0.98504275\n9 0.55901414\n10 1.17920161\n11 -0.16612397\n12 -0.89614357\n13 -0.70229748\n14 1.16583130\n15 -0.17427556\n16 0.05428080\n17 1.26193927\n18 0.63517470\n19 -0.02052002\n20 -1.23316924"
},
{
"code": null,
"e": 1848,
"s": 1817,
"text": "Performing shapiro.test on x −"
},
{
"code": null,
"e": 1868,
"s": 1848,
"text": "shapiro.test(df1$x)"
},
{
"code": null,
"e": 1938,
"s": 1868,
"text": "Error in shapiro.test(df1$x) : sample size must be between 3 and 5000"
},
{
"code": null,
"e": 2006,
"s": 1938,
"text": "Loading nortest package and performing Anderson Darling test on x −"
},
{
"code": null,
"e": 2115,
"s": 2006,
"text": "library(nortest)\nad.test(df1$x)\n Anderson-Darling normality test\ndata: df1$x\nA = 0.21458, p-value = 0.8496"
},
{
"code": null,
"e": 2126,
"s": 2115,
"text": " Live Demo"
},
{
"code": null,
"e": 2193,
"s": 2126,
"text": "y<-sample(0:9,500000,replace=TRUE)\ndf2<-data.frame(y)\nhead(df2,20)"
},
{
"code": null,
"e": 2299,
"s": 2193,
"text": " y\n1 8\n2 9\n3 7\n4 0 \n5 3\n6 4\n7 9\n8 3\n9 1\n10 5\n11 9\n12 4\n13 5\n14 9\n15 5\n16 7\n17 1\n18 0\n19 4\n20 4"
},
{
"code": null,
"e": 2339,
"s": 2299,
"text": "Performing Anderson Darling test on y −"
},
{
"code": null,
"e": 2431,
"s": 2339,
"text": "ad.test(df2$y)\n Anderson-Darling normality test\ndata: df2$y\nA = 8634.6, p-value < 2.2e-16"
}
] |
How to create Static Variables in JavaScript ? - GeeksforGeeks | 22 Jun, 2021
In this article, we will learn to create static variables in JavaScript.
Static keyword in JavaScript: The static keyword is used to define a static method or property of a class. To call the static method we do not need to create an instance or object of the class.
Static variable in JavaScript: We used the static keyword to make a variable static just like the constant variable is defined using the const keyword. It is set at the run time and such type of variable works as a global variable. We can use the static variable anywhere. The value of the static variable can be reassigned, unlike the constant variable.
Why we create a static variable in JavaScript: We create a static variable in JavaScript to prevent replication, fixed-configuration, and it is also useful for caches.
Example 1: In the below example, we will create a static variable and display it on the JavaScript console.
Javascript
<script> class Example { static staticVariable = 'GeeksforGeeks'; //static variable defined static staticMethod() { return 'static method has been called.'; } } // static variable called console.log(Example.staticVariable); // static method called console.log(Example.staticMethod()); </static>
Output:
Static method
Example 2: Static variable is called using this keyword.
Javascript
<script> class Example { static staticVariable = 'GeeksforGeeks'; //static variable defined static staticMethod() { return 'staticVariable : '+this.staticVariable; } } // static method called console.log(Example.staticMethod());</script>
Output:
surindertarika1234
javascript-functions
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25220,
"s": 25192,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 25293,
"s": 25220,
"text": "In this article, we will learn to create static variables in JavaScript."
},
{
"code": null,
"e": 25487,
"s": 25293,
"text": "Static keyword in JavaScript: The static keyword is used to define a static method or property of a class. To call the static method we do not need to create an instance or object of the class."
},
{
"code": null,
"e": 25842,
"s": 25487,
"text": "Static variable in JavaScript: We used the static keyword to make a variable static just like the constant variable is defined using the const keyword. It is set at the run time and such type of variable works as a global variable. We can use the static variable anywhere. The value of the static variable can be reassigned, unlike the constant variable."
},
{
"code": null,
"e": 26011,
"s": 25842,
"text": "Why we create a static variable in JavaScript: We create a static variable in JavaScript to prevent replication, fixed-configuration, and it is also useful for caches. "
},
{
"code": null,
"e": 26119,
"s": 26011,
"text": "Example 1: In the below example, we will create a static variable and display it on the JavaScript console."
},
{
"code": null,
"e": 26130,
"s": 26119,
"text": "Javascript"
},
{
"code": "<script> class Example { static staticVariable = 'GeeksforGeeks'; //static variable defined static staticMethod() { return 'static method has been called.'; } } // static variable called console.log(Example.staticVariable); // static method called console.log(Example.staticMethod()); </static>",
"e": 26450,
"s": 26130,
"text": null
},
{
"code": null,
"e": 26459,
"s": 26450,
"text": "Output: "
},
{
"code": null,
"e": 26473,
"s": 26459,
"text": "Static method"
},
{
"code": null,
"e": 26530,
"s": 26473,
"text": "Example 2: Static variable is called using this keyword."
},
{
"code": null,
"e": 26541,
"s": 26530,
"text": "Javascript"
},
{
"code": "<script> class Example { static staticVariable = 'GeeksforGeeks'; //static variable defined static staticMethod() { return 'staticVariable : '+this.staticVariable; } } // static method called console.log(Example.staticMethod());</script>",
"e": 26799,
"s": 26541,
"text": null
},
{
"code": null,
"e": 26807,
"s": 26799,
"text": "Output:"
},
{
"code": null,
"e": 26826,
"s": 26807,
"text": "surindertarika1234"
},
{
"code": null,
"e": 26847,
"s": 26826,
"text": "javascript-functions"
},
{
"code": null,
"e": 26868,
"s": 26847,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 26875,
"s": 26868,
"text": "Picked"
},
{
"code": null,
"e": 26886,
"s": 26875,
"text": "JavaScript"
},
{
"code": null,
"e": 26903,
"s": 26886,
"text": "Web Technologies"
},
{
"code": null,
"e": 27001,
"s": 26903,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27010,
"s": 27001,
"text": "Comments"
},
{
"code": null,
"e": 27023,
"s": 27010,
"text": "Old Comments"
},
{
"code": null,
"e": 27084,
"s": 27023,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27125,
"s": 27084,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27179,
"s": 27125,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27236,
"s": 27179,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 27298,
"s": 27236,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27340,
"s": 27298,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27373,
"s": 27340,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27435,
"s": 27373,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27478,
"s": 27435,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
LDA on the Texts of Harry Potter. Topic Modeling with Latent Dirichlet... | by Greg Rafferty | Towards Data Science | I’m Greg Rafferty, a data scientist in the Bay Area. You can check out the code for this project on my github. Feel free to contact me with any questions!
In this post, I’ll describe topic modeling with Latent Dirichlet Allocation and compare different algorithms for it, through the lens of Harry Potter. Upcoming posts will cover two more NLP tasks: text summarization and sentiment analysis.
Recently, I was put on a new project with a team who were unanimously shocked and disappointed that I’d never read nor seen the movies about a certain fictional wizard named Harry Potter. In order to fit in with the team, and obviously save my career from an early end, it quickly became evident that I was going to have to take a crash-course in the happenings at Hogwarts. Armed with my ebook reader and seven shiny new pdf files, I settled in to see what the fuss was all about. Meanwhile, I had started working on a side project composed of a bunch of unrelated NLP tasks. I needed a good sized set of text documents and I thought all of these shiny new pdfs would be a great source.
And somewhere around the middle of the third book, I suddenly realized that LDA was basically just an algorithmic Sorting Hat.
LDA, or Latent Dirichlet Allocation, is a generative probabilistic model of (in NLP terms) a corpus of documents made up of words and/or phrases. The model consists of two tables; the first table is the probability of selecting a particular word in the corpus when sampling from a particular topic, and the second table is the probability of selecting a particular topic when sampling from a particular document.
Here’s an example. Let’s say I’ve got these three (rather non-sensical) documents:
document_0 = "Harry Harry wand Harry magic wand"document_1 = "Hermione robe Hermione robe magic Hermione"document_2 = "Malfoy spell Malfoy magic spell Malfoy"document_3 = "Harry Harry Hermione Hermione Malfoy Malfoy"
Here’s the term-frequency matrix for these documents:
Just from glancing at this, it seems pretty obvious that document 0 is mostly about Harry, a little bit about magic, and partly about wand. Document 1 is also a little bit about magic, but mostly about Hermione and robe. And document 2 is again partly about magic, but mostly about Malfoy and spell. Document 3 is equally about Harry, Hermione, and Malfoy. It’s usually not so easy to see this because a more practical corpus would consists of thousands or ten-of-thousands of words, so let’s see what the LDA algorithm chooses for topics:
And that’s roughly what we predicted just by going with term frequencies and our gut. The number of topics is a hyperparameter you’ll need to choose and tune carefully, and I’ll go into that later, but for this example I chose 4 topics to make my point. The upper table shows words versus topics and the lower table shows documents versus topics. Each column in the upper table and each row in the lower table must sum to 1. These tables are telling us that if we were to randomly sample a word from Topic 0, there’s a 70.9% chance we’d grab “Harry”. If we chose a word from Topic 3, it’s near certain that we’d pick “magic”. If we sampled Document 3, there’s an equal chance that we would pick Topic 0, 1, or 2.
It’s up to us as smart humans who can infer meaning from a bag of words to name these topics. In these examples with a very limited vocabulary, the topics quite obviously correspond to single words. If we had run LDA on, say, a couple thousand restaurant descriptions, we might find topics corresponding to cuisine type or atmosphere. It’s important to note that LDA, unlike typical clustering algorithms such as Kmeans, allows a document to exist in multiple topics. So in those restaurant descriptions, we might find one restaurant placed in the “Italian”, “date-night”, and “cafe” topics.
So how is all of this like the Sorting Hat? All new students at Hogwarts go through a ceremony when they arrive on day one to determine which house they’ll be in (I’m probably the only person who didn’t know this up until a few weeks ago). The Sorting Hat, once placed on someone’s head, understands what is in their thoughts, dreams, and experiences. This is a bit like LDA building the term-frequency matrix and understanding what words and N-grams are contained within each document.
The Sorting Hat then compares the student’s attributes with the attributes of the various houses (bravery goes to Gryffindor, loyalty to Hufflepuff, wisdom to Ravenclaw, and sneaky, shifty sleazeballs go to Slytherin (ok, just a quick aside — can ANYONE explain to me why Slytherin has persisted for the thousand-year history of this school? It’s like that one fraternity which finds itself in yet another ridiculously obscene scandal every damn year!)). This is where LDA creates the word-topic table and begins to associate the attributes of the topics.
Harry’s placement was notably split between Gryffindor and Slytherin due to his combination of courage, intelligence, talent, and ambition, but Gryffindor just slightly edged out ahead and Harry Potter became the hero of an entire generation of young millennials instead of its villain. This is where LDA creates the document-topic table and finally determines which is the dominant topic for each document.
OK, so now that we know roughly what LDA does, let’s look at two different implementations in Python. Check out my Github repo for all of the nitty-gritty details.
First of all, one of the best ways to determine how many topics you should model is with an elbow plot. This is the same technique often used to determine how many clusters to choose with the clustering algorithms. In this case, we’ll plot the coherence score against the number of topics:
You’ll generally want to pick the lowest number of topics where the coherence score begins to level off. This is why it’s called an elbow plot — you pick the elbow between steep gains and shallow gains. In this case (and it’s a remarkably spiky case; usually the curves are a little bit smoother than this), I’d go with somewhere around 20 topics.
The first model I used is Gensim’s ldamodel. At 20 topics, Gensim had a coherence score of 0.319. This is not great; indeed the Mallet algorithm which we’ll look at next almost always outperforms Gensim’s. However, one really cool thing with Gensim is the pyLDAvis, an interactive chart you can run in a Jupyter notebook. It plots the clusters with two principal components and shows the proportion of words in each cluster:
The next implementation I looked at was Mallet (MAchine Learning for LanguagE Toolkit), a Java-based package put out by UMASS Amherst. The difference between Mallet and Gensim’s standard LDA is that Gensim uses a Variational Bayes sampling method which is faster but less precise that Mallet’s Gibbs Sampling. Fortunately for those who prefer to code in Python, Gensim has a wrapper for Mallet: Latent Dirichlet Allocation via Mallet. In order to use it, you need to download the Mallet Java package from here http://mallet.cs.umass.edu/dist/mallet-2.0.8.zip and also install the Java Development Kit. Once everything is set up, implementing the model is pretty much the same as Gensim’s standard model. Using Mallet, the coherence score for the 20-topic model increased to 0.375 (remember, Gensim’s standard model output 0.319). It’s a modest increase, but usually persists with a variety of data sources so although Mallet is slightly slower, I prefer it for its increase in return.
Finally, I built a Mallet model on the 192 chapters of all 7 books in the Harry Potter series. Here are the top 10 keywords the model output for each latent topic. How would you name these clusters? | [
{
"code": null,
"e": 326,
"s": 171,
"text": "I’m Greg Rafferty, a data scientist in the Bay Area. You can check out the code for this project on my github. Feel free to contact me with any questions!"
},
{
"code": null,
"e": 566,
"s": 326,
"text": "In this post, I’ll describe topic modeling with Latent Dirichlet Allocation and compare different algorithms for it, through the lens of Harry Potter. Upcoming posts will cover two more NLP tasks: text summarization and sentiment analysis."
},
{
"code": null,
"e": 1254,
"s": 566,
"text": "Recently, I was put on a new project with a team who were unanimously shocked and disappointed that I’d never read nor seen the movies about a certain fictional wizard named Harry Potter. In order to fit in with the team, and obviously save my career from an early end, it quickly became evident that I was going to have to take a crash-course in the happenings at Hogwarts. Armed with my ebook reader and seven shiny new pdf files, I settled in to see what the fuss was all about. Meanwhile, I had started working on a side project composed of a bunch of unrelated NLP tasks. I needed a good sized set of text documents and I thought all of these shiny new pdfs would be a great source."
},
{
"code": null,
"e": 1381,
"s": 1254,
"text": "And somewhere around the middle of the third book, I suddenly realized that LDA was basically just an algorithmic Sorting Hat."
},
{
"code": null,
"e": 1794,
"s": 1381,
"text": "LDA, or Latent Dirichlet Allocation, is a generative probabilistic model of (in NLP terms) a corpus of documents made up of words and/or phrases. The model consists of two tables; the first table is the probability of selecting a particular word in the corpus when sampling from a particular topic, and the second table is the probability of selecting a particular topic when sampling from a particular document."
},
{
"code": null,
"e": 1877,
"s": 1794,
"text": "Here’s an example. Let’s say I’ve got these three (rather non-sensical) documents:"
},
{
"code": null,
"e": 2094,
"s": 1877,
"text": "document_0 = \"Harry Harry wand Harry magic wand\"document_1 = \"Hermione robe Hermione robe magic Hermione\"document_2 = \"Malfoy spell Malfoy magic spell Malfoy\"document_3 = \"Harry Harry Hermione Hermione Malfoy Malfoy\""
},
{
"code": null,
"e": 2148,
"s": 2094,
"text": "Here’s the term-frequency matrix for these documents:"
},
{
"code": null,
"e": 2688,
"s": 2148,
"text": "Just from glancing at this, it seems pretty obvious that document 0 is mostly about Harry, a little bit about magic, and partly about wand. Document 1 is also a little bit about magic, but mostly about Hermione and robe. And document 2 is again partly about magic, but mostly about Malfoy and spell. Document 3 is equally about Harry, Hermione, and Malfoy. It’s usually not so easy to see this because a more practical corpus would consists of thousands or ten-of-thousands of words, so let’s see what the LDA algorithm chooses for topics:"
},
{
"code": null,
"e": 3401,
"s": 2688,
"text": "And that’s roughly what we predicted just by going with term frequencies and our gut. The number of topics is a hyperparameter you’ll need to choose and tune carefully, and I’ll go into that later, but for this example I chose 4 topics to make my point. The upper table shows words versus topics and the lower table shows documents versus topics. Each column in the upper table and each row in the lower table must sum to 1. These tables are telling us that if we were to randomly sample a word from Topic 0, there’s a 70.9% chance we’d grab “Harry”. If we chose a word from Topic 3, it’s near certain that we’d pick “magic”. If we sampled Document 3, there’s an equal chance that we would pick Topic 0, 1, or 2."
},
{
"code": null,
"e": 3993,
"s": 3401,
"text": "It’s up to us as smart humans who can infer meaning from a bag of words to name these topics. In these examples with a very limited vocabulary, the topics quite obviously correspond to single words. If we had run LDA on, say, a couple thousand restaurant descriptions, we might find topics corresponding to cuisine type or atmosphere. It’s important to note that LDA, unlike typical clustering algorithms such as Kmeans, allows a document to exist in multiple topics. So in those restaurant descriptions, we might find one restaurant placed in the “Italian”, “date-night”, and “cafe” topics."
},
{
"code": null,
"e": 4480,
"s": 3993,
"text": "So how is all of this like the Sorting Hat? All new students at Hogwarts go through a ceremony when they arrive on day one to determine which house they’ll be in (I’m probably the only person who didn’t know this up until a few weeks ago). The Sorting Hat, once placed on someone’s head, understands what is in their thoughts, dreams, and experiences. This is a bit like LDA building the term-frequency matrix and understanding what words and N-grams are contained within each document."
},
{
"code": null,
"e": 5036,
"s": 4480,
"text": "The Sorting Hat then compares the student’s attributes with the attributes of the various houses (bravery goes to Gryffindor, loyalty to Hufflepuff, wisdom to Ravenclaw, and sneaky, shifty sleazeballs go to Slytherin (ok, just a quick aside — can ANYONE explain to me why Slytherin has persisted for the thousand-year history of this school? It’s like that one fraternity which finds itself in yet another ridiculously obscene scandal every damn year!)). This is where LDA creates the word-topic table and begins to associate the attributes of the topics."
},
{
"code": null,
"e": 5444,
"s": 5036,
"text": "Harry’s placement was notably split between Gryffindor and Slytherin due to his combination of courage, intelligence, talent, and ambition, but Gryffindor just slightly edged out ahead and Harry Potter became the hero of an entire generation of young millennials instead of its villain. This is where LDA creates the document-topic table and finally determines which is the dominant topic for each document."
},
{
"code": null,
"e": 5608,
"s": 5444,
"text": "OK, so now that we know roughly what LDA does, let’s look at two different implementations in Python. Check out my Github repo for all of the nitty-gritty details."
},
{
"code": null,
"e": 5898,
"s": 5608,
"text": "First of all, one of the best ways to determine how many topics you should model is with an elbow plot. This is the same technique often used to determine how many clusters to choose with the clustering algorithms. In this case, we’ll plot the coherence score against the number of topics:"
},
{
"code": null,
"e": 6246,
"s": 5898,
"text": "You’ll generally want to pick the lowest number of topics where the coherence score begins to level off. This is why it’s called an elbow plot — you pick the elbow between steep gains and shallow gains. In this case (and it’s a remarkably spiky case; usually the curves are a little bit smoother than this), I’d go with somewhere around 20 topics."
},
{
"code": null,
"e": 6671,
"s": 6246,
"text": "The first model I used is Gensim’s ldamodel. At 20 topics, Gensim had a coherence score of 0.319. This is not great; indeed the Mallet algorithm which we’ll look at next almost always outperforms Gensim’s. However, one really cool thing with Gensim is the pyLDAvis, an interactive chart you can run in a Jupyter notebook. It plots the clusters with two principal components and shows the proportion of words in each cluster:"
},
{
"code": null,
"e": 7656,
"s": 6671,
"text": "The next implementation I looked at was Mallet (MAchine Learning for LanguagE Toolkit), a Java-based package put out by UMASS Amherst. The difference between Mallet and Gensim’s standard LDA is that Gensim uses a Variational Bayes sampling method which is faster but less precise that Mallet’s Gibbs Sampling. Fortunately for those who prefer to code in Python, Gensim has a wrapper for Mallet: Latent Dirichlet Allocation via Mallet. In order to use it, you need to download the Mallet Java package from here http://mallet.cs.umass.edu/dist/mallet-2.0.8.zip and also install the Java Development Kit. Once everything is set up, implementing the model is pretty much the same as Gensim’s standard model. Using Mallet, the coherence score for the 20-topic model increased to 0.375 (remember, Gensim’s standard model output 0.319). It’s a modest increase, but usually persists with a variety of data sources so although Mallet is slightly slower, I prefer it for its increase in return."
}
] |
difftime() function in C++ - GeeksforGeeks | 01 Oct, 2018
The difftime() function is defined in ctime header file. The difftime() function is used to calculate the difference between two times in second.
Syntax:
double difftime(time_t end, time_t start);
Parameters: This method accepts two parameters:
start: time_t object for start time.
end: time_t object for end time.
Returns: This function returns the difference between two times in seconds.
Example:-
// C++ program to demonstrate// example of difftime() function. #include <bits/stdc++.h>using namespace std; int main(){ time_t start, ending; long addition; time(&start); for (int i = 0; i < 20000; i++) { for (int j = 0; j < 20000; j++); } for (int i = 0; i < 20000; i++) { for (int j = 0; j < 20000; j++); } for (int i = 0; i < 20000; i++) { for (int j = 0; j < 20000; j++); } time(&ending); cout << "Total time required = " << difftime(ending, start) << " seconds " << endl; return 0;}
Total time required = 2 seconds
CPP-Functions
CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Map in C++ Standard Template Library (STL)
Inheritance in C++
C++ Classes and Objects
Constructors in C++
Bitwise Operators in C/C++
Socket Programming in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Copy Constructor in C++
Virtual Function in C++ | [
{
"code": null,
"e": 24136,
"s": 24108,
"text": "\n01 Oct, 2018"
},
{
"code": null,
"e": 24282,
"s": 24136,
"text": "The difftime() function is defined in ctime header file. The difftime() function is used to calculate the difference between two times in second."
},
{
"code": null,
"e": 24290,
"s": 24282,
"text": "Syntax:"
},
{
"code": null,
"e": 24333,
"s": 24290,
"text": "double difftime(time_t end, time_t start);"
},
{
"code": null,
"e": 24381,
"s": 24333,
"text": "Parameters: This method accepts two parameters:"
},
{
"code": null,
"e": 24418,
"s": 24381,
"text": "start: time_t object for start time."
},
{
"code": null,
"e": 24451,
"s": 24418,
"text": "end: time_t object for end time."
},
{
"code": null,
"e": 24527,
"s": 24451,
"text": "Returns: This function returns the difference between two times in seconds."
},
{
"code": null,
"e": 24537,
"s": 24527,
"text": "Example:-"
},
{
"code": "// C++ program to demonstrate// example of difftime() function. #include <bits/stdc++.h>using namespace std; int main(){ time_t start, ending; long addition; time(&start); for (int i = 0; i < 20000; i++) { for (int j = 0; j < 20000; j++); } for (int i = 0; i < 20000; i++) { for (int j = 0; j < 20000; j++); } for (int i = 0; i < 20000; i++) { for (int j = 0; j < 20000; j++); } time(&ending); cout << \"Total time required = \" << difftime(ending, start) << \" seconds \" << endl; return 0;}",
"e": 25103,
"s": 24537,
"text": null
},
{
"code": null,
"e": 25136,
"s": 25103,
"text": "Total time required = 2 seconds\n"
},
{
"code": null,
"e": 25150,
"s": 25136,
"text": "CPP-Functions"
},
{
"code": null,
"e": 25162,
"s": 25150,
"text": "CPP-Library"
},
{
"code": null,
"e": 25166,
"s": 25162,
"text": "C++"
},
{
"code": null,
"e": 25170,
"s": 25166,
"text": "CPP"
},
{
"code": null,
"e": 25268,
"s": 25170,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25277,
"s": 25268,
"text": "Comments"
},
{
"code": null,
"e": 25290,
"s": 25277,
"text": "Old Comments"
},
{
"code": null,
"e": 25333,
"s": 25290,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 25352,
"s": 25333,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 25376,
"s": 25352,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 25396,
"s": 25376,
"text": "Constructors in C++"
},
{
"code": null,
"e": 25423,
"s": 25396,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 25451,
"s": 25423,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 25479,
"s": 25451,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 25514,
"s": 25479,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 25538,
"s": 25514,
"text": "Copy Constructor in C++"
}
] |
Apache NiFi - Monitoring | In Apache NiFi, there are multiple ways to monitor the different statistics of the system like errors, memory usage, CPU usage, Data Flow statistics, etc. We will discuss the most popular ones in this tutorial.
In this section, we will learn more about in built monitoring in Apache NiFi.
The bulletin board shows the latest ERROR and WARNING getting generated by NiFi processors in real time. To access the bulletin board, a user will have to go the right hand drop down menu and select the Bulletin Board option. It refreshes automatically and a user can disable it also. A user can also navigate to the actual processor by double-clicking the error. A user can also filter the bulletins by working out with the following −
by message
by name
by id
by group id
To monitor the Events occurring on any specific processor or throughout NiFi, a user can access the Data provenance from the same menu as the bulletin board. A user can also filter the events in data provenance repository by working out with the following fields −
by component name
by component type
by type
Apache NiFi summary also can be accessed from the same menu as the bulletin board. This UI contains information about all the components of that particular NiFi instance or cluster. They can be filtered by name, by type or by URI. There are different tabs for different component types. Following are the components, which can be monitored in the NiFi summary UI −
Processors
Input ports
Output ports
Remote process groups
Connections
Process groups
In this UI, there is a link at the bottom right hand side named system diagnostics to check the JVM statistics.
Apache NiFi provides multiple reporting tasks to support external monitoring systems like Ambari, Grafana, etc. A developer can create a custom reporting task or can configure the inbuilt ones to send the metrics of NiFi to the externals monitoring systems. The following table lists down the reporting tasks offered by NiFi 1.7.1.
There is an API named system diagnostics, which can be used to monitor the NiFI stats in any custom developed application. Let us check the API in postman.
http://localhost:8080/nifi-api/system-diagnostics
{
"systemDiagnostics": {
"aggregateSnapshot": {
"totalNonHeap": "183.89 MB",
"totalNonHeapBytes": 192819200,
"usedNonHeap": "173.47 MB",
"usedNonHeapBytes": 181894560,
"freeNonHeap": "10.42 MB",
"freeNonHeapBytes": 10924640,
"maxNonHeap": "-1 bytes",
"maxNonHeapBytes": -1,
"totalHeap": "512 MB",
"totalHeapBytes": 536870912,
"usedHeap": "273.37 MB",
"usedHeapBytes": 286652264,
"freeHeap": "238.63 MB",
"freeHeapBytes": 250218648,
"maxHeap": "512 MB",
"maxHeapBytes": 536870912,
"heapUtilization": "53.0%",
"availableProcessors": 4,
"processorLoadAverage": -1,
"totalThreads": 71,
"daemonThreads": 31,
"uptime": "17:30:35.277",
"flowFileRepositoryStorageUsage": {
"freeSpace": "286.93 GB",
"totalSpace": "464.78 GB",
"usedSpace": "177.85 GB",
"freeSpaceBytes": 308090789888,
"totalSpaceBytes": 499057160192,
"usedSpaceBytes": 190966370304,
"utilization": "38.0%"
},
"contentRepositoryStorageUsage": [
{
"identifier": "default",
"freeSpace": "286.93 GB",
"totalSpace": "464.78 GB",
"usedSpace": "177.85 GB",
"freeSpaceBytes": 308090789888,
"totalSpaceBytes": 499057160192,
"usedSpaceBytes": 190966370304,
"utilization": "38.0%"
}
],
"provenanceRepositoryStorageUsage": [
{
"identifier": "default",
"freeSpace": "286.93 GB",
"totalSpace": "464.78 GB",
"usedSpace": "177.85 GB",
"freeSpaceBytes": 308090789888,
"totalSpaceBytes": 499057160192,
"usedSpaceBytes": 190966370304,
"utilization": "38.0%"
}
],
"garbageCollection": [
{
"name": "G1 Young Generation",
"collectionCount": 344,
"collectionTime": "00:00:06.239",
"collectionMillis": 6239
},
{
"name": "G1 Old Generation",
"collectionCount": 0,
"collectionTime": "00:00:00.000",
"collectionMillis": 0
}
],
"statsLastRefreshed": "09:30:20 SGT",
"versionInfo": {
"niFiVersion": "1.7.1",
"javaVendor": "Oracle Corporation",
"javaVersion": "1.8.0_151",
"osName": "Windows 7",
"osVersion": "6.1",
"osArchitecture": "amd64",
"buildTag": "nifi-1.7.1-RC1",
"buildTimestamp": "07/12/2018 12:54:43 SGT"
}
}
}
}
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": 2529,
"s": 2318,
"text": "In Apache NiFi, there are multiple ways to monitor the different statistics of the system like errors, memory usage, CPU usage, Data Flow statistics, etc. We will discuss the most popular ones in this tutorial."
},
{
"code": null,
"e": 2607,
"s": 2529,
"text": "In this section, we will learn more about in built monitoring in Apache NiFi."
},
{
"code": null,
"e": 3044,
"s": 2607,
"text": "The bulletin board shows the latest ERROR and WARNING getting generated by NiFi processors in real time. To access the bulletin board, a user will have to go the right hand drop down menu and select the Bulletin Board option. It refreshes automatically and a user can disable it also. A user can also navigate to the actual processor by double-clicking the error. A user can also filter the bulletins by working out with the following −"
},
{
"code": null,
"e": 3055,
"s": 3044,
"text": "by message"
},
{
"code": null,
"e": 3063,
"s": 3055,
"text": "by name"
},
{
"code": null,
"e": 3069,
"s": 3063,
"text": "by id"
},
{
"code": null,
"e": 3081,
"s": 3069,
"text": "by group id"
},
{
"code": null,
"e": 3346,
"s": 3081,
"text": "To monitor the Events occurring on any specific processor or throughout NiFi, a user can access the Data provenance from the same menu as the bulletin board. A user can also filter the events in data provenance repository by working out with the following fields −"
},
{
"code": null,
"e": 3364,
"s": 3346,
"text": "by component name"
},
{
"code": null,
"e": 3382,
"s": 3364,
"text": "by component type"
},
{
"code": null,
"e": 3390,
"s": 3382,
"text": "by type"
},
{
"code": null,
"e": 3755,
"s": 3390,
"text": "Apache NiFi summary also can be accessed from the same menu as the bulletin board. This UI contains information about all the components of that particular NiFi instance or cluster. They can be filtered by name, by type or by URI. There are different tabs for different component types. Following are the components, which can be monitored in the NiFi summary UI −"
},
{
"code": null,
"e": 3766,
"s": 3755,
"text": "Processors"
},
{
"code": null,
"e": 3778,
"s": 3766,
"text": "Input ports"
},
{
"code": null,
"e": 3791,
"s": 3778,
"text": "Output ports"
},
{
"code": null,
"e": 3813,
"s": 3791,
"text": "Remote process groups"
},
{
"code": null,
"e": 3825,
"s": 3813,
"text": "Connections"
},
{
"code": null,
"e": 3840,
"s": 3825,
"text": "Process groups"
},
{
"code": null,
"e": 3952,
"s": 3840,
"text": "In this UI, there is a link at the bottom right hand side named system diagnostics to check the JVM statistics."
},
{
"code": null,
"e": 4284,
"s": 3952,
"text": "Apache NiFi provides multiple reporting tasks to support external monitoring systems like Ambari, Grafana, etc. A developer can create a custom reporting task or can configure the inbuilt ones to send the metrics of NiFi to the externals monitoring systems. The following table lists down the reporting tasks offered by NiFi 1.7.1."
},
{
"code": null,
"e": 4440,
"s": 4284,
"text": "There is an API named system diagnostics, which can be used to monitor the NiFI stats in any custom developed application. Let us check the API in postman."
},
{
"code": null,
"e": 4491,
"s": 4440,
"text": "http://localhost:8080/nifi-api/system-diagnostics\n"
},
{
"code": null,
"e": 7396,
"s": 4491,
"text": "{\n \"systemDiagnostics\": {\n \"aggregateSnapshot\": {\n \"totalNonHeap\": \"183.89 MB\",\n \"totalNonHeapBytes\": 192819200,\n \"usedNonHeap\": \"173.47 MB\",\n \"usedNonHeapBytes\": 181894560,\n \"freeNonHeap\": \"10.42 MB\",\n \"freeNonHeapBytes\": 10924640,\n \"maxNonHeap\": \"-1 bytes\",\n \"maxNonHeapBytes\": -1,\n \"totalHeap\": \"512 MB\",\n \"totalHeapBytes\": 536870912,\n \"usedHeap\": \"273.37 MB\",\n \"usedHeapBytes\": 286652264,\n \"freeHeap\": \"238.63 MB\",\n \"freeHeapBytes\": 250218648,\n \"maxHeap\": \"512 MB\",\n \"maxHeapBytes\": 536870912,\n \"heapUtilization\": \"53.0%\",\n \"availableProcessors\": 4,\n \"processorLoadAverage\": -1,\n \"totalThreads\": 71,\n \"daemonThreads\": 31,\n \"uptime\": \"17:30:35.277\",\n \"flowFileRepositoryStorageUsage\": {\n \"freeSpace\": \"286.93 GB\",\n \"totalSpace\": \"464.78 GB\",\n \"usedSpace\": \"177.85 GB\",\n \"freeSpaceBytes\": 308090789888,\n \"totalSpaceBytes\": 499057160192,\n \"usedSpaceBytes\": 190966370304,\n \"utilization\": \"38.0%\"\n },\n \"contentRepositoryStorageUsage\": [\n {\n \"identifier\": \"default\",\n \"freeSpace\": \"286.93 GB\",\n \"totalSpace\": \"464.78 GB\",\n \"usedSpace\": \"177.85 GB\",\n \"freeSpaceBytes\": 308090789888,\n \"totalSpaceBytes\": 499057160192,\n \"usedSpaceBytes\": 190966370304,\n \"utilization\": \"38.0%\"\n }\n ],\n \"provenanceRepositoryStorageUsage\": [\n {\n \"identifier\": \"default\",\n \"freeSpace\": \"286.93 GB\",\n \"totalSpace\": \"464.78 GB\",\n \"usedSpace\": \"177.85 GB\",\n \"freeSpaceBytes\": 308090789888,\n \"totalSpaceBytes\": 499057160192,\n \"usedSpaceBytes\": 190966370304,\n \"utilization\": \"38.0%\"\n }\n ],\n \"garbageCollection\": [\n {\n \"name\": \"G1 Young Generation\",\n \"collectionCount\": 344,\n \"collectionTime\": \"00:00:06.239\",\n \"collectionMillis\": 6239\n },\n {\n \"name\": \"G1 Old Generation\",\n \"collectionCount\": 0,\n \"collectionTime\": \"00:00:00.000\",\n \"collectionMillis\": 0\n }\n ],\n \"statsLastRefreshed\": \"09:30:20 SGT\",\n \"versionInfo\": {\n \"niFiVersion\": \"1.7.1\",\n \"javaVendor\": \"Oracle Corporation\",\n \"javaVersion\": \"1.8.0_151\",\n \"osName\": \"Windows 7\",\n \"osVersion\": \"6.1\",\n \"osArchitecture\": \"amd64\",\n \"buildTag\": \"nifi-1.7.1-RC1\",\n \"buildTimestamp\": \"07/12/2018 12:54:43 SGT\"\n }\n }\n }\n}\n"
},
{
"code": null,
"e": 7431,
"s": 7396,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7450,
"s": 7431,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7485,
"s": 7450,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7506,
"s": 7485,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 7539,
"s": 7506,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7552,
"s": 7539,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 7587,
"s": 7552,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7605,
"s": 7587,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7638,
"s": 7605,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7656,
"s": 7638,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7689,
"s": 7656,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7707,
"s": 7689,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7714,
"s": 7707,
"text": " Print"
},
{
"code": null,
"e": 7725,
"s": 7714,
"text": " Add Notes"
}
] |
Largest subarray of 0's and 1's | Practice | GeeksforGeeks | Given an array of 0s and 1s. Find the length of the largest subarray with equal number of 0s and 1s.
Example 1:
Input:
N = 4
A[] = {0,1,0,1}
Output: 4
Explanation: The array from index [0...3]
contains equal number of 0's and 1's.
Thus maximum length of subarray having
equal number of 0's and 1's is 4.
Example 2:
Input:
N = 5
A[] = {0,0,1,0,0}
Output: 2
Your Task:
You don't need to read input or print anything. Your task is to complete the function maxLen() which takes the array arr[] and the size of the array as inputs and returns the length of the largest subarray with equal number of 0s and 1s.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= N <= 105
0 <= A[] <= 1
0
harshpandeyalfa23 weeks ago
C++
(0.37sec)
int maxLen(int arr[], int N) { for(int i=0;i<N;i++) if(arr[i]==0) arr[i]=-1; int ps=0; int res=0; unordered_map<int,int> s; for(int i=0;i<N;i++) { ps=ps+arr[i]; if(ps==0) res=i+1; else if(s.find(ps) ==s.end()) s.insert({ps,i}); else if(s.find(ps)!=s.end()) res=max(res,i-s[ps]); } return res; }
0
pranjalmaurya20121361 month ago
What are the wrong code please tell me
int sum=0; for(int i=0;i<N;i++){ int co=0, c1=0; for(int j=i;j<N;j++){ if( arr[j]==0){ co++; } else{ c1++; } if(co==c1){ sum=Max(res,j-i+1); } } } return sum;
0
sknwd88643 months ago
int maxLen(int arr[], int n)
{
for(int i = 0; i < n; i++)
{
if(arr[i] == 0)
{
arr[i] = -1;
}
}
unordered_map<int, int> mp;
int longest = 0;
mp[0] = -1;
int sum = 0;
for(int i = 0; i < n; i++)
{
sum += arr[i];
if(mp.count(sum))
{
longest = max(longest, i - mp[sum]);
}
else
{
mp[sum] = i;
}
}
return longest;
}
0
priyeshanand93 months ago
class Solution{ public: int maxLen(int arr[], int N) { for(int i=0; i<N; i++){ if(arr[i]==0) arr[i]=-1; } map<int,int>m; m[arr[0]]=0;; int l=0; for(int i=1; i<N; i++){ arr[i]=arr[i-1]+arr[i]; if(arr[i]==0) l=max(l,i+1); else if(m.count(arr[i])>0) l=max(l,i-m[arr[i]]); else m[arr[i]]=i; } return l; }};
0
kurianspaul3 months ago
Clear and concise solution!
int maxLen(int[] arr, int N)
{
Map<Integer,Integer> map = new HashMap<>();
map.put(0,-1);
int res = 0,cumSum=0;
for(int i=0;i<arr.length;++i) {
cumSum = arr[i]==1 ? cumSum+1 : cumSum-1;
if(map.containsKey(cumSum)) res = Math.max(res,i-map.get(cumSum));
else map.put(cumSum,i);
}
return res;
}
+1
nikhilchakravarthy093 months ago
int maxLen(int arr[], int N)
{
int sum=0;
int ans=0;
unordered_map<int,int> mp;
for(int i=0;i<N;i++){
if(arr[i]==0)
sum-=1;
else
sum+=1;
if(sum==0)
ans=max(ans,i+1);
if(mp.find(sum) != mp.end())
ans=max(ans,i-mp[sum]);
else
mp[sum]=i;
}
return ans;
}
-1
aloksinghbais023 months ago
C++ solution having time complexity as O(N) and space complexity as O(N) is as follows :-
Note :- Similar question in which we try to find largest subarray with given sum k (In this question k is 0).
Link for other similar question :-
https://practice.geeksforgeeks.org/problems/longest-sub-array-with-sum-k0809/1#
Execution Time :- 0.4 / 1.6 sec
int maxLen(int arr[], int N){ unordered_map<int,int> firstLastInd; unordered_map<int,bool> mp; int len = 0; int sum = 0; mp[0] = true, firstLastInd[0] = 0; for(int i=0; i<N; i++){ sum += (arr[i] == 0 ? -1 : 1); if(mp[sum]){ len = max(len,i - firstLastInd[sum] + 1); } mp[sum] = true; if(firstLastInd[sum] == 0 && sum) firstLastInd[sum] = i+1; } return (len); }
0
raunakmishra12433 months ago
int maxLen(int arr[], int N)
{
unordered_map<int,int>m;
for(int i=0;i<N;i++)
{
if(arr[i]==0)
arr[i]=-1;
}
int sum=0;
m[sum]=-1;
int ans=INT_MIN;
for(int i=0;i<N;i++)
{
sum=sum+arr[i];
if(m.find(sum)!=m.end())
{
ans=max(ans,abs(m[sum]-i));
}
else
m[sum]=i;
}
if(ans==INT_MIN)
return 0;
return ans;
}
};
0
radheshyamnitj4 months ago
int length=0;
map<int,int>m;
int sum=0;
m[0]=-1;
for(int i=0;i<N;i++){
if(arr[i]==0)
sum+=-1;
else
sum+=1;
if(m.find(sum)==m.end())
m[sum]=i;
else
{
length=max(length,i-m[sum]);
}
}
return length;
+8
amanshakya0074 months ago
HINT 1. Think this question same as largest subarray with zero sum2. to make it zero sum you have to do something 3. make all 0 to -1
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": 339,
"s": 238,
"text": "Given an array of 0s and 1s. Find the length of the largest subarray with equal number of 0s and 1s."
},
{
"code": null,
"e": 350,
"s": 339,
"text": "Example 1:"
},
{
"code": null,
"e": 543,
"s": 350,
"text": "Input:\nN = 4\nA[] = {0,1,0,1}\nOutput: 4\nExplanation: The array from index [0...3]\ncontains equal number of 0's and 1's.\nThus maximum length of subarray having\nequal number of 0's and 1's is 4.\n"
},
{
"code": null,
"e": 554,
"s": 543,
"text": "Example 2:"
},
{
"code": null,
"e": 595,
"s": 554,
"text": "Input:\nN = 5\nA[] = {0,0,1,0,0}\nOutput: 2"
},
{
"code": null,
"e": 844,
"s": 595,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function maxLen() which takes the array arr[] and the size of the array as inputs and returns the length of the largest subarray with equal number of 0s and 1s."
},
{
"code": null,
"e": 908,
"s": 844,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)."
},
{
"code": null,
"e": 949,
"s": 908,
"text": "Constraints:\n1 <= N <= 105\n0 <= A[] <= 1"
},
{
"code": null,
"e": 951,
"s": 949,
"text": "0"
},
{
"code": null,
"e": 979,
"s": 951,
"text": "harshpandeyalfa23 weeks ago"
},
{
"code": null,
"e": 983,
"s": 979,
"text": "C++"
},
{
"code": null,
"e": 993,
"s": 983,
"text": "(0.37sec)"
},
{
"code": null,
"e": 1431,
"s": 993,
"text": "int maxLen(int arr[], int N) { for(int i=0;i<N;i++) if(arr[i]==0) arr[i]=-1; int ps=0; int res=0; unordered_map<int,int> s; for(int i=0;i<N;i++) { ps=ps+arr[i]; if(ps==0) res=i+1; else if(s.find(ps) ==s.end()) s.insert({ps,i}); else if(s.find(ps)!=s.end()) res=max(res,i-s[ps]); } return res; }"
},
{
"code": null,
"e": 1433,
"s": 1431,
"text": "0"
},
{
"code": null,
"e": 1465,
"s": 1433,
"text": "pranjalmaurya20121361 month ago"
},
{
"code": null,
"e": 1504,
"s": 1465,
"text": "What are the wrong code please tell me"
},
{
"code": null,
"e": 1923,
"s": 1508,
"text": " int sum=0; for(int i=0;i<N;i++){ int co=0, c1=0; for(int j=i;j<N;j++){ if( arr[j]==0){ co++; } else{ c1++; } if(co==c1){ sum=Max(res,j-i+1); } } } return sum;"
},
{
"code": null,
"e": 1929,
"s": 1927,
"text": "0"
},
{
"code": null,
"e": 1951,
"s": 1929,
"text": "sknwd88643 months ago"
},
{
"code": null,
"e": 2592,
"s": 1951,
"text": "int maxLen(int arr[], int n)\n {\n for(int i = 0; i < n; i++)\n {\n if(arr[i] == 0)\n {\n arr[i] = -1;\n }\n }\n \n unordered_map<int, int> mp;\n \n int longest = 0;\n \n mp[0] = -1;\n \n int sum = 0;\n \n for(int i = 0; i < n; i++)\n {\n sum += arr[i];\n \n if(mp.count(sum))\n {\n longest = max(longest, i - mp[sum]);\n }\n else\n {\n mp[sum] = i;\n }\n }\n \n return longest;\n }"
},
{
"code": null,
"e": 2594,
"s": 2592,
"text": "0"
},
{
"code": null,
"e": 2620,
"s": 2594,
"text": "priyeshanand93 months ago"
},
{
"code": null,
"e": 3057,
"s": 2620,
"text": "class Solution{ public: int maxLen(int arr[], int N) { for(int i=0; i<N; i++){ if(arr[i]==0) arr[i]=-1; } map<int,int>m; m[arr[0]]=0;; int l=0; for(int i=1; i<N; i++){ arr[i]=arr[i-1]+arr[i]; if(arr[i]==0) l=max(l,i+1); else if(m.count(arr[i])>0) l=max(l,i-m[arr[i]]); else m[arr[i]]=i; } return l; }};"
},
{
"code": null,
"e": 3059,
"s": 3057,
"text": "0"
},
{
"code": null,
"e": 3083,
"s": 3059,
"text": "kurianspaul3 months ago"
},
{
"code": null,
"e": 3111,
"s": 3083,
"text": "Clear and concise solution!"
},
{
"code": null,
"e": 3485,
"s": 3111,
"text": "int maxLen(int[] arr, int N)\n {\n Map<Integer,Integer> map = new HashMap<>();\n map.put(0,-1);\n int res = 0,cumSum=0;\n for(int i=0;i<arr.length;++i) {\n cumSum = arr[i]==1 ? cumSum+1 : cumSum-1;\n if(map.containsKey(cumSum)) res = Math.max(res,i-map.get(cumSum));\n else map.put(cumSum,i);\n }\n return res;\n }"
},
{
"code": null,
"e": 3488,
"s": 3485,
"text": "+1"
},
{
"code": null,
"e": 3521,
"s": 3488,
"text": "nikhilchakravarthy093 months ago"
},
{
"code": null,
"e": 3950,
"s": 3521,
"text": "int maxLen(int arr[], int N)\n {\n int sum=0;\n int ans=0;\n unordered_map<int,int> mp;\n for(int i=0;i<N;i++){\n if(arr[i]==0)\n sum-=1;\n else\n sum+=1;\n if(sum==0)\n ans=max(ans,i+1);\n if(mp.find(sum) != mp.end())\n ans=max(ans,i-mp[sum]);\n else\n mp[sum]=i;\n }\n return ans;\n }"
},
{
"code": null,
"e": 3953,
"s": 3950,
"text": "-1"
},
{
"code": null,
"e": 3981,
"s": 3953,
"text": "aloksinghbais023 months ago"
},
{
"code": null,
"e": 4071,
"s": 3981,
"text": "C++ solution having time complexity as O(N) and space complexity as O(N) is as follows :-"
},
{
"code": null,
"e": 4183,
"s": 4073,
"text": "Note :- Similar question in which we try to find largest subarray with given sum k (In this question k is 0)."
},
{
"code": null,
"e": 4221,
"s": 4185,
"text": "Link for other similar question :- "
},
{
"code": null,
"e": 4303,
"s": 4223,
"text": "https://practice.geeksforgeeks.org/problems/longest-sub-array-with-sum-k0809/1#"
},
{
"code": null,
"e": 4337,
"s": 4305,
"text": "Execution Time :- 0.4 / 1.6 sec"
},
{
"code": null,
"e": 4863,
"s": 4339,
"text": "int maxLen(int arr[], int N){ unordered_map<int,int> firstLastInd; unordered_map<int,bool> mp; int len = 0; int sum = 0; mp[0] = true, firstLastInd[0] = 0; for(int i=0; i<N; i++){ sum += (arr[i] == 0 ? -1 : 1); if(mp[sum]){ len = max(len,i - firstLastInd[sum] + 1); } mp[sum] = true; if(firstLastInd[sum] == 0 && sum) firstLastInd[sum] = i+1; } return (len); }"
},
{
"code": null,
"e": 4865,
"s": 4863,
"text": "0"
},
{
"code": null,
"e": 4894,
"s": 4865,
"text": "raunakmishra12433 months ago"
},
{
"code": null,
"e": 5494,
"s": 4894,
"text": "int maxLen(int arr[], int N)\n {\n unordered_map<int,int>m;\n \n \n for(int i=0;i<N;i++)\n {\n if(arr[i]==0)\n arr[i]=-1;\n }\n int sum=0;\n m[sum]=-1;\n int ans=INT_MIN;\n for(int i=0;i<N;i++)\n {\n sum=sum+arr[i];\n if(m.find(sum)!=m.end())\n {\n \n ans=max(ans,abs(m[sum]-i));\n \n }\n else\n m[sum]=i;\n \n }\n if(ans==INT_MIN)\n return 0;\n return ans;\n \n }\n};"
},
{
"code": null,
"e": 5496,
"s": 5494,
"text": "0"
},
{
"code": null,
"e": 5523,
"s": 5496,
"text": "radheshyamnitj4 months ago"
},
{
"code": null,
"e": 5927,
"s": 5523,
"text": "int length=0;\n map<int,int>m;\n \n int sum=0;\n m[0]=-1;\n \n for(int i=0;i<N;i++){\n if(arr[i]==0)\n sum+=-1;\n else\n sum+=1;\n \n if(m.find(sum)==m.end())\n m[sum]=i;\n \n else\n {\n length=max(length,i-m[sum]);\n }\n }\n return length;"
},
{
"code": null,
"e": 5930,
"s": 5927,
"text": "+8"
},
{
"code": null,
"e": 5956,
"s": 5930,
"text": "amanshakya0074 months ago"
},
{
"code": null,
"e": 6091,
"s": 5956,
"text": "HINT 1. Think this question same as largest subarray with zero sum2. to make it zero sum you have to do something 3. make all 0 to -1"
},
{
"code": null,
"e": 6237,
"s": 6091,
"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": 6273,
"s": 6237,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6283,
"s": 6273,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6293,
"s": 6283,
"text": "\nContest\n"
},
{
"code": null,
"e": 6356,
"s": 6293,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6504,
"s": 6356,
"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": 6712,
"s": 6504,
"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": 6818,
"s": 6712,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to Easily Create Tables in Python | by Luay Matalka | Towards Data Science | Being able to quickly organize our data into a more readable format, such as when data wrangling, can be extremely helpful in order to analyze the data and plan the next steps. Python offers the ability to easily turn certain tabular data types into nicely formatted plain-text tables, and that’s with the tabulate function.
We first install the tabulate library using pip install in the command line:
pip install tabulate
We then import the tabulate function from the tabulate library in our code:
from tabulate import tabulate
And now we are ready to use the tabulate function!
The tabulate function can transform any of the following into an easy to read plain-text table: (from the tabulate documentation)
list of lists or another iterable of iterables
list or another iterable of dicts (keys as columns)
dict of iterables (keys as columns)
two-dimensional NumPy array
NumPy record arrays (names as columns)
pandas.DataFrame
For example, if we have the following list of lists:
table = [['First Name', 'Last Name', 'Age'], ['John', 'Smith', 39], ['Mary', 'Jane', 25], ['Jennifer', 'Doe', 28]]
We can turn it into into a much more readable plain-text table using the tabulate function:
print(tabulate(table))
Since the first list in the list of lists contains the names of columns as its elements, we can set it as the column or header names by passing ‘firstrow’ as the argument for the headers parameter:
print(tabulate(table, headers='firstrow'))
The tabulate function also contains a tablefmt parameter, which allows us to improve the appearance of our table using pseudo-graphics:
print(tabulate(table, headers='firstrow', tablefmt='grid'))
I prefer to use the ‘fancy_grid’ argument for tablefmt:
print(tabulate(table, headers='firstrow', tablefmt='fancy_grid'))
towardsdatascience.com
We can create the same table above using a dictionary:
info = {'First Name': ['John', 'Mary', 'Jennifer'], 'Last Name': ['Smith', 'Jane', 'Doe'], 'Age': [39, 25, 28]}
In the case of a dictionary, the keys will be the column headers, and the values will be the elements of those columns. We specify that the keys will be the headers by passing ‘keys’ as the argument for the headers parameter:
print(tabulate(info, headers='keys'))
And of course we can use the tablefmt parameter to improve the table’s appearance:
print(tabulate(info, headers='keys', tablefmt='fancy_grid'))
We can also add an index to our table with the showindex parameter:
We can add a custom index by passing in an iterable to the showindex parameter. For example, if we want the index to start at 1, we can pass in a range object as the argument:
towardsdatascience.com
If we remove ‘Jennifer’ from the above info dictionary, our table will contain an empty field:
print(tabulate({'First Name': ['John', 'Mary'], 'Last Name': ['Smith', 'Jane', 'Doe'], 'Age': [39, 25, 28]}, headers="keys", tablefmt='fancy_grid'))
If there any missing values in our table, we can choose what to fill them in with using the missingval parameter. The default value for missingval is an empty string. If we change it to ‘N/A’, this is what what our table will look like:
print(tabulate({'First Name': ['John', 'Mary'], 'Last Name': ['Smith', 'Jane', 'Doe'], 'Age': [39, 25, 28]}, headers="keys", tablefmt='fancy_grid', missingval='N/A'))
towardsdatascience.com
I hope this tutorial on how to easily create nicely formatted tables using the tabulate function was helpful. Thank you for reading! | [
{
"code": null,
"e": 497,
"s": 172,
"text": "Being able to quickly organize our data into a more readable format, such as when data wrangling, can be extremely helpful in order to analyze the data and plan the next steps. Python offers the ability to easily turn certain tabular data types into nicely formatted plain-text tables, and that’s with the tabulate function."
},
{
"code": null,
"e": 574,
"s": 497,
"text": "We first install the tabulate library using pip install in the command line:"
},
{
"code": null,
"e": 595,
"s": 574,
"text": "pip install tabulate"
},
{
"code": null,
"e": 671,
"s": 595,
"text": "We then import the tabulate function from the tabulate library in our code:"
},
{
"code": null,
"e": 701,
"s": 671,
"text": "from tabulate import tabulate"
},
{
"code": null,
"e": 752,
"s": 701,
"text": "And now we are ready to use the tabulate function!"
},
{
"code": null,
"e": 882,
"s": 752,
"text": "The tabulate function can transform any of the following into an easy to read plain-text table: (from the tabulate documentation)"
},
{
"code": null,
"e": 929,
"s": 882,
"text": "list of lists or another iterable of iterables"
},
{
"code": null,
"e": 981,
"s": 929,
"text": "list or another iterable of dicts (keys as columns)"
},
{
"code": null,
"e": 1017,
"s": 981,
"text": "dict of iterables (keys as columns)"
},
{
"code": null,
"e": 1045,
"s": 1017,
"text": "two-dimensional NumPy array"
},
{
"code": null,
"e": 1084,
"s": 1045,
"text": "NumPy record arrays (names as columns)"
},
{
"code": null,
"e": 1101,
"s": 1084,
"text": "pandas.DataFrame"
},
{
"code": null,
"e": 1154,
"s": 1101,
"text": "For example, if we have the following list of lists:"
},
{
"code": null,
"e": 1269,
"s": 1154,
"text": "table = [['First Name', 'Last Name', 'Age'], ['John', 'Smith', 39], ['Mary', 'Jane', 25], ['Jennifer', 'Doe', 28]]"
},
{
"code": null,
"e": 1361,
"s": 1269,
"text": "We can turn it into into a much more readable plain-text table using the tabulate function:"
},
{
"code": null,
"e": 1384,
"s": 1361,
"text": "print(tabulate(table))"
},
{
"code": null,
"e": 1582,
"s": 1384,
"text": "Since the first list in the list of lists contains the names of columns as its elements, we can set it as the column or header names by passing ‘firstrow’ as the argument for the headers parameter:"
},
{
"code": null,
"e": 1625,
"s": 1582,
"text": "print(tabulate(table, headers='firstrow'))"
},
{
"code": null,
"e": 1761,
"s": 1625,
"text": "The tabulate function also contains a tablefmt parameter, which allows us to improve the appearance of our table using pseudo-graphics:"
},
{
"code": null,
"e": 1821,
"s": 1761,
"text": "print(tabulate(table, headers='firstrow', tablefmt='grid'))"
},
{
"code": null,
"e": 1877,
"s": 1821,
"text": "I prefer to use the ‘fancy_grid’ argument for tablefmt:"
},
{
"code": null,
"e": 1943,
"s": 1877,
"text": "print(tabulate(table, headers='firstrow', tablefmt='fancy_grid'))"
},
{
"code": null,
"e": 1966,
"s": 1943,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2021,
"s": 1966,
"text": "We can create the same table above using a dictionary:"
},
{
"code": null,
"e": 2133,
"s": 2021,
"text": "info = {'First Name': ['John', 'Mary', 'Jennifer'], 'Last Name': ['Smith', 'Jane', 'Doe'], 'Age': [39, 25, 28]}"
},
{
"code": null,
"e": 2359,
"s": 2133,
"text": "In the case of a dictionary, the keys will be the column headers, and the values will be the elements of those columns. We specify that the keys will be the headers by passing ‘keys’ as the argument for the headers parameter:"
},
{
"code": null,
"e": 2397,
"s": 2359,
"text": "print(tabulate(info, headers='keys'))"
},
{
"code": null,
"e": 2480,
"s": 2397,
"text": "And of course we can use the tablefmt parameter to improve the table’s appearance:"
},
{
"code": null,
"e": 2541,
"s": 2480,
"text": "print(tabulate(info, headers='keys', tablefmt='fancy_grid'))"
},
{
"code": null,
"e": 2609,
"s": 2541,
"text": "We can also add an index to our table with the showindex parameter:"
},
{
"code": null,
"e": 2785,
"s": 2609,
"text": "We can add a custom index by passing in an iterable to the showindex parameter. For example, if we want the index to start at 1, we can pass in a range object as the argument:"
},
{
"code": null,
"e": 2808,
"s": 2785,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2903,
"s": 2808,
"text": "If we remove ‘Jennifer’ from the above info dictionary, our table will contain an empty field:"
},
{
"code": null,
"e": 3052,
"s": 2903,
"text": "print(tabulate({'First Name': ['John', 'Mary'], 'Last Name': ['Smith', 'Jane', 'Doe'], 'Age': [39, 25, 28]}, headers=\"keys\", tablefmt='fancy_grid'))"
},
{
"code": null,
"e": 3289,
"s": 3052,
"text": "If there any missing values in our table, we can choose what to fill them in with using the missingval parameter. The default value for missingval is an empty string. If we change it to ‘N/A’, this is what what our table will look like:"
},
{
"code": null,
"e": 3456,
"s": 3289,
"text": "print(tabulate({'First Name': ['John', 'Mary'], 'Last Name': ['Smith', 'Jane', 'Doe'], 'Age': [39, 25, 28]}, headers=\"keys\", tablefmt='fancy_grid', missingval='N/A'))"
},
{
"code": null,
"e": 3479,
"s": 3456,
"text": "towardsdatascience.com"
}
] |
How to determine the order of bars in a matplotlib bar chart? | To determine the order of bars in a bar chart in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Make a dataframe, df, of two-dimensional, size-mutable, potentially heterogeneous tabular data.
Add a subplot to the current figure.
Make a bar plot with dataframe, df.
Add a subplot to the current figure.
Create another dataframe, df_sorted, by column marks.
Make a bar plot with df_sorted.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame(
dict(
names=['John', 'James', 'David', 'Gary', 'Watson'],
marks=[23, 34, 30, 19, 20]
)
)
plt.subplot(121)
plt.bar('names', 'marks', data=df, color='green')
plt.subplot(122)
df_sorted = df.sort_values('marks')
plt.bar('names', 'marks', data=df_sorted, color='blue')
plt.show()
It will produce the following output | [
{
"code": null,
"e": 1157,
"s": 1062,
"text": "To determine the order of bars in a bar chart 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": 1329,
"s": 1233,
"text": "Make a dataframe, df, of two-dimensional, size-mutable, potentially heterogeneous tabular data."
},
{
"code": null,
"e": 1366,
"s": 1329,
"text": "Add a subplot to the current figure."
},
{
"code": null,
"e": 1402,
"s": 1366,
"text": "Make a bar plot with dataframe, df."
},
{
"code": null,
"e": 1439,
"s": 1402,
"text": "Add a subplot to the current figure."
},
{
"code": null,
"e": 1493,
"s": 1439,
"text": "Create another dataframe, df_sorted, by column marks."
},
{
"code": null,
"e": 1525,
"s": 1493,
"text": "Make a bar plot with df_sorted."
},
{
"code": null,
"e": 1567,
"s": 1525,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2029,
"s": 1567,
"text": "import pandas as pd\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndf = pd.DataFrame(\n dict(\n names=['John', 'James', 'David', 'Gary', 'Watson'],\n marks=[23, 34, 30, 19, 20]\n )\n)\n\nplt.subplot(121)\nplt.bar('names', 'marks', data=df, color='green')\n\nplt.subplot(122)\ndf_sorted = df.sort_values('marks')\nplt.bar('names', 'marks', data=df_sorted, color='blue')\n\nplt.show()"
},
{
"code": null,
"e": 2066,
"s": 2029,
"text": "It will produce the following output"
}
] |
Apache POI Word - Font & Alignment | This chapter shows how to apply different font styles and alignments in a Word document using Java. Generally, Font Style contains: Font size, Type, Bold, Italic, and Underline. And Alignment is categorized into left, center, right, and justify.
The following code is used to set different styles of font −
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.VerticalAlign;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class FontStyle {
public static void main(String[] args)throws Exception {
//Blank Document
XWPFDocument document = new XWPFDocument();
//Write the Document in file system
FileOutputStream out = new FileOutputStream(new File("fontstyle.docx"));
//create paragraph
XWPFParagraph paragraph = document.createParagraph();
//Set Bold an Italic
XWPFRun paragraphOneRunOne = paragraph.createRun();
paragraphOneRunOne.setBold(true);
paragraphOneRunOne.setItalic(true);
paragraphOneRunOne.setText("Font Style");
paragraphOneRunOne.addBreak();
//Set text Position
XWPFRun paragraphOneRunTwo = paragraph.createRun();
paragraphOneRunTwo.setText("Font Style two");
paragraphOneRunTwo.setTextPosition(100);
//Set Strike through and Font Size and Subscript
XWPFRun paragraphOneRunThree = paragraph.createRun();
paragraphOneRunThree.setStrike(true);
paragraphOneRunThree.setFontSize(20);
paragraphOneRunThree.setSubscript(VerticalAlign.SUBSCRIPT);
paragraphOneRunThree.setText(" Different Font Styles");
document.write(out);
out.close();
System.out.println("fontstyle.docx written successully");
}
}
Save the above code as FontStyle.java and then compile and execute it from the command prompt as follows −
$javac FontStyle.java
$java FontStyle
It will generate a Word file named fontstyle.docx in your current directory and display the following output on the command prompt −
fontstyle.docx written successfully
The fontstyle.docx file looks as follows.
The following code is used to set alignment to the paragraph text −
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class AlignParagraph {
public static void main(String[] args)throws Exception {
//Blank Document
XWPFDocument document = new XWPFDocument();
//Write the Document in file system
FileOutputStream out = new FileOutputStream(
new File("alignparagraph.docx"));
//create paragraph
XWPFParagraph paragraph = document.createParagraph();
//Set alignment paragraph to RIGHT
paragraph.setAlignment(ParagraphAlignment.RIGHT);
XWPFRun run = paragraph.createRun();
run.setText("At tutorialspoint.com, we strive hard to " +
"provide quality tutorials for self-learning " +
"purpose in the domains of Academics, Information " +
"Technology, Management and Computer Programming " +
"Languages.");
//Create Another paragraph
paragraph = document.createParagraph();
//Set alignment paragraph to CENTER
paragraph.setAlignment(ParagraphAlignment.CENTER);
run = paragraph.createRun();
run.setText("The endeavour started by Mohtashim, an AMU " +
"alumni, who is the founder and the managing director " +
"of Tutorials Point (I) Pvt. Ltd. He came up with the " +
"website tutorialspoint.com in year 2006 with the help" +
"of handpicked freelancers, with an array of tutorials" +
" for computer programming languages. ");
document.write(out);
out.close();
System.out.println("alignparagraph.docx written successfully");
}
}
Save the above code as AlignParagraph.java and then compile and execute it from the command prompt as follows −
$javac AlignParagraph.java
$java AlignParagraph
It will generate a Word file named alignparagraph.docx in your current directory and display the following output in the command prompt −
alignparagraph.docx written successfully
The alignparagraph.docx file looks as follows −
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": 2132,
"s": 1886,
"text": "This chapter shows how to apply different font styles and alignments in a Word document using Java. Generally, Font Style contains: Font size, Type, Bold, Italic, and Underline. And Alignment is categorized into left, center, right, and justify."
},
{
"code": null,
"e": 2193,
"s": 2132,
"text": "The following code is used to set different styles of font −"
},
{
"code": null,
"e": 3747,
"s": 2193,
"text": "import java.io.File;\nimport java.io.FileOutputStream;\n\nimport org.apache.poi.xwpf.usermodel.VerticalAlign;\nimport org.apache.poi.xwpf.usermodel.XWPFDocument;\nimport org.apache.poi.xwpf.usermodel.XWPFParagraph;\nimport org.apache.poi.xwpf.usermodel.XWPFRun;\n\npublic class FontStyle {\n\n public static void main(String[] args)throws Exception {\n\n //Blank Document\n XWPFDocument document = new XWPFDocument(); \n \n //Write the Document in file system\n FileOutputStream out = new FileOutputStream(new File(\"fontstyle.docx\"));\n \n //create paragraph\n XWPFParagraph paragraph = document.createParagraph();\n \n //Set Bold an Italic\n XWPFRun paragraphOneRunOne = paragraph.createRun();\n paragraphOneRunOne.setBold(true);\n paragraphOneRunOne.setItalic(true);\n paragraphOneRunOne.setText(\"Font Style\");\n paragraphOneRunOne.addBreak();\n \n //Set text Position\n XWPFRun paragraphOneRunTwo = paragraph.createRun();\n paragraphOneRunTwo.setText(\"Font Style two\");\n paragraphOneRunTwo.setTextPosition(100);\n \n //Set Strike through and Font Size and Subscript\n XWPFRun paragraphOneRunThree = paragraph.createRun();\n paragraphOneRunThree.setStrike(true);\n paragraphOneRunThree.setFontSize(20);\n paragraphOneRunThree.setSubscript(VerticalAlign.SUBSCRIPT);\n paragraphOneRunThree.setText(\" Different Font Styles\");\n \n document.write(out);\n out.close();\n System.out.println(\"fontstyle.docx written successully\");\n }\n}"
},
{
"code": null,
"e": 3854,
"s": 3747,
"text": "Save the above code as FontStyle.java and then compile and execute it from the command prompt as follows −"
},
{
"code": null,
"e": 3893,
"s": 3854,
"text": "$javac FontStyle.java\n$java FontStyle\n"
},
{
"code": null,
"e": 4026,
"s": 3893,
"text": "It will generate a Word file named fontstyle.docx in your current directory and display the following output on the command prompt −"
},
{
"code": null,
"e": 4063,
"s": 4026,
"text": "fontstyle.docx written successfully\n"
},
{
"code": null,
"e": 4105,
"s": 4063,
"text": "The fontstyle.docx file looks as follows."
},
{
"code": null,
"e": 4173,
"s": 4105,
"text": "The following code is used to set alignment to the paragraph text −"
},
{
"code": null,
"e": 5999,
"s": 4173,
"text": "import java.io.File;\nimport java.io.FileOutputStream;\nimport org.apache.poi.xwpf.usermodel.ParagraphAlignment;\nimport org.apache.poi.xwpf.usermodel.XWPFDocument;\nimport org.apache.poi.xwpf.usermodel.XWPFParagraph;\nimport org.apache.poi.xwpf.usermodel.XWPFRun;\n\npublic class AlignParagraph {\n\n public static void main(String[] args)throws Exception {\n\n //Blank Document\n XWPFDocument document = new XWPFDocument(); \n \n //Write the Document in file system\n FileOutputStream out = new FileOutputStream(\n new File(\"alignparagraph.docx\"));\n \n //create paragraph\n XWPFParagraph paragraph = document.createParagraph();\n \n //Set alignment paragraph to RIGHT\n paragraph.setAlignment(ParagraphAlignment.RIGHT);\n XWPFRun run = paragraph.createRun();\n run.setText(\"At tutorialspoint.com, we strive hard to \" +\n \"provide quality tutorials for self-learning \" +\n \"purpose in the domains of Academics, Information \" +\n \"Technology, Management and Computer Programming \" +\n \"Languages.\");\n \n //Create Another paragraph\n paragraph = document.createParagraph();\n \n //Set alignment paragraph to CENTER\n paragraph.setAlignment(ParagraphAlignment.CENTER);\n run = paragraph.createRun();\n run.setText(\"The endeavour started by Mohtashim, an AMU \" +\n \"alumni, who is the founder and the managing director \" +\n \"of Tutorials Point (I) Pvt. Ltd. He came up with the \" +\n \"website tutorialspoint.com in year 2006 with the help\" +\n \"of handpicked freelancers, with an array of tutorials\" +\n \" for computer programming languages. \");\n\t\t\t\n document.write(out);\n out.close();\n System.out.println(\"alignparagraph.docx written successfully\");\n }\n}"
},
{
"code": null,
"e": 6111,
"s": 5999,
"text": "Save the above code as AlignParagraph.java and then compile and execute it from the command prompt as follows −"
},
{
"code": null,
"e": 6160,
"s": 6111,
"text": "$javac AlignParagraph.java\n$java AlignParagraph\n"
},
{
"code": null,
"e": 6298,
"s": 6160,
"text": "It will generate a Word file named alignparagraph.docx in your current directory and display the following output in the command prompt −"
},
{
"code": null,
"e": 6340,
"s": 6298,
"text": "alignparagraph.docx written successfully\n"
},
{
"code": null,
"e": 6388,
"s": 6340,
"text": "The alignparagraph.docx file looks as follows −"
},
{
"code": null,
"e": 6423,
"s": 6388,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6442,
"s": 6423,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6477,
"s": 6442,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6498,
"s": 6477,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 6531,
"s": 6498,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6544,
"s": 6531,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 6579,
"s": 6544,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6597,
"s": 6579,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6630,
"s": 6597,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6648,
"s": 6630,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6681,
"s": 6648,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6699,
"s": 6681,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6706,
"s": 6699,
"text": " Print"
},
{
"code": null,
"e": 6717,
"s": 6706,
"text": " Add Notes"
}
] |
Matplotlib - Pie Chart | A Pie Chart can only display one series of data. Pie charts show the size of items (called wedge) in one data series, proportional to the sum of the items. The data points in a pie chart are shown as a percentage of the whole pie.
Matplotlib API has a pie() function that generates a pie diagram representing data in an array. The fractional area of each wedge is given by x/sum(x). If sum(x)< 1, then the values of x give the fractional area directly and the array will not be normalized. Theresulting pie will have an empty wedge of size 1 - sum(x).
The pie chart looks best if the figure and axes are square, or the Axes aspect is equal.
Following table lists down the parameters foe a pie chart −
Following code uses the pie() function to display the pie chart of the list of students enrolled for various computer language courses. The proportionate percentage is displayed inside the respective wedge with the help of autopct parameter which is set to %1.2f%.
from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.pie(students, labels = langs,autopct='%1.2f%%')
plt.show()
63 Lectures
6 hours
Abhilash Nelson
11 Lectures
4 hours
DATAhill Solutions Srinivas Reddy
9 Lectures
2.5 hours
DATAhill Solutions Srinivas Reddy
32 Lectures
4 hours
Aipython
10 Lectures
2.5 hours
Akbar Khan
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2747,
"s": 2516,
"text": "A Pie Chart can only display one series of data. Pie charts show the size of items (called wedge) in one data series, proportional to the sum of the items. The data points in a pie chart are shown as a percentage of the whole pie."
},
{
"code": null,
"e": 3068,
"s": 2747,
"text": "Matplotlib API has a pie() function that generates a pie diagram representing data in an array. The fractional area of each wedge is given by x/sum(x). If sum(x)< 1, then the values of x give the fractional area directly and the array will not be normalized. Theresulting pie will have an empty wedge of size 1 - sum(x)."
},
{
"code": null,
"e": 3157,
"s": 3068,
"text": "The pie chart looks best if the figure and axes are square, or the Axes aspect is equal."
},
{
"code": null,
"e": 3217,
"s": 3157,
"text": "Following table lists down the parameters foe a pie chart −"
},
{
"code": null,
"e": 3482,
"s": 3217,
"text": "Following code uses the pie() function to display the pie chart of the list of students enrolled for various computer language courses. The proportionate percentage is displayed inside the respective wedge with the help of autopct parameter which is set to %1.2f%."
},
{
"code": null,
"e": 3739,
"s": 3482,
"text": "from matplotlib import pyplot as plt\nimport numpy as np\nfig = plt.figure()\nax = fig.add_axes([0,0,1,1])\nax.axis('equal')\nlangs = ['C', 'C++', 'Java', 'Python', 'PHP']\nstudents = [23,17,35,29,12]\nax.pie(students, labels = langs,autopct='%1.2f%%')\nplt.show()"
},
{
"code": null,
"e": 3772,
"s": 3739,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3789,
"s": 3772,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3822,
"s": 3789,
"text": "\n 11 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3857,
"s": 3822,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3891,
"s": 3857,
"text": "\n 9 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3926,
"s": 3891,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3959,
"s": 3926,
"text": "\n 32 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3969,
"s": 3959,
"text": " Aipython"
},
{
"code": null,
"e": 4004,
"s": 3969,
"text": "\n 10 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4016,
"s": 4004,
"text": " Akbar Khan"
},
{
"code": null,
"e": 4049,
"s": 4016,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4056,
"s": 4049,
"text": " Anmol"
},
{
"code": null,
"e": 4063,
"s": 4056,
"text": " Print"
},
{
"code": null,
"e": 4074,
"s": 4063,
"text": " Add Notes"
}
] |
Filter away object in array with null values JavaScript | Let’s say, we have an array of objects about some employees of a company. But the array
contains some bad data i.e., key pointing to empty strings or false values. Our job is to write a
function that takes in the array and away the objects that have null or undefined or empty string
value for the name key and return the new object.
The array of objects are like this −
let data = [{
"name": "Ramesh Dhiman",
"age": 67,
"experience": 45,
"description": ""
}, {
"name": "",
"age": 31,
"experience": 9,
"description": ""
}, {
"name": "Kunal Dhiman",
"age": 27,
"experience": 7,
"description": ""
}, {
"name": "Raman Kumar",
"age": 34,
"experience": 10,
"description": ""
}, {
"name": "",
"age": 41,
"experience": 19,
"description": ""
}
]
Let’s write the code for this function −
let data = [{
"name": "Ramesh Dhiman",
"age": 67,
"experience": 45,
"description": ""
}, {
"name": "",
"age": 31,
"experience": 9,
"description": ""
}, {
"name": "Kunal Dhiman",
"age": 27,
"experience": 7,
"description": ""
}, {
"name": "Raman Kumar",
"age": 34,
"experience": 10,
"description": ""
}, {
"name": "",
"age": 41,
"experience": 19,
"description": ""
}
]
const filterUnwanted = (arr) => {
const required = arr.filter(el => {
return el.name;
});
return required;
};
console.log(filterUnwanted(data));
The output in the console will be −
[
{ name: 'Ramesh Dhiman', age: 67, experience: 45, description: '' },
{ name: 'Kunal Dhiman', age: 27, experience: 7, description: '' },
{ name: 'Raman Kumar', age: 34, experience: 10, description: '' }
] | [
{
"code": null,
"e": 1396,
"s": 1062,
"text": "Let’s say, we have an array of objects about some employees of a company. But the array\ncontains some bad data i.e., key pointing to empty strings or false values. Our job is to write a\nfunction that takes in the array and away the objects that have null or undefined or empty string\nvalue for the name key and return the new object."
},
{
"code": null,
"e": 1433,
"s": 1396,
"text": "The array of objects are like this −"
},
{
"code": null,
"e": 1911,
"s": 1433,
"text": "let data = [{\n \"name\": \"Ramesh Dhiman\",\n \"age\": 67,\n \"experience\": 45,\n \"description\": \"\"\n}, {\n \"name\": \"\",\n \"age\": 31,\n \"experience\": 9,\n \"description\": \"\"\n}, {\n \"name\": \"Kunal Dhiman\",\n \"age\": 27,\n \"experience\": 7,\n \"description\": \"\"\n}, {\n \"name\": \"Raman Kumar\",\n \"age\": 34,\n \"experience\": 10,\n \"description\": \"\"\n}, {\n \"name\": \"\",\n \"age\": 41,\n \"experience\": 19,\n \"description\": \"\"\n }\n]"
},
{
"code": null,
"e": 1952,
"s": 1911,
"text": "Let’s write the code for this function −"
},
{
"code": null,
"e": 2590,
"s": 1952,
"text": "let data = [{\n \"name\": \"Ramesh Dhiman\",\n \"age\": 67,\n \"experience\": 45,\n \"description\": \"\"\n}, {\n \"name\": \"\",\n \"age\": 31,\n \"experience\": 9,\n \"description\": \"\"\n}, {\n \"name\": \"Kunal Dhiman\",\n \"age\": 27,\n \"experience\": 7,\n \"description\": \"\"\n}, {\n \"name\": \"Raman Kumar\",\n \"age\": 34,\n \"experience\": 10,\n \"description\": \"\"\n}, {\n \"name\": \"\",\n \"age\": 41,\n \"experience\": 19,\n \"description\": \"\"\n }\n]\nconst filterUnwanted = (arr) => {\n const required = arr.filter(el => {\n return el.name;\n });\n return required;\n};\nconsole.log(filterUnwanted(data));"
},
{
"code": null,
"e": 2626,
"s": 2590,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 2841,
"s": 2626,
"text": "[\n { name: 'Ramesh Dhiman', age: 67, experience: 45, description: '' },\n { name: 'Kunal Dhiman', age: 27, experience: 7, description: '' },\n { name: 'Raman Kumar', age: 34, experience: 10, description: '' }\n]"
}
] |
CSS units - %, em, rem, px, vh, vw - GeeksforGeeks | 21 Apr, 2022
In this article, we will see how to set the CSS units in different ways.
% – The % unit is used to set the font-size relative to the current font-size.
em – It is used to set the relative size. It is relative to the font-size of the element. Note: Here 2em meaning 2times the size of current font.
rem – Relative to the browser base font-size.
px – It defines the font-size in terms of pixels. (96px = 1in)
vh – Relative to 1% of the height of the viewport.
vw – Relative to 1% of the width of the viewport.
Example 1: The pixel unit is an absolute unit to set the width i.e. it is always the same. A percentage unit is based on a relative unit i.e. it is based on its parent size.
HTML
<!DOCTYPE html><html> <head> <style> .box { background: red; border: 1px solid black; margin: 10px; } .parent { background: white; border: 1px solid black; } .fifty-percent { width: 50%; } .one-hundred { width: 100px; } .parent { width: 250px; ; } </style></head> <body> <h3>Output-1 </h3> <div class="box fifty-percent">50%</div> <div class="box one-hundred">100px</div> <hr> <h3>Output-2 </h3> <div class="parent"> <div class="box fifty-percent">50%</div> <div class="box one-hundred">100px</div> </div></body> </html>
Output :
Example 2: Another type of relative width is called view width (vw) and view height (vh). 1vw equals one percent of the entire screen size so 100 vw would take up the entire width and 50vw obviously would take up half the width but the important thing about vw versus percentages is that viewport units are based on the entire screen size while rectangles are relative to their parent.
HTML
<!DOCTYPE html><html> <head> <title>Page Title</title> <style> .box { background: red; border: 1px solid black; margin: 10px; } .parent { background: white; border: 1px solid black; } .fifty-percent { width: 50%; } .fifty-vw { width: 50vw; } .twenty-five-vh { height: 25vh; } .parent { width: 100px; ; } </style></head> <body> <h3>Output-1 </h3> <div class="box fifty-percent">50%</div> <div class="box fifty-vw">50vw</div> <div class="box twenty-five-vh">25vh</div> <hr> <h3>Output-2 </h3> <div class="parent"> <div class="box fifty-percent">50%</div> <div class="box fifty-vw">50vw</div> <div class="box twenty-five-vh">25vh</div> </div></body> </html>
Output:
Example 3: Both REM units and EM units are relative but instead of being relative to things around them such as the width of their parents or the height of the parents they’re actually relative to the font size.
HTML
<!DOCTYPE html><html> <head> <title>Page Title</title> <style> .parent { background: white; border: 1px solid black; } .one-rem { font-size: 1rem; } .one-em { font-size: 1em; } .two-rem { font-size: 2rem; } .two-em { font-size: 2em; } .parent { font-size: 30px; } </style></head> <body> <h3>Output-1</h3> <div class="one-rem">1rem</div> <div class="one-em">1em</div> <div class="two-rem">2rem</div> <div class="two-em">2em</div> <hr> <h3>Output-2</h3> <div class="parent"> <div class="one-rem">1rem</div> <div class="one-em">1em</div> <div class="two-rem">2rem</div> <div class="two-em">2em</div> </div></body> </html>
Output:
surindertarika1234
CSS-Properties
CSS-Questions
HTML-Questions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n21 Apr, 2022"
},
{
"code": null,
"e": 25450,
"s": 25376,
"text": "In this article, we will see how to set the CSS units in different ways. "
},
{
"code": null,
"e": 25530,
"s": 25450,
"text": "% – The % unit is used to set the font-size relative to the current font-size. "
},
{
"code": null,
"e": 25677,
"s": 25530,
"text": "em – It is used to set the relative size. It is relative to the font-size of the element. Note: Here 2em meaning 2times the size of current font. "
},
{
"code": null,
"e": 25724,
"s": 25677,
"text": "rem – Relative to the browser base font-size. "
},
{
"code": null,
"e": 25787,
"s": 25724,
"text": "px – It defines the font-size in terms of pixels. (96px = 1in)"
},
{
"code": null,
"e": 25839,
"s": 25787,
"text": "vh – Relative to 1% of the height of the viewport. "
},
{
"code": null,
"e": 25890,
"s": 25839,
"text": "vw – Relative to 1% of the width of the viewport. "
},
{
"code": null,
"e": 26065,
"s": 25890,
"text": "Example 1: The pixel unit is an absolute unit to set the width i.e. it is always the same. A percentage unit is based on a relative unit i.e. it is based on its parent size. "
},
{
"code": null,
"e": 26070,
"s": 26065,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .box { background: red; border: 1px solid black; margin: 10px; } .parent { background: white; border: 1px solid black; } .fifty-percent { width: 50%; } .one-hundred { width: 100px; } .parent { width: 250px; ; } </style></head> <body> <h3>Output-1 </h3> <div class=\"box fifty-percent\">50%</div> <div class=\"box one-hundred\">100px</div> <hr> <h3>Output-2 </h3> <div class=\"parent\"> <div class=\"box fifty-percent\">50%</div> <div class=\"box one-hundred\">100px</div> </div></body> </html>",
"e": 26812,
"s": 26070,
"text": null
},
{
"code": null,
"e": 26821,
"s": 26812,
"text": "Output :"
},
{
"code": null,
"e": 27210,
"s": 26821,
"text": "Example 2: Another type of relative width is called view width (vw) and view height (vh). 1vw equals one percent of the entire screen size so 100 vw would take up the entire width and 50vw obviously would take up half the width but the important thing about vw versus percentages is that viewport units are based on the entire screen size while rectangles are relative to their parent. "
},
{
"code": null,
"e": 27215,
"s": 27210,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Page Title</title> <style> .box { background: red; border: 1px solid black; margin: 10px; } .parent { background: white; border: 1px solid black; } .fifty-percent { width: 50%; } .fifty-vw { width: 50vw; } .twenty-five-vh { height: 25vh; } .parent { width: 100px; ; } </style></head> <body> <h3>Output-1 </h3> <div class=\"box fifty-percent\">50%</div> <div class=\"box fifty-vw\">50vw</div> <div class=\"box twenty-five-vh\">25vh</div> <hr> <h3>Output-2 </h3> <div class=\"parent\"> <div class=\"box fifty-percent\">50%</div> <div class=\"box fifty-vw\">50vw</div> <div class=\"box twenty-five-vh\">25vh</div> </div></body> </html>",
"e": 28131,
"s": 27215,
"text": null
},
{
"code": null,
"e": 28139,
"s": 28131,
"text": "Output:"
},
{
"code": null,
"e": 28352,
"s": 28139,
"text": "Example 3: Both REM units and EM units are relative but instead of being relative to things around them such as the width of their parents or the height of the parents they’re actually relative to the font size."
},
{
"code": null,
"e": 28357,
"s": 28352,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Page Title</title> <style> .parent { background: white; border: 1px solid black; } .one-rem { font-size: 1rem; } .one-em { font-size: 1em; } .two-rem { font-size: 2rem; } .two-em { font-size: 2em; } .parent { font-size: 30px; } </style></head> <body> <h3>Output-1</h3> <div class=\"one-rem\">1rem</div> <div class=\"one-em\">1em</div> <div class=\"two-rem\">2rem</div> <div class=\"two-em\">2em</div> <hr> <h3>Output-2</h3> <div class=\"parent\"> <div class=\"one-rem\">1rem</div> <div class=\"one-em\">1em</div> <div class=\"two-rem\">2rem</div> <div class=\"two-em\">2em</div> </div></body> </html>",
"e": 29214,
"s": 28357,
"text": null
},
{
"code": null,
"e": 29222,
"s": 29214,
"text": "Output:"
},
{
"code": null,
"e": 29241,
"s": 29222,
"text": "surindertarika1234"
},
{
"code": null,
"e": 29256,
"s": 29241,
"text": "CSS-Properties"
},
{
"code": null,
"e": 29270,
"s": 29256,
"text": "CSS-Questions"
},
{
"code": null,
"e": 29285,
"s": 29270,
"text": "HTML-Questions"
},
{
"code": null,
"e": 29289,
"s": 29285,
"text": "CSS"
},
{
"code": null,
"e": 29306,
"s": 29289,
"text": "Web Technologies"
},
{
"code": null,
"e": 29404,
"s": 29306,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29441,
"s": 29404,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29470,
"s": 29441,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29509,
"s": 29470,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29551,
"s": 29509,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 29598,
"s": 29551,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 29640,
"s": 29598,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29673,
"s": 29640,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29716,
"s": 29673,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29761,
"s": 29716,
"text": "Convert a string to an integer in JavaScript"
}
] |
Generating Random Numbers in Golang - GeeksforGeeks | 15 Apr, 2020
Golang provides a package math/rand for generating pseudorandom numbers. This package basically uses a single source that causes the production of a deterministic sequence of values each time a program is executed. Here, if you need different output or outcome for each execution, you can use the seed function to initialize the default source which is safe for concurrent use by multiple goroutines. It generates an integer in the interval of 0 and n. It takes only one argument, the n or the upper bound & throws error if argument is less than zero.
RandomInteger := rand.Int() // generates a random integer
RandomIntegerwithinRange: To generate the number within the range where max is the upper bound and min is the lower bound.
RandomIntegerwithinRange := rand.Intn(max-min) + min // range is min to max
rand.Float64(): It generates the floating point number between 0.0 and 1.0, It is as easy as rand.Int to use.
RandomFloatingNumber := rand.Float64() // generates a random floating point number
Example:
// Generating Random Numbers in Golangpackage main import ( "fmt" "math/rand" "time") func main() { // Intn returns, as an // int, a non-negative // pseudo-random number in // [0,n) from the default Source. // i.e. simply call Intn to // get the next random integer. fmt.Println(rand.Intn(200)) fmt.Println(rand.Intn(200)) fmt.Println(rand.Intn(200)) fmt.Println() // Float64 returns, as // a float64, a pseudo-random // number in [0.0,1.0) // from the default Source. fmt.Println(rand.Float64()) // By default, it uses the value 1. fmt.Println((rand.Float64() * 8) + 7) fmt.Println((rand.Float64() * 8) + 7) fmt.Println() // Seeding - Go provides a method, // Seed(see int64), that allows you // to initialize this default sequence. // Implementation is slow // to make it faster // rand.Seed(time.Now().UnixNano()) // is added. Seed is the current time, // converted to int64 by UnixNano. // Gives constantly changing numbers x1 := rand.NewSource(time.Now().UnixNano()) y1 := rand.New(x1) fmt.Println(y1.Intn(200)) fmt.Println(y1.Intn(200)) fmt.Println() x2 := rand.NewSource(55) y2 := rand.New(x2) fmt.Println(y2.Intn(200)) fmt.Println(y2.Intn(200)) fmt.Println() x3 := rand.NewSource(5) y3 := rand.New(x3) fmt.Println(y3.Intn(200)) fmt.Println(y3.Intn(200))}
Output:
81
87
47
0.4377141871869802
10.397099976570125
12.494584582936875
0
128
112
164
26
36
The above method is not safe if the user wants to keep the random numbers secret. That’s why Golang provides Crypto rand to varies the level of randomness of numbers to come. It is crypto-ready to use and secure but it is slower. It is used for generating passkeys, CSRF tokens or anything related to security.
Example:
package main import ( "crypto/rand" "fmt") func main() { RandomCrypto, _ := rand.Prime(rand.Reader, 128) fmt.Println(RandomCrypto)}
When you will execute this code, you will get different output each time.
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Defer Keyword in Golang
Time Durations in Golang
Anonymous function in Go Language
How to iterate over an Array using for loop in Golang?
Loops in Go Language
time.Parse() Function in Golang With Examples
Strings in Golang
Structures in Golang
Class and Object in Golang | [
{
"code": null,
"e": 24460,
"s": 24432,
"text": "\n15 Apr, 2020"
},
{
"code": null,
"e": 25012,
"s": 24460,
"text": "Golang provides a package math/rand for generating pseudorandom numbers. This package basically uses a single source that causes the production of a deterministic sequence of values each time a program is executed. Here, if you need different output or outcome for each execution, you can use the seed function to initialize the default source which is safe for concurrent use by multiple goroutines. It generates an integer in the interval of 0 and n. It takes only one argument, the n or the upper bound & throws error if argument is less than zero."
},
{
"code": null,
"e": 25072,
"s": 25012,
"text": " RandomInteger := rand.Int() // generates a random integer"
},
{
"code": null,
"e": 25195,
"s": 25072,
"text": "RandomIntegerwithinRange: To generate the number within the range where max is the upper bound and min is the lower bound."
},
{
"code": null,
"e": 25274,
"s": 25195,
"text": "RandomIntegerwithinRange := rand.Intn(max-min) + min // range is min to max"
},
{
"code": null,
"e": 25384,
"s": 25274,
"text": "rand.Float64(): It generates the floating point number between 0.0 and 1.0, It is as easy as rand.Int to use."
},
{
"code": null,
"e": 25468,
"s": 25384,
"text": "RandomFloatingNumber := rand.Float64() // generates a random floating point number "
},
{
"code": null,
"e": 25477,
"s": 25468,
"text": "Example:"
},
{
"code": "// Generating Random Numbers in Golangpackage main import ( \"fmt\" \"math/rand\" \"time\") func main() { // Intn returns, as an // int, a non-negative // pseudo-random number in // [0,n) from the default Source. // i.e. simply call Intn to // get the next random integer. fmt.Println(rand.Intn(200)) fmt.Println(rand.Intn(200)) fmt.Println(rand.Intn(200)) fmt.Println() // Float64 returns, as // a float64, a pseudo-random // number in [0.0,1.0) // from the default Source. fmt.Println(rand.Float64()) // By default, it uses the value 1. fmt.Println((rand.Float64() * 8) + 7) fmt.Println((rand.Float64() * 8) + 7) fmt.Println() // Seeding - Go provides a method, // Seed(see int64), that allows you // to initialize this default sequence. // Implementation is slow // to make it faster // rand.Seed(time.Now().UnixNano()) // is added. Seed is the current time, // converted to int64 by UnixNano. // Gives constantly changing numbers x1 := rand.NewSource(time.Now().UnixNano()) y1 := rand.New(x1) fmt.Println(y1.Intn(200)) fmt.Println(y1.Intn(200)) fmt.Println() x2 := rand.NewSource(55) y2 := rand.New(x2) fmt.Println(y2.Intn(200)) fmt.Println(y2.Intn(200)) fmt.Println() x3 := rand.NewSource(5) y3 := rand.New(x3) fmt.Println(y3.Intn(200)) fmt.Println(y3.Intn(200))}",
"e": 26905,
"s": 25477,
"text": null
},
{
"code": null,
"e": 26913,
"s": 26905,
"text": "Output:"
},
{
"code": null,
"e": 27004,
"s": 26913,
"text": "81\n87\n47\n\n0.4377141871869802\n10.397099976570125\n12.494584582936875\n\n0\n128\n\n112\n164\n\n26\n36\n"
},
{
"code": null,
"e": 27315,
"s": 27004,
"text": "The above method is not safe if the user wants to keep the random numbers secret. That’s why Golang provides Crypto rand to varies the level of randomness of numbers to come. It is crypto-ready to use and secure but it is slower. It is used for generating passkeys, CSRF tokens or anything related to security."
},
{
"code": null,
"e": 27324,
"s": 27315,
"text": "Example:"
},
{
"code": "package main import ( \"crypto/rand\" \"fmt\") func main() { RandomCrypto, _ := rand.Prime(rand.Reader, 128) fmt.Println(RandomCrypto)}",
"e": 27470,
"s": 27324,
"text": null
},
{
"code": null,
"e": 27544,
"s": 27470,
"text": "When you will execute this code, you will get different output each time."
},
{
"code": null,
"e": 27551,
"s": 27544,
"text": "Picked"
},
{
"code": null,
"e": 27563,
"s": 27551,
"text": "Go Language"
},
{
"code": null,
"e": 27661,
"s": 27563,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27690,
"s": 27661,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 27714,
"s": 27690,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 27739,
"s": 27714,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 27773,
"s": 27739,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 27828,
"s": 27773,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 27849,
"s": 27828,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 27895,
"s": 27849,
"text": "time.Parse() Function in Golang With Examples"
},
{
"code": null,
"e": 27913,
"s": 27895,
"text": "Strings in Golang"
},
{
"code": null,
"e": 27934,
"s": 27913,
"text": "Structures in Golang"
}
] |
How to directly modify a specific item in a TKinter listbox? | Tkinter is a Python-based GUI application development library which is generally used to build useful functional desktop applications. The Listbox widget is another tkinter widget, which is used as a container to display a list of items in the form of a Listbox.
To define a list of items in a Listbox widget, you'll need to create a constructor of Listbox(root, width, height, **options). You can insert as many items as you want to display in the listbox.
Suppose you want to modify a specific item in a tkinter Listbox, then you can first create a button to select the item from the list you want to modify, and then call the delete() method to delete any existing values from it. Once the values are deleted, you can insert() a new item in the listbox.Let's take an example to understand how it works.
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")
# Create a Listbox widget
lb = Listbox(win, width=100, height=10, background="purple3", foreground="white", font=('Times 13'), selectbackground="white")
lb.pack()
# Select the list item and delete the item first
# Once the list item is deleted,
# we can insert a new item in the listbox
def edit_current():
for item in lb.curselection():
lb.delete(item)
lb.insert("end", "foo")
# Add items in the Listbox
lb.insert("end", "item1", "item2", "item3", "item4", "item5")
# Add a Button To Edit and Delete the Listbox Item
ttk.Button(win, text="Edit", command=edit_current).pack()
win.mainloop()
In this example, we have created a list of items using the Listbox widget. We have created a button named "Edit" which basically modifies the existing values of selected list items. Using this, you can replace/modify the values of any item in the list in the Listbox widget.
Once executed, it will produce the following output window −
Now, select an item from the list and click the "Edit" button. Suppose you select "item5" and click "Edit", then that particular entry will be replaced by "foo". | [
{
"code": null,
"e": 1325,
"s": 1062,
"text": "Tkinter is a Python-based GUI application development library which is generally used to build useful functional desktop applications. The Listbox widget is another tkinter widget, which is used as a container to display a list of items in the form of a Listbox."
},
{
"code": null,
"e": 1520,
"s": 1325,
"text": "To define a list of items in a Listbox widget, you'll need to create a constructor of Listbox(root, width, height, **options). You can insert as many items as you want to display in the listbox."
},
{
"code": null,
"e": 1868,
"s": 1520,
"text": "Suppose you want to modify a specific item in a tkinter Listbox, then you can first create a button to select the item from the list you want to modify, and then call the delete() method to delete any existing values from it. Once the values are deleted, you can insert() a new item in the listbox.Let's take an example to understand how it works."
},
{
"code": null,
"e": 2672,
"s": 1868,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Create a Listbox widget\nlb = Listbox(win, width=100, height=10, background=\"purple3\", foreground=\"white\", font=('Times 13'), selectbackground=\"white\")\n\nlb.pack()\n\n# Select the list item and delete the item first\n# Once the list item is deleted,\n# we can insert a new item in the listbox\ndef edit_current():\n for item in lb.curselection():\n lb.delete(item)\n lb.insert(\"end\", \"foo\")\n\n# Add items in the Listbox\nlb.insert(\"end\", \"item1\", \"item2\", \"item3\", \"item4\", \"item5\")\n\n# Add a Button To Edit and Delete the Listbox Item\nttk.Button(win, text=\"Edit\", command=edit_current).pack()\n\nwin.mainloop()"
},
{
"code": null,
"e": 2947,
"s": 2672,
"text": "In this example, we have created a list of items using the Listbox widget. We have created a button named \"Edit\" which basically modifies the existing values of selected list items. Using this, you can replace/modify the values of any item in the list in the Listbox widget."
},
{
"code": null,
"e": 3008,
"s": 2947,
"text": "Once executed, it will produce the following output window −"
},
{
"code": null,
"e": 3170,
"s": 3008,
"text": "Now, select an item from the list and click the \"Edit\" button. Suppose you select \"item5\" and click \"Edit\", then that particular entry will be replaced by \"foo\"."
}
] |
Aptitude | GATE CS 1998 | Question 47 - GeeksforGeeks | 15 Mar, 2018
What value would the following function return for the input x=95 ?
function fun (x:integer):integer;
Begin
If x >100 then fun = x-10
Else fun = fun(fun( x+11))
End;
(A) 89(B) 90(C) 91(D) 92Answer: (C)Explanation: for solution refer ISRO CS 2017So option C is correctQuiz of this Question
Aptitude
Aptitude-GATE CS 1998
GATE CS 1998
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2000 | Question 43
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2010 | Question 24
GATE | Gate IT 2007 | Question 30 | [
{
"code": null,
"e": 24444,
"s": 24416,
"text": "\n15 Mar, 2018"
},
{
"code": null,
"e": 24512,
"s": 24444,
"text": "What value would the following function return for the input x=95 ?"
},
{
"code": null,
"e": 24615,
"s": 24512,
"text": "function fun (x:integer):integer;\nBegin\n If x >100 then fun = x-10\n Else fun = fun(fun( x+11))\nEnd;\n"
},
{
"code": null,
"e": 24738,
"s": 24615,
"text": "(A) 89(B) 90(C) 91(D) 92Answer: (C)Explanation: for solution refer ISRO CS 2017So option C is correctQuiz of this Question"
},
{
"code": null,
"e": 24747,
"s": 24738,
"text": "Aptitude"
},
{
"code": null,
"e": 24769,
"s": 24747,
"text": "Aptitude-GATE CS 1998"
},
{
"code": null,
"e": 24782,
"s": 24769,
"text": "GATE CS 1998"
},
{
"code": null,
"e": 24787,
"s": 24782,
"text": "GATE"
},
{
"code": null,
"e": 24885,
"s": 24787,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24919,
"s": 24885,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 24953,
"s": 24919,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 24995,
"s": 24953,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 25037,
"s": 24995,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25071,
"s": 25037,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 25104,
"s": 25071,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25138,
"s": 25104,
"text": "GATE | GATE-CS-2000 | Question 43"
},
{
"code": null,
"e": 25180,
"s": 25138,
"text": "GATE | GATE-CS-2017 (Set 2) | Question 42"
},
{
"code": null,
"e": 25214,
"s": 25180,
"text": "GATE | GATE CS 2010 | Question 24"
}
] |
Establishing the two-way Communication between Server and Client in Java - GeeksforGeeks | 14 Oct, 2019
It is possible to send data from the server and receive a response from the client. Similarly, the client can also send and receive data to-and-from.
Below are the various steps to do so:
We need additional streams both at server and client. For example, to receive data into the server, it is a better idea to use a BufferedReader object, as shown in the following code snippet:InputStream obj = s.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(obj);
InputStream obj = s.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(obj);
Then read() or readLine() methods of the BufferedReader object can be used to read data. To send data from the client we can take the help of the DataOutputStream class as shown in the following code snippet:OutputStream obj + s.getOutputStrean();
DataOutputStream dos = new DataOutputStream(obj);
OutputStream obj + s.getOutputStrean();
DataOutputStream dos = new DataOutputStream(obj);
Then, the writeBytes() method of the DataOutputStream class can be used to send strings in the form of a group of bytes. To establish the two-way communication between a client and server perform the following steps:Creating the Server Program: Let’s create a class named Server2.java to create server such that the server receives data from the client using a BufferedReader object and then sends a reply to the client using a PrintStream object.Server2.javaServer2.java// Server2 class that// receives data and sends data import java.io.*;import java.net.*; class Server2 { public static void main(String args[]) throws Exception { // Create server Socket ServerSocket ss = new ServerSocket(888); // connect it to client socket Socket s = ss.accept(); System.out.println("Connection established"); // to send data to the client PrintStream ps = new PrintStream(s.getOutputStream()); // to read data coming from the client BufferedReader br = new BufferedReader( new InputStreamReader( s.getInputStream())); // to read data from the keyboard BufferedReader kb = new BufferedReader( new InputStreamReader(System.in)); // server executes continuously while (true) { String str, str1; // repeat as long as the client // does not send a null string // read from client while ((str = br.readLine()) != null) { System.out.println(str); str1 = kb.readLine(); // send to client ps.println(str1); } // close connection ps.close(); br.close(); kb.close(); ss.close(); s.close(); // terminate application System.exit(0); } // end of while }}Command to compile the Server2.Java file:D:\Conversation Program>javac Sever2.java
Creating the Client Program: Let’s create a client, named Client2.Java, which first connects to a server, then starts the communication by sending a string to the server. The server sends a response to the client. When ‘exit’ is typed at the client side, the program terminates.Client2.javaClient2.java// Client2 class that// sends data and receives also import java.io.*;import java.net.*; class Client2 { public static void main(String args[]) throws Exception { // Create client socket Socket s = new Socket("localhost", 888); // to send data to the server DataOutputStream dos = new DataOutputStream( s.getOutputStream()); // to read data coming from the server BufferedReader br = new BufferedReader( new InputStreamReader( s.getInputStream())); // to read data from the keyboard BufferedReader kb = new BufferedReader( new InputStreamReader(System.in)); String str, str1; // repeat as long as exit // is not typed at client while (!(str = kb.readLine()).equals("exit")) { // send to the server dos.writeBytes(str + "\n"); // receive from the server str1 = br.readLine(); System.out.println(str1); } // close connection. dos.close(); br.close(); kb.close(); s.close(); }}Command to compile the Client2.java file:D:\Conversation Program>javac Client2.java
Output:To execute the Server2 and Client2 classes, run the Server2.java and Client2.java in two separate Command Prompt windows. Figure 1 shows the output of the Server2 and Client2 classes:Showing the Output of the Server2 and Client2 Classes
Creating the Server Program: Let’s create a class named Server2.java to create server such that the server receives data from the client using a BufferedReader object and then sends a reply to the client using a PrintStream object.Server2.javaServer2.java// Server2 class that// receives data and sends data import java.io.*;import java.net.*; class Server2 { public static void main(String args[]) throws Exception { // Create server Socket ServerSocket ss = new ServerSocket(888); // connect it to client socket Socket s = ss.accept(); System.out.println("Connection established"); // to send data to the client PrintStream ps = new PrintStream(s.getOutputStream()); // to read data coming from the client BufferedReader br = new BufferedReader( new InputStreamReader( s.getInputStream())); // to read data from the keyboard BufferedReader kb = new BufferedReader( new InputStreamReader(System.in)); // server executes continuously while (true) { String str, str1; // repeat as long as the client // does not send a null string // read from client while ((str = br.readLine()) != null) { System.out.println(str); str1 = kb.readLine(); // send to client ps.println(str1); } // close connection ps.close(); br.close(); kb.close(); ss.close(); s.close(); // terminate application System.exit(0); } // end of while }}Command to compile the Server2.Java file:D:\Conversation Program>javac Sever2.java
Server2.java
// Server2 class that// receives data and sends data import java.io.*;import java.net.*; class Server2 { public static void main(String args[]) throws Exception { // Create server Socket ServerSocket ss = new ServerSocket(888); // connect it to client socket Socket s = ss.accept(); System.out.println("Connection established"); // to send data to the client PrintStream ps = new PrintStream(s.getOutputStream()); // to read data coming from the client BufferedReader br = new BufferedReader( new InputStreamReader( s.getInputStream())); // to read data from the keyboard BufferedReader kb = new BufferedReader( new InputStreamReader(System.in)); // server executes continuously while (true) { String str, str1; // repeat as long as the client // does not send a null string // read from client while ((str = br.readLine()) != null) { System.out.println(str); str1 = kb.readLine(); // send to client ps.println(str1); } // close connection ps.close(); br.close(); kb.close(); ss.close(); s.close(); // terminate application System.exit(0); } // end of while }}
Command to compile the Server2.Java file:
D:\Conversation Program>javac Sever2.java
Creating the Client Program: Let’s create a client, named Client2.Java, which first connects to a server, then starts the communication by sending a string to the server. The server sends a response to the client. When ‘exit’ is typed at the client side, the program terminates.Client2.javaClient2.java// Client2 class that// sends data and receives also import java.io.*;import java.net.*; class Client2 { public static void main(String args[]) throws Exception { // Create client socket Socket s = new Socket("localhost", 888); // to send data to the server DataOutputStream dos = new DataOutputStream( s.getOutputStream()); // to read data coming from the server BufferedReader br = new BufferedReader( new InputStreamReader( s.getInputStream())); // to read data from the keyboard BufferedReader kb = new BufferedReader( new InputStreamReader(System.in)); String str, str1; // repeat as long as exit // is not typed at client while (!(str = kb.readLine()).equals("exit")) { // send to the server dos.writeBytes(str + "\n"); // receive from the server str1 = br.readLine(); System.out.println(str1); } // close connection. dos.close(); br.close(); kb.close(); s.close(); }}Command to compile the Client2.java file:D:\Conversation Program>javac Client2.java
Client2.java
// Client2 class that// sends data and receives also import java.io.*;import java.net.*; class Client2 { public static void main(String args[]) throws Exception { // Create client socket Socket s = new Socket("localhost", 888); // to send data to the server DataOutputStream dos = new DataOutputStream( s.getOutputStream()); // to read data coming from the server BufferedReader br = new BufferedReader( new InputStreamReader( s.getInputStream())); // to read data from the keyboard BufferedReader kb = new BufferedReader( new InputStreamReader(System.in)); String str, str1; // repeat as long as exit // is not typed at client while (!(str = kb.readLine()).equals("exit")) { // send to the server dos.writeBytes(str + "\n"); // receive from the server str1 = br.readLine(); System.out.println(str1); } // close connection. dos.close(); br.close(); kb.close(); s.close(); }}
Command to compile the Client2.java file:
D:\Conversation Program>javac Client2.java
Output:To execute the Server2 and Client2 classes, run the Server2.java and Client2.java in two separate Command Prompt windows. Figure 1 shows the output of the Server2 and Client2 classes:Showing the Output of the Server2 and Client2 Classes
Showing the Output of the Server2 and Client2 Classes
Java-Networking
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Iterate HashMap in Java?
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Write Data into Excel Sheet using Java?
Java Program to Convert String to String Array
Modulo or Remainder Operator in Java
SHA-1 Hash
Comparing two ArrayList In Java
How to Replace a Element in Java ArrayList? | [
{
"code": null,
"e": 24904,
"s": 24876,
"text": "\n14 Oct, 2019"
},
{
"code": null,
"e": 25054,
"s": 24904,
"text": "It is possible to send data from the server and receive a response from the client. Similarly, the client can also send and receive data to-and-from."
},
{
"code": null,
"e": 25092,
"s": 25054,
"text": "Below are the various steps to do so:"
},
{
"code": null,
"e": 25389,
"s": 25092,
"text": "We need additional streams both at server and client. For example, to receive data into the server, it is a better idea to use a BufferedReader object, as shown in the following code snippet:InputStream obj = s.getInputStream();\nBufferedReader br = new BufferedReader(new InputStreamReader(obj);\n"
},
{
"code": null,
"e": 25495,
"s": 25389,
"text": "InputStream obj = s.getInputStream();\nBufferedReader br = new BufferedReader(new InputStreamReader(obj);\n"
},
{
"code": null,
"e": 25794,
"s": 25495,
"text": "Then read() or readLine() methods of the BufferedReader object can be used to read data. To send data from the client we can take the help of the DataOutputStream class as shown in the following code snippet:OutputStream obj + s.getOutputStrean();\nDataOutputStream dos = new DataOutputStream(obj);\n"
},
{
"code": null,
"e": 25885,
"s": 25794,
"text": "OutputStream obj + s.getOutputStrean();\nDataOutputStream dos = new DataOutputStream(obj);\n"
},
{
"code": null,
"e": 29759,
"s": 25885,
"text": "Then, the writeBytes() method of the DataOutputStream class can be used to send strings in the form of a group of bytes. To establish the two-way communication between a client and server perform the following steps:Creating the Server Program: Let’s create a class named Server2.java to create server such that the server receives data from the client using a BufferedReader object and then sends a reply to the client using a PrintStream object.Server2.javaServer2.java// Server2 class that// receives data and sends data import java.io.*;import java.net.*; class Server2 { public static void main(String args[]) throws Exception { // Create server Socket ServerSocket ss = new ServerSocket(888); // connect it to client socket Socket s = ss.accept(); System.out.println(\"Connection established\"); // to send data to the client PrintStream ps = new PrintStream(s.getOutputStream()); // to read data coming from the client BufferedReader br = new BufferedReader( new InputStreamReader( s.getInputStream())); // to read data from the keyboard BufferedReader kb = new BufferedReader( new InputStreamReader(System.in)); // server executes continuously while (true) { String str, str1; // repeat as long as the client // does not send a null string // read from client while ((str = br.readLine()) != null) { System.out.println(str); str1 = kb.readLine(); // send to client ps.println(str1); } // close connection ps.close(); br.close(); kb.close(); ss.close(); s.close(); // terminate application System.exit(0); } // end of while }}Command to compile the Server2.Java file:D:\\Conversation Program>javac Sever2.java\nCreating the Client Program: Let’s create a client, named Client2.Java, which first connects to a server, then starts the communication by sending a string to the server. The server sends a response to the client. When ‘exit’ is typed at the client side, the program terminates.Client2.javaClient2.java// Client2 class that// sends data and receives also import java.io.*;import java.net.*; class Client2 { public static void main(String args[]) throws Exception { // Create client socket Socket s = new Socket(\"localhost\", 888); // to send data to the server DataOutputStream dos = new DataOutputStream( s.getOutputStream()); // to read data coming from the server BufferedReader br = new BufferedReader( new InputStreamReader( s.getInputStream())); // to read data from the keyboard BufferedReader kb = new BufferedReader( new InputStreamReader(System.in)); String str, str1; // repeat as long as exit // is not typed at client while (!(str = kb.readLine()).equals(\"exit\")) { // send to the server dos.writeBytes(str + \"\\n\"); // receive from the server str1 = br.readLine(); System.out.println(str1); } // close connection. dos.close(); br.close(); kb.close(); s.close(); }}Command to compile the Client2.java file:D:\\Conversation Program>javac Client2.java\nOutput:To execute the Server2 and Client2 classes, run the Server2.java and Client2.java in two separate Command Prompt windows. Figure 1 shows the output of the Server2 and Client2 classes:Showing the Output of the Server2 and Client2 Classes"
},
{
"code": null,
"e": 31598,
"s": 29759,
"text": "Creating the Server Program: Let’s create a class named Server2.java to create server such that the server receives data from the client using a BufferedReader object and then sends a reply to the client using a PrintStream object.Server2.javaServer2.java// Server2 class that// receives data and sends data import java.io.*;import java.net.*; class Server2 { public static void main(String args[]) throws Exception { // Create server Socket ServerSocket ss = new ServerSocket(888); // connect it to client socket Socket s = ss.accept(); System.out.println(\"Connection established\"); // to send data to the client PrintStream ps = new PrintStream(s.getOutputStream()); // to read data coming from the client BufferedReader br = new BufferedReader( new InputStreamReader( s.getInputStream())); // to read data from the keyboard BufferedReader kb = new BufferedReader( new InputStreamReader(System.in)); // server executes continuously while (true) { String str, str1; // repeat as long as the client // does not send a null string // read from client while ((str = br.readLine()) != null) { System.out.println(str); str1 = kb.readLine(); // send to client ps.println(str1); } // close connection ps.close(); br.close(); kb.close(); ss.close(); s.close(); // terminate application System.exit(0); } // end of while }}Command to compile the Server2.Java file:D:\\Conversation Program>javac Sever2.java\n"
},
{
"code": null,
"e": 31611,
"s": 31598,
"text": "Server2.java"
},
{
"code": "// Server2 class that// receives data and sends data import java.io.*;import java.net.*; class Server2 { public static void main(String args[]) throws Exception { // Create server Socket ServerSocket ss = new ServerSocket(888); // connect it to client socket Socket s = ss.accept(); System.out.println(\"Connection established\"); // to send data to the client PrintStream ps = new PrintStream(s.getOutputStream()); // to read data coming from the client BufferedReader br = new BufferedReader( new InputStreamReader( s.getInputStream())); // to read data from the keyboard BufferedReader kb = new BufferedReader( new InputStreamReader(System.in)); // server executes continuously while (true) { String str, str1; // repeat as long as the client // does not send a null string // read from client while ((str = br.readLine()) != null) { System.out.println(str); str1 = kb.readLine(); // send to client ps.println(str1); } // close connection ps.close(); br.close(); kb.close(); ss.close(); s.close(); // terminate application System.exit(0); } // end of while }}",
"e": 33112,
"s": 31611,
"text": null
},
{
"code": null,
"e": 33154,
"s": 33112,
"text": "Command to compile the Server2.Java file:"
},
{
"code": null,
"e": 33197,
"s": 33154,
"text": "D:\\Conversation Program>javac Sever2.java\n"
},
{
"code": null,
"e": 34774,
"s": 33197,
"text": "Creating the Client Program: Let’s create a client, named Client2.Java, which first connects to a server, then starts the communication by sending a string to the server. The server sends a response to the client. When ‘exit’ is typed at the client side, the program terminates.Client2.javaClient2.java// Client2 class that// sends data and receives also import java.io.*;import java.net.*; class Client2 { public static void main(String args[]) throws Exception { // Create client socket Socket s = new Socket(\"localhost\", 888); // to send data to the server DataOutputStream dos = new DataOutputStream( s.getOutputStream()); // to read data coming from the server BufferedReader br = new BufferedReader( new InputStreamReader( s.getInputStream())); // to read data from the keyboard BufferedReader kb = new BufferedReader( new InputStreamReader(System.in)); String str, str1; // repeat as long as exit // is not typed at client while (!(str = kb.readLine()).equals(\"exit\")) { // send to the server dos.writeBytes(str + \"\\n\"); // receive from the server str1 = br.readLine(); System.out.println(str1); } // close connection. dos.close(); br.close(); kb.close(); s.close(); }}Command to compile the Client2.java file:D:\\Conversation Program>javac Client2.java\n"
},
{
"code": null,
"e": 34787,
"s": 34774,
"text": "Client2.java"
},
{
"code": "// Client2 class that// sends data and receives also import java.io.*;import java.net.*; class Client2 { public static void main(String args[]) throws Exception { // Create client socket Socket s = new Socket(\"localhost\", 888); // to send data to the server DataOutputStream dos = new DataOutputStream( s.getOutputStream()); // to read data coming from the server BufferedReader br = new BufferedReader( new InputStreamReader( s.getInputStream())); // to read data from the keyboard BufferedReader kb = new BufferedReader( new InputStreamReader(System.in)); String str, str1; // repeat as long as exit // is not typed at client while (!(str = kb.readLine()).equals(\"exit\")) { // send to the server dos.writeBytes(str + \"\\n\"); // receive from the server str1 = br.readLine(); System.out.println(str1); } // close connection. dos.close(); br.close(); kb.close(); s.close(); }}",
"e": 35978,
"s": 34787,
"text": null
},
{
"code": null,
"e": 36020,
"s": 35978,
"text": "Command to compile the Client2.java file:"
},
{
"code": null,
"e": 36064,
"s": 36020,
"text": "D:\\Conversation Program>javac Client2.java\n"
},
{
"code": null,
"e": 36308,
"s": 36064,
"text": "Output:To execute the Server2 and Client2 classes, run the Server2.java and Client2.java in two separate Command Prompt windows. Figure 1 shows the output of the Server2 and Client2 classes:Showing the Output of the Server2 and Client2 Classes"
},
{
"code": null,
"e": 36362,
"s": 36308,
"text": "Showing the Output of the Server2 and Client2 Classes"
},
{
"code": null,
"e": 36378,
"s": 36362,
"text": "Java-Networking"
},
{
"code": null,
"e": 36392,
"s": 36378,
"text": "Java Programs"
},
{
"code": null,
"e": 36490,
"s": 36392,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36522,
"s": 36490,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 36570,
"s": 36522,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 36621,
"s": 36570,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 36655,
"s": 36621,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 36702,
"s": 36655,
"text": "How to Write Data into Excel Sheet using Java?"
},
{
"code": null,
"e": 36749,
"s": 36702,
"text": "Java Program to Convert String to String Array"
},
{
"code": null,
"e": 36786,
"s": 36749,
"text": "Modulo or Remainder Operator in Java"
},
{
"code": null,
"e": 36797,
"s": 36786,
"text": "SHA-1 Hash"
},
{
"code": null,
"e": 36829,
"s": 36797,
"text": "Comparing two ArrayList In Java"
}
] |
Change the size and position of button in Kivy - GeeksforGeeks | 19 Oct, 2021
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.In this article, we will see that how can we can change the size and the position of button in kivy Python. There are 4 properties to set up, the size and position of button. There are 2 properties which are for static placement and another 2 are for dynamic placement.
size : It takes two arguments i.e. (width, height).
Python3
b1 = Button(size =(100, 100))b2 = Button(size =(200, 200))
pos : pos stands for position i.e it is used to position the widget. By default (0, 0), the bottom-left corner of the screen is the default position of the button in kivy python.
Python3
b1 = Button(pos =(100, 100))b2 = Button(pos =(200, 200))
size_hint : Provide hint of size. It contains two arguments i.e. width and height it can be floating values. By default, all widgets have their size_hint=(1, 1). To create a button 50% of the width and 25% of the height of the layout and positioned at (20, 20), you can do –
Python3
button = Button( text ='Hello world', size_hint =(.5, .25), pos =(20, 20))
pos_hint : Provide hint of position. We can define upto 8 keys i.e. it takes arguments in form of dictionary.
pos_hint = {“x”:1, “y”:1, “left”:1, “right”:1, "center_x":1,
"center_y":1, "top”:1, “bottom”:1("top":0)}
If you want to create a button that will always be the size of layout minus 20% on each side –
Python3
button = Button(text ='Hello world', size_hint =(.6, .6), pos_hint ={'x':.2, 'y':.2})
Kivy Tutorial – Learn Kivy with Examples.
Note:
You can only use values between 0-1 for both size_hint and pos_hint. Where 0 = 0% and 1 = 100%.
The coordinate system in kivy works from the bottom left! This will be important when placing our objects. (i.e (0, 0) is the bottom left).
Basic Approach:
1) import kivy
2) import kivyApp
3) import all neaded(like button and layouts to use them)
4) Set minimum version(optional)
5) create Layout class
6) create App class
7) Set up the position and size of the buttons
8) return Layout/widget/Class(according to requirement)
9) Run an instance of the class
Below is the implementation of all 4 properties:
Python3
## Sample Python application demonstrating the## How to change button position and size in Kivy.#################################################### import modulesimport kivy # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # creates the button in kivy# if not imported shows the errorfrom kivy.uix.button import Button # This layout allows you to set relative coordinates for children.from kivy.uix.relativelayout import RelativeLayout # To change the kivy default settings# we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # creating the App classclass Pos_Size_App(App): def build(self): # A Relative Layout with a size of (300, 300) is created rl = RelativeLayout(size =(300, 300)) # creating button # size of button is 20 % by height and width of layout # position is 'center_x':.7, 'center_y':.5 b1 = Button(size_hint =(.2, .2), pos_hint ={'center_x':.7, 'center_y':.5}, text ="pos_hint") # creating button # size of button is 20 % by height and 50 % width of layout b2 = Button(size_hint =(.5, .2), text ="size_hint") # creating button # size of button is 20 % by height and width of layout # position is 200, 200 from bottom left b3 = Button( size_hint =(.2, .2), pos =(200, 200), text ="pos") # adding button to widget rl.add_widget(b1) rl.add_widget(b2) rl.add_widget(b3) # returning widget return rl # run the Appif __name__ == "__main__": Pos_Size_App().run()
Output:
gabaa406
Picked
Python-gui
Python-kivy
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
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24412,
"s": 24384,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 24918,
"s": 24412,
"text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.In this article, we will see that how can we can change the size and the position of button in kivy Python. There are 4 properties to set up, the size and position of button. There are 2 properties which are for static placement and another 2 are for dynamic placement. "
},
{
"code": null,
"e": 24971,
"s": 24918,
"text": "size : It takes two arguments i.e. (width, height). "
},
{
"code": null,
"e": 24979,
"s": 24971,
"text": "Python3"
},
{
"code": "b1 = Button(size =(100, 100))b2 = Button(size =(200, 200))",
"e": 25038,
"s": 24979,
"text": null
},
{
"code": null,
"e": 25219,
"s": 25038,
"text": "pos : pos stands for position i.e it is used to position the widget. By default (0, 0), the bottom-left corner of the screen is the default position of the button in kivy python. "
},
{
"code": null,
"e": 25227,
"s": 25219,
"text": "Python3"
},
{
"code": "b1 = Button(pos =(100, 100))b2 = Button(pos =(200, 200))",
"e": 25284,
"s": 25227,
"text": null
},
{
"code": null,
"e": 25560,
"s": 25284,
"text": "size_hint : Provide hint of size. It contains two arguments i.e. width and height it can be floating values. By default, all widgets have their size_hint=(1, 1). To create a button 50% of the width and 25% of the height of the layout and positioned at (20, 20), you can do – "
},
{
"code": null,
"e": 25568,
"s": 25560,
"text": "Python3"
},
{
"code": "button = Button( text ='Hello world', size_hint =(.5, .25), pos =(20, 20))",
"e": 25652,
"s": 25568,
"text": null
},
{
"code": null,
"e": 25764,
"s": 25652,
"text": "pos_hint : Provide hint of position. We can define upto 8 keys i.e. it takes arguments in form of dictionary. "
},
{
"code": null,
"e": 25885,
"s": 25764,
"text": "pos_hint = {“x”:1, “y”:1, “left”:1, “right”:1, \"center_x\":1,\n \"center_y\":1, \"top”:1, “bottom”:1(\"top\":0)}"
},
{
"code": null,
"e": 25981,
"s": 25885,
"text": "If you want to create a button that will always be the size of layout minus 20% on each side – "
},
{
"code": null,
"e": 25989,
"s": 25981,
"text": "Python3"
},
{
"code": "button = Button(text ='Hello world', size_hint =(.6, .6), pos_hint ={'x':.2, 'y':.2})",
"e": 26090,
"s": 25989,
"text": null
},
{
"code": null,
"e": 26134,
"s": 26092,
"text": "Kivy Tutorial – Learn Kivy with Examples."
},
{
"code": null,
"e": 26142,
"s": 26134,
"text": "Note: "
},
{
"code": null,
"e": 26238,
"s": 26142,
"text": "You can only use values between 0-1 for both size_hint and pos_hint. Where 0 = 0% and 1 = 100%."
},
{
"code": null,
"e": 26378,
"s": 26238,
"text": "The coordinate system in kivy works from the bottom left! This will be important when placing our objects. (i.e (0, 0) is the bottom left)."
},
{
"code": null,
"e": 26699,
"s": 26380,
"text": "Basic Approach:\n\n1) import kivy\n2) import kivyApp\n3) import all neaded(like button and layouts to use them)\n4) Set minimum version(optional)\n5) create Layout class\n6) create App class\n7) Set up the position and size of the buttons\n8) return Layout/widget/Class(according to requirement)\n9) Run an instance of the class"
},
{
"code": null,
"e": 26749,
"s": 26699,
"text": "Below is the implementation of all 4 properties: "
},
{
"code": null,
"e": 26757,
"s": 26749,
"text": "Python3"
},
{
"code": "## Sample Python application demonstrating the## How to change button position and size in Kivy.#################################################### import modulesimport kivy # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # creates the button in kivy# if not imported shows the errorfrom kivy.uix.button import Button # This layout allows you to set relative coordinates for children.from kivy.uix.relativelayout import RelativeLayout # To change the kivy default settings# we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # creating the App classclass Pos_Size_App(App): def build(self): # A Relative Layout with a size of (300, 300) is created rl = RelativeLayout(size =(300, 300)) # creating button # size of button is 20 % by height and width of layout # position is 'center_x':.7, 'center_y':.5 b1 = Button(size_hint =(.2, .2), pos_hint ={'center_x':.7, 'center_y':.5}, text =\"pos_hint\") # creating button # size of button is 20 % by height and 50 % width of layout b2 = Button(size_hint =(.5, .2), text =\"size_hint\") # creating button # size of button is 20 % by height and width of layout # position is 200, 200 from bottom left b3 = Button( size_hint =(.2, .2), pos =(200, 200), text =\"pos\") # adding button to widget rl.add_widget(b1) rl.add_widget(b2) rl.add_widget(b3) # returning widget return rl # run the Appif __name__ == \"__main__\": Pos_Size_App().run()",
"e": 28639,
"s": 26757,
"text": null
},
{
"code": null,
"e": 28649,
"s": 28639,
"text": "Output: "
},
{
"code": null,
"e": 28660,
"s": 28651,
"text": "gabaa406"
},
{
"code": null,
"e": 28667,
"s": 28660,
"text": "Picked"
},
{
"code": null,
"e": 28678,
"s": 28667,
"text": "Python-gui"
},
{
"code": null,
"e": 28690,
"s": 28678,
"text": "Python-kivy"
},
{
"code": null,
"e": 28697,
"s": 28690,
"text": "Python"
},
{
"code": null,
"e": 28795,
"s": 28697,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28813,
"s": 28795,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28848,
"s": 28813,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28870,
"s": 28848,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28902,
"s": 28870,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28932,
"s": 28902,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28974,
"s": 28932,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29000,
"s": 28974,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29037,
"s": 29000,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29080,
"s": 29037,
"text": "Python program to convert a list to string"
}
] |
Python MySQL - Introduction | The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard.
You can choose the right database for your application. Python Database API supports a wide range of database servers such as −
GadFly
mSQL
MySQL
PostgreSQL
Microsoft SQL Server 2000
Informix
Interbase
Oracle
Sybase
Here is the list of available Python database interfaces − Python Database Interfaces and APIs. You must download a separate DB API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL database, you must download both the Oracle and the MySQL database modules.
MySQL Python/Connector is an interface for connecting to a MySQL database server from Python. It implements the Python Database API and is built on top of the MySQL.
First of all, you need to make sure you have already installed python in your machine. To do so, open command prompt and type python in it and press Enter. If python is already installed in your system, this command will display its version as shown below −
C:\Users\Tutorialspoint>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Now press ctrl+z and then Enter to get out of the python shell and create a folder (in which you intended to install Python-MySQL connector) named Python_MySQL as −
>>> ^Z
C:\Users\Tutorialspoint>d:
D:\>mkdir Python_MySQL
PIP is a package manager in python using which you can install various modules/packages in Python. Therefore, to install Mysql-python mysql-connector-python you need to make sure that you have PIP installed in your computer and have its location added to path.
You can do so, by executing the pip command. If you didn’t have PIP in your system or, if you haven’t added its location in the Path environment variable, you will get an error message as −
D:\Python_MySQL>pip
'pip' is not recognized as an internal or external command,
operable program or batch file.
To install PIP, download the get-pip.py to the above created folder and, from command navigate it and install pip as follows −
D:\>cd Python_MySQL
D:\Python_MySQL>python get-pip.py
Collecting pip
Downloading
https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl (1.4MB)
|████████████████████████████████| 1.4MB 1.3MB/s
Collecting wheel
Downloading
https://files.pythonhosted.org/packages/00/83/b4a77d044e78ad1a45610eb88f745be2fd2c6d658f9798a15e384b7d57c9/wheel-0.33.6-py2.py3-none-any.whl
Installing collected packages: pip, wheel
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed pip-19.2.2 wheel-0.33.6
Once you have Python and PIP installed, open command prompt and upgrade pip (optional) as shown below −
C:\Users\Tutorialspoint>python -m pip install --upgrade pip
Collecting pip
Using cached
https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl
Installing collected packages: pip
Found existing installation: pip 19.0.3
Uninstalling pip-19.0.3:
Successfully uninstalled pip-19.0.3
Successfully installed pip-19.2.2
Then open command prompt in admin mode and install python MySQL connect as −
C:\WINDOWS\system32>pip install mysql-connector-python
Collecting mysql-connector-python
Using cached
https://files.pythonhosted.org/packages/99/74/f41182e6b7aadc62b038b6939dce784b7f9ec4f89e2ae14f9ba8190dc9ab/mysql_connector_python-8.0.17-py2.py3-none-any.whl
Collecting protobuf>=3.0.0 (from mysql-connector-python)
Using cached
https://files.pythonhosted.org/packages/09/0e/614766ea191e649216b87d331a4179338c623e08c0cca291bcf8638730ce/protobuf-3.9.1-cp37-cp37m-win32.whl
Collecting six>=1.9 (from protobuf>=3.0.0->mysql-connector-python)
Using cached
https://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whl
Requirement already satisfied: setuptools in c:\program files (x86)\python37-32\lib\site-packages (from protobuf>=3.0.0->mysql-connector-python) (40.8.0)
Installing collected packages: six, protobuf, mysql-connector-python
Successfully installed mysql-connector-python-8.0.17 protobuf-3.9.1 six-1.12.0
To verify the installation of the create a sample python script with the following line in it.
import mysql.connector
If the installation is successful, when you execute it, you should not get any errors −
D:\Python_MySQL>python test.py
D:\Python_MySQL>
Simply, if you need to install Python from scratch. Visit the Python Home Page.
Click on the Downloads button, you will be redirected to the downloads page which provides links for latest version of python for various platforms choose one and download it.
For instance, we have downloaded python-3.7.4.exe (for windows). Start the installation process by double-clicking the downloaded .exe file.
Check the Add Python 3.7 to Path option and proceed with the installation. After completion of this process, python will be installed in your system.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2342,
"s": 2219,
"text": "The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard."
},
{
"code": null,
"e": 2470,
"s": 2342,
"text": "You can choose the right database for your application. Python Database API supports a wide range of database servers such as −"
},
{
"code": null,
"e": 2477,
"s": 2470,
"text": "GadFly"
},
{
"code": null,
"e": 2482,
"s": 2477,
"text": "mSQL"
},
{
"code": null,
"e": 2488,
"s": 2482,
"text": "MySQL"
},
{
"code": null,
"e": 2499,
"s": 2488,
"text": "PostgreSQL"
},
{
"code": null,
"e": 2525,
"s": 2499,
"text": "Microsoft SQL Server 2000"
},
{
"code": null,
"e": 2534,
"s": 2525,
"text": "Informix"
},
{
"code": null,
"e": 2544,
"s": 2534,
"text": "Interbase"
},
{
"code": null,
"e": 2551,
"s": 2544,
"text": "Oracle"
},
{
"code": null,
"e": 2558,
"s": 2551,
"text": "Sybase"
},
{
"code": null,
"e": 2884,
"s": 2558,
"text": "Here is the list of available Python database interfaces − Python Database Interfaces and APIs. You must download a separate DB API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL database, you must download both the Oracle and the MySQL database modules."
},
{
"code": null,
"e": 3050,
"s": 2884,
"text": "MySQL Python/Connector is an interface for connecting to a MySQL database server from Python. It implements the Python Database API and is built on top of the MySQL."
},
{
"code": null,
"e": 3308,
"s": 3050,
"text": "First of all, you need to make sure you have already installed python in your machine. To do so, open command prompt and type python in it and press Enter. If python is already installed in your system, this command will display its version as shown below −"
},
{
"code": null,
"e": 3508,
"s": 3308,
"text": "C:\\Users\\Tutorialspoint>python\nPython 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>>\n"
},
{
"code": null,
"e": 3673,
"s": 3508,
"text": "Now press ctrl+z and then Enter to get out of the python shell and create a folder (in which you intended to install Python-MySQL connector) named Python_MySQL as −"
},
{
"code": null,
"e": 3732,
"s": 3673,
"text": ">>> ^Z \nC:\\Users\\Tutorialspoint>d:\nD:\\>mkdir Python_MySQL\n"
},
{
"code": null,
"e": 3993,
"s": 3732,
"text": "PIP is a package manager in python using which you can install various modules/packages in Python. Therefore, to install Mysql-python mysql-connector-python you need to make sure that you have PIP installed in your computer and have its location added to path."
},
{
"code": null,
"e": 4183,
"s": 3993,
"text": "You can do so, by executing the pip command. If you didn’t have PIP in your system or, if you haven’t added its location in the Path environment variable, you will get an error message as −"
},
{
"code": null,
"e": 4296,
"s": 4183,
"text": "D:\\Python_MySQL>pip\n'pip' is not recognized as an internal or external command,\noperable program or batch file.\n"
},
{
"code": null,
"e": 4423,
"s": 4296,
"text": "To install PIP, download the get-pip.py to the above created folder and, from command navigate it and install pip as follows −"
},
{
"code": null,
"e": 5084,
"s": 4423,
"text": "D:\\>cd Python_MySQL\nD:\\Python_MySQL>python get-pip.py\nCollecting pip\n Downloading\nhttps://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl (1.4MB)\n |████████████████████████████████| 1.4MB 1.3MB/s\nCollecting wheel\n Downloading \nhttps://files.pythonhosted.org/packages/00/83/b4a77d044e78ad1a45610eb88f745be2fd2c6d658f9798a15e384b7d57c9/wheel-0.33.6-py2.py3-none-any.whl\nInstalling collected packages: pip, wheel\nConsider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.\nSuccessfully installed pip-19.2.2 wheel-0.33.6\n"
},
{
"code": null,
"e": 5188,
"s": 5084,
"text": "Once you have Python and PIP installed, open command prompt and upgrade pip (optional) as shown below −"
},
{
"code": null,
"e": 5608,
"s": 5188,
"text": "C:\\Users\\Tutorialspoint>python -m pip install --upgrade pip\nCollecting pip\n Using cached \nhttps://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl\nInstalling collected packages: pip\n Found existing installation: pip 19.0.3\n Uninstalling pip-19.0.3:\n Successfully uninstalled pip-19.0.3\nSuccessfully installed pip-19.2.2\n"
},
{
"code": null,
"e": 5685,
"s": 5608,
"text": "Then open command prompt in admin mode and install python MySQL connect as −"
},
{
"code": null,
"e": 6692,
"s": 5685,
"text": "C:\\WINDOWS\\system32>pip install mysql-connector-python\nCollecting mysql-connector-python\n Using cached \nhttps://files.pythonhosted.org/packages/99/74/f41182e6b7aadc62b038b6939dce784b7f9ec4f89e2ae14f9ba8190dc9ab/mysql_connector_python-8.0.17-py2.py3-none-any.whl\nCollecting protobuf>=3.0.0 (from mysql-connector-python)\n Using cached \nhttps://files.pythonhosted.org/packages/09/0e/614766ea191e649216b87d331a4179338c623e08c0cca291bcf8638730ce/protobuf-3.9.1-cp37-cp37m-win32.whl\nCollecting six>=1.9 (from protobuf>=3.0.0->mysql-connector-python)\n Using cached \nhttps://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whl\nRequirement already satisfied: setuptools in c:\\program files (x86)\\python37-32\\lib\\site-packages (from protobuf>=3.0.0->mysql-connector-python) (40.8.0)\nInstalling collected packages: six, protobuf, mysql-connector-python\nSuccessfully installed mysql-connector-python-8.0.17 protobuf-3.9.1 six-1.12.0\n"
},
{
"code": null,
"e": 6787,
"s": 6692,
"text": "To verify the installation of the create a sample python script with the following line in it."
},
{
"code": null,
"e": 6811,
"s": 6787,
"text": "import mysql.connector\n"
},
{
"code": null,
"e": 6899,
"s": 6811,
"text": "If the installation is successful, when you execute it, you should not get any errors −"
},
{
"code": null,
"e": 6948,
"s": 6899,
"text": "D:\\Python_MySQL>python test.py\nD:\\Python_MySQL>\n"
},
{
"code": null,
"e": 7028,
"s": 6948,
"text": "Simply, if you need to install Python from scratch. Visit the Python Home Page."
},
{
"code": null,
"e": 7204,
"s": 7028,
"text": "Click on the Downloads button, you will be redirected to the downloads page which provides links for latest version of python for various platforms choose one and download it."
},
{
"code": null,
"e": 7345,
"s": 7204,
"text": "For instance, we have downloaded python-3.7.4.exe (for windows). Start the installation process by double-clicking the downloaded .exe file."
},
{
"code": null,
"e": 7495,
"s": 7345,
"text": "Check the Add Python 3.7 to Path option and proceed with the installation. After completion of this process, python will be installed in your system."
},
{
"code": null,
"e": 7532,
"s": 7495,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7548,
"s": 7532,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7581,
"s": 7548,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 7600,
"s": 7581,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7635,
"s": 7600,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 7657,
"s": 7635,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 7691,
"s": 7657,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 7719,
"s": 7691,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7754,
"s": 7719,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 7768,
"s": 7754,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7801,
"s": 7768,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7818,
"s": 7801,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7825,
"s": 7818,
"text": " Print"
},
{
"code": null,
"e": 7836,
"s": 7825,
"text": " Add Notes"
}
] |
Java Program to Concatenate Two Arrays | One way of doing it is, create an array of length equals to the sum of lengths of the two arrays and, add elements of both arrays to it one by one.
Live Demo
public class HelloWorld {
public static void main(String[] args) {
int[]a = {1,2,3,4};
int[]b = {4,16,1,2,3,22};
int[]c = new int[a.length+b.length];
int count = 0;
for(int i = 0; i<a.length; i++) {
c[i] = a[i];
count++;
}
for(int j = 0;j<b.length;j++) {
c[count++] = b[j];
}
for(int i = 0;i<c.length;i++) System.out.print(c[i]+" ");
}
}
1 2 3 4 4 16 1 2 3 22 | [
{
"code": null,
"e": 1210,
"s": 1062,
"text": "One way of doing it is, create an array of length equals to the sum of lengths of the two arrays and, add elements of both arrays to it one by one."
},
{
"code": null,
"e": 1220,
"s": 1210,
"text": "Live Demo"
},
{
"code": null,
"e": 1648,
"s": 1220,
"text": "public class HelloWorld {\n public static void main(String[] args) {\n int[]a = {1,2,3,4};\n int[]b = {4,16,1,2,3,22};\n int[]c = new int[a.length+b.length];\n int count = 0;\n\n for(int i = 0; i<a.length; i++) {\n c[i] = a[i];\n count++;\n }\n\n for(int j = 0;j<b.length;j++) {\n c[count++] = b[j];\n }\n\n for(int i = 0;i<c.length;i++) System.out.print(c[i]+\" \");\n }\n}"
},
{
"code": null,
"e": 1670,
"s": 1648,
"text": "1 2 3 4 4 16 1 2 3 22"
}
] |
\sf - Tex Command | \sf - Used to turn on sans serif mode for uppercase and lowercase letters and digits, and for uppercase Greek.
{ \sf}
\sf command turns on sans serif mode for uppercase and lowercase letters and digits, and for uppercase Greek.
\sf ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
\sf 0123456789
0123456789
\sf abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
ABCDE 01234 abcde
ABCDE01234abcde
{\sf AB\Delta\Gamma\Lambda}\ AB\Delta\Gamma\Lambda
ABΔΓΛ ABΔΓΛ
\sf AB \rm AB
ABAB
\sf{AB}CD
ABCD
\sf ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
\sf ABCDEFGHIJKLMNOPQRSTUVWXYZ
\sf 0123456789
0123456789
\sf 0123456789
\sf abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
\sf abcdefghijklmnopqrstuvwxyz
ABCDE 01234 abcde
ABCDE01234abcde
ABCDE 01234 abcde
{\sf AB\Delta\Gamma\Lambda}\ AB\Delta\Gamma\Lambda
ABΔΓΛ ABΔΓΛ
{\sf AB\Delta\Gamma\Lambda}\ AB\Delta\Gamma\Lambda
\sf AB \rm AB
ABAB
\sf AB \rm AB
\sf{AB}CD
ABCD
\sf{AB}CD
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8097,
"s": 7986,
"text": "\\sf - Used to turn on sans serif mode for uppercase and lowercase letters and digits, and for uppercase Greek."
},
{
"code": null,
"e": 8104,
"s": 8097,
"text": "{ \\sf}"
},
{
"code": null,
"e": 8214,
"s": 8104,
"text": "\\sf command turns on sans serif mode for uppercase and lowercase letters and digits, and for uppercase Greek."
},
{
"code": null,
"e": 8510,
"s": 8214,
"text": "\n\\sf ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\nABCDEFGHIJKLMNOPQRSTUVWXYZ\n\n\n\\sf 0123456789\n\n0123456789\n\n\n\\sf abcdefghijklmnopqrstuvwxyz\n\nabcdefghijklmnopqrstuvwxyz\n\n\nABCDE 01234 abcde\n\nABCDE01234abcde\n\n\n{\\sf AB\\Delta\\Gamma\\Lambda}\\ AB\\Delta\\Gamma\\Lambda\n\nABΔΓΛ ABΔΓΛ\n\n\n\\sf AB \\rm AB\n\nABAB\n\n\n\\sf{AB}CD\n\nABCD\n\n\n"
},
{
"code": null,
"e": 8571,
"s": 8510,
"text": "\\sf ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\nABCDEFGHIJKLMNOPQRSTUVWXYZ\n\n"
},
{
"code": null,
"e": 8602,
"s": 8571,
"text": "\\sf ABCDEFGHIJKLMNOPQRSTUVWXYZ"
},
{
"code": null,
"e": 8631,
"s": 8602,
"text": "\\sf 0123456789\n\n0123456789\n\n"
},
{
"code": null,
"e": 8646,
"s": 8631,
"text": "\\sf 0123456789"
},
{
"code": null,
"e": 8707,
"s": 8646,
"text": "\\sf abcdefghijklmnopqrstuvwxyz\n\nabcdefghijklmnopqrstuvwxyz\n\n"
},
{
"code": null,
"e": 8738,
"s": 8707,
"text": "\\sf abcdefghijklmnopqrstuvwxyz"
},
{
"code": null,
"e": 8775,
"s": 8738,
"text": "ABCDE 01234 abcde\n\nABCDE01234abcde\n\n"
},
{
"code": null,
"e": 8793,
"s": 8775,
"text": "ABCDE 01234 abcde"
},
{
"code": null,
"e": 8859,
"s": 8793,
"text": "{\\sf AB\\Delta\\Gamma\\Lambda}\\ AB\\Delta\\Gamma\\Lambda\n\nABΔΓΛ ABΔΓΛ\n\n"
},
{
"code": null,
"e": 8910,
"s": 8859,
"text": "{\\sf AB\\Delta\\Gamma\\Lambda}\\ AB\\Delta\\Gamma\\Lambda"
},
{
"code": null,
"e": 8932,
"s": 8910,
"text": "\\sf AB \\rm AB\n\nABAB\n\n"
},
{
"code": null,
"e": 8946,
"s": 8932,
"text": "\\sf AB \\rm AB"
},
{
"code": null,
"e": 8964,
"s": 8946,
"text": "\\sf{AB}CD\n\nABCD\n\n"
},
{
"code": null,
"e": 8974,
"s": 8964,
"text": "\\sf{AB}CD"
},
{
"code": null,
"e": 9006,
"s": 8974,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 9019,
"s": 9006,
"text": " Ashraf Said"
},
{
"code": null,
"e": 9052,
"s": 9019,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9065,
"s": 9052,
"text": " Ashraf Said"
},
{
"code": null,
"e": 9097,
"s": 9065,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9133,
"s": 9097,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 9168,
"s": 9133,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9185,
"s": 9168,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 9218,
"s": 9185,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9232,
"s": 9218,
"text": " Daniel Stern"
},
{
"code": null,
"e": 9264,
"s": 9232,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 9279,
"s": 9264,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 9286,
"s": 9279,
"text": " Print"
},
{
"code": null,
"e": 9297,
"s": 9286,
"text": " Add Notes"
}
] |
Tryit Editor v3.7 | Tryit: Create input field with an icon inside | [] |
How to unzip all zipped files in a Linux directory? | Unzip is the Linux command utility that we will use to unzip all zipped files present in a Linux directory.
By default, the unzip utility is not present on most of the Linux distributions and we can install the same with the help of the commands mentioned below.
sudo apt install unzip
sudo yum install unzip
unzip file.zip
In the above syntax we just need to replace the file.zip with the file that we want to unzip.
Consider a case where I have a directory named direct1 that looks something like this −
immukul@192 direct1 % ls -ltr
total 5216
-rwxrwxrwx 1 immukul staff 446966 Sep 23 1998 wget-1.5.3.tar.gz
drwxr-xr-x 2 immukul staff 64 Jul 13 11:36 dr1
drwxr-xr-x 3 immukul staff 96 Jul 13 11:36 dr2
-rw-r--r-- 1 immukul staff 2201512 Jul 14 09:19 zipContent.zip
-rw-r--r-- 1 immukul staff 122 Jul 14 16:10 somefile.txt
drwxrwxrwx 5 immukul staff 160 Jul 16 10:01 d1
-rwxrwxrwx 1 immukul staff 300 Jul 16 10:06 sample.sh
-rw-r--r-- 1 immukul staff 83 Jul 16 10:58 sample.txt
drwxr-xr-x 3 immukul staff 96 Jul 16 11:05 dir1
drwxr-xr-x 3 immukul staff 96 Jul 16 11:46 dir2
-rw-r--r-- 1 immukul staff 661 Jul 16 11:47 newZip.zip
As one can notice, there are few .zip files present in the above directory and we can unzip all these .zip files with the help of the command shown below.
unzip “*.zip”
Now once we run the following command, all the .zip files will be unzipped and their contents will be printed in the terminal.
immukul@192 direct1 % ls -ltr
total 13504
-rwxrwxrwx 1 immukul staff 446966 Sep 23 1998 wget-1.5.3.tar.gz
-rwxrwxrwx 1 immukul staff 7 Jul 7 10:37 2.txt
-rwxrwxrwx 1 immukul staff 4234901 Jul 7 17:41 file.txt
-rwxrwxrwx 1 immukul staff 8 Jul 8 19:05 3.txt
-rwxrwxrwx 1 immukul staff 946 Jul 12 18:45 sample.sh
drwxr-xr-x 2 immukul staff 64 Jul 13 11:36 dr1
drwxr-xr-x 3 immukul staff 96 Jul 13 11:36 dr2
-rw-r--r-- 1 immukul staff 2201512 Jul 14 09:19 zipContent.zip
-rw-r--r-- 1 immukul staff 122 Jul 14 16:10 somefile.txt
-rw-r--r-- 1 immukul staff 83 Jul 16 10:58 sample.txt
drwxr-xr-x 3 immukul staff 96 Jul 16 11:05 dir1
drwxr-xr-x 3 immukul staff 96 Jul 16 11:46 dir2
-rw-r--r-- 1 immukul staff 661 Jul 16 11:47 newZip.zip
drwxrwxrwx 5 immukul staff 160 Jul 16 11:48 d1
drwxr-xr-x 4 immukul staff 128 Jul 16 11:48 d2 | [
{
"code": null,
"e": 1170,
"s": 1062,
"text": "Unzip is the Linux command utility that we will use to unzip all zipped files present in a Linux directory."
},
{
"code": null,
"e": 1325,
"s": 1170,
"text": "By default, the unzip utility is not present on most of the Linux distributions and we can install the same with the help of the commands mentioned below."
},
{
"code": null,
"e": 1348,
"s": 1325,
"text": "sudo apt install unzip"
},
{
"code": null,
"e": 1371,
"s": 1348,
"text": "sudo yum install unzip"
},
{
"code": null,
"e": 1386,
"s": 1371,
"text": "unzip file.zip"
},
{
"code": null,
"e": 1480,
"s": 1386,
"text": "In the above syntax we just need to replace the file.zip with the file that we want to unzip."
},
{
"code": null,
"e": 1568,
"s": 1480,
"text": "Consider a case where I have a directory named direct1 that looks something like this −"
},
{
"code": null,
"e": 2193,
"s": 1568,
"text": "immukul@192 direct1 % ls -ltr\ntotal 5216\n-rwxrwxrwx 1 immukul staff 446966 Sep 23 1998 wget-1.5.3.tar.gz\ndrwxr-xr-x 2 immukul staff 64 Jul 13 11:36 dr1\ndrwxr-xr-x 3 immukul staff 96 Jul 13 11:36 dr2\n-rw-r--r-- 1 immukul staff 2201512 Jul 14 09:19 zipContent.zip\n-rw-r--r-- 1 immukul staff 122 Jul 14 16:10 somefile.txt\ndrwxrwxrwx 5 immukul staff 160 Jul 16 10:01 d1\n-rwxrwxrwx 1 immukul staff 300 Jul 16 10:06 sample.sh\n-rw-r--r-- 1 immukul staff 83 Jul 16 10:58 sample.txt\ndrwxr-xr-x 3 immukul staff 96 Jul 16 11:05 dir1\ndrwxr-xr-x 3 immukul staff 96 Jul 16 11:46 dir2\n-rw-r--r-- 1 immukul staff 661 Jul 16 11:47 newZip.zip"
},
{
"code": null,
"e": 2348,
"s": 2193,
"text": "As one can notice, there are few .zip files present in the above directory and we can unzip all these .zip files with the help of the command shown below."
},
{
"code": null,
"e": 2362,
"s": 2348,
"text": "unzip “*.zip”"
},
{
"code": null,
"e": 2489,
"s": 2362,
"text": "Now once we run the following command, all the .zip files will be unzipped and their contents will be printed in the terminal."
},
{
"code": null,
"e": 3312,
"s": 2489,
"text": "immukul@192 direct1 % ls -ltr\ntotal 13504\n-rwxrwxrwx 1 immukul staff 446966 Sep 23 1998 wget-1.5.3.tar.gz\n-rwxrwxrwx 1 immukul staff 7 Jul 7 10:37 2.txt\n-rwxrwxrwx 1 immukul staff 4234901 Jul 7 17:41 file.txt\n-rwxrwxrwx 1 immukul staff 8 Jul 8 19:05 3.txt\n-rwxrwxrwx 1 immukul staff 946 Jul 12 18:45 sample.sh\ndrwxr-xr-x 2 immukul staff 64 Jul 13 11:36 dr1\ndrwxr-xr-x 3 immukul staff 96 Jul 13 11:36 dr2\n-rw-r--r-- 1 immukul staff 2201512 Jul 14 09:19 zipContent.zip\n-rw-r--r-- 1 immukul staff 122 Jul 14 16:10 somefile.txt\n-rw-r--r-- 1 immukul staff 83 Jul 16 10:58 sample.txt\ndrwxr-xr-x 3 immukul staff 96 Jul 16 11:05 dir1\ndrwxr-xr-x 3 immukul staff 96 Jul 16 11:46 dir2\n-rw-r--r-- 1 immukul staff 661 Jul 16 11:47 newZip.zip\ndrwxrwxrwx 5 immukul staff 160 Jul 16 11:48 d1\ndrwxr-xr-x 4 immukul staff 128 Jul 16 11:48 d2"
}
] |
How to create new alias with PowerShell? | Anyone can create a new alias which is a shortcut to another command. To create your own alias you need to use Set-Alias cmdlet. Here, we will create a new alias Edit, which will open a
Notepad.exe. First, we will check if Edit alias exists or not.
$Alias:Edit
As this is going to be a new Alias there will be no output for it. Now, we will create new alias by the below command. You can provide any program path and create an alias for it.
Set-Alias Edit Notepad.exe
Just check if this Edit alias created successfully or not.
PS E:\scripts\Powershell> $Alias:Edit
Notepad.exe
This new alias is not permanent. Once you close the PowerShell console, all newly created aliases will be discarded. But the built-in alias will still remain.
If you want to create an alias permanently you have few options.
Manually each time − You need to set the alias each time when PowerShell console starts but this is not a feasible option.
Manually each time − You need to set the alias each time when PowerShell console starts but this is not a feasible option.
Import and Export − You can export the newly created alias and import it when the PowerShell starts.
Import and Export − You can export the newly created alias and import it when the PowerShell starts.
Save Alias in Profile − You can add your alias to your profile path. So when the profile starts, the alias will be created automatically when PowerShell starts.
Save Alias in Profile − You can add your alias to your profile path. So when the profile starts, the alias will be created automatically when PowerShell starts. | [
{
"code": null,
"e": 1311,
"s": 1062,
"text": "Anyone can create a new alias which is a shortcut to another command. To create your own alias you need to use Set-Alias cmdlet. Here, we will create a new alias Edit, which will open a\nNotepad.exe. First, we will check if Edit alias exists or not."
},
{
"code": null,
"e": 1323,
"s": 1311,
"text": "$Alias:Edit"
},
{
"code": null,
"e": 1503,
"s": 1323,
"text": "As this is going to be a new Alias there will be no output for it. Now, we will create new alias by the below command. You can provide any program path and create an alias for it."
},
{
"code": null,
"e": 1530,
"s": 1503,
"text": "Set-Alias Edit Notepad.exe"
},
{
"code": null,
"e": 1589,
"s": 1530,
"text": "Just check if this Edit alias created successfully or not."
},
{
"code": null,
"e": 1639,
"s": 1589,
"text": "PS E:\\scripts\\Powershell> $Alias:Edit\nNotepad.exe"
},
{
"code": null,
"e": 1798,
"s": 1639,
"text": "This new alias is not permanent. Once you close the PowerShell console, all newly created aliases will be discarded. But the built-in alias will still remain."
},
{
"code": null,
"e": 1863,
"s": 1798,
"text": "If you want to create an alias permanently you have few options."
},
{
"code": null,
"e": 1986,
"s": 1863,
"text": "Manually each time − You need to set the alias each time when PowerShell console starts but this is not a feasible option."
},
{
"code": null,
"e": 2109,
"s": 1986,
"text": "Manually each time − You need to set the alias each time when PowerShell console starts but this is not a feasible option."
},
{
"code": null,
"e": 2210,
"s": 2109,
"text": "Import and Export − You can export the newly created alias and import it when the PowerShell starts."
},
{
"code": null,
"e": 2311,
"s": 2210,
"text": "Import and Export − You can export the newly created alias and import it when the PowerShell starts."
},
{
"code": null,
"e": 2472,
"s": 2311,
"text": "Save Alias in Profile − You can add your alias to your profile path. So when the profile starts, the alias will be created automatically when PowerShell starts."
},
{
"code": null,
"e": 2633,
"s": 2472,
"text": "Save Alias in Profile − You can add your alias to your profile path. So when the profile starts, the alias will be created automatically when PowerShell starts."
}
] |
Why Is Everyone at Kaggle Obsessed with Optuna For Hyperparameter Tuning? | by Bex T. | Towards Data Science | Turns out I have been living under a rock.
While every single MOOC taught me to use GridSearch for hyperparameter tuning, Kagglers have been using Optuna almost exclusively for 2 years. This even predates the time I started learning data science.
Kaggle community is known for its brutal competitiveness, and for a package to achieve this level of domination, it needs to be damn good. After being active on the platform for the last month (and achieving expert status in two tiers), I saw Optuna used almost everywhere and by everyone.
So, what makes Optuna so widely received by the largest machine learning community out there? We will answer this question in this post by getting hands-on on the framework. We will learn how it works and how it squeezes every bit of performance out of any model, including neural networks.
Optuna is a next-generation automatic hyperparameter tuning framework written completely in Python.
Its most prominent features are:
the ability to define Pythonic search spaces using loops and conditionals.
Platform-agnostic API — you can tune estimators of almost any ML, DL package/framework, including Sklearn, PyTorch, TensorFlow, Keras, XGBoost, LightGBM, CatBoost, etc.
a large suite of optimization algorithms with early stopping and pruning features baked in.
Easy parallelization with little or no changes to the code.
Built-in support for visual exploration of search results.
We will try to validate these overly optimistic claims made in Optuna’s documentation in the coming sections.
Let’s familiarize ourselves with Optuna API by tuning a simple function like (x-1)2 + (y+3)2. We know the function reaches its minimum at x=1 and y=-3.
You can find the notebook for this article here.
Let’s see if Optuna can find these:
After importing optuna, we define an objective that returns the function we want to minimize.
In the body of the objective, we define the parameters to be optimized, in this case, simple x and y. The argument trial is a special Trial object of optuna, which does the optimization for each hyperparameter.
Among others, it has a suggest_float method that takes the name of the hyperparameter and the range to look for its optimal value. In other words,
x = trial.suggest_float("x", -7, 7)
is almost the same as {"x": np.arange(-7, 7)} when doing GridSearch.
To start the optimization, we create a study object from Optuna and pass the objective function to its optimize method:
Pretty close, but not as close as you would want. Here, we only did 100 trials, as can be seen with:
>>> len(study.trials)100
Now, I will introduce the first magic that comes with Optuna. We can resume the optimization even after it is finished if we are not satisfied with the results!
This is a distinct advantage over other similar tools because after the search is done, they completely forget the history of previous trials. Optuna does not!
To continue searching, call optimize again with the desired params. Here, we will run 100 more trials:
This time, the results are much closer to the optimal parameters.
In Optuna, the whole optimization process is called a study. For example, tuning XGBoost parameters with a log loss as a metric is one study:
A study needs a function it can optimize. Typically, this function is defined by the user, should be named objective and expected to have this signature:
It should accept an optuna.Trial object as a parameter and return the metric we want to optimize for.
As we saw in the first example, a study is a collection of trials wherein each trial, we evaluate the objective function using a single set of hyperparameters from the given search space.
Each trial in the study is represented as optuna.Trial class. This class is key to how Optuna finds optimal values for parameters.
To start a study, we create a study object with direction:
If the metric we want to optimize is a point-performance score like ROC AUC or accuracy, we set the direction to maximize. Otherwise, we minimize a loss function like RMSE, RMSLE, log loss, etc. by setting direction to minimize.
Then, we will call the optimize method of the study passing the objective function name and the number of trials we want:
Next, we will take a closer look into creating these objective functions.
Usually, the first thing you do in an objective function is to create the search space using built-in Optuna methods:
In the above objective function, we are creating a small search space of Random Forest hyperparameters.
The search space is a plain-old dictionary. To create possible values to search over, you must use the trial object’s suggest_* functions.
These functions require at least the hyperparameter name, min, and max of the range to search over or possible categories for categorical hyperparameters.
To make the space smaller, suggest_float and suggest_int have additional step or log arguments:
Above, we are binning the distribution of n_estimators by 200-intervals to make it sparser. Also, learning_rate is defined at a logarithmic scale.
Under the hood, Optuna has several classes responsible for parameter sampling. These are:
GridSampler: the same as GridSearch of Sklearn. Never use for large search spaces!
RandomSampler: the same as RandomizedGridSearch of Sklearn.
TPESampler: Tree-structured Parzen Estimator sampler - bayesian optimization using kernel fitting
CmaEsSampler: a sampler based on CMA ES algorithm (does not allow categorical hyperparameters).
I have no idea of how the last two samplers work and I don’t expect this to affect any interaction I have with Optuna.
TPE Sampler is used by default — it tries to sample hyperparameter candidates by improving on the last trial’s scores. In other words, you can expect incremental (maybe marginal) improvements from trial to trial with this sampler.
If you ever want to switch samplers, this is how you do it:
Let’s put everything we have learned into something tangible. We will be predicting penguin body weights using several numeric and categorical features.
We will establish a base score with Sklearn GradientBoostingRegressor and improve it by tuning with Optuna:
Now, we will create the objective function and define the search space:
We built a grid of 5 hyperparameters with different ranges and some static ones for random seed and early stopping.
The above objective function is slightly different — it accepts additional arguments for the data sets, scoring and cv. That's why we have to wrap it inside another function. Generally, you do this with a lambda function like below:
This is the recommended syntax if you want to pass objective functions that accept multiple parameters.
In just under a minute, we achieved a significant score boost (in terms of log errors, 0.004 is pretty sweet). We did this with only 100 trials. Let’s boldly run another 200 and see what happens:
The score did improve but marginally. It looks like we hit it close to the max in the first run!
Most importantly, we achieved this score in just over 2 minutes using a search space that would probably take hours with regular GridSearch.
I don’t know about you, but I am sold!
Optuna offers a wide range of plots under its visualization subpackage. Here, we will discuss only 2, which I think are the most useful.
First, let’s plot the optimization history of the last study:
This plot tells us that Optuna made the score converge to the minimum after only a few trials.
Next, let’s plot hyperparameter importances:
This plot is massively useful! It tells us several things, including:
max_depth and learning_rate are the most important
subsample and max_features are useless for minimizing the loss
A plot like this comes in handy when tuning models with many hyperparameters. For example, you could take a test run of 40–50 trials and plot the parameter importances.
Depending on the plot, you might decide to discard some less important parameters and give a larger search space for other ones, possibly reducing the search time and space.
You can check out this page of the documentation for more information on Optuna’s supported plot types.
I think we can all agree that Optuna lived up to the whole hype I made in the introduction. It is awesome!
This article only gave you the basics you can do with Optuna. Actually, Optuna is capable of much more. Some of the critical topics we didn’t cover today:
Use cases of Optuna with other ML/DL frameworks
Choosing a pruning algorithm to weed out unpromising trials immediately
Parallelization
and the coolest of all:
Using SQLite or other databases (local or remote) to run massive-scale optimization with resume/pause capabilities
Do check out the links to the relevant documentation pages.
Automatic Hyperparameter Tuning with Sklearn GridSearchCV and RandomizedSearchCV
11 Times Faster Hyperparameter Tuning with HalvingGridSearch
20 Burning XGBoost FAQs Answered to Use the Library Like a Pro | [
{
"code": null,
"e": 214,
"s": 171,
"text": "Turns out I have been living under a rock."
},
{
"code": null,
"e": 418,
"s": 214,
"text": "While every single MOOC taught me to use GridSearch for hyperparameter tuning, Kagglers have been using Optuna almost exclusively for 2 years. This even predates the time I started learning data science."
},
{
"code": null,
"e": 708,
"s": 418,
"text": "Kaggle community is known for its brutal competitiveness, and for a package to achieve this level of domination, it needs to be damn good. After being active on the platform for the last month (and achieving expert status in two tiers), I saw Optuna used almost everywhere and by everyone."
},
{
"code": null,
"e": 999,
"s": 708,
"text": "So, what makes Optuna so widely received by the largest machine learning community out there? We will answer this question in this post by getting hands-on on the framework. We will learn how it works and how it squeezes every bit of performance out of any model, including neural networks."
},
{
"code": null,
"e": 1099,
"s": 999,
"text": "Optuna is a next-generation automatic hyperparameter tuning framework written completely in Python."
},
{
"code": null,
"e": 1132,
"s": 1099,
"text": "Its most prominent features are:"
},
{
"code": null,
"e": 1207,
"s": 1132,
"text": "the ability to define Pythonic search spaces using loops and conditionals."
},
{
"code": null,
"e": 1376,
"s": 1207,
"text": "Platform-agnostic API — you can tune estimators of almost any ML, DL package/framework, including Sklearn, PyTorch, TensorFlow, Keras, XGBoost, LightGBM, CatBoost, etc."
},
{
"code": null,
"e": 1468,
"s": 1376,
"text": "a large suite of optimization algorithms with early stopping and pruning features baked in."
},
{
"code": null,
"e": 1528,
"s": 1468,
"text": "Easy parallelization with little or no changes to the code."
},
{
"code": null,
"e": 1587,
"s": 1528,
"text": "Built-in support for visual exploration of search results."
},
{
"code": null,
"e": 1697,
"s": 1587,
"text": "We will try to validate these overly optimistic claims made in Optuna’s documentation in the coming sections."
},
{
"code": null,
"e": 1849,
"s": 1697,
"text": "Let’s familiarize ourselves with Optuna API by tuning a simple function like (x-1)2 + (y+3)2. We know the function reaches its minimum at x=1 and y=-3."
},
{
"code": null,
"e": 1898,
"s": 1849,
"text": "You can find the notebook for this article here."
},
{
"code": null,
"e": 1934,
"s": 1898,
"text": "Let’s see if Optuna can find these:"
},
{
"code": null,
"e": 2028,
"s": 1934,
"text": "After importing optuna, we define an objective that returns the function we want to minimize."
},
{
"code": null,
"e": 2239,
"s": 2028,
"text": "In the body of the objective, we define the parameters to be optimized, in this case, simple x and y. The argument trial is a special Trial object of optuna, which does the optimization for each hyperparameter."
},
{
"code": null,
"e": 2386,
"s": 2239,
"text": "Among others, it has a suggest_float method that takes the name of the hyperparameter and the range to look for its optimal value. In other words,"
},
{
"code": null,
"e": 2422,
"s": 2386,
"text": "x = trial.suggest_float(\"x\", -7, 7)"
},
{
"code": null,
"e": 2491,
"s": 2422,
"text": "is almost the same as {\"x\": np.arange(-7, 7)} when doing GridSearch."
},
{
"code": null,
"e": 2611,
"s": 2491,
"text": "To start the optimization, we create a study object from Optuna and pass the objective function to its optimize method:"
},
{
"code": null,
"e": 2712,
"s": 2611,
"text": "Pretty close, but not as close as you would want. Here, we only did 100 trials, as can be seen with:"
},
{
"code": null,
"e": 2737,
"s": 2712,
"text": ">>> len(study.trials)100"
},
{
"code": null,
"e": 2898,
"s": 2737,
"text": "Now, I will introduce the first magic that comes with Optuna. We can resume the optimization even after it is finished if we are not satisfied with the results!"
},
{
"code": null,
"e": 3058,
"s": 2898,
"text": "This is a distinct advantage over other similar tools because after the search is done, they completely forget the history of previous trials. Optuna does not!"
},
{
"code": null,
"e": 3161,
"s": 3058,
"text": "To continue searching, call optimize again with the desired params. Here, we will run 100 more trials:"
},
{
"code": null,
"e": 3227,
"s": 3161,
"text": "This time, the results are much closer to the optimal parameters."
},
{
"code": null,
"e": 3369,
"s": 3227,
"text": "In Optuna, the whole optimization process is called a study. For example, tuning XGBoost parameters with a log loss as a metric is one study:"
},
{
"code": null,
"e": 3523,
"s": 3369,
"text": "A study needs a function it can optimize. Typically, this function is defined by the user, should be named objective and expected to have this signature:"
},
{
"code": null,
"e": 3625,
"s": 3523,
"text": "It should accept an optuna.Trial object as a parameter and return the metric we want to optimize for."
},
{
"code": null,
"e": 3813,
"s": 3625,
"text": "As we saw in the first example, a study is a collection of trials wherein each trial, we evaluate the objective function using a single set of hyperparameters from the given search space."
},
{
"code": null,
"e": 3944,
"s": 3813,
"text": "Each trial in the study is represented as optuna.Trial class. This class is key to how Optuna finds optimal values for parameters."
},
{
"code": null,
"e": 4003,
"s": 3944,
"text": "To start a study, we create a study object with direction:"
},
{
"code": null,
"e": 4232,
"s": 4003,
"text": "If the metric we want to optimize is a point-performance score like ROC AUC or accuracy, we set the direction to maximize. Otherwise, we minimize a loss function like RMSE, RMSLE, log loss, etc. by setting direction to minimize."
},
{
"code": null,
"e": 4354,
"s": 4232,
"text": "Then, we will call the optimize method of the study passing the objective function name and the number of trials we want:"
},
{
"code": null,
"e": 4428,
"s": 4354,
"text": "Next, we will take a closer look into creating these objective functions."
},
{
"code": null,
"e": 4546,
"s": 4428,
"text": "Usually, the first thing you do in an objective function is to create the search space using built-in Optuna methods:"
},
{
"code": null,
"e": 4650,
"s": 4546,
"text": "In the above objective function, we are creating a small search space of Random Forest hyperparameters."
},
{
"code": null,
"e": 4789,
"s": 4650,
"text": "The search space is a plain-old dictionary. To create possible values to search over, you must use the trial object’s suggest_* functions."
},
{
"code": null,
"e": 4944,
"s": 4789,
"text": "These functions require at least the hyperparameter name, min, and max of the range to search over or possible categories for categorical hyperparameters."
},
{
"code": null,
"e": 5040,
"s": 4944,
"text": "To make the space smaller, suggest_float and suggest_int have additional step or log arguments:"
},
{
"code": null,
"e": 5187,
"s": 5040,
"text": "Above, we are binning the distribution of n_estimators by 200-intervals to make it sparser. Also, learning_rate is defined at a logarithmic scale."
},
{
"code": null,
"e": 5277,
"s": 5187,
"text": "Under the hood, Optuna has several classes responsible for parameter sampling. These are:"
},
{
"code": null,
"e": 5360,
"s": 5277,
"text": "GridSampler: the same as GridSearch of Sklearn. Never use for large search spaces!"
},
{
"code": null,
"e": 5420,
"s": 5360,
"text": "RandomSampler: the same as RandomizedGridSearch of Sklearn."
},
{
"code": null,
"e": 5518,
"s": 5420,
"text": "TPESampler: Tree-structured Parzen Estimator sampler - bayesian optimization using kernel fitting"
},
{
"code": null,
"e": 5614,
"s": 5518,
"text": "CmaEsSampler: a sampler based on CMA ES algorithm (does not allow categorical hyperparameters)."
},
{
"code": null,
"e": 5733,
"s": 5614,
"text": "I have no idea of how the last two samplers work and I don’t expect this to affect any interaction I have with Optuna."
},
{
"code": null,
"e": 5964,
"s": 5733,
"text": "TPE Sampler is used by default — it tries to sample hyperparameter candidates by improving on the last trial’s scores. In other words, you can expect incremental (maybe marginal) improvements from trial to trial with this sampler."
},
{
"code": null,
"e": 6024,
"s": 5964,
"text": "If you ever want to switch samplers, this is how you do it:"
},
{
"code": null,
"e": 6177,
"s": 6024,
"text": "Let’s put everything we have learned into something tangible. We will be predicting penguin body weights using several numeric and categorical features."
},
{
"code": null,
"e": 6285,
"s": 6177,
"text": "We will establish a base score with Sklearn GradientBoostingRegressor and improve it by tuning with Optuna:"
},
{
"code": null,
"e": 6357,
"s": 6285,
"text": "Now, we will create the objective function and define the search space:"
},
{
"code": null,
"e": 6473,
"s": 6357,
"text": "We built a grid of 5 hyperparameters with different ranges and some static ones for random seed and early stopping."
},
{
"code": null,
"e": 6706,
"s": 6473,
"text": "The above objective function is slightly different — it accepts additional arguments for the data sets, scoring and cv. That's why we have to wrap it inside another function. Generally, you do this with a lambda function like below:"
},
{
"code": null,
"e": 6810,
"s": 6706,
"text": "This is the recommended syntax if you want to pass objective functions that accept multiple parameters."
},
{
"code": null,
"e": 7006,
"s": 6810,
"text": "In just under a minute, we achieved a significant score boost (in terms of log errors, 0.004 is pretty sweet). We did this with only 100 trials. Let’s boldly run another 200 and see what happens:"
},
{
"code": null,
"e": 7103,
"s": 7006,
"text": "The score did improve but marginally. It looks like we hit it close to the max in the first run!"
},
{
"code": null,
"e": 7244,
"s": 7103,
"text": "Most importantly, we achieved this score in just over 2 minutes using a search space that would probably take hours with regular GridSearch."
},
{
"code": null,
"e": 7283,
"s": 7244,
"text": "I don’t know about you, but I am sold!"
},
{
"code": null,
"e": 7420,
"s": 7283,
"text": "Optuna offers a wide range of plots under its visualization subpackage. Here, we will discuss only 2, which I think are the most useful."
},
{
"code": null,
"e": 7482,
"s": 7420,
"text": "First, let’s plot the optimization history of the last study:"
},
{
"code": null,
"e": 7577,
"s": 7482,
"text": "This plot tells us that Optuna made the score converge to the minimum after only a few trials."
},
{
"code": null,
"e": 7622,
"s": 7577,
"text": "Next, let’s plot hyperparameter importances:"
},
{
"code": null,
"e": 7692,
"s": 7622,
"text": "This plot is massively useful! It tells us several things, including:"
},
{
"code": null,
"e": 7743,
"s": 7692,
"text": "max_depth and learning_rate are the most important"
},
{
"code": null,
"e": 7806,
"s": 7743,
"text": "subsample and max_features are useless for minimizing the loss"
},
{
"code": null,
"e": 7975,
"s": 7806,
"text": "A plot like this comes in handy when tuning models with many hyperparameters. For example, you could take a test run of 40–50 trials and plot the parameter importances."
},
{
"code": null,
"e": 8149,
"s": 7975,
"text": "Depending on the plot, you might decide to discard some less important parameters and give a larger search space for other ones, possibly reducing the search time and space."
},
{
"code": null,
"e": 8253,
"s": 8149,
"text": "You can check out this page of the documentation for more information on Optuna’s supported plot types."
},
{
"code": null,
"e": 8360,
"s": 8253,
"text": "I think we can all agree that Optuna lived up to the whole hype I made in the introduction. It is awesome!"
},
{
"code": null,
"e": 8515,
"s": 8360,
"text": "This article only gave you the basics you can do with Optuna. Actually, Optuna is capable of much more. Some of the critical topics we didn’t cover today:"
},
{
"code": null,
"e": 8563,
"s": 8515,
"text": "Use cases of Optuna with other ML/DL frameworks"
},
{
"code": null,
"e": 8635,
"s": 8563,
"text": "Choosing a pruning algorithm to weed out unpromising trials immediately"
},
{
"code": null,
"e": 8651,
"s": 8635,
"text": "Parallelization"
},
{
"code": null,
"e": 8675,
"s": 8651,
"text": "and the coolest of all:"
},
{
"code": null,
"e": 8790,
"s": 8675,
"text": "Using SQLite or other databases (local or remote) to run massive-scale optimization with resume/pause capabilities"
},
{
"code": null,
"e": 8850,
"s": 8790,
"text": "Do check out the links to the relevant documentation pages."
},
{
"code": null,
"e": 8931,
"s": 8850,
"text": "Automatic Hyperparameter Tuning with Sklearn GridSearchCV and RandomizedSearchCV"
},
{
"code": null,
"e": 8992,
"s": 8931,
"text": "11 Times Faster Hyperparameter Tuning with HalvingGridSearch"
}
] |
Supercharge Python’s Requests with Async IO & HTTPX | by Maulin Tolia | Towards Data Science | If you have some experience with Python, chances are good that you have used the Requests library at some point. It is a wonderful library for making HTTP requests and interacting with APIs.
The advantage of Requests is that it’s simple and syntactically sweet. The disadvantage is that it currently doesn’t work with Async IO — which can be really slow if you are dealing with many HTTP requests.
HTTPX is a new HTTP client with async support. It is very similar to Requests. In this tutorial, I will create a program with requests, give you an introduction to Async IO, and finally use Async IO & HTTPX to make the program much faster.
This tutorial assumes you have used Python’s Request library before.
In this example, I am going to use Google’s Books API to give me the names of books given their ISBN codes. Let's call it book finder.
Explanation
This is the flow of the book finder program:
I have a list of ISBN codes of various books stored in isbn_list. I use time.monotonic() to get the time I start making requests. Then I enumerate and iterate through the list.Next, I print the index and the name of the book returned by the print_book_name() function by passing the list index & ISBN code as a parameter. The reason I print the list index will be apparent in the async version.Finally, I calculate the difference between the current time and start time to get the time it took for the script to run.
I have a list of ISBN codes of various books stored in isbn_list. I use time.monotonic() to get the time I start making requests. Then I enumerate and iterate through the list.
Next, I print the index and the name of the book returned by the print_book_name() function by passing the list index & ISBN code as a parameter. The reason I print the list index will be apparent in the async version.
Finally, I calculate the difference between the current time and start time to get the time it took for the script to run.
This is the output of the script:
0 : The Hobbit1 : The Fellowship of the Ring2 : 19843 : Brave New World4 : The Player of Games5 : Watchmen6 : Crime and Punishment7 : Mistborn8 : The Adventures of Sherlock Holmes9 : The Great Gatsby10 : Moby-Dick11 : The Way of Kings12 : War and Peace13 : The Metamorphosis - Franz Kafka, New Edition14 : Liar's PokerTime Taken:6.764999999999418
It took 6.76 seconds to print the book names.
Async IO uses co-operative multitasking. Instead of creating threads for multitasking, you use a single event loop. Think of the event loop like a while loop that keeps switching between tasks in the program until there are no more tasks left.
The task switching takes place almost always when there is an I/O bound task(network calls, file I/O) in the program where the CPU remains idle while waiting for that resource to be available.
Picture this — You need to make an HTTP request and store the response data. With just 1 request it is simple. But what if you have to make 10s or 100s of requests in a loop like in the book finder program. When the program is synchronous the flow is:
Make the request.Wait for the response.Process the response.Repeat Steps 1–3 for all the requests.
Make the request.
Wait for the response.
Process the response.
Repeat Steps 1–3 for all the requests.
These steps are repeated for each request. The problem is that while the program is waiting for a response from the web server, the CPU is idle when it can be doing some other task.
With Async IO you can make the program switch to another task while it awaits a response from the web server. In our example, we will make all the HTTP requests concurrently and process each response as and when it comes. The program flow for 10 requests becomes like this:
Make all 10 requests sequentially & wait for the response.Process whichever response arrives first.
Make all 10 requests sequentially & wait for the response.
Process whichever response arrives first.
The advantage here is that when we can make all the 10 requests at once, some responses might come slowly while others may be a lot faster. We can process whichever response comes on a first come, first served basis which is much faster than in the synchronous version.
Concurrency is not parallelism. It's easy to get confused with the two terms.
Async IO was introduced in Python version 3.4 with the asyncio library. The async / await keywords have become part of Python's standard library since version 3.6. For this tutorial, I have used Python version 3.8. I will explain the implementation of asyncio by modifying the book finder program.
Note: The asyncio library changes quite a bit in every python version so please check your version before you get annoyed by syntax errors :)
Enough theory! Let's get back to writing some code.
First, install httpx with this command:
pip install httpx
Let’s modify our book finder program with asyncio & HTTPX. It may seem a little overwhelming at first but hang on. I will explain everything.
Explanation
An async function is called a coroutine. Coroutines are functions that are cooperative. It can only be executed inside an event loop. It can suspend its execution in the middle and pass control to the event loop which will then execute another coroutine. The execution is suspended when the coroutine needs to wait for a resource, in our case — the response from the server. It will resume execution when the response arrives.
Async programs are simply collections of coroutines. In python, the async keyword is added before the function definition to indicate that it's a coroutine.
I will go over the program flow:
I run asyncio.run() to start the event loop which will call the main() coroutine.Next, I gather a list of coroutine objects of get_book_name() with each ISBN code & index number as parameters in task_list. Notice that despite calling the coroutine, it did not execute. It instead returns a coroutine object. A coroutine object here, in simple words, is an instance of get_book_name() but needs to be scheduled inside the event loop to be executed. In order to schedule the coroutine object for execution you must use the await keyword before it. I will explain more about it in step 4.I use asyncio.gather() to execute the coroutine objects.asyncio.gather() is a coroutine that schedules awaitable objects(like coroutines) to be executed by the event loop. It also creates a list of objects returned from each coroutine call. In my coroutine(get_book_name()), I am not returning anything, so I don’t require this list.In get_book_name() I create an async client with HTTPX. Then I send the request to the same URL. Notice the await keyword before client.get(). This is because get() is also a coroutine. The await keyword lets you indicate where in the coroutine the execution needs to suspend. Here I use the await keyword before client.get() as I have to wait for the response from the server before proceeding.Note: Every coroutine is an awaitable object. Even asyncio.gather() is awaitable. This is because you can switch over to another task while it waits for a response. Every awaitable object requires the await keyword before it in order to execute it.After the client sends the request, the coroutine gives control of the execution back to the event loop which will call the next scheduledcoroutine object. The process will repeat for all the objects in task_list.As soon as a response arrives from any of the requests, the event loop will resume execution of that specific coroutine from where it was awaited. This means that the output will not be in the order of the requests as some responses will be faster than others. If a response arrives while a coroutine is being executed, then that responses’ coroutine gets scheduled waiting to resume execution.Once all the coroutines are executed, the event loop exits and the time taken is printed.
I run asyncio.run() to start the event loop which will call the main() coroutine.
Next, I gather a list of coroutine objects of get_book_name() with each ISBN code & index number as parameters in task_list. Notice that despite calling the coroutine, it did not execute. It instead returns a coroutine object. A coroutine object here, in simple words, is an instance of get_book_name() but needs to be scheduled inside the event loop to be executed. In order to schedule the coroutine object for execution you must use the await keyword before it. I will explain more about it in step 4.
I use asyncio.gather() to execute the coroutine objects.asyncio.gather() is a coroutine that schedules awaitable objects(like coroutines) to be executed by the event loop. It also creates a list of objects returned from each coroutine call. In my coroutine(get_book_name()), I am not returning anything, so I don’t require this list.
In get_book_name() I create an async client with HTTPX. Then I send the request to the same URL. Notice the await keyword before client.get(). This is because get() is also a coroutine. The await keyword lets you indicate where in the coroutine the execution needs to suspend. Here I use the await keyword before client.get() as I have to wait for the response from the server before proceeding.Note: Every coroutine is an awaitable object. Even asyncio.gather() is awaitable. This is because you can switch over to another task while it waits for a response. Every awaitable object requires the await keyword before it in order to execute it.
After the client sends the request, the coroutine gives control of the execution back to the event loop which will call the next scheduledcoroutine object. The process will repeat for all the objects in task_list.
As soon as a response arrives from any of the requests, the event loop will resume execution of that specific coroutine from where it was awaited. This means that the output will not be in the order of the requests as some responses will be faster than others. If a response arrives while a coroutine is being executed, then that responses’ coroutine gets scheduled waiting to resume execution.
Once all the coroutines are executed, the event loop exits and the time taken is printed.
When you run the program, you will get an output similar to this:
8: The Adventures of Sherlock Holmes0: The Hobbit14: Liar's Poker9: The Great Gatsby 11: The Way of Kings 4: The Player of Games5: Watchmen2: 198413: The Metamorphosis - Franz Kafka, New Edition10: Moby-Dick7: Mistborn1: The Fellowship of the Ring3: Brave New World6: Crime and PunishmentTime Taken:0.75
You can use the index to see the order of the response. It took just 0.75 seconds! That is a 900% increase. Of course, the results will vary based upon your internet speed but the async & HTTPX program in all cases will be much faster.
Before I conclude, it is important to set limits to the number of concurrent requests in HTTPX. A lot of APIs and websites have limits to the number of requests you can send per second or per minute. Luckily HTTPX has a function that can do this.
You can set limits by creating a Limits() object
limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)
Then you need to pass the limit object to the httpx client.
client = httpx.Client(limits=limits)
HTTPX sets by default 10 keepalive connections and 100 max_connections at any given point. You can also set both to None, if you want your client to send as many requests as it can.
You can see how the asyncio library can speed up your programs. It can take a while for you to wrap your head around it but it is definitely worth the effort!
On the downside, it can make your program harder to read and complex to manage as you chain more coroutines.
Async IO has a lot of features to offer. You can also use it create TCP servers, speed up file I/O etc. | [
{
"code": null,
"e": 362,
"s": 171,
"text": "If you have some experience with Python, chances are good that you have used the Requests library at some point. It is a wonderful library for making HTTP requests and interacting with APIs."
},
{
"code": null,
"e": 569,
"s": 362,
"text": "The advantage of Requests is that it’s simple and syntactically sweet. The disadvantage is that it currently doesn’t work with Async IO — which can be really slow if you are dealing with many HTTP requests."
},
{
"code": null,
"e": 809,
"s": 569,
"text": "HTTPX is a new HTTP client with async support. It is very similar to Requests. In this tutorial, I will create a program with requests, give you an introduction to Async IO, and finally use Async IO & HTTPX to make the program much faster."
},
{
"code": null,
"e": 878,
"s": 809,
"text": "This tutorial assumes you have used Python’s Request library before."
},
{
"code": null,
"e": 1013,
"s": 878,
"text": "In this example, I am going to use Google’s Books API to give me the names of books given their ISBN codes. Let's call it book finder."
},
{
"code": null,
"e": 1025,
"s": 1013,
"text": "Explanation"
},
{
"code": null,
"e": 1070,
"s": 1025,
"text": "This is the flow of the book finder program:"
},
{
"code": null,
"e": 1587,
"s": 1070,
"text": "I have a list of ISBN codes of various books stored in isbn_list. I use time.monotonic() to get the time I start making requests. Then I enumerate and iterate through the list.Next, I print the index and the name of the book returned by the print_book_name() function by passing the list index & ISBN code as a parameter. The reason I print the list index will be apparent in the async version.Finally, I calculate the difference between the current time and start time to get the time it took for the script to run."
},
{
"code": null,
"e": 1764,
"s": 1587,
"text": "I have a list of ISBN codes of various books stored in isbn_list. I use time.monotonic() to get the time I start making requests. Then I enumerate and iterate through the list."
},
{
"code": null,
"e": 1983,
"s": 1764,
"text": "Next, I print the index and the name of the book returned by the print_book_name() function by passing the list index & ISBN code as a parameter. The reason I print the list index will be apparent in the async version."
},
{
"code": null,
"e": 2106,
"s": 1983,
"text": "Finally, I calculate the difference between the current time and start time to get the time it took for the script to run."
},
{
"code": null,
"e": 2140,
"s": 2106,
"text": "This is the output of the script:"
},
{
"code": null,
"e": 2487,
"s": 2140,
"text": "0 : The Hobbit1 : The Fellowship of the Ring2 : 19843 : Brave New World4 : The Player of Games5 : Watchmen6 : Crime and Punishment7 : Mistborn8 : The Adventures of Sherlock Holmes9 : The Great Gatsby10 : Moby-Dick11 : The Way of Kings12 : War and Peace13 : The Metamorphosis - Franz Kafka, New Edition14 : Liar's PokerTime Taken:6.764999999999418"
},
{
"code": null,
"e": 2533,
"s": 2487,
"text": "It took 6.76 seconds to print the book names."
},
{
"code": null,
"e": 2777,
"s": 2533,
"text": "Async IO uses co-operative multitasking. Instead of creating threads for multitasking, you use a single event loop. Think of the event loop like a while loop that keeps switching between tasks in the program until there are no more tasks left."
},
{
"code": null,
"e": 2970,
"s": 2777,
"text": "The task switching takes place almost always when there is an I/O bound task(network calls, file I/O) in the program where the CPU remains idle while waiting for that resource to be available."
},
{
"code": null,
"e": 3222,
"s": 2970,
"text": "Picture this — You need to make an HTTP request and store the response data. With just 1 request it is simple. But what if you have to make 10s or 100s of requests in a loop like in the book finder program. When the program is synchronous the flow is:"
},
{
"code": null,
"e": 3321,
"s": 3222,
"text": "Make the request.Wait for the response.Process the response.Repeat Steps 1–3 for all the requests."
},
{
"code": null,
"e": 3339,
"s": 3321,
"text": "Make the request."
},
{
"code": null,
"e": 3362,
"s": 3339,
"text": "Wait for the response."
},
{
"code": null,
"e": 3384,
"s": 3362,
"text": "Process the response."
},
{
"code": null,
"e": 3423,
"s": 3384,
"text": "Repeat Steps 1–3 for all the requests."
},
{
"code": null,
"e": 3605,
"s": 3423,
"text": "These steps are repeated for each request. The problem is that while the program is waiting for a response from the web server, the CPU is idle when it can be doing some other task."
},
{
"code": null,
"e": 3879,
"s": 3605,
"text": "With Async IO you can make the program switch to another task while it awaits a response from the web server. In our example, we will make all the HTTP requests concurrently and process each response as and when it comes. The program flow for 10 requests becomes like this:"
},
{
"code": null,
"e": 3979,
"s": 3879,
"text": "Make all 10 requests sequentially & wait for the response.Process whichever response arrives first."
},
{
"code": null,
"e": 4038,
"s": 3979,
"text": "Make all 10 requests sequentially & wait for the response."
},
{
"code": null,
"e": 4080,
"s": 4038,
"text": "Process whichever response arrives first."
},
{
"code": null,
"e": 4350,
"s": 4080,
"text": "The advantage here is that when we can make all the 10 requests at once, some responses might come slowly while others may be a lot faster. We can process whichever response comes on a first come, first served basis which is much faster than in the synchronous version."
},
{
"code": null,
"e": 4428,
"s": 4350,
"text": "Concurrency is not parallelism. It's easy to get confused with the two terms."
},
{
"code": null,
"e": 4726,
"s": 4428,
"text": "Async IO was introduced in Python version 3.4 with the asyncio library. The async / await keywords have become part of Python's standard library since version 3.6. For this tutorial, I have used Python version 3.8. I will explain the implementation of asyncio by modifying the book finder program."
},
{
"code": null,
"e": 4868,
"s": 4726,
"text": "Note: The asyncio library changes quite a bit in every python version so please check your version before you get annoyed by syntax errors :)"
},
{
"code": null,
"e": 4920,
"s": 4868,
"text": "Enough theory! Let's get back to writing some code."
},
{
"code": null,
"e": 4960,
"s": 4920,
"text": "First, install httpx with this command:"
},
{
"code": null,
"e": 4978,
"s": 4960,
"text": "pip install httpx"
},
{
"code": null,
"e": 5120,
"s": 4978,
"text": "Let’s modify our book finder program with asyncio & HTTPX. It may seem a little overwhelming at first but hang on. I will explain everything."
},
{
"code": null,
"e": 5132,
"s": 5120,
"text": "Explanation"
},
{
"code": null,
"e": 5559,
"s": 5132,
"text": "An async function is called a coroutine. Coroutines are functions that are cooperative. It can only be executed inside an event loop. It can suspend its execution in the middle and pass control to the event loop which will then execute another coroutine. The execution is suspended when the coroutine needs to wait for a resource, in our case — the response from the server. It will resume execution when the response arrives."
},
{
"code": null,
"e": 5716,
"s": 5559,
"text": "Async programs are simply collections of coroutines. In python, the async keyword is added before the function definition to indicate that it's a coroutine."
},
{
"code": null,
"e": 5749,
"s": 5716,
"text": "I will go over the program flow:"
},
{
"code": null,
"e": 8007,
"s": 5749,
"text": "I run asyncio.run() to start the event loop which will call the main() coroutine.Next, I gather a list of coroutine objects of get_book_name() with each ISBN code & index number as parameters in task_list. Notice that despite calling the coroutine, it did not execute. It instead returns a coroutine object. A coroutine object here, in simple words, is an instance of get_book_name() but needs to be scheduled inside the event loop to be executed. In order to schedule the coroutine object for execution you must use the await keyword before it. I will explain more about it in step 4.I use asyncio.gather() to execute the coroutine objects.asyncio.gather() is a coroutine that schedules awaitable objects(like coroutines) to be executed by the event loop. It also creates a list of objects returned from each coroutine call. In my coroutine(get_book_name()), I am not returning anything, so I don’t require this list.In get_book_name() I create an async client with HTTPX. Then I send the request to the same URL. Notice the await keyword before client.get(). This is because get() is also a coroutine. The await keyword lets you indicate where in the coroutine the execution needs to suspend. Here I use the await keyword before client.get() as I have to wait for the response from the server before proceeding.Note: Every coroutine is an awaitable object. Even asyncio.gather() is awaitable. This is because you can switch over to another task while it waits for a response. Every awaitable object requires the await keyword before it in order to execute it.After the client sends the request, the coroutine gives control of the execution back to the event loop which will call the next scheduledcoroutine object. The process will repeat for all the objects in task_list.As soon as a response arrives from any of the requests, the event loop will resume execution of that specific coroutine from where it was awaited. This means that the output will not be in the order of the requests as some responses will be faster than others. If a response arrives while a coroutine is being executed, then that responses’ coroutine gets scheduled waiting to resume execution.Once all the coroutines are executed, the event loop exits and the time taken is printed."
},
{
"code": null,
"e": 8089,
"s": 8007,
"text": "I run asyncio.run() to start the event loop which will call the main() coroutine."
},
{
"code": null,
"e": 8594,
"s": 8089,
"text": "Next, I gather a list of coroutine objects of get_book_name() with each ISBN code & index number as parameters in task_list. Notice that despite calling the coroutine, it did not execute. It instead returns a coroutine object. A coroutine object here, in simple words, is an instance of get_book_name() but needs to be scheduled inside the event loop to be executed. In order to schedule the coroutine object for execution you must use the await keyword before it. I will explain more about it in step 4."
},
{
"code": null,
"e": 8928,
"s": 8594,
"text": "I use asyncio.gather() to execute the coroutine objects.asyncio.gather() is a coroutine that schedules awaitable objects(like coroutines) to be executed by the event loop. It also creates a list of objects returned from each coroutine call. In my coroutine(get_book_name()), I am not returning anything, so I don’t require this list."
},
{
"code": null,
"e": 9572,
"s": 8928,
"text": "In get_book_name() I create an async client with HTTPX. Then I send the request to the same URL. Notice the await keyword before client.get(). This is because get() is also a coroutine. The await keyword lets you indicate where in the coroutine the execution needs to suspend. Here I use the await keyword before client.get() as I have to wait for the response from the server before proceeding.Note: Every coroutine is an awaitable object. Even asyncio.gather() is awaitable. This is because you can switch over to another task while it waits for a response. Every awaitable object requires the await keyword before it in order to execute it."
},
{
"code": null,
"e": 9786,
"s": 9572,
"text": "After the client sends the request, the coroutine gives control of the execution back to the event loop which will call the next scheduledcoroutine object. The process will repeat for all the objects in task_list."
},
{
"code": null,
"e": 10181,
"s": 9786,
"text": "As soon as a response arrives from any of the requests, the event loop will resume execution of that specific coroutine from where it was awaited. This means that the output will not be in the order of the requests as some responses will be faster than others. If a response arrives while a coroutine is being executed, then that responses’ coroutine gets scheduled waiting to resume execution."
},
{
"code": null,
"e": 10271,
"s": 10181,
"text": "Once all the coroutines are executed, the event loop exits and the time taken is printed."
},
{
"code": null,
"e": 10337,
"s": 10271,
"text": "When you run the program, you will get an output similar to this:"
},
{
"code": null,
"e": 10644,
"s": 10337,
"text": "8: The Adventures of Sherlock Holmes0: The Hobbit14: Liar's Poker9: The Great Gatsby 11: The Way of Kings 4: The Player of Games5: Watchmen2: 198413: The Metamorphosis - Franz Kafka, New Edition10: Moby-Dick7: Mistborn1: The Fellowship of the Ring3: Brave New World6: Crime and PunishmentTime Taken:0.75"
},
{
"code": null,
"e": 10880,
"s": 10644,
"text": "You can use the index to see the order of the response. It took just 0.75 seconds! That is a 900% increase. Of course, the results will vary based upon your internet speed but the async & HTTPX program in all cases will be much faster."
},
{
"code": null,
"e": 11127,
"s": 10880,
"text": "Before I conclude, it is important to set limits to the number of concurrent requests in HTTPX. A lot of APIs and websites have limits to the number of requests you can send per second or per minute. Luckily HTTPX has a function that can do this."
},
{
"code": null,
"e": 11176,
"s": 11127,
"text": "You can set limits by creating a Limits() object"
},
{
"code": null,
"e": 11247,
"s": 11176,
"text": "limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)"
},
{
"code": null,
"e": 11307,
"s": 11247,
"text": "Then you need to pass the limit object to the httpx client."
},
{
"code": null,
"e": 11344,
"s": 11307,
"text": "client = httpx.Client(limits=limits)"
},
{
"code": null,
"e": 11526,
"s": 11344,
"text": "HTTPX sets by default 10 keepalive connections and 100 max_connections at any given point. You can also set both to None, if you want your client to send as many requests as it can."
},
{
"code": null,
"e": 11685,
"s": 11526,
"text": "You can see how the asyncio library can speed up your programs. It can take a while for you to wrap your head around it but it is definitely worth the effort!"
},
{
"code": null,
"e": 11794,
"s": 11685,
"text": "On the downside, it can make your program harder to read and complex to manage as you chain more coroutines."
}
] |
How to convert lists to XML in Python? - GeeksforGeeks | 24 Jan, 2021
In this article, the task is to convert a given list to XML in Python. But first, let’s discuss what is an XML?
It could also be terminology that defines a gaggle of rules for encoding documents during a format that’s both human-readable and machine-readable. The design goals of XML specialize in simplicity, generality, and usefulness across the web. It is a textual format with strong support via Unicode for various human languages.
You can refer to the article Create XML Documents using Python for further information.
Method 1: Using Element tree
Python features a built-in library, ElementTree, that has functions to read and manipulate XMLs (and other similarly structured files). ElementTree represents the whole XML document as a tree that helps while performing the operations. The element represents a single node in this tree. Reading and writing from the whole document are done on the ElementTree level. Interactions with one XML element and its sub-elements are done on the Element level. Refer: Modify XML files with Python
import xml.etree.ElementTree as ET
XML documents have sections, called elements, defined by a beginning and an ending tag. A tag is a markup construct that begins with < and ends with >.
Approach Used :
Use ElementTree to insert items of listsCreate the root element as “userconfig”Create sub-elementsInsert list entries into sub-elementWrite the tree into an XML file
Use ElementTree to insert items of lists
Create the root element as “userconfig”
Create sub-elements
Insert list entries into sub-element
Write the tree into an XML file
Python3
# Firstly we have to import 'xml.etree.ElementTree' for creating a subtreeimport xml.etree.ElementTree as ET users_list = ["GeeksForGeeks", "Arka", "Computer Science", "Engineering", "Portal"] def create_xml(): # we make root element usrconfig = ET.Element("usrconfig") # create sub element usrconfig = ET.SubElement(usrconfig, "usrconfig") # insert list element into sub elements for user in range(len( users_list)): usr = ET.SubElement(usrconfig, "usr") usr.text = str(users_list[user]) tree = ET.ElementTree(usrconfig) # write the tree into an XML file tree.write("Output.xml", encoding ='utf-8', xml_declaration = True) create_xml()
Output:
Method 2: Using xml.dome
The xml.dom.minidom module provides an easy parser for creating DOM trees. DOM (document object model) may be a cross-language API from W3C i.e. World Wide Web Consortium for accessing and modifying XML documents. Python enables you to parse XML files with the assistance of xml.dom.minidom, which is that the minimal implementation of the DOM interface. It is simpler than the complete DOM API and will be considered as smaller.
For further reference of the given library, visit Parse XML using Minidom in Python.
Python3
from xml.dom import minidom import os users_list = ["GeeksForGeeks", "Arka", "Computer Science", "Engineering", "Portal"] # create fileroot = minidom.Document() # creat root elementxml = root.createElement('root') root.appendChild(xml) for user in range(len( users_list)): # create child element productChild = root.createElement('product'+ str(user)) # insert user data into element productChild.setAttribute('list', users_list[user] ) xml.appendChild(productChild) xml_str = root.toprettyxml(indent ="\t") # save filesave_path_file = "gfg.xml" with open(save_path_file, "w") as f: f.write(xml_str)
Output:
Picked
Python-XML
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 24404,
"s": 24292,
"text": "In this article, the task is to convert a given list to XML in Python. But first, let’s discuss what is an XML?"
},
{
"code": null,
"e": 24730,
"s": 24404,
"text": "It could also be terminology that defines a gaggle of rules for encoding documents during a format that’s both human-readable and machine-readable. The design goals of XML specialize in simplicity, generality, and usefulness across the web. It is a textual format with strong support via Unicode for various human languages. "
},
{
"code": null,
"e": 24818,
"s": 24730,
"text": "You can refer to the article Create XML Documents using Python for further information."
},
{
"code": null,
"e": 24847,
"s": 24818,
"text": "Method 1: Using Element tree"
},
{
"code": null,
"e": 25335,
"s": 24847,
"text": "Python features a built-in library, ElementTree, that has functions to read and manipulate XMLs (and other similarly structured files). ElementTree represents the whole XML document as a tree that helps while performing the operations. The element represents a single node in this tree. Reading and writing from the whole document are done on the ElementTree level. Interactions with one XML element and its sub-elements are done on the Element level. Refer: Modify XML files with Python"
},
{
"code": null,
"e": 25370,
"s": 25335,
"text": "import xml.etree.ElementTree as ET"
},
{
"code": null,
"e": 25522,
"s": 25370,
"text": "XML documents have sections, called elements, defined by a beginning and an ending tag. A tag is a markup construct that begins with < and ends with >."
},
{
"code": null,
"e": 25538,
"s": 25522,
"text": "Approach Used :"
},
{
"code": null,
"e": 25704,
"s": 25538,
"text": "Use ElementTree to insert items of listsCreate the root element as “userconfig”Create sub-elementsInsert list entries into sub-elementWrite the tree into an XML file"
},
{
"code": null,
"e": 25745,
"s": 25704,
"text": "Use ElementTree to insert items of lists"
},
{
"code": null,
"e": 25785,
"s": 25745,
"text": "Create the root element as “userconfig”"
},
{
"code": null,
"e": 25805,
"s": 25785,
"text": "Create sub-elements"
},
{
"code": null,
"e": 25842,
"s": 25805,
"text": "Insert list entries into sub-element"
},
{
"code": null,
"e": 25874,
"s": 25842,
"text": "Write the tree into an XML file"
},
{
"code": null,
"e": 25882,
"s": 25874,
"text": "Python3"
},
{
"code": "# Firstly we have to import 'xml.etree.ElementTree' for creating a subtreeimport xml.etree.ElementTree as ET users_list = [\"GeeksForGeeks\", \"Arka\", \"Computer Science\", \"Engineering\", \"Portal\"] def create_xml(): # we make root element usrconfig = ET.Element(\"usrconfig\") # create sub element usrconfig = ET.SubElement(usrconfig, \"usrconfig\") # insert list element into sub elements for user in range(len( users_list)): usr = ET.SubElement(usrconfig, \"usr\") usr.text = str(users_list[user]) tree = ET.ElementTree(usrconfig) # write the tree into an XML file tree.write(\"Output.xml\", encoding ='utf-8', xml_declaration = True) create_xml()",
"e": 26627,
"s": 25882,
"text": null
},
{
"code": null,
"e": 26635,
"s": 26627,
"text": "Output:"
},
{
"code": null,
"e": 26660,
"s": 26635,
"text": "Method 2: Using xml.dome"
},
{
"code": null,
"e": 27090,
"s": 26660,
"text": "The xml.dom.minidom module provides an easy parser for creating DOM trees. DOM (document object model) may be a cross-language API from W3C i.e. World Wide Web Consortium for accessing and modifying XML documents. Python enables you to parse XML files with the assistance of xml.dom.minidom, which is that the minimal implementation of the DOM interface. It is simpler than the complete DOM API and will be considered as smaller."
},
{
"code": null,
"e": 27175,
"s": 27090,
"text": "For further reference of the given library, visit Parse XML using Minidom in Python."
},
{
"code": null,
"e": 27183,
"s": 27175,
"text": "Python3"
},
{
"code": "from xml.dom import minidom import os users_list = [\"GeeksForGeeks\", \"Arka\", \"Computer Science\", \"Engineering\", \"Portal\"] # create fileroot = minidom.Document() # creat root elementxml = root.createElement('root') root.appendChild(xml) for user in range(len( users_list)): # create child element productChild = root.createElement('product'+ str(user)) # insert user data into element productChild.setAttribute('list', users_list[user] ) xml.appendChild(productChild) xml_str = root.toprettyxml(indent =\"\\t\") # save filesave_path_file = \"gfg.xml\" with open(save_path_file, \"w\") as f: f.write(xml_str) ",
"e": 27820,
"s": 27183,
"text": null
},
{
"code": null,
"e": 27828,
"s": 27820,
"text": "Output:"
},
{
"code": null,
"e": 27835,
"s": 27828,
"text": "Picked"
},
{
"code": null,
"e": 27846,
"s": 27835,
"text": "Python-XML"
},
{
"code": null,
"e": 27853,
"s": 27846,
"text": "Python"
},
{
"code": null,
"e": 27951,
"s": 27853,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27983,
"s": 27951,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28025,
"s": 27983,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28081,
"s": 28025,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28123,
"s": 28081,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28178,
"s": 28123,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28209,
"s": 28178,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28231,
"s": 28209,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28270,
"s": 28231,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28299,
"s": 28270,
"text": "Create a directory in Python"
}
] |
Extracting & Plotting Feature Names & Importance from Scikit-Learn Pipelines | by Kyle Gilde | Towards Data Science | If you have ever been tasked with productionalizing a machine learning model, you probably know that Scikit-Learn library offers one of the best ways — if not the best way — of creating production-quality machine learning workflows. The ecosystem’s Pipeline, ColumnTransformer, preprocessors, imputers & feature selection classes are powerful tools that transform raw data into model-ready features.
However, before anyone is going to let you deploy to production, you are going to want to have some rudimentary understanding of how the new model works. The most common way to explain how a black-box model works is by plotting feature names and importance values. If you have ever tried to extract the feature names from a heterogeneous dataset processed by ColumnTransformer, you know that this is no easy task. Exhaustive Internet searches have only brought to my attention where others have asked the same question or offered a partial answer, instead of yielding a comprehensive and satisfying solution.
To remedy this situation, I have developed a class called FeatureImportance that will extract feature names and importance values from a Pipeline instance. It then uses the Plotly library to plot the feature importance using only a few lines of code. In this post, I will load a fitted Pipeline, demonstrate how to use my class and then give an overview of how it works. The complete code can be found here or at the end of this blog post.
Note: My class may not work starting with the changes in scikit-learn 1.0.
There are two things I should note before continuing:
I credit Joey Gao’s code on this thread with showing the way to tackle this problem.My post assumes that you have worked with Scikit-Learn and Pandas before and are familiar with how ColumnTransformer, Pipeline & preprocessing classes facilitate reproducible feature engineering processes. If you need a refresher, check out this Scikit-Learn example.
I credit Joey Gao’s code on this thread with showing the way to tackle this problem.
My post assumes that you have worked with Scikit-Learn and Pandas before and are familiar with how ColumnTransformer, Pipeline & preprocessing classes facilitate reproducible feature engineering processes. If you need a refresher, check out this Scikit-Learn example.
For the purposes of demonstration, I’ve written a script called fit_pipeline_ames.py. It loads the Ames housing training data from Kaggle and fits a moderately complex Pipeline. I’ve plotted its visual representation below.
from sklearn import set_config from sklearn.utils import estimator_html_repr from IPython.core.display import display, HTML from fit_pipeline_ames import pipe # create & fit pipelineset_config(display='diagram')display(HTML(estimator_html_repr(pipe)))
This pipe instance contains the following 4 steps:
The ColumnTransformer instance is composed of 3 Pipelines, containing a total of 4 transformer instances, including SimpleImputer, OneHotEncoder & GLMMEncoder from the category_encoders package. See my previous blog post for a full explanation of how I dynamically constructed this particular ColumnTransformer.The VarianceThreshold uses the default threshold of 0, which removes any features that contain only a single value. Some models will fail if a feature has no variance.The SelectPercentile uses the f_regression scoring function with a percentile threshold of 90. These settings retain the top 90% of features and discard the bottom 10%.The CatBoostRegressor model is fit to the SalesPrice dependent variable using the features created and selected in the preceding steps.
The ColumnTransformer instance is composed of 3 Pipelines, containing a total of 4 transformer instances, including SimpleImputer, OneHotEncoder & GLMMEncoder from the category_encoders package. See my previous blog post for a full explanation of how I dynamically constructed this particular ColumnTransformer.
The VarianceThreshold uses the default threshold of 0, which removes any features that contain only a single value. Some models will fail if a feature has no variance.
The SelectPercentile uses the f_regression scoring function with a percentile threshold of 90. These settings retain the top 90% of features and discard the bottom 10%.
The CatBoostRegressor model is fit to the SalesPrice dependent variable using the features created and selected in the preceding steps.
With the help of FeatureImportance, we can extract the feature names and importance values and plot them with 3 lines of code.
from feature_importance import FeatureImportancefeature_importance = FeatureImportance(pipe)feature_importance.plot(top_n_features=25)
The plot method takes a number of arguments that control the plot's display. The most important ones are the following:
top_n_features: This controls how many features will be plotted. The default value is 100. The plot's title will indicate this value as well as how many features there are in total. To plot all features, just set top_n_features to a number larger than the total features.
rank_features: This argument controls whether the integer ranks are displayed in front of the feature names. The default is True. I find that this aids with interpretation, especially when comparing the feature importance from multiple models.
max_scale: This determines whether the importance values are scaled by the maximum value & multiplied by 100. The default is True. I find that this enables an intuitive way to compare how important other features are vis-a-viz the most important one. For instance, in the plot of above, we can say that GrLivArea is about 81% as important to the model as the top feature, OverallQty.
The FeatureImportance class should be instantiated using a fitted Pipeline instance. (You can also change the verbose argument to True if you want to have all of the diagnostics printed to your console.) My class validates that this Pipeline starts with a ColumnTransformer instance and ends with a regression or classification model that has the feature_importance_ attribute. The Pipeline can have any number of or no instances of classes from sklearn.feature_selection as intermediate steps.
The FeatureImportance class is composed of 4 methods.
get_feature_names was the hardest method to devise. It iterates through the ColumnTransformer transformers, uses the hasattr function to discern what type of class we are dealing with and pulls the feature names accordingly. (Special Note: If the ColumnTransformer contains Pipelines and if one of the transformers in the Pipeline is adding completely new columns, it must come last in the pipeline. For example, OneHotEncoder, MissingIndicator & SimpleImputer(add_indicator=True) add columns to the dataset that didn't exist before, so they should come last in the Pipeline.)get_selected_features calls get_feature_names. Then it tests for whether the main Pipeline contains any classes from sklearn.feature_selection based upon the existence of the get_support method. If it does, this method returns only the features names that were retained by the selector class or classes. It stores the features that were not selected in the discarded_featuresattribute. Here are the 24 features that were removed by the selectors in my pipeline:
get_feature_names was the hardest method to devise. It iterates through the ColumnTransformer transformers, uses the hasattr function to discern what type of class we are dealing with and pulls the feature names accordingly. (Special Note: If the ColumnTransformer contains Pipelines and if one of the transformers in the Pipeline is adding completely new columns, it must come last in the pipeline. For example, OneHotEncoder, MissingIndicator & SimpleImputer(add_indicator=True) add columns to the dataset that didn't exist before, so they should come last in the Pipeline.)
get_selected_features calls get_feature_names. Then it tests for whether the main Pipeline contains any classes from sklearn.feature_selection based upon the existence of the get_support method. If it does, this method returns only the features names that were retained by the selector class or classes. It stores the features that were not selected in the discarded_featuresattribute. Here are the 24 features that were removed by the selectors in my pipeline:
feature_importance.discarded_features['BsmtFinSF2','BsmtHalfBath','Alley_Pave','LandContour_Lvl','Utilities_AllPub','Utilities_NoSeWa','LotConfig_Corner','LotConfig_FR2','Condition1_RRNe','Condition2_RRAe','Condition2_RRAn','HouseStyle_SLvl','RoofStyle_Mansard','RoofMatl_ClyTile','RoofMatl_Metal','RoofMatl_Roll','RoofMatl_Tar&Grv','ExterCond_Ex','Foundation_Stone','Foundation_Wood','BsmtFinType2_GLQ','Electrical_missing_value','FireplaceQu_Fa','GarageCond_Gd','MiscFeature_Gar2','SaleType_ConLI']
3. get_feature_importance calls get_selected_features and then creates a Pandas Series where values are the feature importance values from the model and its index is the feature names created by the first 2 methods. This Series is then stored in the feature_importance attribute.
4. plot calls get_feature_importance and plots the output based upon the specifications.
The original notebook for this blog post can be found here. The complete code for FeatureImportance is shown below and can be found here.
If you create a Pipeline that you believe should be supported FeatureImportanceby but is not, please provide a reproducible example, and I will consider making the necessary changes.
Stay tuned for further posts on training & regularizing models with Scikit-Learn ColumnTransformers and Pipelines. Let me know if you found this post helpful or have any ideas for improvement. Thanks! | [
{
"code": null,
"e": 571,
"s": 171,
"text": "If you have ever been tasked with productionalizing a machine learning model, you probably know that Scikit-Learn library offers one of the best ways — if not the best way — of creating production-quality machine learning workflows. The ecosystem’s Pipeline, ColumnTransformer, preprocessors, imputers & feature selection classes are powerful tools that transform raw data into model-ready features."
},
{
"code": null,
"e": 1180,
"s": 571,
"text": "However, before anyone is going to let you deploy to production, you are going to want to have some rudimentary understanding of how the new model works. The most common way to explain how a black-box model works is by plotting feature names and importance values. If you have ever tried to extract the feature names from a heterogeneous dataset processed by ColumnTransformer, you know that this is no easy task. Exhaustive Internet searches have only brought to my attention where others have asked the same question or offered a partial answer, instead of yielding a comprehensive and satisfying solution."
},
{
"code": null,
"e": 1620,
"s": 1180,
"text": "To remedy this situation, I have developed a class called FeatureImportance that will extract feature names and importance values from a Pipeline instance. It then uses the Plotly library to plot the feature importance using only a few lines of code. In this post, I will load a fitted Pipeline, demonstrate how to use my class and then give an overview of how it works. The complete code can be found here or at the end of this blog post."
},
{
"code": null,
"e": 1695,
"s": 1620,
"text": "Note: My class may not work starting with the changes in scikit-learn 1.0."
},
{
"code": null,
"e": 1749,
"s": 1695,
"text": "There are two things I should note before continuing:"
},
{
"code": null,
"e": 2101,
"s": 1749,
"text": "I credit Joey Gao’s code on this thread with showing the way to tackle this problem.My post assumes that you have worked with Scikit-Learn and Pandas before and are familiar with how ColumnTransformer, Pipeline & preprocessing classes facilitate reproducible feature engineering processes. If you need a refresher, check out this Scikit-Learn example."
},
{
"code": null,
"e": 2186,
"s": 2101,
"text": "I credit Joey Gao’s code on this thread with showing the way to tackle this problem."
},
{
"code": null,
"e": 2454,
"s": 2186,
"text": "My post assumes that you have worked with Scikit-Learn and Pandas before and are familiar with how ColumnTransformer, Pipeline & preprocessing classes facilitate reproducible feature engineering processes. If you need a refresher, check out this Scikit-Learn example."
},
{
"code": null,
"e": 2678,
"s": 2454,
"text": "For the purposes of demonstration, I’ve written a script called fit_pipeline_ames.py. It loads the Ames housing training data from Kaggle and fits a moderately complex Pipeline. I’ve plotted its visual representation below."
},
{
"code": null,
"e": 2932,
"s": 2678,
"text": "from sklearn import set_config from sklearn.utils import estimator_html_repr from IPython.core.display import display, HTML from fit_pipeline_ames import pipe # create & fit pipelineset_config(display='diagram')display(HTML(estimator_html_repr(pipe)))"
},
{
"code": null,
"e": 2983,
"s": 2932,
"text": "This pipe instance contains the following 4 steps:"
},
{
"code": null,
"e": 3765,
"s": 2983,
"text": "The ColumnTransformer instance is composed of 3 Pipelines, containing a total of 4 transformer instances, including SimpleImputer, OneHotEncoder & GLMMEncoder from the category_encoders package. See my previous blog post for a full explanation of how I dynamically constructed this particular ColumnTransformer.The VarianceThreshold uses the default threshold of 0, which removes any features that contain only a single value. Some models will fail if a feature has no variance.The SelectPercentile uses the f_regression scoring function with a percentile threshold of 90. These settings retain the top 90% of features and discard the bottom 10%.The CatBoostRegressor model is fit to the SalesPrice dependent variable using the features created and selected in the preceding steps."
},
{
"code": null,
"e": 4077,
"s": 3765,
"text": "The ColumnTransformer instance is composed of 3 Pipelines, containing a total of 4 transformer instances, including SimpleImputer, OneHotEncoder & GLMMEncoder from the category_encoders package. See my previous blog post for a full explanation of how I dynamically constructed this particular ColumnTransformer."
},
{
"code": null,
"e": 4245,
"s": 4077,
"text": "The VarianceThreshold uses the default threshold of 0, which removes any features that contain only a single value. Some models will fail if a feature has no variance."
},
{
"code": null,
"e": 4414,
"s": 4245,
"text": "The SelectPercentile uses the f_regression scoring function with a percentile threshold of 90. These settings retain the top 90% of features and discard the bottom 10%."
},
{
"code": null,
"e": 4550,
"s": 4414,
"text": "The CatBoostRegressor model is fit to the SalesPrice dependent variable using the features created and selected in the preceding steps."
},
{
"code": null,
"e": 4677,
"s": 4550,
"text": "With the help of FeatureImportance, we can extract the feature names and importance values and plot them with 3 lines of code."
},
{
"code": null,
"e": 4812,
"s": 4677,
"text": "from feature_importance import FeatureImportancefeature_importance = FeatureImportance(pipe)feature_importance.plot(top_n_features=25)"
},
{
"code": null,
"e": 4932,
"s": 4812,
"text": "The plot method takes a number of arguments that control the plot's display. The most important ones are the following:"
},
{
"code": null,
"e": 5204,
"s": 4932,
"text": "top_n_features: This controls how many features will be plotted. The default value is 100. The plot's title will indicate this value as well as how many features there are in total. To plot all features, just set top_n_features to a number larger than the total features."
},
{
"code": null,
"e": 5448,
"s": 5204,
"text": "rank_features: This argument controls whether the integer ranks are displayed in front of the feature names. The default is True. I find that this aids with interpretation, especially when comparing the feature importance from multiple models."
},
{
"code": null,
"e": 5832,
"s": 5448,
"text": "max_scale: This determines whether the importance values are scaled by the maximum value & multiplied by 100. The default is True. I find that this enables an intuitive way to compare how important other features are vis-a-viz the most important one. For instance, in the plot of above, we can say that GrLivArea is about 81% as important to the model as the top feature, OverallQty."
},
{
"code": null,
"e": 6327,
"s": 5832,
"text": "The FeatureImportance class should be instantiated using a fitted Pipeline instance. (You can also change the verbose argument to True if you want to have all of the diagnostics printed to your console.) My class validates that this Pipeline starts with a ColumnTransformer instance and ends with a regression or classification model that has the feature_importance_ attribute. The Pipeline can have any number of or no instances of classes from sklearn.feature_selection as intermediate steps."
},
{
"code": null,
"e": 6381,
"s": 6327,
"text": "The FeatureImportance class is composed of 4 methods."
},
{
"code": null,
"e": 7419,
"s": 6381,
"text": "get_feature_names was the hardest method to devise. It iterates through the ColumnTransformer transformers, uses the hasattr function to discern what type of class we are dealing with and pulls the feature names accordingly. (Special Note: If the ColumnTransformer contains Pipelines and if one of the transformers in the Pipeline is adding completely new columns, it must come last in the pipeline. For example, OneHotEncoder, MissingIndicator & SimpleImputer(add_indicator=True) add columns to the dataset that didn't exist before, so they should come last in the Pipeline.)get_selected_features calls get_feature_names. Then it tests for whether the main Pipeline contains any classes from sklearn.feature_selection based upon the existence of the get_support method. If it does, this method returns only the features names that were retained by the selector class or classes. It stores the features that were not selected in the discarded_featuresattribute. Here are the 24 features that were removed by the selectors in my pipeline:"
},
{
"code": null,
"e": 7996,
"s": 7419,
"text": "get_feature_names was the hardest method to devise. It iterates through the ColumnTransformer transformers, uses the hasattr function to discern what type of class we are dealing with and pulls the feature names accordingly. (Special Note: If the ColumnTransformer contains Pipelines and if one of the transformers in the Pipeline is adding completely new columns, it must come last in the pipeline. For example, OneHotEncoder, MissingIndicator & SimpleImputer(add_indicator=True) add columns to the dataset that didn't exist before, so they should come last in the Pipeline.)"
},
{
"code": null,
"e": 8458,
"s": 7996,
"text": "get_selected_features calls get_feature_names. Then it tests for whether the main Pipeline contains any classes from sklearn.feature_selection based upon the existence of the get_support method. If it does, this method returns only the features names that were retained by the selector class or classes. It stores the features that were not selected in the discarded_featuresattribute. Here are the 24 features that were removed by the selectors in my pipeline:"
},
{
"code": null,
"e": 8959,
"s": 8458,
"text": "feature_importance.discarded_features['BsmtFinSF2','BsmtHalfBath','Alley_Pave','LandContour_Lvl','Utilities_AllPub','Utilities_NoSeWa','LotConfig_Corner','LotConfig_FR2','Condition1_RRNe','Condition2_RRAe','Condition2_RRAn','HouseStyle_SLvl','RoofStyle_Mansard','RoofMatl_ClyTile','RoofMatl_Metal','RoofMatl_Roll','RoofMatl_Tar&Grv','ExterCond_Ex','Foundation_Stone','Foundation_Wood','BsmtFinType2_GLQ','Electrical_missing_value','FireplaceQu_Fa','GarageCond_Gd','MiscFeature_Gar2','SaleType_ConLI']"
},
{
"code": null,
"e": 9239,
"s": 8959,
"text": "3. get_feature_importance calls get_selected_features and then creates a Pandas Series where values are the feature importance values from the model and its index is the feature names created by the first 2 methods. This Series is then stored in the feature_importance attribute."
},
{
"code": null,
"e": 9328,
"s": 9239,
"text": "4. plot calls get_feature_importance and plots the output based upon the specifications."
},
{
"code": null,
"e": 9466,
"s": 9328,
"text": "The original notebook for this blog post can be found here. The complete code for FeatureImportance is shown below and can be found here."
},
{
"code": null,
"e": 9649,
"s": 9466,
"text": "If you create a Pipeline that you believe should be supported FeatureImportanceby but is not, please provide a reproducible example, and I will consider making the necessary changes."
}
] |
C# program to find Intersection of two lists | To find intersection of two lists in C#, use the Intersect() method.
The following is our list 1.
List<int> list1 = new List<int>();
list1.Add(2);
list1.Add(3);
list1.Add(5);
list1.Add(7);
The following is our list 2.
List<int> list2 = new List<int>();
list2.Add(5);
list2.Add(4);
list2.Add(6);
list2.Add(8);
The following is the code to find the intersection of two lists in C#.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Demo {
public class Program {
public static void Main(String[] args) {
List<int> list1 = new List<int>();
list1.Add(2);
list1.Add(3);
list1.Add(5);
list1.Add(7);
Console.WriteLine(list1.Count);
List<int> list2 = new List<int>();
list2.Add(5);
list2.Add(4);
list2.Add(6);
list2.Add(8);
Console.WriteLine(list2.Count);
List<int> common = list1.Intersect(list2).ToList();
Console.WriteLine(common.Count);
}
}
}
4
4
1 | [
{
"code": null,
"e": 1131,
"s": 1062,
"text": "To find intersection of two lists in C#, use the Intersect() method."
},
{
"code": null,
"e": 1160,
"s": 1131,
"text": "The following is our list 1."
},
{
"code": null,
"e": 1251,
"s": 1160,
"text": "List<int> list1 = new List<int>();\nlist1.Add(2);\nlist1.Add(3);\nlist1.Add(5);\nlist1.Add(7);"
},
{
"code": null,
"e": 1280,
"s": 1251,
"text": "The following is our list 2."
},
{
"code": null,
"e": 1371,
"s": 1280,
"text": "List<int> list2 = new List<int>();\nlist2.Add(5);\nlist2.Add(4);\nlist2.Add(6);\nlist2.Add(8);"
},
{
"code": null,
"e": 1442,
"s": 1371,
"text": "The following is the code to find the intersection of two lists in C#."
},
{
"code": null,
"e": 1453,
"s": 1442,
"text": " Live Demo"
},
{
"code": null,
"e": 2120,
"s": 1453,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nnamespace Demo {\n public class Program {\n public static void Main(String[] args) {\n List<int> list1 = new List<int>();\n list1.Add(2);\n list1.Add(3);\n list1.Add(5);\n list1.Add(7);\n Console.WriteLine(list1.Count);\n List<int> list2 = new List<int>();\n list2.Add(5);\n list2.Add(4);\n list2.Add(6);\n list2.Add(8);\n Console.WriteLine(list2.Count);\n List<int> common = list1.Intersect(list2).ToList();\n Console.WriteLine(common.Count);\n }\n }\n}"
},
{
"code": null,
"e": 2126,
"s": 2120,
"text": "4\n4\n1"
}
] |
How to change the datatype of a column in an existing table using JDBC API? | You can change the datatype of a column in a table using the ALTER TABLE command.
ALTER TABLE Sales MODIFY COLUMN column_name column_new_datatuype
Assume we have a table named Sales in the database with 7 columns namely ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location and, ID with description as:
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductName | varchar(255) | YES | | NULL | |
| CustomerName | varchar(255) | YES | | NULL | |
| DispatchDate | date | YES | | NULL | |
| DeliveryTime | time | YES | | NULL | |
| Price | int(11) | YES | | NULL | |
| Location | varchar(255) | YES | | NULL | |
| ID | int(11) | NO | | NULL| | |
+--------------+--------------+------+-----+---------+-------+
Following JDBC program establishes connection with MySQL database, and changes the data-type of the column location from varchar to text.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class ChangingDatatype {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement();
//Query to alter the table
String query = "ALTER TABLE Sales MODIFY COLUMN Location Text";
//Executing the query
stmt.executeUpdate(query);
System.out.println("Column datatype changed......");
}
}
Connection established......
Column datatype changed......
Since we have altered the type of location column, if you get the description of the Sales table using the describe command you can observe that the data-type of the column named location is changed from varchar to text.
mysql> describe sales;
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductName | varchar(255) | YES | | NULL | |
| CustomerName | varchar(255) | YES | | NULL | |
| DispatchDate | date | YES | | NULL | |
| DeliveryTime | time | YES | | NULL | |
| Price | int(11) | YES | | NULL | |
| Location | text | YES | | NULL | |
| ID | int(11) | NO | | NULL | |
+--------------+--------------+------+-----+---------+-------+
7 rows in set (0.00 sec) | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "You can change the datatype of a column in a table using the ALTER TABLE command."
},
{
"code": null,
"e": 1209,
"s": 1144,
"text": "ALTER TABLE Sales MODIFY COLUMN column_name column_new_datatuype"
},
{
"code": null,
"e": 1382,
"s": 1209,
"text": "Assume we have a table named Sales in the database with 7 columns namely ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location and, ID with description as:"
},
{
"code": null,
"e": 2075,
"s": 1382,
"text": "+--------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------+--------------+------+-----+---------+-------+\n| ProductName | varchar(255) | YES | | NULL | |\n| CustomerName | varchar(255) | YES | | NULL | |\n| DispatchDate | date | YES | | NULL | |\n| DeliveryTime | time | YES | | NULL | |\n| Price | int(11) | YES | | NULL | |\n| Location | varchar(255) | YES | | NULL | |\n| ID | int(11) | NO | | NULL| | |\n+--------------+--------------+------+-----+---------+-------+"
},
{
"code": null,
"e": 2213,
"s": 2075,
"text": "Following JDBC program establishes connection with MySQL database, and changes the data-type of the column location from varchar to text."
},
{
"code": null,
"e": 3060,
"s": 2213,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class ChangingDatatype {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to alter the table\n String query = \"ALTER TABLE Sales MODIFY COLUMN Location Text\";\n //Executing the query\n stmt.executeUpdate(query);\n System.out.println(\"Column datatype changed......\");\n }\n}"
},
{
"code": null,
"e": 3119,
"s": 3060,
"text": "Connection established......\nColumn datatype changed......"
},
{
"code": null,
"e": 3340,
"s": 3119,
"text": "Since we have altered the type of location column, if you get the description of the Sales table using the describe command you can observe that the data-type of the column named location is changed from varchar to text."
},
{
"code": null,
"e": 4081,
"s": 3340,
"text": "mysql> describe sales;\n+--------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------+--------------+------+-----+---------+-------+\n| ProductName | varchar(255) | YES | | NULL | |\n| CustomerName | varchar(255) | YES | | NULL | |\n| DispatchDate | date | YES | | NULL | |\n| DeliveryTime | time | YES | | NULL | |\n| Price | int(11) | YES | | NULL | |\n| Location | text | YES | | NULL | |\n| ID | int(11) | NO | | NULL | |\n+--------------+--------------+------+-----+---------+-------+\n7 rows in set (0.00 sec)"
}
] |
Truly Customizing Power BI with React, Angular, or any web framework | by Thiago Candido | Towards Data Science | With the growth of the amount of data available in organizations, presenting it in a clear and direct way is increasingly important. In this context, Power BI — Microsoft’s business analysis tool — has gained prominence.
Even counting on integrated components and navigation mechanisms, enough to meet most of the regular enterprise needs, the platform still stands out for its customization possibilities.
Besides being able to customize the platform’s built-in components, it is possible, with some front-end engineering skills, to develop new ones from scratch.
The development process of a new component takes place through the programming of Custom Visuals, using the PowerBI Visual Tools package, or pbiviz, which can be installed with Node Package Manager — NPM.
The development of a Custom Visual requires only knowledge of conventional web technologies such as Typescript, HTML and CSS and can be enhanced by the use of frameworks such as React, Angular or D3.js.
The design of a Custom Visual is generated, with all that is necessary, by a CLI tool, provided by the NPM package that was indicated above.
Basically, the web developer will need to write little code — just two methods: the constructor and the update of a class that implements IVisual. In addition, the file capabilities.json, also generated by the CLI tool, allows the user to define properties, such as colors and fonts, which can be customized later during use by the end-user in Power BI.
export class Visual implements IVisual { constructor(options: VisualConstructorOptions) { // code here } public update(options: VisualUpdateOptions) { // ... and here }}
The tooling provided by pbiviz allows the web developer to have instant feedback on his work, with updates that occur with hot reload. All supported by Power BI Service.
Besides being able to benefit from the work done on your reports and dashboards, it is also possible to share the creation in App Source — application store for Microsoft companies. While this article was written, over 260 free custom visuals were available.
I hope you enjoyed reading this post.
If you did, consider following me on Twitter.
Thank you for your time.
Take care and keep coding! | [
{
"code": null,
"e": 268,
"s": 47,
"text": "With the growth of the amount of data available in organizations, presenting it in a clear and direct way is increasingly important. In this context, Power BI — Microsoft’s business analysis tool — has gained prominence."
},
{
"code": null,
"e": 454,
"s": 268,
"text": "Even counting on integrated components and navigation mechanisms, enough to meet most of the regular enterprise needs, the platform still stands out for its customization possibilities."
},
{
"code": null,
"e": 612,
"s": 454,
"text": "Besides being able to customize the platform’s built-in components, it is possible, with some front-end engineering skills, to develop new ones from scratch."
},
{
"code": null,
"e": 817,
"s": 612,
"text": "The development process of a new component takes place through the programming of Custom Visuals, using the PowerBI Visual Tools package, or pbiviz, which can be installed with Node Package Manager — NPM."
},
{
"code": null,
"e": 1020,
"s": 817,
"text": "The development of a Custom Visual requires only knowledge of conventional web technologies such as Typescript, HTML and CSS and can be enhanced by the use of frameworks such as React, Angular or D3.js."
},
{
"code": null,
"e": 1161,
"s": 1020,
"text": "The design of a Custom Visual is generated, with all that is necessary, by a CLI tool, provided by the NPM package that was indicated above."
},
{
"code": null,
"e": 1515,
"s": 1161,
"text": "Basically, the web developer will need to write little code — just two methods: the constructor and the update of a class that implements IVisual. In addition, the file capabilities.json, also generated by the CLI tool, allows the user to define properties, such as colors and fonts, which can be customized later during use by the end-user in Power BI."
},
{
"code": null,
"e": 1691,
"s": 1515,
"text": "export class Visual implements IVisual { constructor(options: VisualConstructorOptions) { // code here } public update(options: VisualUpdateOptions) { // ... and here }}"
},
{
"code": null,
"e": 1861,
"s": 1691,
"text": "The tooling provided by pbiviz allows the web developer to have instant feedback on his work, with updates that occur with hot reload. All supported by Power BI Service."
},
{
"code": null,
"e": 2120,
"s": 1861,
"text": "Besides being able to benefit from the work done on your reports and dashboards, it is also possible to share the creation in App Source — application store for Microsoft companies. While this article was written, over 260 free custom visuals were available."
},
{
"code": null,
"e": 2158,
"s": 2120,
"text": "I hope you enjoyed reading this post."
},
{
"code": null,
"e": 2204,
"s": 2158,
"text": "If you did, consider following me on Twitter."
},
{
"code": null,
"e": 2229,
"s": 2204,
"text": "Thank you for your time."
}
] |
How to take input in Octave GNU? - GeeksforGeeks | 01 Aug, 2020
Octave is open-source, free available for many of the platforms. It is a high-level language. It comes up with a text interface along with an experimental graphical interface. It is also used for various Machine Learning algorithms for solving various numeric problems. You can say that it is similar to MATLAB but slower than MATLAB.
There are multiple library functions to take input from the user in Octave.
The input() function prints the prompt and waits for the user to enter a value, it takes an expression, evaluates it, and then returns it. The return arguments depend on the expression entered.
Syntax : input(prompt, “s”)Parameters :
prompt : the text prompted on the terminal
“s” : indicates not to evaluate the entered expression
Returns : depends on the input value
Example 1 :
var = input("Enter an expression : ");% entered expression is 2 + 3 fprintf("Input is %d\n", var);
Output :
Enter an expression : 2 + 3
Input is 5
Example 2 : Using the “s” attribute :
var = input("Enter an expression : ", "s");% entered expression is 2 + 3 fprintf("Input is %s\n", var);
Output :
Enter an expression : 2 + 3
Input is 2 + 3
The yes_or_no() function accepts only two input values, either yes or no.
Syntax : yes_or_no(“prompt”)Parameters :
prompt : the text prompted on the terminal
Returns : 1 if “yes”, 0 if “no”
If any other value except yes or no is entered, the prompt will reappear asking for the input.
Example :
var = yes_or_no("Enter a value : ");% entered value is yesdisp(var) var = yes_or_no("Enter a value : ");% entered value is nodisp(var)
Output:
Enter a value : (yes or no) yes
1
Enter a value : (yes or no) no
0
The kbhit() function waits for any keypress, after the key is pressed, it returns that key.
Syntax : kbhit(argument)Parameters :
argument : if called with an argument, it does not wait for a keypress
Returns : depends on the input value
Example :
kbhit()% entered value is a kbhit(1)
ans = a
ans =
The menu() function is used to display a menu with a heading title and options, and wait for the user input. If the GUI is running, the menu is displayed graphically Otherwise, the title and menu options are printed on the console.
Syntax : menu(title, opt1, ...)Parameters :
title : title of the menu window
opt1, opt2 ... : list of options in the menu window
Returns : depends on the option selected
Example :
% generating the menuchoice = menu("title", "opt1","opt2","opt3"); % displaying the choicefprintf("The choice is : ");disp(choice);
Output :
The choice is : 1
Octave-GNU
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Programming Languages to Learn in 2022
Difference between Shallow and Deep copy of a class
Advantages and Disadvantages of OOP
Java Swing | JComboBox with examples
Top 10 Fastest Programming Languages
Prolog | An Introduction
JLabel | Java Swing
Control Structures in Programming Languages
Program to calculate Electricity Bill
return 0 vs return 1 in C++ | [
{
"code": null,
"e": 24141,
"s": 24113,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 24476,
"s": 24141,
"text": "Octave is open-source, free available for many of the platforms. It is a high-level language. It comes up with a text interface along with an experimental graphical interface. It is also used for various Machine Learning algorithms for solving various numeric problems. You can say that it is similar to MATLAB but slower than MATLAB."
},
{
"code": null,
"e": 24552,
"s": 24476,
"text": "There are multiple library functions to take input from the user in Octave."
},
{
"code": null,
"e": 24746,
"s": 24552,
"text": "The input() function prints the prompt and waits for the user to enter a value, it takes an expression, evaluates it, and then returns it. The return arguments depend on the expression entered."
},
{
"code": null,
"e": 24786,
"s": 24746,
"text": "Syntax : input(prompt, “s”)Parameters :"
},
{
"code": null,
"e": 24829,
"s": 24786,
"text": "prompt : the text prompted on the terminal"
},
{
"code": null,
"e": 24884,
"s": 24829,
"text": "“s” : indicates not to evaluate the entered expression"
},
{
"code": null,
"e": 24921,
"s": 24884,
"text": "Returns : depends on the input value"
},
{
"code": null,
"e": 24933,
"s": 24921,
"text": "Example 1 :"
},
{
"code": "var = input(\"Enter an expression : \");% entered expression is 2 + 3 fprintf(\"Input is %d\\n\", var);",
"e": 25033,
"s": 24933,
"text": null
},
{
"code": null,
"e": 25042,
"s": 25033,
"text": "Output :"
},
{
"code": null,
"e": 25082,
"s": 25042,
"text": "Enter an expression : 2 + 3\nInput is 5\n"
},
{
"code": null,
"e": 25120,
"s": 25082,
"text": "Example 2 : Using the “s” attribute :"
},
{
"code": "var = input(\"Enter an expression : \", \"s\");% entered expression is 2 + 3 fprintf(\"Input is %s\\n\", var);",
"e": 25225,
"s": 25120,
"text": null
},
{
"code": null,
"e": 25234,
"s": 25225,
"text": "Output :"
},
{
"code": null,
"e": 25278,
"s": 25234,
"text": "Enter an expression : 2 + 3\nInput is 2 + 3\n"
},
{
"code": null,
"e": 25352,
"s": 25278,
"text": "The yes_or_no() function accepts only two input values, either yes or no."
},
{
"code": null,
"e": 25393,
"s": 25352,
"text": "Syntax : yes_or_no(“prompt”)Parameters :"
},
{
"code": null,
"e": 25436,
"s": 25393,
"text": "prompt : the text prompted on the terminal"
},
{
"code": null,
"e": 25468,
"s": 25436,
"text": "Returns : 1 if “yes”, 0 if “no”"
},
{
"code": null,
"e": 25563,
"s": 25468,
"text": "If any other value except yes or no is entered, the prompt will reappear asking for the input."
},
{
"code": null,
"e": 25573,
"s": 25563,
"text": "Example :"
},
{
"code": "var = yes_or_no(\"Enter a value : \");% entered value is yesdisp(var) var = yes_or_no(\"Enter a value : \");% entered value is nodisp(var)",
"e": 25709,
"s": 25573,
"text": null
},
{
"code": null,
"e": 25717,
"s": 25709,
"text": "Output:"
},
{
"code": null,
"e": 25785,
"s": 25717,
"text": "Enter a value : (yes or no) yes\n1\nEnter a value : (yes or no) no\n0\n"
},
{
"code": null,
"e": 25877,
"s": 25785,
"text": "The kbhit() function waits for any keypress, after the key is pressed, it returns that key."
},
{
"code": null,
"e": 25914,
"s": 25877,
"text": "Syntax : kbhit(argument)Parameters :"
},
{
"code": null,
"e": 25985,
"s": 25914,
"text": "argument : if called with an argument, it does not wait for a keypress"
},
{
"code": null,
"e": 26022,
"s": 25985,
"text": "Returns : depends on the input value"
},
{
"code": null,
"e": 26032,
"s": 26022,
"text": "Example :"
},
{
"code": "kbhit()% entered value is a kbhit(1)",
"e": 26070,
"s": 26032,
"text": null
},
{
"code": null,
"e": 26085,
"s": 26070,
"text": "ans = a\nans =\n"
},
{
"code": null,
"e": 26317,
"s": 26085,
"text": "The menu() function is used to display a menu with a heading title and options, and wait for the user input. If the GUI is running, the menu is displayed graphically Otherwise, the title and menu options are printed on the console."
},
{
"code": null,
"e": 26361,
"s": 26317,
"text": "Syntax : menu(title, opt1, ...)Parameters :"
},
{
"code": null,
"e": 26394,
"s": 26361,
"text": "title : title of the menu window"
},
{
"code": null,
"e": 26446,
"s": 26394,
"text": "opt1, opt2 ... : list of options in the menu window"
},
{
"code": null,
"e": 26487,
"s": 26446,
"text": "Returns : depends on the option selected"
},
{
"code": null,
"e": 26497,
"s": 26487,
"text": "Example :"
},
{
"code": "% generating the menuchoice = menu(\"title\", \"opt1\",\"opt2\",\"opt3\"); % displaying the choicefprintf(\"The choice is : \");disp(choice);",
"e": 26630,
"s": 26497,
"text": null
},
{
"code": null,
"e": 26639,
"s": 26630,
"text": "Output :"
},
{
"code": null,
"e": 26659,
"s": 26639,
"text": "The choice is : 1\n"
},
{
"code": null,
"e": 26670,
"s": 26659,
"text": "Octave-GNU"
},
{
"code": null,
"e": 26691,
"s": 26670,
"text": "Programming Language"
},
{
"code": null,
"e": 26789,
"s": 26691,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26798,
"s": 26789,
"text": "Comments"
},
{
"code": null,
"e": 26811,
"s": 26798,
"text": "Old Comments"
},
{
"code": null,
"e": 26857,
"s": 26811,
"text": "Top 10 Programming Languages to Learn in 2022"
},
{
"code": null,
"e": 26909,
"s": 26857,
"text": "Difference between Shallow and Deep copy of a class"
},
{
"code": null,
"e": 26945,
"s": 26909,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 26982,
"s": 26945,
"text": "Java Swing | JComboBox with examples"
},
{
"code": null,
"e": 27019,
"s": 26982,
"text": "Top 10 Fastest Programming Languages"
},
{
"code": null,
"e": 27044,
"s": 27019,
"text": "Prolog | An Introduction"
},
{
"code": null,
"e": 27064,
"s": 27044,
"text": "JLabel | Java Swing"
},
{
"code": null,
"e": 27108,
"s": 27064,
"text": "Control Structures in Programming Languages"
},
{
"code": null,
"e": 27146,
"s": 27108,
"text": "Program to calculate Electricity Bill"
}
] |
Data Structures in C++ — Part 1. Implementing common data structures in... | by Vijini Mallawaarachchi | Towards Data Science | C++ is an extension of the C programming language which supports the creation of classes, hence known as “C with classes”. It is used to create high-performance applications and provides us with a high level of control over computing resources. In this article, I will present you the C++ implementations of 4 of the data structures which I have discussed in my previous article, 8 Common Data Structures every Programmer must know.
towardsdatascience.com
Let’s dive into the code.
An array is a structure of fixed-size, which can hold items of the same data type. Arrays are indexed, meaning that random access is possible. An array is usually presented as a native data structure in many programming languages. However, one shall not confuse array with the list like data structures in languages like python. Let us see arrays are presented in C++;
// simple declarationint array[] = {1, 2, 3, 4, 5 };// in pointer form (refers to an object stored in heap)int * array = new int[5];
However, we are accustomed to the more friendly vector<T> data structure to which we can push without worrying about the size. Let us see how we can implement one of our own list like data structures that will resize on its own.
using namespace std;class DynamicArray{private: int size_; int max_; int *arrayholder_;public: DynamicArray() { this->size_ = 0; this->max_ = 5; this->arrayholder_ = new int[5]; } ~DynamicArray() { delete[] this->arrayholder_; } int size() { return this->size_; } int& operator[](int i) { assert(i < this->size_); return this->arrayholder_[i]; } void add(int n) { if (this->max_ < this->size_ + 1) { this->max_ *= 2; int *tmp_ = new int[this->max_]; for (size_t i = 0; i < this->size_; i++) { tmp_[i] = this->arrayholder_[i]; } delete[] this->arrayholder_; this->arrayholder_ = tmp_; this->arrayholder_[this->size_] = n; this->size_ += 1; } else { this->arrayholder_[this->size_] = n; this->size_ += 1; } }};int main(int argc, char **argv){ DynamicArray darray; vector<int> varray; for (size_t i = 0; i <= 15; i++) { darray.add(i); } return 0;}
We can see that the above DynamicArray has an initial size of 5. Also in the add function, we can see that if we have reached the max capacity, the array size is doubled and copied. This is how vector<T> data structure works in reality. Usually, the base size is around 30. Knowing this could come in handle in an interview.
One more thing to note is that we are using both constructors and destructors. This is because we have a pointer to memory that we allocate as the array expands. This allocated memory must be released to avoid overflows. The beauty of this implementation is that the user does not have to know anything about the ugly pointers. Overloading the operator[] allows indexed access like a native array. Having this knowledge, let us move on to our next data structure, linked lists.
A linked list is a sequential structure that consists of a sequence of items in linear order which are linked to each other. You are only required to know one end of the chain to traverse through this data structure. In a scenario where the size changes frequency, using an array might not be advantageous unless data is accessed randomly (expansions can cause higher copy times and use more memory unless you implement a shrink operation). So a linked list can be considered as a data structure that supports frequent size variations and sequential access.
Let us have a look at our implementation.
using namespace std;template <typename T>class Node{ public: T value; Node *next; Node *previous; Node(T value) { this->value = value; }};template <typename T>class LinkedList{ private: int size_; Node<T> *head_ = NULL; Node<T> *tail_ = NULL; Node<T> *itr_ = NULL; public: LinkedList() { this->size_ = 0; } void append(T value) { if (this->head_ == NULL) { this->head_ = new Node<T>(value); this->tail_ = this->head_; } else { this->tail_->next = new Node<T>(value); this->tail_->next->previous = this->tail_; this->tail_ = this->tail_->next; } this->size_ += 1; } void prepend(T value) { if (this->head_ == NULL) { this->head_ = new Node<T>(value); this->tail_ = this->head_; } else { this->head_->previous = new Node<T>(value); this->head_->previous->next = this->head_; this->head_ = this->head_->previous; } this->size_ += 1; } Node<T> * iterate() { if (this->itr_ == NULL) { this->itr_ = this->head_; } else { this->itr_ = this->itr_->next; } return this->itr_; } T ptr() { return this->itr_->value; } void resetIterator() { this->tail_ = NULL; }};int main(int argc, char **argv){ LinkedList<int> llist; llist.append(10); llist.append(12); llist.append(14); llist.append(16); llist.prepend(5); llist.prepend(4); llist.prepend(3); llist.prepend(2); llist.prepend(1); cout << "Printing Linked List" << endl; while(llist.iterate() != NULL) { cout << llist.ptr() << "\t"; } cout << endl; return 0;}
Here we are using a support structure called a Node. This Node will carry pointers to next item and the previous item. Usually having the next item is sufficient. But having both next and previous can increase append and prepend performance as we have O(1) access to both ends. Appending means we will update the tail pointer’s next element followed by updating tail to be the added item. Conversely, prepending would create a new element and set its next item to be the current head. Note that I have not included memory cleanup operations since we aren’t dealing with explicit deletions and to make code more simple. However, one must have them in a separate destructor to avoid memory leaks. Also, we are using a simple iterator just to print items.
A stack is a LIFO (Last In First Out — the element placed at last can be accessed at first) structure. Although this data structure has a different behaviour, this can be considered as a derivation of the linked list with only a head or access to the top element.
#include <iostream>using namespace std;template <typename T>class Node{public: T value; Node *next; Node(T value) { this->value = value; }};template <typename T>class Stack{private: int size_; Node<T> *top_ = NULL; Node<T> *itr_ = NULL;public: Stack() { this->size_ = 0; } void push(T value) { if (this->top_ == NULL) { this->top_ = new Node<T>(value); } else { Node<T> *tmp = new Node<T>(value); tmp->next = this->top_; this->top_ = tmp; } this->size_ += 1; } Node<T> *pop() { Node<T> *tmp = this->top_; this->top_ = this->top_->next; this->size_ -= 1; return tmp; } Node<T> *peek() { return this->top_; } int size() { return this->size_; } Node<T> *iterate() { if (this->itr_ == NULL) { this->itr_ = this->top_; } else { this->itr_ = this->itr_->next; } return this->itr_; } T ptr() { return this->itr_->value; } void resetIterator() { this->itr_ = NULL; }};int main(int argc, char **argv){ Stack<int> stk1; stk1.push(10); stk1.push(12); stk1.push(14); stk1.push(16); stk1.push(5); stk1.push(4); stk1.push(3); stk1.push(2); stk1.push(1); cout << "Printing Stack" << endl; while (stk1.iterate() != NULL) { cout << stk1.ptr() << "\t"; } cout << endl; return 0;}
Note that the Node has only a reference to the next item. Adding an item would update the top of the data structure. Furthermore, removal and retrieval are done from the top as well. For this, we use pop() and top() methods respectively.
A queue is a FIFO (First In First Out — the element placed at first can be accessed at first) structure. This can be considered as the reverse scenario of the stack. In simpler terms, it is a linked list where we add from one end read from the other end. This emulates the real-world line-up at a driveway. Here we can think of a Node structure as follows.
template <typename T>class Node{ public: T value; Node *next; Node *previous; Node(T value) { this->value = value; }};
The main data structure would be;
template <typename T>class Queue{ private: int size_; Node<T> *head_ = NULL; Node<T> *tail_ = NULL; public: Queue() { this->size_ = 0; } void enqueue(T value) { if (this->head_ == NULL) { this->head_ = new Node<T>(value); this->tail_ = this->head_; } else { this->tail_->next = new Node<T>(value); this->tail_->next->previous = this->tail_; this->tail_ = this->tail_->next; } this->size_ += 1; } Node<T> dequeue() { Node<T> *tmp = this->tail_; this->tail_ = this->tail->previous; this->tail_->next = NULL; this->size_ -= 1; return tmp; }};
We have implemented 4 common data structures using the C++ programming language. I will present the remaining implementations in a future article.
Hope you all found these C++ implementations of arrays, linked lists, stacks and queues useful. You can check out my other articles on data structures from the links given below.
towardsdatascience.com
towardsdatascience.com
Thank you for reading! Share among your networks if you found this article useful. | [
{
"code": null,
"e": 605,
"s": 172,
"text": "C++ is an extension of the C programming language which supports the creation of classes, hence known as “C with classes”. It is used to create high-performance applications and provides us with a high level of control over computing resources. In this article, I will present you the C++ implementations of 4 of the data structures which I have discussed in my previous article, 8 Common Data Structures every Programmer must know."
},
{
"code": null,
"e": 628,
"s": 605,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 654,
"s": 628,
"text": "Let’s dive into the code."
},
{
"code": null,
"e": 1023,
"s": 654,
"text": "An array is a structure of fixed-size, which can hold items of the same data type. Arrays are indexed, meaning that random access is possible. An array is usually presented as a native data structure in many programming languages. However, one shall not confuse array with the list like data structures in languages like python. Let us see arrays are presented in C++;"
},
{
"code": null,
"e": 1157,
"s": 1023,
"text": "// simple declarationint array[] = {1, 2, 3, 4, 5 };// in pointer form (refers to an object stored in heap)int * array = new int[5]; "
},
{
"code": null,
"e": 1386,
"s": 1157,
"text": "However, we are accustomed to the more friendly vector<T> data structure to which we can push without worrying about the size. Let us see how we can implement one of our own list like data structures that will resize on its own."
},
{
"code": null,
"e": 2555,
"s": 1386,
"text": "using namespace std;class DynamicArray{private: int size_; int max_; int *arrayholder_;public: DynamicArray() { this->size_ = 0; this->max_ = 5; this->arrayholder_ = new int[5]; } ~DynamicArray() { delete[] this->arrayholder_; } int size() { return this->size_; } int& operator[](int i) { assert(i < this->size_); return this->arrayholder_[i]; } void add(int n) { if (this->max_ < this->size_ + 1) { this->max_ *= 2; int *tmp_ = new int[this->max_]; for (size_t i = 0; i < this->size_; i++) { tmp_[i] = this->arrayholder_[i]; } delete[] this->arrayholder_; this->arrayholder_ = tmp_; this->arrayholder_[this->size_] = n; this->size_ += 1; } else { this->arrayholder_[this->size_] = n; this->size_ += 1; } }};int main(int argc, char **argv){ DynamicArray darray; vector<int> varray; for (size_t i = 0; i <= 15; i++) { darray.add(i); } return 0;}"
},
{
"code": null,
"e": 2880,
"s": 2555,
"text": "We can see that the above DynamicArray has an initial size of 5. Also in the add function, we can see that if we have reached the max capacity, the array size is doubled and copied. This is how vector<T> data structure works in reality. Usually, the base size is around 30. Knowing this could come in handle in an interview."
},
{
"code": null,
"e": 3358,
"s": 2880,
"text": "One more thing to note is that we are using both constructors and destructors. This is because we have a pointer to memory that we allocate as the array expands. This allocated memory must be released to avoid overflows. The beauty of this implementation is that the user does not have to know anything about the ugly pointers. Overloading the operator[] allows indexed access like a native array. Having this knowledge, let us move on to our next data structure, linked lists."
},
{
"code": null,
"e": 3916,
"s": 3358,
"text": "A linked list is a sequential structure that consists of a sequence of items in linear order which are linked to each other. You are only required to know one end of the chain to traverse through this data structure. In a scenario where the size changes frequency, using an array might not be advantageous unless data is accessed randomly (expansions can cause higher copy times and use more memory unless you implement a shrink operation). So a linked list can be considered as a data structure that supports frequent size variations and sequential access."
},
{
"code": null,
"e": 3958,
"s": 3916,
"text": "Let us have a look at our implementation."
},
{
"code": null,
"e": 5816,
"s": 3958,
"text": "using namespace std;template <typename T>class Node{ public: T value; Node *next; Node *previous; Node(T value) { this->value = value; }};template <typename T>class LinkedList{ private: int size_; Node<T> *head_ = NULL; Node<T> *tail_ = NULL; Node<T> *itr_ = NULL; public: LinkedList() { this->size_ = 0; } void append(T value) { if (this->head_ == NULL) { this->head_ = new Node<T>(value); this->tail_ = this->head_; } else { this->tail_->next = new Node<T>(value); this->tail_->next->previous = this->tail_; this->tail_ = this->tail_->next; } this->size_ += 1; } void prepend(T value) { if (this->head_ == NULL) { this->head_ = new Node<T>(value); this->tail_ = this->head_; } else { this->head_->previous = new Node<T>(value); this->head_->previous->next = this->head_; this->head_ = this->head_->previous; } this->size_ += 1; } Node<T> * iterate() { if (this->itr_ == NULL) { this->itr_ = this->head_; } else { this->itr_ = this->itr_->next; } return this->itr_; } T ptr() { return this->itr_->value; } void resetIterator() { this->tail_ = NULL; }};int main(int argc, char **argv){ LinkedList<int> llist; llist.append(10); llist.append(12); llist.append(14); llist.append(16); llist.prepend(5); llist.prepend(4); llist.prepend(3); llist.prepend(2); llist.prepend(1); cout << \"Printing Linked List\" << endl; while(llist.iterate() != NULL) { cout << llist.ptr() << \"\\t\"; } cout << endl; return 0;}"
},
{
"code": null,
"e": 6569,
"s": 5816,
"text": "Here we are using a support structure called a Node. This Node will carry pointers to next item and the previous item. Usually having the next item is sufficient. But having both next and previous can increase append and prepend performance as we have O(1) access to both ends. Appending means we will update the tail pointer’s next element followed by updating tail to be the added item. Conversely, prepending would create a new element and set its next item to be the current head. Note that I have not included memory cleanup operations since we aren’t dealing with explicit deletions and to make code more simple. However, one must have them in a separate destructor to avoid memory leaks. Also, we are using a simple iterator just to print items."
},
{
"code": null,
"e": 6833,
"s": 6569,
"text": "A stack is a LIFO (Last In First Out — the element placed at last can be accessed at first) structure. Although this data structure has a different behaviour, this can be considered as a derivation of the linked list with only a head or access to the top element."
},
{
"code": null,
"e": 8380,
"s": 6833,
"text": "#include <iostream>using namespace std;template <typename T>class Node{public: T value; Node *next; Node(T value) { this->value = value; }};template <typename T>class Stack{private: int size_; Node<T> *top_ = NULL; Node<T> *itr_ = NULL;public: Stack() { this->size_ = 0; } void push(T value) { if (this->top_ == NULL) { this->top_ = new Node<T>(value); } else { Node<T> *tmp = new Node<T>(value); tmp->next = this->top_; this->top_ = tmp; } this->size_ += 1; } Node<T> *pop() { Node<T> *tmp = this->top_; this->top_ = this->top_->next; this->size_ -= 1; return tmp; } Node<T> *peek() { return this->top_; } int size() { return this->size_; } Node<T> *iterate() { if (this->itr_ == NULL) { this->itr_ = this->top_; } else { this->itr_ = this->itr_->next; } return this->itr_; } T ptr() { return this->itr_->value; } void resetIterator() { this->itr_ = NULL; }};int main(int argc, char **argv){ Stack<int> stk1; stk1.push(10); stk1.push(12); stk1.push(14); stk1.push(16); stk1.push(5); stk1.push(4); stk1.push(3); stk1.push(2); stk1.push(1); cout << \"Printing Stack\" << endl; while (stk1.iterate() != NULL) { cout << stk1.ptr() << \"\\t\"; } cout << endl; return 0;}"
},
{
"code": null,
"e": 8618,
"s": 8380,
"text": "Note that the Node has only a reference to the next item. Adding an item would update the top of the data structure. Furthermore, removal and retrieval are done from the top as well. For this, we use pop() and top() methods respectively."
},
{
"code": null,
"e": 8975,
"s": 8618,
"text": "A queue is a FIFO (First In First Out — the element placed at first can be accessed at first) structure. This can be considered as the reverse scenario of the stack. In simpler terms, it is a linked list where we add from one end read from the other end. This emulates the real-world line-up at a driveway. Here we can think of a Node structure as follows."
},
{
"code": null,
"e": 9122,
"s": 8975,
"text": "template <typename T>class Node{ public: T value; Node *next; Node *previous; Node(T value) { this->value = value; }};"
},
{
"code": null,
"e": 9156,
"s": 9122,
"text": "The main data structure would be;"
},
{
"code": null,
"e": 9884,
"s": 9156,
"text": "template <typename T>class Queue{ private: int size_; Node<T> *head_ = NULL; Node<T> *tail_ = NULL; public: Queue() { this->size_ = 0; } void enqueue(T value) { if (this->head_ == NULL) { this->head_ = new Node<T>(value); this->tail_ = this->head_; } else { this->tail_->next = new Node<T>(value); this->tail_->next->previous = this->tail_; this->tail_ = this->tail_->next; } this->size_ += 1; } Node<T> dequeue() { Node<T> *tmp = this->tail_; this->tail_ = this->tail->previous; this->tail_->next = NULL; this->size_ -= 1; return tmp; }};"
},
{
"code": null,
"e": 10031,
"s": 9884,
"text": "We have implemented 4 common data structures using the C++ programming language. I will present the remaining implementations in a future article."
},
{
"code": null,
"e": 10210,
"s": 10031,
"text": "Hope you all found these C++ implementations of arrays, linked lists, stacks and queues useful. You can check out my other articles on data structures from the links given below."
},
{
"code": null,
"e": 10233,
"s": 10210,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10256,
"s": 10233,
"text": "towardsdatascience.com"
}
] |
Spring Autowiring 'byName' | This mode specifies autowiring by property name. Spring container looks at the beans on which auto-wire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file. If matches are found, it will inject those beans. Otherwise, bean(s) will not be wired.
For example, if a bean definition is set to autowire byName in the configuration file, and it contains a spellChecker property (that is, it has a setSpellChecker(...)method), Spring looks for a bean definition named spellChecker, and uses it to set the property. Still you can wire the remaining properties using <property> tags. The following example will illustrate the concept.
Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −
Here is the content of TextEditor.java file −
package com.tutorialspoint;
public class TextEditor {
private SpellChecker spellChecker;
private String name;
public void setSpellChecker( SpellChecker spellChecker ){
this.spellChecker = spellChecker;
}
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
Following is the content of another dependent class file SpellChecker.java
package com.tutorialspoint;
public class SpellChecker {
public SpellChecker() {
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
Following is the content of the MainApp.java file −
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}
Following is the configuration file Beans.xml in normal condition
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
<property name = "spellChecker" ref = "spellChecker" />
<property name = "name" value = "Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>
But if you are going to use autowiring 'byName', then your XML configuration file will become as follows −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id = "textEditor" class = "com.tutorialspoint.TextEditor" autowire = "byName">
<property name = "name" value = "Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −
Inside SpellChecker constructor.
Inside checkSpelling.
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2657,
"s": 2292,
"text": "This mode specifies autowiring by property name. Spring container looks at the beans on which auto-wire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file. If matches are found, it will inject those beans. Otherwise, bean(s) will not be wired."
},
{
"code": null,
"e": 3038,
"s": 2657,
"text": "For example, if a bean definition is set to autowire byName in the configuration file, and it contains a spellChecker property (that is, it has a setSpellChecker(...)method), Spring looks for a bean definition named spellChecker, and uses it to set the property. Still you can wire the remaining properties using <property> tags. The following example will illustrate the concept."
},
{
"code": null,
"e": 3143,
"s": 3038,
"text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −"
},
{
"code": null,
"e": 3189,
"s": 3143,
"text": "Here is the content of TextEditor.java file −"
},
{
"code": null,
"e": 3684,
"s": 3189,
"text": "package com.tutorialspoint;\n\npublic class TextEditor {\n private SpellChecker spellChecker;\n private String name;\n \n public void setSpellChecker( SpellChecker spellChecker ){\n this.spellChecker = spellChecker;\n }\n public SpellChecker getSpellChecker() {\n return spellChecker;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n public void spellCheck() {\n spellChecker.checkSpelling();\n }\n}"
},
{
"code": null,
"e": 3759,
"s": 3684,
"text": "Following is the content of another dependent class file SpellChecker.java"
},
{
"code": null,
"e": 4003,
"s": 3759,
"text": "package com.tutorialspoint;\n\npublic class SpellChecker {\n public SpellChecker() {\n System.out.println(\"Inside SpellChecker constructor.\" );\n }\n public void checkSpelling() {\n System.out.println(\"Inside checkSpelling.\" );\n }\n}"
},
{
"code": null,
"e": 4055,
"s": 4003,
"text": "Following is the content of the MainApp.java file −"
},
{
"code": null,
"e": 4462,
"s": 4055,
"text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n TextEditor te = (TextEditor) context.getBean(\"textEditor\");\n te.spellCheck();\n }\n}"
},
{
"code": null,
"e": 4528,
"s": 4462,
"text": "Following is the configuration file Beans.xml in normal condition"
},
{
"code": null,
"e": 5214,
"s": 4528,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <!-- Definition for textEditor bean -->\n <bean id = \"textEditor\" class = \"com.tutorialspoint.TextEditor\">\n <property name = \"spellChecker\" ref = \"spellChecker\" />\n <property name = \"name\" value = \"Generic Text Editor\" />\n </bean>\n\n <!-- Definition for spellChecker bean -->\n <bean id = \"spellChecker\" class = \"com.tutorialspoint.SpellChecker\"></bean>\n\n</beans>"
},
{
"code": null,
"e": 5321,
"s": 5214,
"text": "But if you are going to use autowiring 'byName', then your XML configuration file will become as follows −"
},
{
"code": null,
"e": 5965,
"s": 5321,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <!-- Definition for textEditor bean -->\n <bean id = \"textEditor\" class = \"com.tutorialspoint.TextEditor\" autowire = \"byName\">\n <property name = \"name\" value = \"Generic Text Editor\" />\n </bean>\n\n <!-- Definition for spellChecker bean -->\n <bean id = \"spellChecker\" class = \"com.tutorialspoint.SpellChecker\"></bean>\n\n</beans>"
},
{
"code": null,
"e": 6144,
"s": 5965,
"text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −"
},
{
"code": null,
"e": 6200,
"s": 6144,
"text": "Inside SpellChecker constructor.\nInside checkSpelling.\n"
},
{
"code": null,
"e": 6234,
"s": 6200,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6248,
"s": 6234,
"text": " Karthikeya T"
},
{
"code": null,
"e": 6281,
"s": 6248,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6296,
"s": 6281,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 6331,
"s": 6296,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6343,
"s": 6331,
"text": " Senol Atac"
},
{
"code": null,
"e": 6378,
"s": 6343,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6390,
"s": 6378,
"text": " Senol Atac"
},
{
"code": null,
"e": 6425,
"s": 6390,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6437,
"s": 6425,
"text": " Senol Atac"
},
{
"code": null,
"e": 6470,
"s": 6437,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6482,
"s": 6470,
"text": " Senol Atac"
},
{
"code": null,
"e": 6489,
"s": 6482,
"text": " Print"
},
{
"code": null,
"e": 6500,
"s": 6489,
"text": " Add Notes"
}
] |
Z-Buffer or Depth-Buffer method in C++ | The z-buffer also known as depth-buffer is a method that is used for hidden surface detection.
For any picture that has objects and surfaces that are transparent. In this case, objects that are behind other objects are hidden. For proper visual of the image, we need to remove these hidden surfaces is required. The identification is called hidden surface problem.
In z-buffer, we will compare surfaces in the z-axis as depths.
Step 1: initialize the depth of all pixel max.
d(i,j) = infinity
Step 2: Initialize color for all pixels.
c(i,j) = background-color
Step 3: for each pixel in polygon projection do,
Step 3.1: find z i.e. depth of projection’s (i,j) pixel.
Step 3.2: if z < d(i,j) do
Step 3.2.1 : d(i,j) = z and c(i,j) = color of polygon.
Using this method pixel by pixel, we will find the depth of each pixel of the plane. The smallest surface determines the color of the buffer. Generally, all z values are close to the range[0,1].
z=0, back clipping plane and z= 1, front clipping plane.
No initial sorting of polygons(planes) is required to apply the z-buffer method.
No initial sorting of polygons(planes) is required to apply the z-buffer method.
Z-buffer provides fast results even if the number of planes is large.
Z-buffer provides fast results even if the number of planes is large.
Object comparison is not required in the z-buffer method.
Object comparison is not required in the z-buffer method.
Non-polygonal hidden objects can also be detected using this method.
Non-polygonal hidden objects can also be detected using this method.
No extra data-structure for storing and resolving is required.
No extra data-structure for storing and resolving is required.
Hardware implementation is possible to speed up the process and is actively used in solve graphic workstations.
Hardware implementation is possible to speed up the process and is actively used in solve graphic workstations.
The method is applicable only when the objects under consideration are opaque i.e. transparent objects might give an error.
The method is applicable only when the objects under consideration are opaque i.e. transparent objects might give an error.
Drawing of the hidden surface might be a time-consuming process.
Drawing of the hidden surface might be a time-consuming process. | [
{
"code": null,
"e": 1157,
"s": 1062,
"text": "The z-buffer also known as depth-buffer is a method that is used for hidden surface detection."
},
{
"code": null,
"e": 1427,
"s": 1157,
"text": "For any picture that has objects and surfaces that are transparent. In this case, objects that are behind other objects are hidden. For proper visual of the image, we need to remove these hidden surfaces is required. The identification is called hidden surface problem."
},
{
"code": null,
"e": 1490,
"s": 1427,
"text": "In z-buffer, we will compare surfaces in the z-axis as depths."
},
{
"code": null,
"e": 1828,
"s": 1490,
"text": "Step 1: initialize the depth of all pixel max.\n d(i,j) = infinity\nStep 2: Initialize color for all pixels.\n c(i,j) = background-color\nStep 3: for each pixel in polygon projection do,\n Step 3.1: find z i.e. depth of projection’s (i,j) pixel.\n Step 3.2: if z < d(i,j) do\n Step 3.2.1 : d(i,j) = z and c(i,j) = color of polygon."
},
{
"code": null,
"e": 2023,
"s": 1828,
"text": "Using this method pixel by pixel, we will find the depth of each pixel of the plane. The smallest surface determines the color of the buffer. Generally, all z values are close to the range[0,1]."
},
{
"code": null,
"e": 2080,
"s": 2023,
"text": "z=0, back clipping plane and z= 1, front clipping plane."
},
{
"code": null,
"e": 2161,
"s": 2080,
"text": "No initial sorting of polygons(planes) is required to apply the z-buffer method."
},
{
"code": null,
"e": 2242,
"s": 2161,
"text": "No initial sorting of polygons(planes) is required to apply the z-buffer method."
},
{
"code": null,
"e": 2312,
"s": 2242,
"text": "Z-buffer provides fast results even if the number of planes is large."
},
{
"code": null,
"e": 2382,
"s": 2312,
"text": "Z-buffer provides fast results even if the number of planes is large."
},
{
"code": null,
"e": 2440,
"s": 2382,
"text": "Object comparison is not required in the z-buffer method."
},
{
"code": null,
"e": 2498,
"s": 2440,
"text": "Object comparison is not required in the z-buffer method."
},
{
"code": null,
"e": 2567,
"s": 2498,
"text": "Non-polygonal hidden objects can also be detected using this method."
},
{
"code": null,
"e": 2636,
"s": 2567,
"text": "Non-polygonal hidden objects can also be detected using this method."
},
{
"code": null,
"e": 2699,
"s": 2636,
"text": "No extra data-structure for storing and resolving is required."
},
{
"code": null,
"e": 2762,
"s": 2699,
"text": "No extra data-structure for storing and resolving is required."
},
{
"code": null,
"e": 2874,
"s": 2762,
"text": "Hardware implementation is possible to speed up the process and is actively used in solve graphic workstations."
},
{
"code": null,
"e": 2986,
"s": 2874,
"text": "Hardware implementation is possible to speed up the process and is actively used in solve graphic workstations."
},
{
"code": null,
"e": 3110,
"s": 2986,
"text": "The method is applicable only when the objects under consideration are opaque i.e. transparent objects might give an error."
},
{
"code": null,
"e": 3234,
"s": 3110,
"text": "The method is applicable only when the objects under consideration are opaque i.e. transparent objects might give an error."
},
{
"code": null,
"e": 3299,
"s": 3234,
"text": "Drawing of the hidden surface might be a time-consuming process."
},
{
"code": null,
"e": 3364,
"s": 3299,
"text": "Drawing of the hidden surface might be a time-consuming process."
}
] |
Exception Handling in Kotlin with Examples - GeeksforGeeks | 16 Aug, 2020
Exceptions are the error which comes at the runtime and disrupts your flow of execution of the program. Basically exception is the unwanted event that occurs at runtime. The method by which we can handle this kind of error is called Exception Handling.
Checked Exception: Exceptions that occur at the compile-time, or we can say that checked at the compile time is called Checked Exception. Example — IOException, Some file related Exception, etcUnchecked Exception: Exceptions that occur at the runtime is called Unchecked Exception. Example — OutofBound exception.
Checked Exception: Exceptions that occur at the compile-time, or we can say that checked at the compile time is called Checked Exception. Example — IOException, Some file related Exception, etc
Unchecked Exception: Exceptions that occur at the runtime is called Unchecked Exception. Example — OutofBound exception.
Note: In Kotlin we have only unchecked Exceptions which only figure out at the runtime.
We have some keywords which help us to handle Exceptions.
Try // This will try to find the exceptionThrow // If exception found then it will throw the exceptionCatch // After throwing it will catch the exception and execute their body.
Try // This will try to find the exception
Throw // If exception found then it will throw the exception
Catch // After throwing it will catch the exception and execute their body.
We have one more keyword called Finally, It will always execute either we got exception or not. In this, we have some important codes that always need to execute.
Note: If the program exit by exitProcess(Int) or abort(), then the finally will not be executed.
try{ // your code which // may throw an exception}catch(ex : ExceptionName){ // Exception handle code}finally{ // this will execute every time // either we found exception or not}
Example 1: Divide By Zero
Kotlin
fun main(){ try { // calling the function divide(10, 0) } catch (ex : Exception) { // or you can also write your // own handle here println(ex.message) }} // function which may give exceptionfun divide(a : Int, b : Int){ if (b == 0) throw Exception("Divide by zero") // even if you didn't write // this throw it will work fine. println("Division is :" + a / b)}
Output:
Divide by zero
Example 2: Let’s try the same code with try-catch and finally.
Kotlin
fun main(){ // first try block try { // didn't throw any exception divide(20, 10) } catch (ex : Exception) { // or you can also write your // own handle here println(ex.message) } finally { println("I'm executed") } // 2nd try block try { // throw an exception divide(10, 0) } catch (ex : Exception) { // or you can also write your // own handle here println(ex.message) } finally { println("I'm executed") }} fun divide(a : Int, b : Int){ if (b == 0) throw Exception("Divide by zero") println("Division is :" + a / b)}
Output:
Division is : 2
I'm executed
Divide by zero
I'm executed
Note that In the above example, finally is executed in both cases either exception occurs or not.
Kotlin Exception-Handling
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
How to Build a Weather App in Android?
ImageView in Android with Example
Kotlin extension function
ScrollView in Android
How to Send Data From Activity to Fragment in Android?
Notifications in Android with Example
Kotlin Coroutines on Android
Suspend Function In Kotlin Coroutines | [
{
"code": null,
"e": 24518,
"s": 24490,
"text": "\n16 Aug, 2020"
},
{
"code": null,
"e": 24771,
"s": 24518,
"text": "Exceptions are the error which comes at the runtime and disrupts your flow of execution of the program. Basically exception is the unwanted event that occurs at runtime. The method by which we can handle this kind of error is called Exception Handling."
},
{
"code": null,
"e": 25085,
"s": 24771,
"text": "Checked Exception: Exceptions that occur at the compile-time, or we can say that checked at the compile time is called Checked Exception. Example — IOException, Some file related Exception, etcUnchecked Exception: Exceptions that occur at the runtime is called Unchecked Exception. Example — OutofBound exception."
},
{
"code": null,
"e": 25279,
"s": 25085,
"text": "Checked Exception: Exceptions that occur at the compile-time, or we can say that checked at the compile time is called Checked Exception. Example — IOException, Some file related Exception, etc"
},
{
"code": null,
"e": 25400,
"s": 25279,
"text": "Unchecked Exception: Exceptions that occur at the runtime is called Unchecked Exception. Example — OutofBound exception."
},
{
"code": null,
"e": 25488,
"s": 25400,
"text": "Note: In Kotlin we have only unchecked Exceptions which only figure out at the runtime."
},
{
"code": null,
"e": 25546,
"s": 25488,
"text": "We have some keywords which help us to handle Exceptions."
},
{
"code": null,
"e": 25746,
"s": 25546,
"text": "Try // This will try to find the exceptionThrow // If exception found then it will throw the exceptionCatch // After throwing it will catch the exception and execute their body."
},
{
"code": null,
"e": 25800,
"s": 25746,
"text": "Try // This will try to find the exception"
},
{
"code": null,
"e": 25866,
"s": 25800,
"text": "Throw // If exception found then it will throw the exception"
},
{
"code": null,
"e": 25948,
"s": 25866,
"text": "Catch // After throwing it will catch the exception and execute their body."
},
{
"code": null,
"e": 26111,
"s": 25948,
"text": "We have one more keyword called Finally, It will always execute either we got exception or not. In this, we have some important codes that always need to execute."
},
{
"code": null,
"e": 26208,
"s": 26111,
"text": "Note: If the program exit by exitProcess(Int) or abort(), then the finally will not be executed."
},
{
"code": "try{ // your code which // may throw an exception}catch(ex : ExceptionName){ // Exception handle code}finally{ // this will execute every time // either we found exception or not}",
"e": 26393,
"s": 26208,
"text": null
},
{
"code": null,
"e": 26420,
"s": 26393,
"text": "Example 1: Divide By Zero "
},
{
"code": null,
"e": 26427,
"s": 26420,
"text": "Kotlin"
},
{
"code": "fun main(){ try { // calling the function divide(10, 0) } catch (ex : Exception) { // or you can also write your // own handle here println(ex.message) }} // function which may give exceptionfun divide(a : Int, b : Int){ if (b == 0) throw Exception(\"Divide by zero\") // even if you didn't write // this throw it will work fine. println(\"Division is :\" + a / b)}",
"e": 26857,
"s": 26427,
"text": null
},
{
"code": null,
"e": 26865,
"s": 26857,
"text": "Output:"
},
{
"code": null,
"e": 26881,
"s": 26865,
"text": "Divide by zero\n"
},
{
"code": null,
"e": 26944,
"s": 26881,
"text": "Example 2: Let’s try the same code with try-catch and finally."
},
{
"code": null,
"e": 26951,
"s": 26944,
"text": "Kotlin"
},
{
"code": "fun main(){ // first try block try { // didn't throw any exception divide(20, 10) } catch (ex : Exception) { // or you can also write your // own handle here println(ex.message) } finally { println(\"I'm executed\") } // 2nd try block try { // throw an exception divide(10, 0) } catch (ex : Exception) { // or you can also write your // own handle here println(ex.message) } finally { println(\"I'm executed\") }} fun divide(a : Int, b : Int){ if (b == 0) throw Exception(\"Divide by zero\") println(\"Division is :\" + a / b)}",
"e": 27620,
"s": 26951,
"text": null
},
{
"code": null,
"e": 27628,
"s": 27620,
"text": "Output:"
},
{
"code": null,
"e": 27686,
"s": 27628,
"text": "Division is : 2\nI'm executed\nDivide by zero\nI'm executed\n"
},
{
"code": null,
"e": 27784,
"s": 27686,
"text": "Note that In the above example, finally is executed in both cases either exception occurs or not."
},
{
"code": null,
"e": 27810,
"s": 27784,
"text": "Kotlin Exception-Handling"
},
{
"code": null,
"e": 27817,
"s": 27810,
"text": "Picked"
},
{
"code": null,
"e": 27824,
"s": 27817,
"text": "Kotlin"
},
{
"code": null,
"e": 27922,
"s": 27824,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27964,
"s": 27922,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 28004,
"s": 27964,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 28043,
"s": 28004,
"text": "How to Build a Weather App in Android?"
},
{
"code": null,
"e": 28077,
"s": 28043,
"text": "ImageView in Android with Example"
},
{
"code": null,
"e": 28103,
"s": 28077,
"text": "Kotlin extension function"
},
{
"code": null,
"e": 28125,
"s": 28103,
"text": "ScrollView in Android"
},
{
"code": null,
"e": 28180,
"s": 28125,
"text": "How to Send Data From Activity to Fragment in Android?"
},
{
"code": null,
"e": 28218,
"s": 28180,
"text": "Notifications in Android with Example"
},
{
"code": null,
"e": 28247,
"s": 28218,
"text": "Kotlin Coroutines on Android"
}
] |
fopen() function in PHP | The fopen() function opens a file or URL. If the function fails, it returns FALSE and an error on failure. Add an '@' in front of the function name to hide the error output.
fopen(file_path, mode, include_path, context)
file_path − The path of the file.
file_path − The path of the file.
mode − The type of access you require to the file“r” - Read Only"r+" - Read/Write"w" - Write only"w+" - Read/Write"a" - Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist)"a+" - Read/Write. Preserves file content by writing to the end of the file)"x" - Write only. Creates a new file. Returns FALSE and an error if file already exists)"x+" - Read/Write. Creates a new file. Returns FALSE and an error if file already exists)
mode − The type of access you require to the file
“r” - Read Only
"r+" - Read/Write
"w" - Write only
"w+" - Read/Write
"a" - Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist)
"a+" - Read/Write. Preserves file content by writing to the end of the file)
"x" - Write only. Creates a new file. Returns FALSE and an error if file already exists)
"x+" - Read/Write. Creates a new file. Returns FALSE and an error if file already exists)
incude_path − Set it to '1' if you want to search for the file in the include_path (in php.ini) as well.
incude_path − Set it to '1' if you want to search for the file in the include_path (in php.ini) as well.
context − the context of the file pointer.
context − the context of the file pointer.
The fopen() function returns returns FALSE and an error on failure. Add an '@' in front of the function name to hide the error output.
Let’s say we have a file “new.txt” with the following content.
The content of the file!
Now, let us see the example −
<?php
// read/ write mode
$file_pointer = fopen("new.txt", 'r+')
or die("File does not exist");
$res = fgets($file_pointer);
echo $res;
fclose($ile_pointer);
?>
The content of the file!
Let us see an example with “one.txt” file.
<?php
// read/write mode
$file_pointer = fopen("one.txt", "w+");
// writing to file
fwrite($file_pointer, 'demo content');
echo fread($file_pointer, filesize("new.txt"));
fclose($file_pointer);
?>
demo content | [
{
"code": null,
"e": 1236,
"s": 1062,
"text": "The fopen() function opens a file or URL. If the function fails, it returns FALSE and an error on failure. Add an '@' in front of the function name to hide the error output."
},
{
"code": null,
"e": 1282,
"s": 1236,
"text": "fopen(file_path, mode, include_path, context)"
},
{
"code": null,
"e": 1316,
"s": 1282,
"text": "file_path − The path of the file."
},
{
"code": null,
"e": 1350,
"s": 1316,
"text": "file_path − The path of the file."
},
{
"code": null,
"e": 1818,
"s": 1350,
"text": "mode − The type of access you require to the file“r” - Read Only\"r+\" - Read/Write\"w\" - Write only\"w+\" - Read/Write\"a\" - Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist)\"a+\" - Read/Write. Preserves file content by writing to the end of the file)\"x\" - Write only. Creates a new file. Returns FALSE and an error if file already exists)\"x+\" - Read/Write. Creates a new file. Returns FALSE and an error if file already exists)"
},
{
"code": null,
"e": 1868,
"s": 1818,
"text": "mode − The type of access you require to the file"
},
{
"code": null,
"e": 1884,
"s": 1868,
"text": "“r” - Read Only"
},
{
"code": null,
"e": 1902,
"s": 1884,
"text": "\"r+\" - Read/Write"
},
{
"code": null,
"e": 1919,
"s": 1902,
"text": "\"w\" - Write only"
},
{
"code": null,
"e": 1937,
"s": 1919,
"text": "\"w+\" - Read/Write"
},
{
"code": null,
"e": 2038,
"s": 1937,
"text": "\"a\" - Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist)"
},
{
"code": null,
"e": 2115,
"s": 2038,
"text": "\"a+\" - Read/Write. Preserves file content by writing to the end of the file)"
},
{
"code": null,
"e": 2204,
"s": 2115,
"text": "\"x\" - Write only. Creates a new file. Returns FALSE and an error if file already exists)"
},
{
"code": null,
"e": 2294,
"s": 2204,
"text": "\"x+\" - Read/Write. Creates a new file. Returns FALSE and an error if file already exists)"
},
{
"code": null,
"e": 2399,
"s": 2294,
"text": "incude_path − Set it to '1' if you want to search for the file in the include_path (in php.ini) as well."
},
{
"code": null,
"e": 2504,
"s": 2399,
"text": "incude_path − Set it to '1' if you want to search for the file in the include_path (in php.ini) as well."
},
{
"code": null,
"e": 2547,
"s": 2504,
"text": "context − the context of the file pointer."
},
{
"code": null,
"e": 2590,
"s": 2547,
"text": "context − the context of the file pointer."
},
{
"code": null,
"e": 2725,
"s": 2590,
"text": "The fopen() function returns returns FALSE and an error on failure. Add an '@' in front of the function name to hide the error output."
},
{
"code": null,
"e": 2788,
"s": 2725,
"text": "Let’s say we have a file “new.txt” with the following content."
},
{
"code": null,
"e": 2813,
"s": 2788,
"text": "The content of the file!"
},
{
"code": null,
"e": 2843,
"s": 2813,
"text": "Now, let us see the example −"
},
{
"code": null,
"e": 3022,
"s": 2843,
"text": "<?php\n // read/ write mode\n $file_pointer = fopen(\"new.txt\", 'r+')\n or die(\"File does not exist\");\n $res = fgets($file_pointer);\n echo $res;\n fclose($ile_pointer);\n?>"
},
{
"code": null,
"e": 3047,
"s": 3022,
"text": "The content of the file!"
},
{
"code": null,
"e": 3090,
"s": 3047,
"text": "Let us see an example with “one.txt” file."
},
{
"code": null,
"e": 3305,
"s": 3090,
"text": "<?php\n // read/write mode\n $file_pointer = fopen(\"one.txt\", \"w+\");\n // writing to file\n fwrite($file_pointer, 'demo content');\n echo fread($file_pointer, filesize(\"new.txt\"));\n fclose($file_pointer);\n?>"
},
{
"code": null,
"e": 3318,
"s": 3305,
"text": "demo content"
}
] |
Project specific array field in a MongoDB collection? | Let us first create a collection with documents −
> db.projectionAnElementDemo.insertOne(
... {
... "CustomerId":100,
... "CustomerDetails": [
... {
... "CustomerName": "Chris",
... "CustomerCountryName": "US"
... },
... {
... "CustomerName": "Robert",
... "CustomerCountryName": "UK"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd31c56b64f4b851c3a13ea")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.projectionAnElementDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd31c56b64f4b851c3a13ea"),
"CustomerId" : 100,
"CustomerDetails" : [
{
"CustomerName" : "Chris",
"CustomerCountryName" : "US"
},
{
"CustomerName" : "Robert",
"CustomerCountryName" : "UK"
}
]
}
Following is the query to project element in array field −
> db.projectionAnElementDemo.find({},{CustomerId:1, "CustomerDetails.CustomerName":1}).pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd31c56b64f4b851c3a13ea"),
"CustomerId" : 100,
"CustomerDetails" : [
{
"CustomerName" : "Chris"
},
{
"CustomerName" : "Robert"
}
]
} | [
{
"code": null,
"e": 1112,
"s": 1062,
"text": "Let us first create a collection with documents −"
},
{
"code": null,
"e": 1565,
"s": 1112,
"text": "> db.projectionAnElementDemo.insertOne(\n... {\n... \"CustomerId\":100,\n... \"CustomerDetails\": [\n... {\n... \"CustomerName\": \"Chris\",\n... \"CustomerCountryName\": \"US\"\n... },\n... {\n... \"CustomerName\": \"Robert\",\n... \"CustomerCountryName\": \"UK\"\n... }\n... ]\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd31c56b64f4b851c3a13ea\")\n}"
},
{
"code": null,
"e": 1664,
"s": 1565,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1710,
"s": 1664,
"text": "> db.projectionAnElementDemo.find().pretty();"
},
{
"code": null,
"e": 1751,
"s": 1710,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2037,
"s": 1751,
"text": "{\n \"_id\" : ObjectId(\"5cd31c56b64f4b851c3a13ea\"),\n \"CustomerId\" : 100,\n \"CustomerDetails\" : [\n {\n \"CustomerName\" : \"Chris\",\n \"CustomerCountryName\" : \"US\"\n },\n {\n \"CustomerName\" : \"Robert\",\n \"CustomerCountryName\" : \"UK\"\n }\n ]\n}"
},
{
"code": null,
"e": 2096,
"s": 2037,
"text": "Following is the query to project element in array field −"
},
{
"code": null,
"e": 2193,
"s": 2096,
"text": "> db.projectionAnElementDemo.find({},{CustomerId:1, \"CustomerDetails.CustomerName\":1}).pretty();"
},
{
"code": null,
"e": 2234,
"s": 2193,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2442,
"s": 2234,
"text": "{\n \"_id\" : ObjectId(\"5cd31c56b64f4b851c3a13ea\"),\n \"CustomerId\" : 100,\n \"CustomerDetails\" : [\n {\n \"CustomerName\" : \"Chris\"\n },\n {\n \"CustomerName\" : \"Robert\"\n }\n ]\n}"
}
] |
How to I connect to wifi network on Android programmatically? | This example demonstrates how do I connect wifi network in Android programatically.
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
android:id="@+id/activity_main"
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">
<Switch
android:id="@+id/switchWifi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/switchWifi"
android:layout_centerHorizontal="true"
android:layout_marginBottom="42dp"
android:text="WiFi OFF"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.content.Context;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Switch WiFiButton;
TextView textview;
WifiManager wifiManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = findViewById(R.id.textView);
WiFiButton = findViewById(R.id.switchWifi);
WiFiButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked) {
textview.setText("WII ON");
EnableWiFi() ;
} else {
textview.setText("WII OFF");
DisableWiFi();
}
}
});
}
public void EnableWiFi(){
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
public void DisableWiFi(){
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "This example demonstrates how do I connect wifi network in Android programatically."
},
{
"code": null,
"e": 1275,
"s": 1146,
"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": 1340,
"s": 1275,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2254,
"s": 1340,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n android:id=\"@+id/activity_main\"\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\"MainActivity\">\n <Switch\n android:id=\"@+id/switchWifi\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_centerVertical=\"true\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_above=\"@+id/switchWifi\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginBottom=\"42dp\"\n android:text=\"WiFi OFF\"\n android:textAppearance=\"?android:attr/textAppearanceLarge\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2311,
"s": 2254,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3713,
"s": 2311,
"text": "import android.content.Context;\nimport android.net.wifi.WifiManager;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.CompoundButton;\nimport android.widget.Switch;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n Switch WiFiButton;\n TextView textview;\n WifiManager wifiManager;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textview = findViewById(R.id.textView);\n WiFiButton = findViewById(R.id.switchWifi);\n WiFiButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n // TODO Auto-generated method stub\n if(isChecked) {\n textview.setText(\"WII ON\");\n EnableWiFi() ;\n } else {\n textview.setText(\"WII OFF\");\n DisableWiFi();\n }\n }\n });\n }\n public void EnableWiFi(){\n wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);\n wifiManager.setWifiEnabled(true);\n }\n public void DisableWiFi(){\n wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);\n wifiManager.setWifiEnabled(false);\n }\n}"
},
{
"code": null,
"e": 3768,
"s": 3713,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4654,
"s": 3768,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\" />\n <uses-permission android:name=\"android.permission.INTERNET\" />\n <uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\" />\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": 5001,
"s": 4654,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 5042,
"s": 5001,
"text": "Click here to download the project code."
}
] |
Get first and last elements from Array and Vector in CPP - GeeksforGeeks | 10 Nov, 2018
Given an array, find first and last elements of it.
Input: {4, 5, 7, 13, 25, 65, 98}
Output: First element: 4
Last element: 98
In C++, we can use sizeof operator to find number of elements in an array.
// C++ Program to print first and last element in an array#include <iostream>using namespace std;int main(){ int arr[] = { 4, 5, 7, 13, 25, 65, 98 }; int f, l, n; n = sizeof(arr) / sizeof(arr[0]); f = arr[0]; l = arr[n - 1]; cout << "First element: " << f << endl; cout << "Last element: " << l << endl; return 0;}
First element: 4
Last element: 98
We should not sizeof when arrays are passed as parameters, there we must pass size and use that size to find first and last elements.
// C++ Program to print first and last element in an array#include <iostream>using namespace std; int printFirstLast(int arr[], int n){ int f = arr[0]; int l = arr[n - 1]; cout << "First element: " << f << endl; cout << "Last element: " << l << endl;} int main(){ int arr[] = { 4, 5, 7, 13, 25, 65, 98 }; int n = sizeof(arr) / sizeof(arr[0]); printFirstLast(arr, n); return 0;}
First element: 4
Last element: 98
In case of vectors in C++, there are functions like front and back to find first and last elements.
// C++ Program to find first and last elements in vector#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v; v.push_back(4); v.push_back(5); v.push_back(7); v.push_back(13); v.push_back(25); v.push_back(65); v.push_back(98); cout << "v.front() is now " << v.front() << '\n'; cout << "v.back() is now " << v.back() << '\n'; return 0;}
v.front() is now 4
v.back() is now 98
We can use front and back even when vector is passed as a parameter.
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
Convert string to char array in C++
Pair in C++ Standard Template Library (STL)
Iterators in C++ STL
Inline Functions in C++
Multithreading in C++
List in C++ Standard Template Library (STL) | [
{
"code": null,
"e": 24098,
"s": 24070,
"text": "\n10 Nov, 2018"
},
{
"code": null,
"e": 24150,
"s": 24098,
"text": "Given an array, find first and last elements of it."
},
{
"code": null,
"e": 24226,
"s": 24150,
"text": "Input: {4, 5, 7, 13, 25, 65, 98}\nOutput: First element: 4\nLast element: 98\n"
},
{
"code": null,
"e": 24301,
"s": 24226,
"text": "In C++, we can use sizeof operator to find number of elements in an array."
},
{
"code": "// C++ Program to print first and last element in an array#include <iostream>using namespace std;int main(){ int arr[] = { 4, 5, 7, 13, 25, 65, 98 }; int f, l, n; n = sizeof(arr) / sizeof(arr[0]); f = arr[0]; l = arr[n - 1]; cout << \"First element: \" << f << endl; cout << \"Last element: \" << l << endl; return 0;}",
"e": 24640,
"s": 24301,
"text": null
},
{
"code": null,
"e": 24675,
"s": 24640,
"text": "First element: 4\nLast element: 98\n"
},
{
"code": null,
"e": 24809,
"s": 24675,
"text": "We should not sizeof when arrays are passed as parameters, there we must pass size and use that size to find first and last elements."
},
{
"code": "// C++ Program to print first and last element in an array#include <iostream>using namespace std; int printFirstLast(int arr[], int n){ int f = arr[0]; int l = arr[n - 1]; cout << \"First element: \" << f << endl; cout << \"Last element: \" << l << endl;} int main(){ int arr[] = { 4, 5, 7, 13, 25, 65, 98 }; int n = sizeof(arr) / sizeof(arr[0]); printFirstLast(arr, n); return 0;}",
"e": 25213,
"s": 24809,
"text": null
},
{
"code": null,
"e": 25248,
"s": 25213,
"text": "First element: 4\nLast element: 98\n"
},
{
"code": null,
"e": 25348,
"s": 25248,
"text": "In case of vectors in C++, there are functions like front and back to find first and last elements."
},
{
"code": "// C++ Program to find first and last elements in vector#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v; v.push_back(4); v.push_back(5); v.push_back(7); v.push_back(13); v.push_back(25); v.push_back(65); v.push_back(98); cout << \"v.front() is now \" << v.front() << '\\n'; cout << \"v.back() is now \" << v.back() << '\\n'; return 0;}",
"e": 25747,
"s": 25348,
"text": null
},
{
"code": null,
"e": 25786,
"s": 25747,
"text": "v.front() is now 4\nv.back() is now 98\n"
},
{
"code": null,
"e": 25855,
"s": 25786,
"text": "We can use front and back even when vector is passed as a parameter."
},
{
"code": null,
"e": 25866,
"s": 25855,
"text": "cpp-vector"
},
{
"code": null,
"e": 25870,
"s": 25866,
"text": "STL"
},
{
"code": null,
"e": 25874,
"s": 25870,
"text": "C++"
},
{
"code": null,
"e": 25878,
"s": 25874,
"text": "STL"
},
{
"code": null,
"e": 25882,
"s": 25878,
"text": "CPP"
},
{
"code": null,
"e": 25980,
"s": 25882,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26008,
"s": 25980,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26028,
"s": 26008,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 26061,
"s": 26028,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 26085,
"s": 26061,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 26121,
"s": 26085,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 26165,
"s": 26121,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26186,
"s": 26165,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 26210,
"s": 26186,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 26232,
"s": 26210,
"text": "Multithreading in C++"
}
] |
Advantages and Disadvantages of Array in C - GeeksforGeeks | 29 Oct, 2020
An array is a collection of similar types of elements. For example, an integer array holds the elements of int types while a character array holds the elements of char types. Below is the representation of the array:
Though, array got its own set of advantages and disadvantages.
Below are some advantages of the array:
In an array, accessing an element is very easy by using the index number.
The search process can be applied to an array easily.
2D Array is used to represent matrices.
For any reason a user wishes to store multiple values of similar type then the Array can be used and utilized efficiently.
Now let’s see some disadvantages of the array and how to overcome it:
Array size is fixed: The array is static, which means its size is always fixed. The memory which is allocated to it cannot be increased or decreased. Below is the program for the same:
C
// C program to illustrate that the// array size is fixed#include <stdio.h> // Driver Codeint main(){ int arr[10]; // Assign values to array arr[0] = 5; arr[5] = 6; arr[7] = -9; // Print array element at index 0 printf("Element at index 0" " is %d\n", arr[0]); // Print array element at index 11 printf("Element at index 11" " is %d", arr[11]); return 0;}
Element at index 0 is 5
Element at index 11 is -1176897384
Explanation: In the above program the array of size 10 is declared and the value is assigned at a particular index. But when the value at index 11 is printed then it prints the garbage value because the array was accessed out of the bound index. In some compiler, it gives error as “Array Index Out Of Bound.”.
How to overcome: To overcome that problem use Dynamic Memory Allocation like malloc(), calloc(). It also helps us to deallocates the memory using the free() method which helps to reduce wastage of memory by releasing it. Below is the program for the same:
C
// C program to illustrate the use of// array using Dynamic Memory Allocation#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Pointer will hold the base address int* ptr; int n = 10; // Dynamically allocates memory // using malloc() function ptr = (int*)malloc(n * sizeof(int)); // Assign values to the array for (int i = 0; i < n; i++) { ptr[i] = i + 1; } // Print the array printf("The elements are: "); for (int i = 0; i < n; i++) { printf("%d ", ptr[i]); } // Free the dynamically // allocated memory free(ptr); return 0;}
The elements are: 1 2 3 4 5 6 7 8 9 10
Array is homogeneous:The array is homogeneous, i.e., only one type of value can be store in the array. For example, if an array type “int“, can only store integer elements and cannot allow the elements of other types such as double, float, char so on. Below is the program for the same:
C
// C++ program to illustrate that// the array is homogeneous#include <stdio.h> // Driver Codeint main(){ // Below declaration will give // Compilation Error int a[5] = { 0, 1, 2, "string", 9, 4.85 }; return 0;}
100
547.000000
Ram
Output:
Explanation: The above code gives “Compilation Error” as an integer type array is assigned value to a string and float type.
How to overcome: To overcome that problem, the idea is to structure, where it can store non-homogeneous (heterogeneous) value. Below is the program for the same:
C
// C program to illustrate the use of// structure to store heterogeneous// variables#include <stdio.h> // Structure studentsstruct student { int student_id; float marks; char name[30];}; // Driver Codeint main(){ // Structure variable s1 struct student s1 = { 100, 547, "Ram" }; // Accessing structure members // using structure pointer printf("%d\n", s1.student_id); printf("%f\n", s1.marks); for (int i = 0; s1.name[i] != '\0'; i++) { printf("%c", s1.name[i]); } return 0;}
100
547.000000
Ram
Array is Contiguous blocks of memory: The array stores data in contiguous(one by one) memory location. Below is the representation of the same:
How to overcome: To overcome the sequential access to the array, the idea is to use the Linked list. In a Linked list, the elements are not stored in contiguous memory locations. Below is the representation of the same:
Insertion and deletion are not easy in Array: The operation insertion and deletion over an array are problematic as to insert or delete anywhere in the array, it is necessary to traverse the array and then shift the remaining elements as per the operation. This operation cost is more.
Example: For inserting 22 in 3rd position of the array then below are the steps:
Below is the program to illustrate the same:
C
// C Program to insert an element at// a specific position in an array#include <stdio.h> // Driver Codeint main(){ int arr[100] = { 0 }; int i, x, pos, n = 10; // Initial array of size 10 for (i = 0; i < 10; i++) { arr[i] = i + 1; } // Print the original array for (i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); // Element to be inserted x = 50; // Position at which element // is to be inserted pos = 5; printf("Array after inserting %d" " at position %d\n", x, pos); // Increase the size by 1 n++; // Shift elements forward for (i = n - 1; i >= pos; i--) { arr[i] = arr[i - 1]; } // Insert x at pos arr[pos - 1] = x; // Print the updated array for (i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0;}
1 2 3 4 5 6 7 8 9 10
Array after inserting 50 at position 5
1 2 3 4 50 5 6 7 8 9 10
How to overcome: To overcome the above problem using a Linked List. Below is the representation of the same:
Below is the program to implement the same:
C
// C program to insert an element at// a position using linked list#include <stdio.h>#include <stdlib.h> // Structure for the linked liststruct node { int data; struct node* next;}; // head Nodestruct node* head; // Function to insert any element// at the end of the linked listint insert_last(int k){ struct node *ptr, *s; ptr = (struct node*) malloc(sizeof(struct node)); ptr->data = k; ptr->next = NULL; // If head is NULL if (head == NULL) { head = ptr; } // Else else { s = head; // Traverse the LL to last while (s->next != NULL) { s = s->next; } s->next = ptr; }} // Function to display linked listvoid display(){ struct node* s; // Store the head s = head; // Traverse till s is NULL while (s != NULL) { // Print the data printf("%d ", s->data); s = s->next; } printf("\n");} // Function to insert any element at// the given position of linked listint insert_position(int a, int b){ int f = 0, i; struct node *ptr, *s; // Allocate new Node ptr = (struct node*) malloc(sizeof(struct node)); ptr->data = a; // If first position if (b == 1) { ptr->next = head; head = ptr; } // Otherwise else { s = head; // Move to (b - 1) position for (i = 0; i < b - 2; i++) { s = s->next; } // Assign node ptr->next = s->next; s->next = ptr; } return 0;} // Driver Codeint main(){ // Given Linked List insert_last(3); insert_last(1); insert_last(5); insert_last(7); printf("Current Linked List is: "); // Display the LL display(); // Insert 6 at position 4 insert_position(6, 4); printf("\n Linked List after insert" " 6 in 4th position: "); // Display the LL display(); return 0;}
Current Linked List is: 3 1 5 7
Linked List after insert 6 in 4th position: 3 1 5 6 7
cpp-structure
Arrays
Articles
C Language
C Programs
Data Structures
Difference Between
Linked List
Data Structures
Linked List
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Building Heap from Array
Move all negative numbers to beginning and positive to end with constant extra space
Amazon Interview Questions
Deadlock Prevention And Avoidance
Differences and Applications of List, Tuple, Set and Dictionary in Python
Functional Dependency and Attribute Closure
Const keyword in C++ | [
{
"code": null,
"e": 24822,
"s": 24794,
"text": "\n29 Oct, 2020"
},
{
"code": null,
"e": 25039,
"s": 24822,
"text": "An array is a collection of similar types of elements. For example, an integer array holds the elements of int types while a character array holds the elements of char types. Below is the representation of the array:"
},
{
"code": null,
"e": 25102,
"s": 25039,
"text": "Though, array got its own set of advantages and disadvantages."
},
{
"code": null,
"e": 25142,
"s": 25102,
"text": "Below are some advantages of the array:"
},
{
"code": null,
"e": 25216,
"s": 25142,
"text": "In an array, accessing an element is very easy by using the index number."
},
{
"code": null,
"e": 25270,
"s": 25216,
"text": "The search process can be applied to an array easily."
},
{
"code": null,
"e": 25310,
"s": 25270,
"text": "2D Array is used to represent matrices."
},
{
"code": null,
"e": 25433,
"s": 25310,
"text": "For any reason a user wishes to store multiple values of similar type then the Array can be used and utilized efficiently."
},
{
"code": null,
"e": 25503,
"s": 25433,
"text": "Now let’s see some disadvantages of the array and how to overcome it:"
},
{
"code": null,
"e": 25688,
"s": 25503,
"text": "Array size is fixed: The array is static, which means its size is always fixed. The memory which is allocated to it cannot be increased or decreased. Below is the program for the same:"
},
{
"code": null,
"e": 25690,
"s": 25688,
"text": "C"
},
{
"code": "// C program to illustrate that the// array size is fixed#include <stdio.h> // Driver Codeint main(){ int arr[10]; // Assign values to array arr[0] = 5; arr[5] = 6; arr[7] = -9; // Print array element at index 0 printf(\"Element at index 0\" \" is %d\\n\", arr[0]); // Print array element at index 11 printf(\"Element at index 11\" \" is %d\", arr[11]); return 0;}",
"e": 26125,
"s": 25690,
"text": null
},
{
"code": null,
"e": 26185,
"s": 26125,
"text": "Element at index 0 is 5\nElement at index 11 is -1176897384\n"
},
{
"code": null,
"e": 26496,
"s": 26185,
"text": "Explanation: In the above program the array of size 10 is declared and the value is assigned at a particular index. But when the value at index 11 is printed then it prints the garbage value because the array was accessed out of the bound index. In some compiler, it gives error as “Array Index Out Of Bound.”."
},
{
"code": null,
"e": 26752,
"s": 26496,
"text": "How to overcome: To overcome that problem use Dynamic Memory Allocation like malloc(), calloc(). It also helps us to deallocates the memory using the free() method which helps to reduce wastage of memory by releasing it. Below is the program for the same:"
},
{
"code": null,
"e": 26754,
"s": 26752,
"text": "C"
},
{
"code": "// C program to illustrate the use of// array using Dynamic Memory Allocation#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Pointer will hold the base address int* ptr; int n = 10; // Dynamically allocates memory // using malloc() function ptr = (int*)malloc(n * sizeof(int)); // Assign values to the array for (int i = 0; i < n; i++) { ptr[i] = i + 1; } // Print the array printf(\"The elements are: \"); for (int i = 0; i < n; i++) { printf(\"%d \", ptr[i]); } // Free the dynamically // allocated memory free(ptr); return 0;}",
"e": 27377,
"s": 26754,
"text": null
},
{
"code": null,
"e": 27417,
"s": 27377,
"text": "The elements are: 1 2 3 4 5 6 7 8 9 10\n"
},
{
"code": null,
"e": 27704,
"s": 27417,
"text": "Array is homogeneous:The array is homogeneous, i.e., only one type of value can be store in the array. For example, if an array type “int“, can only store integer elements and cannot allow the elements of other types such as double, float, char so on. Below is the program for the same:"
},
{
"code": null,
"e": 27706,
"s": 27704,
"text": "C"
},
{
"code": "// C++ program to illustrate that// the array is homogeneous#include <stdio.h> // Driver Codeint main(){ // Below declaration will give // Compilation Error int a[5] = { 0, 1, 2, \"string\", 9, 4.85 }; return 0;}",
"e": 27932,
"s": 27706,
"text": null
},
{
"code": null,
"e": 27952,
"s": 27932,
"text": "100\n547.000000\nRam\n"
},
{
"code": null,
"e": 27960,
"s": 27952,
"text": "Output:"
},
{
"code": null,
"e": 28085,
"s": 27960,
"text": "Explanation: The above code gives “Compilation Error” as an integer type array is assigned value to a string and float type."
},
{
"code": null,
"e": 28247,
"s": 28085,
"text": "How to overcome: To overcome that problem, the idea is to structure, where it can store non-homogeneous (heterogeneous) value. Below is the program for the same:"
},
{
"code": null,
"e": 28249,
"s": 28247,
"text": "C"
},
{
"code": "// C program to illustrate the use of// structure to store heterogeneous// variables#include <stdio.h> // Structure studentsstruct student { int student_id; float marks; char name[30];}; // Driver Codeint main(){ // Structure variable s1 struct student s1 = { 100, 547, \"Ram\" }; // Accessing structure members // using structure pointer printf(\"%d\\n\", s1.student_id); printf(\"%f\\n\", s1.marks); for (int i = 0; s1.name[i] != '\\0'; i++) { printf(\"%c\", s1.name[i]); } return 0;}",
"e": 28786,
"s": 28249,
"text": null
},
{
"code": null,
"e": 28806,
"s": 28786,
"text": "100\n547.000000\nRam\n"
},
{
"code": null,
"e": 28950,
"s": 28806,
"text": "Array is Contiguous blocks of memory: The array stores data in contiguous(one by one) memory location. Below is the representation of the same:"
},
{
"code": null,
"e": 29170,
"s": 28950,
"text": "How to overcome: To overcome the sequential access to the array, the idea is to use the Linked list. In a Linked list, the elements are not stored in contiguous memory locations. Below is the representation of the same:"
},
{
"code": null,
"e": 29456,
"s": 29170,
"text": "Insertion and deletion are not easy in Array: The operation insertion and deletion over an array are problematic as to insert or delete anywhere in the array, it is necessary to traverse the array and then shift the remaining elements as per the operation. This operation cost is more."
},
{
"code": null,
"e": 29537,
"s": 29456,
"text": "Example: For inserting 22 in 3rd position of the array then below are the steps:"
},
{
"code": null,
"e": 29582,
"s": 29537,
"text": "Below is the program to illustrate the same:"
},
{
"code": null,
"e": 29584,
"s": 29582,
"text": "C"
},
{
"code": "// C Program to insert an element at// a specific position in an array#include <stdio.h> // Driver Codeint main(){ int arr[100] = { 0 }; int i, x, pos, n = 10; // Initial array of size 10 for (i = 0; i < 10; i++) { arr[i] = i + 1; } // Print the original array for (i = 0; i < n; i++) { printf(\"%d \", arr[i]); } printf(\"\\n\"); // Element to be inserted x = 50; // Position at which element // is to be inserted pos = 5; printf(\"Array after inserting %d\" \" at position %d\\n\", x, pos); // Increase the size by 1 n++; // Shift elements forward for (i = n - 1; i >= pos; i--) { arr[i] = arr[i - 1]; } // Insert x at pos arr[pos - 1] = x; // Print the updated array for (i = 0; i < n; i++) { printf(\"%d \", arr[i]); } return 0;}",
"e": 30455,
"s": 29584,
"text": null
},
{
"code": null,
"e": 30541,
"s": 30455,
"text": "1 2 3 4 5 6 7 8 9 10 \nArray after inserting 50 at position 5\n1 2 3 4 50 5 6 7 8 9 10\n"
},
{
"code": null,
"e": 30650,
"s": 30541,
"text": "How to overcome: To overcome the above problem using a Linked List. Below is the representation of the same:"
},
{
"code": null,
"e": 30694,
"s": 30650,
"text": "Below is the program to implement the same:"
},
{
"code": null,
"e": 30696,
"s": 30694,
"text": "C"
},
{
"code": "// C program to insert an element at// a position using linked list#include <stdio.h>#include <stdlib.h> // Structure for the linked liststruct node { int data; struct node* next;}; // head Nodestruct node* head; // Function to insert any element// at the end of the linked listint insert_last(int k){ struct node *ptr, *s; ptr = (struct node*) malloc(sizeof(struct node)); ptr->data = k; ptr->next = NULL; // If head is NULL if (head == NULL) { head = ptr; } // Else else { s = head; // Traverse the LL to last while (s->next != NULL) { s = s->next; } s->next = ptr; }} // Function to display linked listvoid display(){ struct node* s; // Store the head s = head; // Traverse till s is NULL while (s != NULL) { // Print the data printf(\"%d \", s->data); s = s->next; } printf(\"\\n\");} // Function to insert any element at// the given position of linked listint insert_position(int a, int b){ int f = 0, i; struct node *ptr, *s; // Allocate new Node ptr = (struct node*) malloc(sizeof(struct node)); ptr->data = a; // If first position if (b == 1) { ptr->next = head; head = ptr; } // Otherwise else { s = head; // Move to (b - 1) position for (i = 0; i < b - 2; i++) { s = s->next; } // Assign node ptr->next = s->next; s->next = ptr; } return 0;} // Driver Codeint main(){ // Given Linked List insert_last(3); insert_last(1); insert_last(5); insert_last(7); printf(\"Current Linked List is: \"); // Display the LL display(); // Insert 6 at position 4 insert_position(6, 4); printf(\"\\n Linked List after insert\" \" 6 in 4th position: \"); // Display the LL display(); return 0;}",
"e": 32619,
"s": 30696,
"text": null
},
{
"code": null,
"e": 32709,
"s": 32619,
"text": "Current Linked List is: 3 1 5 7 \n\n Linked List after insert 6 in 4th position: 3 1 5 6 7\n"
},
{
"code": null,
"e": 32723,
"s": 32709,
"text": "cpp-structure"
},
{
"code": null,
"e": 32730,
"s": 32723,
"text": "Arrays"
},
{
"code": null,
"e": 32739,
"s": 32730,
"text": "Articles"
},
{
"code": null,
"e": 32750,
"s": 32739,
"text": "C Language"
},
{
"code": null,
"e": 32761,
"s": 32750,
"text": "C Programs"
},
{
"code": null,
"e": 32777,
"s": 32761,
"text": "Data Structures"
},
{
"code": null,
"e": 32796,
"s": 32777,
"text": "Difference Between"
},
{
"code": null,
"e": 32808,
"s": 32796,
"text": "Linked List"
},
{
"code": null,
"e": 32824,
"s": 32808,
"text": "Data Structures"
},
{
"code": null,
"e": 32836,
"s": 32824,
"text": "Linked List"
},
{
"code": null,
"e": 32843,
"s": 32836,
"text": "Arrays"
},
{
"code": null,
"e": 32941,
"s": 32843,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32966,
"s": 32941,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32986,
"s": 32966,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 33024,
"s": 32986,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 33049,
"s": 33024,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 33134,
"s": 33049,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 33161,
"s": 33134,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 33195,
"s": 33161,
"text": "Deadlock Prevention And Avoidance"
},
{
"code": null,
"e": 33269,
"s": 33195,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 33313,
"s": 33269,
"text": "Functional Dependency and Attribute Closure"
}
] |
Display auto increment user id sequence number to begin from 001 in MySQL? | For this, use ZEROFILL and alter the table to begin from the same sequence −
alter table yourTableName
change yourColumnName yourColumnName int(3) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT PRIMARY KEY;
To understand the above syntax, let us first create a table −
mysql> create table DemoTable1958
(
UserId int,
UserName varchar(20)
);
Query OK, 0 rows affected (0.00 sec)
Here is the query to alter generated sequence number to begin from 001:
mysql> alter table DemoTable1958
change UserId UserId int(3) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT PRIMARY KEY;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the table description:
mysql> desc DemoTable1958;
This will produce the following output −
+----------+--------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------------------+------+-----+---------+----------------+
| UserId | int(3) unsigned zerofill | NO | PRI | NULL | auto_increment |
| UserName | varchar(20) | YES | | NULL | |
+----------+--------------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1958(UserName) values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1958(UserName) values('David');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1958;
This will produce the following output −
+--------+----------+
| UserId | UserName |
+--------+----------+
| 001 | Chris |
| 002 | David |
+--------+----------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "For this, use ZEROFILL and alter the table to begin from the same sequence −"
},
{
"code": null,
"e": 1267,
"s": 1139,
"text": "alter table yourTableName\n change yourColumnName yourColumnName int(3) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT PRIMARY KEY;"
},
{
"code": null,
"e": 1329,
"s": 1267,
"text": "To understand the above syntax, let us first create a table −"
},
{
"code": null,
"e": 1450,
"s": 1329,
"text": "mysql> create table DemoTable1958\n (\n UserId int,\n UserName varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 1522,
"s": 1450,
"text": "Here is the query to alter generated sequence number to begin from 001:"
},
{
"code": null,
"e": 1717,
"s": 1522,
"text": "mysql> alter table DemoTable1958\n change UserId UserId int(3) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT PRIMARY KEY;\nQuery OK, 0 rows affected (0.00 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 1753,
"s": 1717,
"text": "Let us check the table description:"
},
{
"code": null,
"e": 1780,
"s": 1753,
"text": "mysql> desc DemoTable1958;"
},
{
"code": null,
"e": 1821,
"s": 1780,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2326,
"s": 1821,
"text": "+----------+--------------------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+----------+--------------------------+------+-----+---------+----------------+\n| UserId | int(3) unsigned zerofill | NO | PRI | NULL | auto_increment |\n| UserName | varchar(20) | YES | | NULL | |\n+----------+--------------------------+------+-----+---------+----------------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2382,
"s": 2326,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2574,
"s": 2382,
"text": "mysql> insert into DemoTable1958(UserName) values('Chris');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1958(UserName) values('David');\nQuery OK, 1 row affected (0.00 sec)"
},
{
"code": null,
"e": 2634,
"s": 2574,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2670,
"s": 2634,
"text": "mysql> select * from DemoTable1958;"
},
{
"code": null,
"e": 2711,
"s": 2670,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2868,
"s": 2711,
"text": "+--------+----------+\n| UserId | UserName |\n+--------+----------+\n| 001 | Chris |\n| 002 | David |\n+--------+----------+\n2 rows in set (0.00 sec)"
}
] |
Ngx-Bootstrap - Buttons | ngx-bootstrap buttons have two specific directives which makes a group of buttons to behave as checkbox or radio buttons or hybrid where a radio button can be unchecked.
Add checkbox functionality to any element.
[btnCheckbox]
[btnCheckbox]
btnCheckboxFalse − boolean, Falsy value, will be set to ngModel, default: false
btnCheckboxFalse − boolean, Falsy value, will be set to ngModel, default: false
btnCheckboxTrue − boolean, Truthy value, will be set to ngModel, default: true
btnCheckboxTrue − boolean, Truthy value, will be set to ngModel, default: true
Create radio buttons or groups of buttons. A value of a selected button is bound to a variable specified via ngModel.
[btnRadio]
[btnRadio]
btnRadio − string, Radio button value, will be set to ngModel
btnRadio − string, Radio button value, will be set to ngModel
disabled − boolean, If true - radio button is disabled
disabled − boolean, If true - radio button is disabled
uncheckable − boolean, If true - radio button can be unchecked
uncheckable − boolean, If true - radio button can be unchecked
value − string, Current value of radio component or group
value − string, Current value of radio component or group
A group of radio buttons. A value of a selected button is bound to a variable specified via ngModel.
[btnRadioGroup]
[btnRadioGroup]
As we're going to use buttons, We've to update app.module.ts used in ngx-bootstrap Alerts chapter to use ButtonsModule. We're also adding support for input controls using FormModule.
Update app.module.ts to use the AlertModule and AlertConfig.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { AccordionModule } from 'ngx-bootstrap/accordion';
import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';
import { ButtonsModule } from 'ngx-bootstrap/buttons';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserAnimationsModule,
BrowserModule,
AccordionModule,
AlertModule,
ButtonsModule,
FormsModule
],
providers: [AlertConfig],
bootstrap: [AppComponent]
})
export class AppModule { }
Update test.component.html to use the buttons.
test.component.html
<button type="button" class="btn btn-primary" (click)="clicked()">
Single Button
</button>
<pre class="card card-block card-header">
{{clickCounter}}
</pre>
<p>Button as Checkbox</p>
<div class="btn-group">
<label class="btn btn-primary" [(ngModel)]="checkModel.left"
btnCheckbox tabindex="0" role="button">Left</label>
<label class="btn btn-primary" [(ngModel)]="checkModel.right"
btnCheckbox tabindex="0" role="button">Right</label>
</div>
<pre class="card card-block card-header">
{{checkModel | json}}
</pre>
<p>Button as RadionButton</p>
<div class="form-inline">
<div class="btn-group" btnRadioGroup [(ngModel)]="radioModel">
<label class="btn btn-success" btnRadio="Left">Left</label>
<label class="btn btn-success" btnRadio="Right">Right</label>
</div>
</div>
<pre class="card card-block card-header">
{{radioModel}}
</pre>
Update test.component.ts for corresponding variables and methods.
test.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
checkModel = { left: false, right: false };
radioModel = 'Left';
clickCounter = 0;
constructor() { }
ngOnInit(): void {
}
clicked(): void {
this.clickCounter++;
}
}
Run the following command to start the angular server.
ng serve
Once server is up and running. Open http://localhost:4200 and verify the following output.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2270,
"s": 2100,
"text": "ngx-bootstrap buttons have two specific directives which makes a group of buttons to behave as checkbox or radio buttons or hybrid where a radio button can be unchecked."
},
{
"code": null,
"e": 2313,
"s": 2270,
"text": "Add checkbox functionality to any element."
},
{
"code": null,
"e": 2327,
"s": 2313,
"text": "[btnCheckbox]"
},
{
"code": null,
"e": 2341,
"s": 2327,
"text": "[btnCheckbox]"
},
{
"code": null,
"e": 2421,
"s": 2341,
"text": "btnCheckboxFalse − boolean, Falsy value, will be set to ngModel, default: false"
},
{
"code": null,
"e": 2501,
"s": 2421,
"text": "btnCheckboxFalse − boolean, Falsy value, will be set to ngModel, default: false"
},
{
"code": null,
"e": 2580,
"s": 2501,
"text": "btnCheckboxTrue − boolean, Truthy value, will be set to ngModel, default: true"
},
{
"code": null,
"e": 2659,
"s": 2580,
"text": "btnCheckboxTrue − boolean, Truthy value, will be set to ngModel, default: true"
},
{
"code": null,
"e": 2777,
"s": 2659,
"text": "Create radio buttons or groups of buttons. A value of a selected button is bound to a variable specified via ngModel."
},
{
"code": null,
"e": 2788,
"s": 2777,
"text": "[btnRadio]"
},
{
"code": null,
"e": 2799,
"s": 2788,
"text": "[btnRadio]"
},
{
"code": null,
"e": 2861,
"s": 2799,
"text": "btnRadio − string, Radio button value, will be set to ngModel"
},
{
"code": null,
"e": 2923,
"s": 2861,
"text": "btnRadio − string, Radio button value, will be set to ngModel"
},
{
"code": null,
"e": 2978,
"s": 2923,
"text": "disabled − boolean, If true - radio button is disabled"
},
{
"code": null,
"e": 3033,
"s": 2978,
"text": "disabled − boolean, If true - radio button is disabled"
},
{
"code": null,
"e": 3096,
"s": 3033,
"text": "uncheckable − boolean, If true - radio button can be unchecked"
},
{
"code": null,
"e": 3159,
"s": 3096,
"text": "uncheckable − boolean, If true - radio button can be unchecked"
},
{
"code": null,
"e": 3217,
"s": 3159,
"text": "value − string, Current value of radio component or group"
},
{
"code": null,
"e": 3275,
"s": 3217,
"text": "value − string, Current value of radio component or group"
},
{
"code": null,
"e": 3376,
"s": 3275,
"text": "A group of radio buttons. A value of a selected button is bound to a variable specified via ngModel."
},
{
"code": null,
"e": 3392,
"s": 3376,
"text": "[btnRadioGroup]"
},
{
"code": null,
"e": 3408,
"s": 3392,
"text": "[btnRadioGroup]"
},
{
"code": null,
"e": 3591,
"s": 3408,
"text": "As we're going to use buttons, We've to update app.module.ts used in ngx-bootstrap Alerts chapter to use ButtonsModule. We're also adding support for input controls using FormModule."
},
{
"code": null,
"e": 3652,
"s": 3591,
"text": "Update app.module.ts to use the AlertModule and AlertConfig."
},
{
"code": null,
"e": 3666,
"s": 3652,
"text": "app.module.ts"
},
{
"code": null,
"e": 4491,
"s": 3666,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule\n ],\n providers: [AlertConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 4538,
"s": 4491,
"text": "Update test.component.html to use the buttons."
},
{
"code": null,
"e": 4558,
"s": 4538,
"text": "test.component.html"
},
{
"code": null,
"e": 5438,
"s": 4558,
"text": "<button type=\"button\" class=\"btn btn-primary\" (click)=\"clicked()\">\n Single Button\n</button>\n<pre class=\"card card-block card-header\">\n {{clickCounter}}\n</pre>\n<p>Button as Checkbox</p>\n<div class=\"btn-group\">\n <label class=\"btn btn-primary\" [(ngModel)]=\"checkModel.left\"\n btnCheckbox tabindex=\"0\" role=\"button\">Left</label>\n <label class=\"btn btn-primary\" [(ngModel)]=\"checkModel.right\"\n btnCheckbox tabindex=\"0\" role=\"button\">Right</label>\n</div>\n<pre class=\"card card-block card-header\">\n {{checkModel | json}}\n</pre>\n<p>Button as RadionButton</p>\n<div class=\"form-inline\">\n <div class=\"btn-group\" btnRadioGroup [(ngModel)]=\"radioModel\">\n <label class=\"btn btn-success\" btnRadio=\"Left\">Left</label>\n <label class=\"btn btn-success\" btnRadio=\"Right\">Right</label>\n </div>\n</div>\n<pre class=\"card card-block card-header\">\n {{radioModel}}\n</pre>"
},
{
"code": null,
"e": 5504,
"s": 5438,
"text": "Update test.component.ts for corresponding variables and methods."
},
{
"code": null,
"e": 5522,
"s": 5504,
"text": "test.component.ts"
},
{
"code": null,
"e": 5937,
"s": 5522,
"text": "import { Component, OnInit } from '@angular/core';\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n checkModel = { left: false, right: false };\n radioModel = 'Left';\n clickCounter = 0;\n constructor() { }\n\n ngOnInit(): void {\n }\n clicked(): void {\n this.clickCounter++;\n }\n}"
},
{
"code": null,
"e": 5992,
"s": 5937,
"text": "Run the following command to start the angular server."
},
{
"code": null,
"e": 6002,
"s": 5992,
"text": "ng serve\n"
},
{
"code": null,
"e": 6093,
"s": 6002,
"text": "Once server is up and running. Open http://localhost:4200 and verify the following output."
},
{
"code": null,
"e": 6100,
"s": 6093,
"text": " Print"
},
{
"code": null,
"e": 6111,
"s": 6100,
"text": " Add Notes"
}
] |
Merge two sorted arrays in Python using heapq - GeeksforGeeks | 23 Nov, 2020
Given two sorted arrays, the task is to merge them in a sorted manner.
Examples:
Input : arr1 = [1, 3, 4, 5]
arr2 = [2, 4, 6, 8]
Output : arr3 = [1, 2, 3, 4, 4, 5, 6, 8]
Input : arr1 = [5, 8, 9]
arr2 = [4, 7, 8]
Output : arr3 = [4, 5, 7, 8, 8, 9]
This problem has existing solution please refer Merge two sorted arrays link. We will solve this problem in python using heapq.merge() in a single line of code.
# Function to merge two sorted arraysfrom heapq import merge def mergeArray(arr1,arr2): return list(merge(arr1, arr2)) # Driver functionif __name__ == "__main__": arr1 = [1,3,4,5] arr2 = [2,4,6,8] print (mergeArray(arr1, arr2))
Output:
[1, 2, 3, 4, 4, 5, 6, 8]
This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.To create a heap, use a list initialized to [], or you can transform a populated list into a heap via function heapify().The following functions are provided:
heapq.heappush(heap,item) : Push the value item onto the heap, maintaining the heap invariant.
heapq.heappop(heap) : Pop and return the smallest item from the heap, maintaining the heap invariant. If the heap is empty, IndexError is raised. To access the smallest item without popping it, use heap[0].
heapq.heappushpop(heap, item) : Push item on the heap, then pop and return the smallest item from the heap. The combined action runs more efficiently than heappush() followed by a separate call to heappop().
heapq.heapify(x) : Transform list x into a heap, in-place, in linear time.
heapq.merge(*iterables) : Merge multiple sorted inputs into a single sorted output (for example, merge timestamped entries from multiple log files). Returns an iterator over the sorted values.This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
array-merge
Arrays
Heap
Python
Arrays
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
HeapSort
Binary Heap
Huffman Coding | Greedy Algo-3
Building Heap from Array
Sliding Window Maximum (Maximum of all subarrays of size k) | [
{
"code": null,
"e": 24429,
"s": 24401,
"text": "\n23 Nov, 2020"
},
{
"code": null,
"e": 24500,
"s": 24429,
"text": "Given two sorted arrays, the task is to merge them in a sorted manner."
},
{
"code": null,
"e": 24510,
"s": 24500,
"text": "Examples:"
},
{
"code": null,
"e": 24702,
"s": 24510,
"text": "Input : arr1 = [1, 3, 4, 5] \n arr2 = [2, 4, 6, 8]\nOutput : arr3 = [1, 2, 3, 4, 4, 5, 6, 8]\n\nInput : arr1 = [5, 8, 9] \n arr2 = [4, 7, 8]\nOutput : arr3 = [4, 5, 7, 8, 8, 9]\n"
},
{
"code": null,
"e": 24863,
"s": 24702,
"text": "This problem has existing solution please refer Merge two sorted arrays link. We will solve this problem in python using heapq.merge() in a single line of code."
},
{
"code": "# Function to merge two sorted arraysfrom heapq import merge def mergeArray(arr1,arr2): return list(merge(arr1, arr2)) # Driver functionif __name__ == \"__main__\": arr1 = [1,3,4,5] arr2 = [2,4,6,8] print (mergeArray(arr1, arr2))",
"e": 25107,
"s": 24863,
"text": null
},
{
"code": null,
"e": 25115,
"s": 25107,
"text": "Output:"
},
{
"code": null,
"e": 25141,
"s": 25115,
"text": "[1, 2, 3, 4, 4, 5, 6, 8]\n"
},
{
"code": null,
"e": 25411,
"s": 25141,
"text": "This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.To create a heap, use a list initialized to [], or you can transform a populated list into a heap via function heapify().The following functions are provided:"
},
{
"code": null,
"e": 25506,
"s": 25411,
"text": "heapq.heappush(heap,item) : Push the value item onto the heap, maintaining the heap invariant."
},
{
"code": null,
"e": 25713,
"s": 25506,
"text": "heapq.heappop(heap) : Pop and return the smallest item from the heap, maintaining the heap invariant. If the heap is empty, IndexError is raised. To access the smallest item without popping it, use heap[0]."
},
{
"code": null,
"e": 25921,
"s": 25713,
"text": "heapq.heappushpop(heap, item) : Push item on the heap, then pop and return the smallest item from the heap. The combined action runs more efficiently than heappush() followed by a separate call to heappop()."
},
{
"code": null,
"e": 25996,
"s": 25921,
"text": "heapq.heapify(x) : Transform list x into a heap, in-place, in linear time."
},
{
"code": null,
"e": 26658,
"s": 25996,
"text": "heapq.merge(*iterables) : Merge multiple sorted inputs into a single sorted output (for example, merge timestamped entries from multiple log files). Returns an iterator over the sorted values.This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 26969,
"s": 26658,
"text": "This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27094,
"s": 26969,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27106,
"s": 27094,
"text": "array-merge"
},
{
"code": null,
"e": 27113,
"s": 27106,
"text": "Arrays"
},
{
"code": null,
"e": 27118,
"s": 27113,
"text": "Heap"
},
{
"code": null,
"e": 27125,
"s": 27118,
"text": "Python"
},
{
"code": null,
"e": 27132,
"s": 27125,
"text": "Arrays"
},
{
"code": null,
"e": 27137,
"s": 27132,
"text": "Heap"
},
{
"code": null,
"e": 27235,
"s": 27137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27244,
"s": 27235,
"text": "Comments"
},
{
"code": null,
"e": 27257,
"s": 27244,
"text": "Old Comments"
},
{
"code": null,
"e": 27278,
"s": 27257,
"text": "Next Greater Element"
},
{
"code": null,
"e": 27303,
"s": 27278,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 27330,
"s": 27303,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 27379,
"s": 27330,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 27417,
"s": 27379,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 27426,
"s": 27417,
"text": "HeapSort"
},
{
"code": null,
"e": 27438,
"s": 27426,
"text": "Binary Heap"
},
{
"code": null,
"e": 27469,
"s": 27438,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 27494,
"s": 27469,
"text": "Building Heap from Array"
}
] |
Visualization of Quick sort using Matplotlib - GeeksforGeeks | 02 Sep, 2021
Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. For this we will use matplotlib, to plot bar graphs to represent the elements of the array,
Approach :
We will generate an array with random elements.The algorithm will be called on that array and yield statement will be used instead of return statement for visualization purposes.We will yield the current states of the array after comparing and swapping. Hence the algorithm will return a generator object.Matplotlib the animation will be used to visualize the comparing and swapping of the array.The array will be stored in a matplotlib bar container object (‘bar_rects’), where the size of each bar will be equal to the corresponding value of the element in the array.The inbuilt FuncAnimation method of matplotlib animation will pass the container and generator objects to the function used to create animation. Each frame of the animation corresponds to a single iteration of the generator.The animation function being repeatedly called will set the height of the rectangle equal to the value of the elements.
We will generate an array with random elements.
The algorithm will be called on that array and yield statement will be used instead of return statement for visualization purposes.
We will yield the current states of the array after comparing and swapping. Hence the algorithm will return a generator object.
Matplotlib the animation will be used to visualize the comparing and swapping of the array.
The array will be stored in a matplotlib bar container object (‘bar_rects’), where the size of each bar will be equal to the corresponding value of the element in the array.
The inbuilt FuncAnimation method of matplotlib animation will pass the container and generator objects to the function used to create animation. Each frame of the animation corresponds to a single iteration of the generator.
The animation function being repeatedly called will set the height of the rectangle equal to the value of the elements.
python3
# import all the modulesimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationfrom mpl_toolkits.mplot3d import axes3dimport matplotlib as mpimport numpy as npimport random # quicksort functiondef quicksort(a, l, r): if l >= r: return x = a[l] j = l for i in range(l + 1, r + 1): if a[i] <= x: j += 1 a[j], a[i] = a[i], a[j] yield a a[l], a[j]= a[j], a[l] yield a # yield from statement used to yield # the array after dividing yield from quicksort(a, l, j-1) yield from quicksort(a, j + 1, r) # function to plot barsdef showGraph(): # for random unique values n = int(input("enter array size\n")) a = [i for i in range(1, n + 1)] random.shuffle(a) datasetName ='Random' # generator object returned by the function generator = quicksort(a, 0, n-1) algoName = 'Quick Sort' # style of the chart plt.style.use('fivethirtyeight') # set colors of the bars data_normalizer = mp.colors.Normalize() color_map = mp.colors.LinearSegmentedColormap( "my_map", { "red": [(0, 1.0, 1.0), (1.0, .5, .5)], "green": [(0, 0.5, 0.5), (1.0, 0, 0)], "blue": [(0, 0.50, 0.5), (1.0, 0, 0)] } ) fig, ax = plt.subplots() # bar container bar_rects = ax.bar(range(len(a)), a, align ="edge", color = color_map(data_normalizer(range(n)))) # setting the limits of x and y axes ax.set_xlim(0, len(a)) ax.set_ylim(0, int(1.1 * len(a))) ax.set_title("ALGORITHM : "+ algoName + "\n" + "DATA SET : " + datasetName, fontdict = {'fontsize': 13, 'fontweight': 'medium', 'color' : '#E4365D'}) # the text to be shown on the upper left indicating the number of iterations # transform indicates the position with relevance to the axes coordinates. text = ax.text(0.01, 0.95, "", transform = ax.transAxes, color = "#E4365D") iteration = [0] def animate(A, rects, iteration): for rect, val in zip(rects, A): # setting the size of each bar equal to the value of the elements rect.set_height(val) iteration[0] += 1 text.set_text("iterations : {}".format(iteration[0])) # call animate function repeatedly anim = FuncAnimation(fig, func = animate, fargs = (bar_rects, iteration), frames = generator, interval = 50, repeat = False) plt.show() showGraph()
Output :
For array size 20
rajeev0719singh
Python-matplotlib
Quick Sort
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python | [
{
"code": null,
"e": 29911,
"s": 29883,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 30165,
"s": 29911,
"text": "Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. For this we will use matplotlib, to plot bar graphs to represent the elements of the array, "
},
{
"code": null,
"e": 30176,
"s": 30165,
"text": "Approach :"
},
{
"code": null,
"e": 31089,
"s": 30176,
"text": "We will generate an array with random elements.The algorithm will be called on that array and yield statement will be used instead of return statement for visualization purposes.We will yield the current states of the array after comparing and swapping. Hence the algorithm will return a generator object.Matplotlib the animation will be used to visualize the comparing and swapping of the array.The array will be stored in a matplotlib bar container object (‘bar_rects’), where the size of each bar will be equal to the corresponding value of the element in the array.The inbuilt FuncAnimation method of matplotlib animation will pass the container and generator objects to the function used to create animation. Each frame of the animation corresponds to a single iteration of the generator.The animation function being repeatedly called will set the height of the rectangle equal to the value of the elements."
},
{
"code": null,
"e": 31137,
"s": 31089,
"text": "We will generate an array with random elements."
},
{
"code": null,
"e": 31269,
"s": 31137,
"text": "The algorithm will be called on that array and yield statement will be used instead of return statement for visualization purposes."
},
{
"code": null,
"e": 31397,
"s": 31269,
"text": "We will yield the current states of the array after comparing and swapping. Hence the algorithm will return a generator object."
},
{
"code": null,
"e": 31489,
"s": 31397,
"text": "Matplotlib the animation will be used to visualize the comparing and swapping of the array."
},
{
"code": null,
"e": 31663,
"s": 31489,
"text": "The array will be stored in a matplotlib bar container object (‘bar_rects’), where the size of each bar will be equal to the corresponding value of the element in the array."
},
{
"code": null,
"e": 31888,
"s": 31663,
"text": "The inbuilt FuncAnimation method of matplotlib animation will pass the container and generator objects to the function used to create animation. Each frame of the animation corresponds to a single iteration of the generator."
},
{
"code": null,
"e": 32008,
"s": 31888,
"text": "The animation function being repeatedly called will set the height of the rectangle equal to the value of the elements."
},
{
"code": null,
"e": 32016,
"s": 32008,
"text": "python3"
},
{
"code": "# import all the modulesimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationfrom mpl_toolkits.mplot3d import axes3dimport matplotlib as mpimport numpy as npimport random # quicksort functiondef quicksort(a, l, r): if l >= r: return x = a[l] j = l for i in range(l + 1, r + 1): if a[i] <= x: j += 1 a[j], a[i] = a[i], a[j] yield a a[l], a[j]= a[j], a[l] yield a # yield from statement used to yield # the array after dividing yield from quicksort(a, l, j-1) yield from quicksort(a, j + 1, r) # function to plot barsdef showGraph(): # for random unique values n = int(input(\"enter array size\\n\")) a = [i for i in range(1, n + 1)] random.shuffle(a) datasetName ='Random' # generator object returned by the function generator = quicksort(a, 0, n-1) algoName = 'Quick Sort' # style of the chart plt.style.use('fivethirtyeight') # set colors of the bars data_normalizer = mp.colors.Normalize() color_map = mp.colors.LinearSegmentedColormap( \"my_map\", { \"red\": [(0, 1.0, 1.0), (1.0, .5, .5)], \"green\": [(0, 0.5, 0.5), (1.0, 0, 0)], \"blue\": [(0, 0.50, 0.5), (1.0, 0, 0)] } ) fig, ax = plt.subplots() # bar container bar_rects = ax.bar(range(len(a)), a, align =\"edge\", color = color_map(data_normalizer(range(n)))) # setting the limits of x and y axes ax.set_xlim(0, len(a)) ax.set_ylim(0, int(1.1 * len(a))) ax.set_title(\"ALGORITHM : \"+ algoName + \"\\n\" + \"DATA SET : \" + datasetName, fontdict = {'fontsize': 13, 'fontweight': 'medium', 'color' : '#E4365D'}) # the text to be shown on the upper left indicating the number of iterations # transform indicates the position with relevance to the axes coordinates. text = ax.text(0.01, 0.95, \"\", transform = ax.transAxes, color = \"#E4365D\") iteration = [0] def animate(A, rects, iteration): for rect, val in zip(rects, A): # setting the size of each bar equal to the value of the elements rect.set_height(val) iteration[0] += 1 text.set_text(\"iterations : {}\".format(iteration[0])) # call animate function repeatedly anim = FuncAnimation(fig, func = animate, fargs = (bar_rects, iteration), frames = generator, interval = 50, repeat = False) plt.show() showGraph()",
"e": 34557,
"s": 32016,
"text": null
},
{
"code": null,
"e": 34568,
"s": 34557,
"text": "Output : "
},
{
"code": null,
"e": 34586,
"s": 34568,
"text": "For array size 20"
},
{
"code": null,
"e": 34606,
"s": 34590,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 34624,
"s": 34606,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 34635,
"s": 34624,
"text": "Quick Sort"
},
{
"code": null,
"e": 34642,
"s": 34635,
"text": "Python"
},
{
"code": null,
"e": 34740,
"s": 34642,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34749,
"s": 34740,
"text": "Comments"
},
{
"code": null,
"e": 34762,
"s": 34749,
"text": "Old Comments"
},
{
"code": null,
"e": 34790,
"s": 34762,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 34840,
"s": 34790,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 34862,
"s": 34840,
"text": "Python map() function"
},
{
"code": null,
"e": 34906,
"s": 34862,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 34924,
"s": 34906,
"text": "Python Dictionary"
},
{
"code": null,
"e": 34947,
"s": 34924,
"text": "Taking input in Python"
},
{
"code": null,
"e": 34982,
"s": 34947,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 35004,
"s": 34982,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 35036,
"s": 35004,
"text": "How to Install PIP on Windows ?"
}
] |
exec() in Python | Exec function can dynamically execute code of python programs. The code can be passed in as string or object code to this function. The object code is executed as is while the string is first parsed and checked for any syntax error. If no syntax error, then the parsed string is executed as a python statement.
exec(object, globals, locals)
Where
Object − A string or a code object passed onto the method.
Object − A string or a code object passed onto the method.
globals − A dictionary of available global methods and variables.
globals − A dictionary of available global methods and variables.
locals − A dictionary of available local methods and variables.
locals − A dictionary of available local methods and variables.
In the below example we pass a single line of code as string to the exec() function. Itr gets parsed and executed to give the output.
x = 9
exec ('print(5*x)')
Running the above code gives us the following result −
45
Now we see how to pass a block of code with multiple code statements. As it is a code object, it gets executed directly giving the result. Please note how we have used \n and space to create a python code block with proper indention.
prog_block = 'x = 3 \nif(x < 5): \n print x*x'
exec(prog_block)
Running the above code gives us the following result −
9
When we do not pass any value for global and local parameter we get the default available functions as per the package imported into the program. In the below example we see the code giving us all the available functions when both global and local parameter values are skipped.
from time import *
exec("print(dir())")
Running the above code gives us the following result −
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__file__', '__name__',
'__package__', '_dh', '_exit_code', '_i', '_i1', '_i10', '_i11', '_i12', '_i13', '_i14', '_i15',
'_i16', '_i17', '_i18', '_i19', '_i2', '_i20', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'clock',
'copysign', 'cos', 'cosh', 'ctime', 'daylight', 'degrees', 'e', 'erf', 'erfc', 'exit', 'exp', 'expm1',
'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'get_ipython', 'gmtime', 'hypot',
'isinf', 'isnan', 'ldexp', 'lgamma', 'localtime', 'log', 'log10', 'log1p', 'mktime', 'modf', 'pi',
'pow', 'prog', 'prog_block', 'quit', 'radians', 'sin', 'sinh', 'sleep', 'sqrt', 'strftime', 'strptime',
'struct_time', 'tan', 'tanh', 'time', 'timezone', 'trunc', 'tzname', 'x']
We can restrict the access to any of the functions of the imported module by passing on an empty dictionary as the global parameter. In this case the result will show only the built-in function and it will not show any of the function from the imported module. That is how we restrict and make the function more secure.
Live Demo
from time import *
exec("print(dir())",{})
Running the above code gives us the following result −
['__builtins__']
Next we see how we can apply only certain chosen functions to the exec() method from the imported module. In the below example we allow only the required function as a parameter with the Global option. The localtime() function is part of the time module which is imported in the program.Example
Live Demo
from time import *
exec("print lclt()",{"lclt":localtime})
Running the above code gives us the following result −
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=19, tm_hour=12, tm_min=33, tm_sec=53, tm_wday=4, tm_yday=200, tm_isdst=0)
We can also restrict the usage of various functions form the imported modules by using the local parameter and excluding the built in functions completely. In the below example we choose None as the value for built-in global parameter.
Live Demo
from time import *
exec("print(dir())", {"__builtins__" : None}, {"gtime": gmtime, "print": print, "dir": dir})
Running the above code gives us the following result −
['dir', 'gtime', 'print'] | [
{
"code": null,
"e": 1373,
"s": 1062,
"text": "Exec function can dynamically execute code of python programs. The code can be passed in as string or object code to this function. The object code is executed as is while the string is first parsed and checked for any syntax error. If no syntax error, then the parsed string is executed as a python statement."
},
{
"code": null,
"e": 1403,
"s": 1373,
"text": "exec(object, globals, locals)"
},
{
"code": null,
"e": 1409,
"s": 1403,
"text": "Where"
},
{
"code": null,
"e": 1468,
"s": 1409,
"text": "Object − A string or a code object passed onto the method."
},
{
"code": null,
"e": 1527,
"s": 1468,
"text": "Object − A string or a code object passed onto the method."
},
{
"code": null,
"e": 1593,
"s": 1527,
"text": "globals − A dictionary of available global methods and variables."
},
{
"code": null,
"e": 1659,
"s": 1593,
"text": "globals − A dictionary of available global methods and variables."
},
{
"code": null,
"e": 1723,
"s": 1659,
"text": "locals − A dictionary of available local methods and variables."
},
{
"code": null,
"e": 1787,
"s": 1723,
"text": "locals − A dictionary of available local methods and variables."
},
{
"code": null,
"e": 1921,
"s": 1787,
"text": "In the below example we pass a single line of code as string to the exec() function. Itr gets parsed and executed to give the output."
},
{
"code": null,
"e": 1947,
"s": 1921,
"text": "x = 9\nexec ('print(5*x)')"
},
{
"code": null,
"e": 2002,
"s": 1947,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2005,
"s": 2002,
"text": "45"
},
{
"code": null,
"e": 2239,
"s": 2005,
"text": "Now we see how to pass a block of code with multiple code statements. As it is a code object, it gets executed directly giving the result. Please note how we have used \\n and space to create a python code block with proper indention."
},
{
"code": null,
"e": 2303,
"s": 2239,
"text": "prog_block = 'x = 3 \\nif(x < 5): \\n print x*x'\nexec(prog_block)"
},
{
"code": null,
"e": 2358,
"s": 2303,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2360,
"s": 2358,
"text": "9"
},
{
"code": null,
"e": 2638,
"s": 2360,
"text": "When we do not pass any value for global and local parameter we get the default available functions as per the package imported into the program. In the below example we see the code giving us all the available functions when both global and local parameter values are skipped."
},
{
"code": null,
"e": 2678,
"s": 2638,
"text": "from time import *\nexec(\"print(dir())\")"
},
{
"code": null,
"e": 2733,
"s": 2678,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3512,
"s": 2733,
"text": "['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__file__', '__name__', \n'__package__', '_dh', '_exit_code', '_i', '_i1', '_i10', '_i11', '_i12', '_i13', '_i14', '_i15',\n '_i16', '_i17', '_i18', '_i19', '_i2', '_i20', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'clock', \n'copysign', 'cos', 'cosh', 'ctime', 'daylight', 'degrees', 'e', 'erf', 'erfc', 'exit', 'exp', 'expm1', \n'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'get_ipython', 'gmtime', 'hypot', \n'isinf', 'isnan', 'ldexp', 'lgamma', 'localtime', 'log', 'log10', 'log1p', 'mktime', 'modf', 'pi', \n'pow', 'prog', 'prog_block', 'quit', 'radians', 'sin', 'sinh', 'sleep', 'sqrt', 'strftime', 'strptime', \n'struct_time', 'tan', 'tanh', 'time', 'timezone', 'trunc', 'tzname', 'x']"
},
{
"code": null,
"e": 3832,
"s": 3512,
"text": "We can restrict the access to any of the functions of the imported module by passing on an empty dictionary as the global parameter. In this case the result will show only the built-in function and it will not show any of the function from the imported module. That is how we restrict and make the function more secure."
},
{
"code": null,
"e": 3843,
"s": 3832,
"text": " Live Demo"
},
{
"code": null,
"e": 3886,
"s": 3843,
"text": "from time import *\nexec(\"print(dir())\",{})"
},
{
"code": null,
"e": 3941,
"s": 3886,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3958,
"s": 3941,
"text": "['__builtins__']"
},
{
"code": null,
"e": 4253,
"s": 3958,
"text": "Next we see how we can apply only certain chosen functions to the exec() method from the imported module. In the below example we allow only the required function as a parameter with the Global option. The localtime() function is part of the time module which is imported in the program.Example"
},
{
"code": null,
"e": 4264,
"s": 4253,
"text": " Live Demo"
},
{
"code": null,
"e": 4323,
"s": 4264,
"text": "from time import *\nexec(\"print lclt()\",{\"lclt\":localtime})"
},
{
"code": null,
"e": 4378,
"s": 4323,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 4501,
"s": 4378,
"text": "time.struct_time(tm_year=2019, tm_mon=7, tm_mday=19, tm_hour=12, tm_min=33, tm_sec=53, tm_wday=4, tm_yday=200, tm_isdst=0)"
},
{
"code": null,
"e": 4737,
"s": 4501,
"text": "We can also restrict the usage of various functions form the imported modules by using the local parameter and excluding the built in functions completely. In the below example we choose None as the value for built-in global parameter."
},
{
"code": null,
"e": 4748,
"s": 4737,
"text": " Live Demo"
},
{
"code": null,
"e": 4860,
"s": 4748,
"text": "from time import *\nexec(\"print(dir())\", {\"__builtins__\" : None}, {\"gtime\": gmtime, \"print\": print, \"dir\": dir})"
},
{
"code": null,
"e": 4915,
"s": 4860,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 4941,
"s": 4915,
"text": "['dir', 'gtime', 'print']"
}
] |
D3.js bezierCurveTo() Function - GeeksforGeeks | 07 Aug, 2020
The d3.bezierCurveTo() function in d3.js is used to draw the cubic-bezier segment to a certain point from the current given point via certain control points.
Syntax:
path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y);
Parameters: This function takes the following parameters.
cpx1: It is the x1-coordinate of the bezier control point.
cpy1: It is the y1-coordinate of the bezier control point.
cpx2: It is the x2-coordinate of the bezier control point.
cpy2: It is the y2-coordinate of the bezier control point.
x: It is the x-coordinate of the endpoints.
y: It is the y-coordinate of the endpoint.
Return Value: This function does not return any value.
Example 1:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width,initial-scale=1.0"> <script src= "https://d3js.org/d3.v4.min.js"> </script> <style> h1 { color: green; } svg { background-color: #f2f2f2; } .path2 { stroke: #000; } </style></head> <body> <div> <h1>GeeksforGeeks</h1> <b>D3.js | Path.bezierCurveTo() Function</b> <br><br> <svg width="100" height="100"> <path class="path2"> </svg> </div> <script> // Creating a path var path = d3.path(); path.moveTo(10, 10); path.bezierCurveTo(95, 10, 50, 90, 10, 10) // Closing the path path.closePath(); d3.select(".path2").attr("d", path); </script></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width,initial-scale=1.0"> <script src= "https://d3js.org/d3.v4.min.js"> </script> <style> h1 { color: green; } svg { background-color: #f2f2f2; } .path2 { stroke: #000; } </style></head> <body> <div> <h1>GeeksforGeeks</h1> <b>D3.js | Path.bezierCurveTo() Function</b> <br><br> <svg width="100" height="100"> <path class="path2"> </svg> </div> <script> // Creating a path var path = d3.path(); path.moveTo(10, 10); path.bezierCurveTo(95, 10, 50, 90, 10, 10) // Closing the path path.closePath(); path.bezierCurveTo(90, 10, 15, 110, 10, 10) // Closing the path path.closePath(); d3.select(".path2").attr("d", path); </script></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24364,
"s": 24336,
"text": "\n07 Aug, 2020"
},
{
"code": null,
"e": 24522,
"s": 24364,
"text": "The d3.bezierCurveTo() function in d3.js is used to draw the cubic-bezier segment to a certain point from the current given point via certain control points."
},
{
"code": null,
"e": 24530,
"s": 24522,
"text": "Syntax:"
},
{
"code": null,
"e": 24580,
"s": 24530,
"text": "path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y);"
},
{
"code": null,
"e": 24638,
"s": 24580,
"text": "Parameters: This function takes the following parameters."
},
{
"code": null,
"e": 24697,
"s": 24638,
"text": "cpx1: It is the x1-coordinate of the bezier control point."
},
{
"code": null,
"e": 24756,
"s": 24697,
"text": "cpy1: It is the y1-coordinate of the bezier control point."
},
{
"code": null,
"e": 24815,
"s": 24756,
"text": "cpx2: It is the x2-coordinate of the bezier control point."
},
{
"code": null,
"e": 24874,
"s": 24815,
"text": "cpy2: It is the y2-coordinate of the bezier control point."
},
{
"code": null,
"e": 24918,
"s": 24874,
"text": "x: It is the x-coordinate of the endpoints."
},
{
"code": null,
"e": 24961,
"s": 24918,
"text": "y: It is the y-coordinate of the endpoint."
},
{
"code": null,
"e": 25016,
"s": 24961,
"text": "Return Value: This function does not return any value."
},
{
"code": null,
"e": 25027,
"s": 25016,
"text": "Example 1:"
},
{
"code": null,
"e": 25032,
"s": 25027,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width,initial-scale=1.0\"> <script src= \"https://d3js.org/d3.v4.min.js\"> </script> <style> h1 { color: green; } svg { background-color: #f2f2f2; } .path2 { stroke: #000; } </style></head> <body> <div> <h1>GeeksforGeeks</h1> <b>D3.js | Path.bezierCurveTo() Function</b> <br><br> <svg width=\"100\" height=\"100\"> <path class=\"path2\"> </svg> </div> <script> // Creating a path var path = d3.path(); path.moveTo(10, 10); path.bezierCurveTo(95, 10, 50, 90, 10, 10) // Closing the path path.closePath(); d3.select(\".path2\").attr(\"d\", path); </script></body> </html>",
"e": 25940,
"s": 25032,
"text": null
},
{
"code": null,
"e": 25948,
"s": 25940,
"text": "Output:"
},
{
"code": null,
"e": 25959,
"s": 25948,
"text": "Example 2:"
},
{
"code": null,
"e": 25964,
"s": 25959,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width,initial-scale=1.0\"> <script src= \"https://d3js.org/d3.v4.min.js\"> </script> <style> h1 { color: green; } svg { background-color: #f2f2f2; } .path2 { stroke: #000; } </style></head> <body> <div> <h1>GeeksforGeeks</h1> <b>D3.js | Path.bezierCurveTo() Function</b> <br><br> <svg width=\"100\" height=\"100\"> <path class=\"path2\"> </svg> </div> <script> // Creating a path var path = d3.path(); path.moveTo(10, 10); path.bezierCurveTo(95, 10, 50, 90, 10, 10) // Closing the path path.closePath(); path.bezierCurveTo(90, 10, 15, 110, 10, 10) // Closing the path path.closePath(); d3.select(\".path2\").attr(\"d\", path); </script></body> </html>",
"e": 26986,
"s": 25964,
"text": null
},
{
"code": null,
"e": 26994,
"s": 26986,
"text": "Output:"
},
{
"code": null,
"e": 27000,
"s": 26994,
"text": "D3.js"
},
{
"code": null,
"e": 27011,
"s": 27000,
"text": "JavaScript"
},
{
"code": null,
"e": 27028,
"s": 27011,
"text": "Web Technologies"
},
{
"code": null,
"e": 27126,
"s": 27028,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27171,
"s": 27126,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27232,
"s": 27171,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27304,
"s": 27232,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27356,
"s": 27304,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27402,
"s": 27356,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 27444,
"s": 27402,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27477,
"s": 27444,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27520,
"s": 27477,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27582,
"s": 27520,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Rearrange characters to form palindrome if possible - GeeksforGeeks | 02 Mar, 2022
Given a string, convert the string to palindrome without any modifications like adding a character, removing a character, replacing a character etc.
Examples:
Input : "mdaam"
Output : "madam" or "amdma"
Input : "abb"
Output : "bab"
Input : "geeksforgeeks"
Output : "No Palindrome"
1. Count occurrences of all characters. 2. Count odd occurrences. If this count is greater than 1 or is equal to 1 and length of the string is even then obviously palindrome cannot be formed from the given string. 3. Initialize two empty strings firstHalf and secondHalf. 4. Traverse the map. For every character with count as count, attach count/2 characters to end of firstHalf and beginning of secondHalf. 5. Finally return the result by appending firstHalf and secondHalf
C++
Java
Python3
Javascript
// C++ program to rearrange a string to// make palindrome.#include <bits/stdc++.h>using namespace std; string getPalindrome(string str){ // Store counts of characters unordered_map<char, int> hmap; for (int i = 0; i < str.length(); i++) hmap[str[i]]++; /* find the number of odd elements. Takes O(n) */ int oddCount = 0; char oddChar; for (auto x : hmap) { if (x.second % 2 != 0) { oddCount++; oddChar = x.first; } } /* odd_cnt = 1 only if the length of str is odd */ if (oddCount > 1 || oddCount == 1 && str.length() % 2 == 0) return "NO PALINDROME"; /* Generate first halh of palindrome */ string firstHalf = "", secondHalf = ""; for (auto x : hmap) { // Build a string of floor(count/2) // occurrences of current character string s(x.second / 2, x.first); // Attach the built string to end of // and begin of second half firstHalf = firstHalf + s; secondHalf = s + secondHalf; } // Insert odd character if there // is any return (oddCount == 1) ? (firstHalf + oddChar + secondHalf) : (firstHalf + secondHalf);} int main(){ string s = "mdaam"; cout << getPalindrome(s); return 0;}
// Java program to rearrange a string to// make palindromeimport java.util.HashMap;import java.util.Map.Entry; class GFG{ public static String getPalindrome(String str){ // Store counts of characters HashMap<Character, Integer> counting = new HashMap<>(); for(char ch : str.toCharArray()) { if (counting.containsKey(ch)) { counting.put(ch, counting.get(ch) + 1); } else { counting.put(ch, 1); } } /* Find the number of odd elements. Takes O(n) */ int oddCount = 0; char oddChar = 0; for(Entry<Character, Integer> itr : counting.entrySet()) { if (itr.getValue() % 2 != 0) { oddCount++; oddChar = itr.getKey(); } } /* odd_cnt = 1 only if the length of str is odd */ if (oddCount > 1 || oddCount == 1 && str.length() % 2 == 0) { return "NO PALINDROME"; } /* Generate first halh of palindrome */ String firstHalf = "", lastHalf = ""; for(Entry<Character, Integer> itr : counting.entrySet()) { // Build a string of floor(count/2) // occurrences of current character String ss = ""; for(int i = 0; i < itr.getValue() / 2; i++) { ss += itr.getKey(); } // Attach the built string to end of // and begin of second half firstHalf = firstHalf + ss; lastHalf = ss + lastHalf; } // Insert odd character if there // is any return (oddCount == 1) ? (firstHalf + oddChar + lastHalf) : (firstHalf + lastHalf);} // Driver codepublic static void main(String[] args){ String str = "mdaam"; System.out.println(getPalindrome(str));}} // This code is contributed by Satyam Singh
# Python3 program to rearrange a string to# make palindrome.from collections import defaultdict def getPalindrome(st): # Store counts of characters hmap = defaultdict(int) for i in range(len(st)): hmap[st[i]] += 1 # Find the number of odd elements. # Takes O(n) oddCount = 0 for x in hmap: if (hmap[x] % 2 != 0): oddCount += 1 oddChar = x # odd_cnt = 1 only if the length of # str is odd if (oddCount > 1 or oddCount == 1 and len(st) % 2 == 0): return "NO PALINDROME" # Generate first halh of palindrome firstHalf = "" secondHalf = "" for x in sorted(hmap.keys()): # Build a string of floor(count/2) # occurrences of current character s = (hmap[x] // 2) * x # Attach the built string to end of # and begin of second half firstHalf = firstHalf + s secondHalf = s + secondHalf # Insert odd character if there # is any if (oddCount == 1): return (firstHalf + oddChar + secondHalf) else: return (firstHalf + secondHalf) # Driver codeif __name__ == "__main__": s = "mdaam" print(getPalindrome(s)) # This code is contributed by ukasp
<script> // JavaScript program to rearrange a string to// make palindrome.function getPalindrome(str){ // Store counts of characters let hmap = new Map(); for (let i = 0; i < str.length; i++){ if(hmap.has(str[i])){ hmap.set(str[i],hmap.get(str[i])+1); } else{ hmap.set(str[i],1); } } /* find the number of odd elements. Takes O(n) */ let oddCount = 0; let oddChar; for (let [x,y] of hmap) { if (y % 2 != 0) { oddCount++; oddChar = x; } } /* odd_cnt = 1 only if the length of str is odd */ if (oddCount > 1 || oddCount == 1 && str.length % 2 == 0) return "NO PALINDROME"; /* Generate first halh of palindrome */ let firstHalf = "", secondHalf = ""; for (let [x,y] of hmap) { // Build a string of floor(count/2) // occurrences of current character let s = ""; for(let i = 0; i < Math.floor(y/2); i++){ s += x; } // Attach the built string to end of // and begin of second half firstHalf = firstHalf + s; secondHalf = s + secondHalf; } // Insert odd character if there // is any return (oddCount == 1) ? (firstHalf + oddChar + secondHalf) : (firstHalf + secondHalf);} // driver programlet s = "mdaam";document.write(getPalindrome(s)); // This code is contributed by shinjanpatra.</script>
amdma
ukasp
satyamsinghkv2
shinjanpatra
cpp-unordered_map
frequency-counting
palindrome
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
Length of the longest substring without repeating characters
How to split a string in C/C++, Python and Java? | [
{
"code": null,
"e": 24998,
"s": 24970,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 25148,
"s": 24998,
"text": "Given a string, convert the string to palindrome without any modifications like adding a character, removing a character, replacing a character etc. "
},
{
"code": null,
"e": 25159,
"s": 25148,
"text": "Examples: "
},
{
"code": null,
"e": 25283,
"s": 25159,
"text": "Input : \"mdaam\"\nOutput : \"madam\" or \"amdma\"\n\nInput : \"abb\"\nOutput : \"bab\"\n\nInput : \"geeksforgeeks\"\nOutput : \"No Palindrome\""
},
{
"code": null,
"e": 25759,
"s": 25283,
"text": "1. Count occurrences of all characters. 2. Count odd occurrences. If this count is greater than 1 or is equal to 1 and length of the string is even then obviously palindrome cannot be formed from the given string. 3. Initialize two empty strings firstHalf and secondHalf. 4. Traverse the map. For every character with count as count, attach count/2 characters to end of firstHalf and beginning of secondHalf. 5. Finally return the result by appending firstHalf and secondHalf"
},
{
"code": null,
"e": 25763,
"s": 25759,
"text": "C++"
},
{
"code": null,
"e": 25768,
"s": 25763,
"text": "Java"
},
{
"code": null,
"e": 25776,
"s": 25768,
"text": "Python3"
},
{
"code": null,
"e": 25787,
"s": 25776,
"text": "Javascript"
},
{
"code": "// C++ program to rearrange a string to// make palindrome.#include <bits/stdc++.h>using namespace std; string getPalindrome(string str){ // Store counts of characters unordered_map<char, int> hmap; for (int i = 0; i < str.length(); i++) hmap[str[i]]++; /* find the number of odd elements. Takes O(n) */ int oddCount = 0; char oddChar; for (auto x : hmap) { if (x.second % 2 != 0) { oddCount++; oddChar = x.first; } } /* odd_cnt = 1 only if the length of str is odd */ if (oddCount > 1 || oddCount == 1 && str.length() % 2 == 0) return \"NO PALINDROME\"; /* Generate first halh of palindrome */ string firstHalf = \"\", secondHalf = \"\"; for (auto x : hmap) { // Build a string of floor(count/2) // occurrences of current character string s(x.second / 2, x.first); // Attach the built string to end of // and begin of second half firstHalf = firstHalf + s; secondHalf = s + secondHalf; } // Insert odd character if there // is any return (oddCount == 1) ? (firstHalf + oddChar + secondHalf) : (firstHalf + secondHalf);} int main(){ string s = \"mdaam\"; cout << getPalindrome(s); return 0;}",
"e": 27083,
"s": 25787,
"text": null
},
{
"code": "// Java program to rearrange a string to// make palindromeimport java.util.HashMap;import java.util.Map.Entry; class GFG{ public static String getPalindrome(String str){ // Store counts of characters HashMap<Character, Integer> counting = new HashMap<>(); for(char ch : str.toCharArray()) { if (counting.containsKey(ch)) { counting.put(ch, counting.get(ch) + 1); } else { counting.put(ch, 1); } } /* Find the number of odd elements. Takes O(n) */ int oddCount = 0; char oddChar = 0; for(Entry<Character, Integer> itr : counting.entrySet()) { if (itr.getValue() % 2 != 0) { oddCount++; oddChar = itr.getKey(); } } /* odd_cnt = 1 only if the length of str is odd */ if (oddCount > 1 || oddCount == 1 && str.length() % 2 == 0) { return \"NO PALINDROME\"; } /* Generate first halh of palindrome */ String firstHalf = \"\", lastHalf = \"\"; for(Entry<Character, Integer> itr : counting.entrySet()) { // Build a string of floor(count/2) // occurrences of current character String ss = \"\"; for(int i = 0; i < itr.getValue() / 2; i++) { ss += itr.getKey(); } // Attach the built string to end of // and begin of second half firstHalf = firstHalf + ss; lastHalf = ss + lastHalf; } // Insert odd character if there // is any return (oddCount == 1) ? (firstHalf + oddChar + lastHalf) : (firstHalf + lastHalf);} // Driver codepublic static void main(String[] args){ String str = \"mdaam\"; System.out.println(getPalindrome(str));}} // This code is contributed by Satyam Singh",
"e": 28914,
"s": 27083,
"text": null
},
{
"code": "# Python3 program to rearrange a string to# make palindrome.from collections import defaultdict def getPalindrome(st): # Store counts of characters hmap = defaultdict(int) for i in range(len(st)): hmap[st[i]] += 1 # Find the number of odd elements. # Takes O(n) oddCount = 0 for x in hmap: if (hmap[x] % 2 != 0): oddCount += 1 oddChar = x # odd_cnt = 1 only if the length of # str is odd if (oddCount > 1 or oddCount == 1 and len(st) % 2 == 0): return \"NO PALINDROME\" # Generate first halh of palindrome firstHalf = \"\" secondHalf = \"\" for x in sorted(hmap.keys()): # Build a string of floor(count/2) # occurrences of current character s = (hmap[x] // 2) * x # Attach the built string to end of # and begin of second half firstHalf = firstHalf + s secondHalf = s + secondHalf # Insert odd character if there # is any if (oddCount == 1): return (firstHalf + oddChar + secondHalf) else: return (firstHalf + secondHalf) # Driver codeif __name__ == \"__main__\": s = \"mdaam\" print(getPalindrome(s)) # This code is contributed by ukasp",
"e": 30132,
"s": 28914,
"text": null
},
{
"code": "<script> // JavaScript program to rearrange a string to// make palindrome.function getPalindrome(str){ // Store counts of characters let hmap = new Map(); for (let i = 0; i < str.length; i++){ if(hmap.has(str[i])){ hmap.set(str[i],hmap.get(str[i])+1); } else{ hmap.set(str[i],1); } } /* find the number of odd elements. Takes O(n) */ let oddCount = 0; let oddChar; for (let [x,y] of hmap) { if (y % 2 != 0) { oddCount++; oddChar = x; } } /* odd_cnt = 1 only if the length of str is odd */ if (oddCount > 1 || oddCount == 1 && str.length % 2 == 0) return \"NO PALINDROME\"; /* Generate first halh of palindrome */ let firstHalf = \"\", secondHalf = \"\"; for (let [x,y] of hmap) { // Build a string of floor(count/2) // occurrences of current character let s = \"\"; for(let i = 0; i < Math.floor(y/2); i++){ s += x; } // Attach the built string to end of // and begin of second half firstHalf = firstHalf + s; secondHalf = s + secondHalf; } // Insert odd character if there // is any return (oddCount == 1) ? (firstHalf + oddChar + secondHalf) : (firstHalf + secondHalf);} // driver programlet s = \"mdaam\";document.write(getPalindrome(s)); // This code is contributed by shinjanpatra.</script>",
"e": 31594,
"s": 30132,
"text": null
},
{
"code": null,
"e": 31600,
"s": 31594,
"text": "amdma"
},
{
"code": null,
"e": 31606,
"s": 31600,
"text": "ukasp"
},
{
"code": null,
"e": 31621,
"s": 31606,
"text": "satyamsinghkv2"
},
{
"code": null,
"e": 31634,
"s": 31621,
"text": "shinjanpatra"
},
{
"code": null,
"e": 31652,
"s": 31634,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 31671,
"s": 31652,
"text": "frequency-counting"
},
{
"code": null,
"e": 31682,
"s": 31671,
"text": "palindrome"
},
{
"code": null,
"e": 31690,
"s": 31682,
"text": "Strings"
},
{
"code": null,
"e": 31698,
"s": 31690,
"text": "Strings"
},
{
"code": null,
"e": 31709,
"s": 31698,
"text": "palindrome"
},
{
"code": null,
"e": 31807,
"s": 31709,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31882,
"s": 31807,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 31918,
"s": 31882,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 31954,
"s": 31918,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 31992,
"s": 31954,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 32045,
"s": 31992,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 32075,
"s": 32045,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 32127,
"s": 32075,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 32172,
"s": 32127,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 32233,
"s": 32172,
"text": "Length of the longest substring without repeating characters"
}
] |
Sentinel Linear Search - GeeksforGeeks | 04 Aug, 2021
Sentinel Linear Search as the name suggests is a type of Linear Search where the number of comparisons is reduced as compared to a traditional linear search. When a linear search is performed on an array of size N then in the worst case a total of N comparisons are made when the element to be searched is compared to all the elements of the array and (N + 1) comparisons are made for the index of the element to be compared so that the index is not out of bounds of the array which can be reduced in a Sentinel Linear Search.In this search, the last element of the array is replaced with the element to be searched and then the linear search is performed on the array without checking whether the current index is inside the index range of the array or not because the element to be searched will definitely be found inside the array even if it was not present in the original array since the last element got replaced with it. So, the index to be checked will never be out of bounds of the array. The number of comparisons in the worst case here will be (N + 2).Examples:
Input: arr[] = {10, 20, 180, 30, 60, 50, 110, 100, 70}, x = 180 Output: 180 is present at index 2Input: arr[] = {10, 20, 180, 30, 60, 50, 110, 100, 70}, x = 90 Output: Not found
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function to search x in the given arrayvoid sentinelSearch(int arr[], int n, int key){ // Last element of the array int last = arr[n - 1]; // Element to be searched is // placed at the last index arr[n - 1] = key; int i = 0; while (arr[i] != key) i++; // Put the last element back arr[n - 1] = last; if ((i < n - 1) || (arr[n - 1] == key)) cout << key << " is present at index " << i; else cout << "Element Not found";} // Driver codeint main(){ int arr[] = { 10, 20, 180, 30, 60, 50, 110, 100, 70 }; int n = sizeof(arr) / sizeof(arr[0]); int key = 180; sentinelSearch(arr, n, key); return 0;}// This code is contributed by Mandeep Dalavi
// Java implementation of the approachclass GFG { // Function to search x in the given array static void sentinelSearch(int arr[], int n, int key) { // Last element of the array int last = arr[n - 1]; // Element to be searched is // placed at the last index arr[n - 1] = key; int i = 0; while (arr[i] != key) i++; // Put the last element back arr[n - 1] = last; if ((i < n - 1) || (arr[n - 1] == key)) System.out.println(key + " is present at index " + i); else System.out.println("Element Not found"); } // Driver code public static void main(String[] args) { int arr[] = { 10, 20, 180, 30, 60, 50, 110, 100, 70 }; int n = arr.length; int key = 180; sentinelSearch(arr, n, key); }} // This code is contributed by Ankit Rai, Mandeep Dalavi
# Python3 implementation of the approach# Function to search key in the given array def sentinelSearch(arr, n, key): # Last element of the array last = arr[n - 1] # Element to be searched is # placed at the last index arr[n - 1] = key i = 0 while (arr[i] != key): i += 1 # Put the last element back arr[n - 1] = last if ((i < n - 1) or (arr[n - 1] == key)): print(key, "is present at index", i) else: print("Element Not found") # Driver codearr = [10, 20, 180, 30, 60, 50, 110, 100, 70]n = len(arr)key = 180 sentinelSearch(arr, n, key) # This code is contributed by divyamohan123, Mandeep Dalavi
// C# implementation of the approachusing System; class GFG { // Function to search x in the given array static void sentinelSearch(int[] arr, int n, int key) { // Last element of the array int last = arr[n - 1]; // Element to be searched is // placed at the last index arr[n - 1] = key; int i = 0; while (arr[i] != key) i++; // Put the last element back arr[n - 1] = last; if ((i < n - 1) || (arr[n - 1] == key)) Console.WriteLine(key + " is present" + " at index " + i); else Console.WriteLine("Element Not found"); } // Driver code public static void Main() { int[] arr = { 10, 20, 180, 30, 60, 50, 110, 100, 70 }; int n = arr.Length; int key = 180; sentinelSearch(arr, n, key); }} // This code is contributed by Mohit kumar, Mandeep Dalavi
<script>// javascript implementation of the approach // Function to search x in the given array function sentinelSearch(arr , n , key) { // Last element of the array var last = arr[n - 1]; // Element to be searched is // placed at the last index arr[n - 1] = key; var i = 0; while (arr[i] != key) i++; // Put the last element back arr[n - 1] = last; if ((i < n - 1) || (arr[n - 1] == key)) document.write(key + " is present at index " + i); else document.write("Element Not found"); } // Driver code var arr = [ 10, 20, 180, 30, 60, 50, 110, 100, 70 ]; var n = arr.length; var key = 180; sentinelSearch(arr, n, key); // This code is contributed by todaysgaurav</script>
180 is present at index 2
Time Complexity: O(N)Auxiliary Space: O(1)
divyamohan123
ankthon
mohit kumar 29
mandeepdalavi
todaysgaurav
pankajsharmagfg
Algorithms
Arrays
Searching
Arrays
Searching
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Difference between Algorithm, Pseudocode and Program
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation | [
{
"code": null,
"e": 25941,
"s": 25913,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 27016,
"s": 25941,
"text": "Sentinel Linear Search as the name suggests is a type of Linear Search where the number of comparisons is reduced as compared to a traditional linear search. When a linear search is performed on an array of size N then in the worst case a total of N comparisons are made when the element to be searched is compared to all the elements of the array and (N + 1) comparisons are made for the index of the element to be compared so that the index is not out of bounds of the array which can be reduced in a Sentinel Linear Search.In this search, the last element of the array is replaced with the element to be searched and then the linear search is performed on the array without checking whether the current index is inside the index range of the array or not because the element to be searched will definitely be found inside the array even if it was not present in the original array since the last element got replaced with it. So, the index to be checked will never be out of bounds of the array. The number of comparisons in the worst case here will be (N + 2).Examples: "
},
{
"code": null,
"e": 27195,
"s": 27016,
"text": "Input: arr[] = {10, 20, 180, 30, 60, 50, 110, 100, 70}, x = 180 Output: 180 is present at index 2Input: arr[] = {10, 20, 180, 30, 60, 50, 110, 100, 70}, x = 90 Output: Not found "
},
{
"code": null,
"e": 27248,
"s": 27195,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27252,
"s": 27248,
"text": "C++"
},
{
"code": null,
"e": 27257,
"s": 27252,
"text": "Java"
},
{
"code": null,
"e": 27265,
"s": 27257,
"text": "Python3"
},
{
"code": null,
"e": 27268,
"s": 27265,
"text": "C#"
},
{
"code": null,
"e": 27279,
"s": 27268,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to search x in the given arrayvoid sentinelSearch(int arr[], int n, int key){ // Last element of the array int last = arr[n - 1]; // Element to be searched is // placed at the last index arr[n - 1] = key; int i = 0; while (arr[i] != key) i++; // Put the last element back arr[n - 1] = last; if ((i < n - 1) || (arr[n - 1] == key)) cout << key << \" is present at index \" << i; else cout << \"Element Not found\";} // Driver codeint main(){ int arr[] = { 10, 20, 180, 30, 60, 50, 110, 100, 70 }; int n = sizeof(arr) / sizeof(arr[0]); int key = 180; sentinelSearch(arr, n, key); return 0;}// This code is contributed by Mandeep Dalavi",
"e": 28074,
"s": 27279,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to search x in the given array static void sentinelSearch(int arr[], int n, int key) { // Last element of the array int last = arr[n - 1]; // Element to be searched is // placed at the last index arr[n - 1] = key; int i = 0; while (arr[i] != key) i++; // Put the last element back arr[n - 1] = last; if ((i < n - 1) || (arr[n - 1] == key)) System.out.println(key + \" is present at index \" + i); else System.out.println(\"Element Not found\"); } // Driver code public static void main(String[] args) { int arr[] = { 10, 20, 180, 30, 60, 50, 110, 100, 70 }; int n = arr.length; int key = 180; sentinelSearch(arr, n, key); }} // This code is contributed by Ankit Rai, Mandeep Dalavi",
"e": 29025,
"s": 28074,
"text": null
},
{
"code": "# Python3 implementation of the approach# Function to search key in the given array def sentinelSearch(arr, n, key): # Last element of the array last = arr[n - 1] # Element to be searched is # placed at the last index arr[n - 1] = key i = 0 while (arr[i] != key): i += 1 # Put the last element back arr[n - 1] = last if ((i < n - 1) or (arr[n - 1] == key)): print(key, \"is present at index\", i) else: print(\"Element Not found\") # Driver codearr = [10, 20, 180, 30, 60, 50, 110, 100, 70]n = len(arr)key = 180 sentinelSearch(arr, n, key) # This code is contributed by divyamohan123, Mandeep Dalavi",
"e": 29682,
"s": 29025,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG { // Function to search x in the given array static void sentinelSearch(int[] arr, int n, int key) { // Last element of the array int last = arr[n - 1]; // Element to be searched is // placed at the last index arr[n - 1] = key; int i = 0; while (arr[i] != key) i++; // Put the last element back arr[n - 1] = last; if ((i < n - 1) || (arr[n - 1] == key)) Console.WriteLine(key + \" is present\" + \" at index \" + i); else Console.WriteLine(\"Element Not found\"); } // Driver code public static void Main() { int[] arr = { 10, 20, 180, 30, 60, 50, 110, 100, 70 }; int n = arr.Length; int key = 180; sentinelSearch(arr, n, key); }} // This code is contributed by Mohit kumar, Mandeep Dalavi",
"e": 30636,
"s": 29682,
"text": null
},
{
"code": "<script>// javascript implementation of the approach // Function to search x in the given array function sentinelSearch(arr , n , key) { // Last element of the array var last = arr[n - 1]; // Element to be searched is // placed at the last index arr[n - 1] = key; var i = 0; while (arr[i] != key) i++; // Put the last element back arr[n - 1] = last; if ((i < n - 1) || (arr[n - 1] == key)) document.write(key + \" is present at index \" + i); else document.write(\"Element Not found\"); } // Driver code var arr = [ 10, 20, 180, 30, 60, 50, 110, 100, 70 ]; var n = arr.length; var key = 180; sentinelSearch(arr, n, key); // This code is contributed by todaysgaurav</script>",
"e": 31467,
"s": 30636,
"text": null
},
{
"code": null,
"e": 31493,
"s": 31467,
"text": "180 is present at index 2"
},
{
"code": null,
"e": 31538,
"s": 31495,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31552,
"s": 31538,
"text": "divyamohan123"
},
{
"code": null,
"e": 31560,
"s": 31552,
"text": "ankthon"
},
{
"code": null,
"e": 31575,
"s": 31560,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31589,
"s": 31575,
"text": "mandeepdalavi"
},
{
"code": null,
"e": 31602,
"s": 31589,
"text": "todaysgaurav"
},
{
"code": null,
"e": 31618,
"s": 31602,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 31629,
"s": 31618,
"text": "Algorithms"
},
{
"code": null,
"e": 31636,
"s": 31629,
"text": "Arrays"
},
{
"code": null,
"e": 31646,
"s": 31636,
"text": "Searching"
},
{
"code": null,
"e": 31653,
"s": 31646,
"text": "Arrays"
},
{
"code": null,
"e": 31663,
"s": 31653,
"text": "Searching"
},
{
"code": null,
"e": 31674,
"s": 31663,
"text": "Algorithms"
},
{
"code": null,
"e": 31772,
"s": 31674,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31797,
"s": 31772,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31824,
"s": 31797,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 31877,
"s": 31824,
"text": "Difference between Algorithm, Pseudocode and Program"
},
{
"code": null,
"e": 31911,
"s": 31877,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 31978,
"s": 31911,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 31993,
"s": 31978,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32009,
"s": 31993,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 32077,
"s": 32009,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32123,
"s": 32077,
"text": "Write a program to reverse an array or string"
}
] |
HTML | type Attribute - GeeksforGeeks | 09 Dec, 2021
The HTML <input> type Attribute is used to specify the type of <input> element to display. The default type of <input> type attribute is text.Syntax:
<input type="value">
Attribute Values:
button: It is used to define a clickable Button in a Document. It is mostly used with the JavaScript to activate the script.
checkbox: It is used to define a checkbox field. The checkbox is shown as a square box that is ticked when it is activated. It allows the user to select one or more option among all the limited choices.
color: It is used to define a color picker. The value should be a seven-character hexadecimal notation. Its default value is #000000(black).
date: It is used to define a date picker or control field. The value will be the year, month and day.
email: It is used to define a field for email address. The input email id is automatically validated to check the format of the email id is correct or not.
file: It is used to specify the file select field and add a button to choose a file for upload to the form.
hidden: It is used to define an input hidden field. A hidden field also includes those data that could not be seen or modified by the users when submitted the form. A hidden field only stores those database records that need to be updated when submitting the form.
image: It is used to define an image as the submit button.
month: It is used to specify the control of month and year field. The value must be in the format of “YYYY-MM”.
number: It is used to specify an input field for entering a number.
password: It is used to specify the password field of input tag. Password should be served over the HTTPS pages because it include the sensitive information of the user.
radio: It is used to define a Radio Button. Radio Buttons are used to let the user select exactly one option from a list of predefined options. Radio Button input controls are created by using the “input” element with a type attribute having value as “radio”.
range: It is used to define control for a number entered by the user. It can set restrictions on unimportant number or value which will be entered by the user. Its default range from 0 to 100.
reset: It is used to defines a reset button. The reset button is used to reset all the form values to its initial values.
search: It is used to define a text field that entered a search string.
submit: It is used to define a submit button. It is used to submit all the user value to the form handler. The Form Handler is a server page that activates a script for processing all the input values.
tel: It is used to define a field that entering a user telephone Number.
text: It is used to define a single-line text field . The default width of the text field is 20 characters.
time: It is used to specify the entering time control field.
url: It is used to define a field that entered a URL. This input value is automatically validated before submitted the form.
week: It is used to define a week and a year control field.
Example:
html
<!DOCTYPE html><html> <head> <title>HTML Input type = "Date" </title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML <input type="date"></h2> <input type="date" id="test" value="2019-07-02T25:32Z"> </body> </html>
Output:
Supported Browsers: The browsers supported by HTML <input> type attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
ManasChhabra2
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
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": 26139,
"s": 26111,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 26291,
"s": 26139,
"text": "The HTML <input> type Attribute is used to specify the type of <input> element to display. The default type of <input> type attribute is text.Syntax: "
},
{
"code": null,
"e": 26312,
"s": 26291,
"text": "<input type=\"value\">"
},
{
"code": null,
"e": 26332,
"s": 26312,
"text": "Attribute Values: "
},
{
"code": null,
"e": 26457,
"s": 26332,
"text": "button: It is used to define a clickable Button in a Document. It is mostly used with the JavaScript to activate the script."
},
{
"code": null,
"e": 26660,
"s": 26457,
"text": "checkbox: It is used to define a checkbox field. The checkbox is shown as a square box that is ticked when it is activated. It allows the user to select one or more option among all the limited choices."
},
{
"code": null,
"e": 26801,
"s": 26660,
"text": "color: It is used to define a color picker. The value should be a seven-character hexadecimal notation. Its default value is #000000(black)."
},
{
"code": null,
"e": 26903,
"s": 26801,
"text": "date: It is used to define a date picker or control field. The value will be the year, month and day."
},
{
"code": null,
"e": 27059,
"s": 26903,
"text": "email: It is used to define a field for email address. The input email id is automatically validated to check the format of the email id is correct or not."
},
{
"code": null,
"e": 27167,
"s": 27059,
"text": "file: It is used to specify the file select field and add a button to choose a file for upload to the form."
},
{
"code": null,
"e": 27432,
"s": 27167,
"text": "hidden: It is used to define an input hidden field. A hidden field also includes those data that could not be seen or modified by the users when submitted the form. A hidden field only stores those database records that need to be updated when submitting the form."
},
{
"code": null,
"e": 27491,
"s": 27432,
"text": "image: It is used to define an image as the submit button."
},
{
"code": null,
"e": 27603,
"s": 27491,
"text": "month: It is used to specify the control of month and year field. The value must be in the format of “YYYY-MM”."
},
{
"code": null,
"e": 27671,
"s": 27603,
"text": "number: It is used to specify an input field for entering a number."
},
{
"code": null,
"e": 27841,
"s": 27671,
"text": "password: It is used to specify the password field of input tag. Password should be served over the HTTPS pages because it include the sensitive information of the user."
},
{
"code": null,
"e": 28101,
"s": 27841,
"text": "radio: It is used to define a Radio Button. Radio Buttons are used to let the user select exactly one option from a list of predefined options. Radio Button input controls are created by using the “input” element with a type attribute having value as “radio”."
},
{
"code": null,
"e": 28294,
"s": 28101,
"text": "range: It is used to define control for a number entered by the user. It can set restrictions on unimportant number or value which will be entered by the user. Its default range from 0 to 100."
},
{
"code": null,
"e": 28416,
"s": 28294,
"text": "reset: It is used to defines a reset button. The reset button is used to reset all the form values to its initial values."
},
{
"code": null,
"e": 28488,
"s": 28416,
"text": "search: It is used to define a text field that entered a search string."
},
{
"code": null,
"e": 28690,
"s": 28488,
"text": "submit: It is used to define a submit button. It is used to submit all the user value to the form handler. The Form Handler is a server page that activates a script for processing all the input values."
},
{
"code": null,
"e": 28763,
"s": 28690,
"text": "tel: It is used to define a field that entering a user telephone Number."
},
{
"code": null,
"e": 28871,
"s": 28763,
"text": "text: It is used to define a single-line text field . The default width of the text field is 20 characters."
},
{
"code": null,
"e": 28932,
"s": 28871,
"text": "time: It is used to specify the entering time control field."
},
{
"code": null,
"e": 29057,
"s": 28932,
"text": "url: It is used to define a field that entered a URL. This input value is automatically validated before submitted the form."
},
{
"code": null,
"e": 29117,
"s": 29057,
"text": "week: It is used to define a week and a year control field."
},
{
"code": null,
"e": 29128,
"s": 29117,
"text": "Example: "
},
{
"code": null,
"e": 29133,
"s": 29128,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML Input type = \"Date\" </title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML <input type=\"date\"></h2> <input type=\"date\" id=\"test\" value=\"2019-07-02T25:32Z\"> </body> </html>",
"e": 29568,
"s": 29133,
"text": null
},
{
"code": null,
"e": 29578,
"s": 29568,
"text": "Output: "
},
{
"code": null,
"e": 29672,
"s": 29578,
"text": "Supported Browsers: The browsers supported by HTML <input> type attribute are listed below: "
},
{
"code": null,
"e": 29686,
"s": 29672,
"text": "Google Chrome"
},
{
"code": null,
"e": 29704,
"s": 29686,
"text": "Internet Explorer"
},
{
"code": null,
"e": 29712,
"s": 29704,
"text": "Firefox"
},
{
"code": null,
"e": 29719,
"s": 29712,
"text": "Safari"
},
{
"code": null,
"e": 29725,
"s": 29719,
"text": "Opera"
},
{
"code": null,
"e": 29864,
"s": 29727,
"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": 29878,
"s": 29864,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 29894,
"s": 29878,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 29899,
"s": 29894,
"text": "HTML"
},
{
"code": null,
"e": 29916,
"s": 29899,
"text": "Web Technologies"
},
{
"code": null,
"e": 29921,
"s": 29916,
"text": "HTML"
},
{
"code": null,
"e": 30019,
"s": 29921,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30043,
"s": 30019,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 30084,
"s": 30043,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 30121,
"s": 30084,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30150,
"s": 30121,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30170,
"s": 30150,
"text": "Angular File Upload"
},
{
"code": null,
"e": 30210,
"s": 30170,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30243,
"s": 30210,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30288,
"s": 30243,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30331,
"s": 30288,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Find a Sublist in a List in Java? - GeeksforGeeks | 22 Oct, 2020
List in Java contains index-based methods. This enables us to maintain the order collection. So this enables us to search, insert, delete, and even update the elements. This enables us to store multiple copies of the same element already existing on our list. Also, in addition, null elements are allowed to be a part of the List.
We access the list through their index numbers called Interface that we won’t be discussing here.
Types of List
ArrayList
LinkedList
Stack
Vector
ArrayList is used where elements to be inserted are known because there is no flexibility once we have declared the ArrayList but is frequently used as operation over elements are much faster and the good part of Arraylist is we can directly access the element through ArrayList interface.
The syntax for ArrayList :
ArrayList<String> cars = new ArrayList<String>();
LinkedList is preferred over Arraylist if we want a flexible list with no size constraint and operations over elements are quite slower.
LinkedList<E> extends AbstractList<E> implements List<E>, Deque<E> ;
Vector method is similar to Arraylist just Vector has an edge over ArrayList because all elements in vectors are synchronized and are only useful if making multithreaded applications. So, in practice vector class isn‘t used more frequently anymore.
Vector object= new vector(datatype parameter1, datatype parameter2, ...., datatype parameterN)
The subList() method of java.util.ArrayList class is used to return a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all the optional list operations.
Syntax:
public List subList(int fromIndex, int toIndex)
Parameters: This method takes the following argument as a parameter.
fromIndex: low endpoint (inclusive) of the subList
toIndex: high endpoint (exclusive) of the subList
Return type: A view of the specified range within this list. Exception: This method throws the following Exception.
IndexOutOfBoundsException – if an endpoint index value is out of range (fromIndex size)
IllegalArgumentException – if the endpoint indices are out of order (fromIndex > toIndex)
Example 1:
Java
// Java Program to find // Sublist in a List import java.util.*; public class GFG1 { // Main Method public static void main(String[] argv) throws Exception { // Try block for exception try { ArrayList<Integer> arrlist = new ArrayList<Integer>(); // Populating arrlist1 arrlist.add(1); arrlist.add(4); arrlist.add(9); arrlist.add(25); arrlist.add(36); // Print arrlist System.out.println("Original arrlist: " + arrlist); // Getting the subList // using subList() method List<Integer> arrlist2 = arrlist.subList(2, 4); // Print the subList System.out.println("Sublist of arrlist: " + arrlist2); } // Catch block for exception catch (IndexOutOfBoundsException e) { System.out.println("Exception thrown : " + e); } // Catch block for exception catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } } }
Output:
Original arrlist: [1, 4, 9, 25, 36]
Sublist of arrlist: [9, 25]
Example 2:
Java
// Java program to find// sublist in a List import java.util.*; public class GFG1 { // Main Method public static void main(String[] argv) throws Exception { // Exception try-catch block try { ArrayList<String> arrlist = new ArrayList<String>(); // Populating arrlist1 arrlist.add("Example"); arrlist.add("in"); arrlist.add("Geeks"); arrlist.add("for"); arrlist.add("Geeks"); // print arrlist System.out.println("Original arrlist: " + arrlist); // Getting the subList // using subList() method List<String> arrlist2 = arrlist.subList(2, 5); // print the subList System.out.println("Sublist of arrlist: " + arrlist2); } // Exception try-catch block catch (IndexOutOfBoundsException e) { System.out.println("Exception thrown : " + e); } // Exception try-catch block catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } } }
Output :
Original arrlist: [Example, in, Geeks, for, Geeks]
Sublist of arrlist: [Geeks, for, Geeks]
Example 3: For IllegalArgumentException
Java
// Java program to demonstrate // subList() method // for IllegalArgumentException import java.util.*; public class GFG1{ // Main Method public static void main(String[] argv) throws Exception { // Exception try-catch block try { ArrayList<String> arrlist = new ArrayList<String>(); // Populating arrlist1 arrlist.add("Example"); arrlist.add("in"); arrlist.add("Geeks"); arrlist.add("for"); arrlist.add("Geeks"); // Print arrlist System.out.println("Original arrlist: " + arrlist); // Getting the subList // Using subList() method System.out.println("\nEndpoint indices " + "are out of order" + " (fromIndex > toIndex)"); List<String> arrlist2 = arrlist.subList(9, 3); // print the subList System.out.println("Sublist of arrlist: " + arrlist2); } // Exception try-catch block catch (IndexOutOfBoundsException e) { System.out.println("Exception thrown: " + e); } // Exception try-catch block catch (IllegalArgumentException e) { System.out.println("Exception thrown: " + e); } } }
Output:
Original arrlist: [Example, in, Geeks, for, Geeks]
Endpoint indices are out of order (fromIndex > toIndex)
Exception thrown: java.lang.IllegalArgumentException: fromIndex(9) > toIndex(3)
Example 4: For IndexOutOfBoundsException
Java
// Java program to demonstrate subList() // method for IndexOutOfBoundsException import java.util.*; public class GFG1 { // Main Method public static void main(String[] argv) throws Exception { // Exception try-catch block try { ArrayList<Integer> arrlist = new ArrayList<Integer>(); // Populating arrlist1 arrlist.add(1); arrlist.add(4); arrlist.add(9); arrlist.add(25); arrlist.add(36); // Print arrlist System.out.println("Original arrlist: " + arrlist); // Getting the subList // Using subList() method System.out.println("\nEnd index value is out of range"); List<Integer> arrlist2 = arrlist.subList(2, 7); // Print the subList System.out.println("Sublist of arrlist: " + arrlist2); } // Exception try-catch block catch (IndexOutOfBoundsException e) { System.out.println("Exception thrown : " + e); } // Exception try-catch block catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } } }
Output:
Original arrlist: [1, 4, 9, 25, 36]
End index value is out of range
Exception thrown : java.lang.IndexOutOfBoundsException: toIndex = 7
java-list
Java-List-Programs
Picked
Java
Java Programs
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": 25250,
"s": 25222,
"text": "\n22 Oct, 2020"
},
{
"code": null,
"e": 25581,
"s": 25250,
"text": "List in Java contains index-based methods. This enables us to maintain the order collection. So this enables us to search, insert, delete, and even update the elements. This enables us to store multiple copies of the same element already existing on our list. Also, in addition, null elements are allowed to be a part of the List."
},
{
"code": null,
"e": 25679,
"s": 25581,
"text": "We access the list through their index numbers called Interface that we won’t be discussing here."
},
{
"code": null,
"e": 25693,
"s": 25679,
"text": "Types of List"
},
{
"code": null,
"e": 25703,
"s": 25693,
"text": "ArrayList"
},
{
"code": null,
"e": 25714,
"s": 25703,
"text": "LinkedList"
},
{
"code": null,
"e": 25720,
"s": 25714,
"text": "Stack"
},
{
"code": null,
"e": 25728,
"s": 25720,
"text": "Vector "
},
{
"code": null,
"e": 26018,
"s": 25728,
"text": "ArrayList is used where elements to be inserted are known because there is no flexibility once we have declared the ArrayList but is frequently used as operation over elements are much faster and the good part of Arraylist is we can directly access the element through ArrayList interface."
},
{
"code": null,
"e": 26045,
"s": 26018,
"text": "The syntax for ArrayList :"
},
{
"code": null,
"e": 26096,
"s": 26045,
"text": "ArrayList<String> cars = new ArrayList<String>();\n"
},
{
"code": null,
"e": 26235,
"s": 26096,
"text": " LinkedList is preferred over Arraylist if we want a flexible list with no size constraint and operations over elements are quite slower. "
},
{
"code": null,
"e": 26305,
"s": 26235,
"text": "LinkedList<E> extends AbstractList<E> implements List<E>, Deque<E> ;\n"
},
{
"code": null,
"e": 26555,
"s": 26305,
"text": "Vector method is similar to Arraylist just Vector has an edge over ArrayList because all elements in vectors are synchronized and are only useful if making multithreaded applications. So, in practice vector class isn‘t used more frequently anymore. "
},
{
"code": null,
"e": 26651,
"s": 26555,
"text": "Vector object= new vector(datatype parameter1, datatype parameter2, ...., datatype parameterN)\n"
},
{
"code": null,
"e": 26822,
"s": 26651,
"text": "The subList() method of java.util.ArrayList class is used to return a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive."
},
{
"code": null,
"e": 27016,
"s": 26822,
"text": "The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all the optional list operations."
},
{
"code": null,
"e": 27024,
"s": 27016,
"text": "Syntax:"
},
{
"code": null,
"e": 27073,
"s": 27024,
"text": "public List subList(int fromIndex, int toIndex)\n"
},
{
"code": null,
"e": 27142,
"s": 27073,
"text": "Parameters: This method takes the following argument as a parameter."
},
{
"code": null,
"e": 27193,
"s": 27142,
"text": "fromIndex: low endpoint (inclusive) of the subList"
},
{
"code": null,
"e": 27243,
"s": 27193,
"text": "toIndex: high endpoint (exclusive) of the subList"
},
{
"code": null,
"e": 27359,
"s": 27243,
"text": "Return type: A view of the specified range within this list. Exception: This method throws the following Exception."
},
{
"code": null,
"e": 27447,
"s": 27359,
"text": "IndexOutOfBoundsException – if an endpoint index value is out of range (fromIndex size)"
},
{
"code": null,
"e": 27537,
"s": 27447,
"text": "IllegalArgumentException – if the endpoint indices are out of order (fromIndex > toIndex)"
},
{
"code": null,
"e": 27548,
"s": 27537,
"text": "Example 1:"
},
{
"code": null,
"e": 27553,
"s": 27548,
"text": "Java"
},
{
"code": "// Java Program to find // Sublist in a List import java.util.*; public class GFG1 { // Main Method public static void main(String[] argv) throws Exception { // Try block for exception try { ArrayList<Integer> arrlist = new ArrayList<Integer>(); // Populating arrlist1 arrlist.add(1); arrlist.add(4); arrlist.add(9); arrlist.add(25); arrlist.add(36); // Print arrlist System.out.println(\"Original arrlist: \" + arrlist); // Getting the subList // using subList() method List<Integer> arrlist2 = arrlist.subList(2, 4); // Print the subList System.out.println(\"Sublist of arrlist: \" + arrlist2); } // Catch block for exception catch (IndexOutOfBoundsException e) { System.out.println(\"Exception thrown : \" + e); } // Catch block for exception catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } } }",
"e": 28773,
"s": 27553,
"text": null
},
{
"code": null,
"e": 28781,
"s": 28773,
"text": "Output:"
},
{
"code": null,
"e": 28846,
"s": 28781,
"text": "Original arrlist: [1, 4, 9, 25, 36]\nSublist of arrlist: [9, 25]\n"
},
{
"code": null,
"e": 28857,
"s": 28846,
"text": "Example 2:"
},
{
"code": null,
"e": 28862,
"s": 28857,
"text": "Java"
},
{
"code": "// Java program to find// sublist in a List import java.util.*; public class GFG1 { // Main Method public static void main(String[] argv) throws Exception { // Exception try-catch block try { ArrayList<String> arrlist = new ArrayList<String>(); // Populating arrlist1 arrlist.add(\"Example\"); arrlist.add(\"in\"); arrlist.add(\"Geeks\"); arrlist.add(\"for\"); arrlist.add(\"Geeks\"); // print arrlist System.out.println(\"Original arrlist: \" + arrlist); // Getting the subList // using subList() method List<String> arrlist2 = arrlist.subList(2, 5); // print the subList System.out.println(\"Sublist of arrlist: \" + arrlist2); } // Exception try-catch block catch (IndexOutOfBoundsException e) { System.out.println(\"Exception thrown : \" + e); } // Exception try-catch block catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } } } ",
"e": 30082,
"s": 28862,
"text": null
},
{
"code": null,
"e": 30092,
"s": 30082,
"text": "Output : "
},
{
"code": null,
"e": 30184,
"s": 30092,
"text": "Original arrlist: [Example, in, Geeks, for, Geeks]\nSublist of arrlist: [Geeks, for, Geeks]\n"
},
{
"code": null,
"e": 30224,
"s": 30184,
"text": "Example 3: For IllegalArgumentException"
},
{
"code": null,
"e": 30229,
"s": 30224,
"text": "Java"
},
{
"code": "// Java program to demonstrate // subList() method // for IllegalArgumentException import java.util.*; public class GFG1{ // Main Method public static void main(String[] argv) throws Exception { // Exception try-catch block try { ArrayList<String> arrlist = new ArrayList<String>(); // Populating arrlist1 arrlist.add(\"Example\"); arrlist.add(\"in\"); arrlist.add(\"Geeks\"); arrlist.add(\"for\"); arrlist.add(\"Geeks\"); // Print arrlist System.out.println(\"Original arrlist: \" + arrlist); // Getting the subList // Using subList() method System.out.println(\"\\nEndpoint indices \" + \"are out of order\" + \" (fromIndex > toIndex)\"); List<String> arrlist2 = arrlist.subList(9, 3); // print the subList System.out.println(\"Sublist of arrlist: \" + arrlist2); } // Exception try-catch block catch (IndexOutOfBoundsException e) { System.out.println(\"Exception thrown: \" + e); } // Exception try-catch block catch (IllegalArgumentException e) { System.out.println(\"Exception thrown: \" + e); } } }",
"e": 31671,
"s": 30229,
"text": null
},
{
"code": null,
"e": 31679,
"s": 31671,
"text": "Output:"
},
{
"code": null,
"e": 31868,
"s": 31679,
"text": "Original arrlist: [Example, in, Geeks, for, Geeks]\n\nEndpoint indices are out of order (fromIndex > toIndex)\nException thrown: java.lang.IllegalArgumentException: fromIndex(9) > toIndex(3)\n"
},
{
"code": null,
"e": 31909,
"s": 31868,
"text": "Example 4: For IndexOutOfBoundsException"
},
{
"code": null,
"e": 31914,
"s": 31909,
"text": "Java"
},
{
"code": "// Java program to demonstrate subList() // method for IndexOutOfBoundsException import java.util.*; public class GFG1 { // Main Method public static void main(String[] argv) throws Exception { // Exception try-catch block try { ArrayList<Integer> arrlist = new ArrayList<Integer>(); // Populating arrlist1 arrlist.add(1); arrlist.add(4); arrlist.add(9); arrlist.add(25); arrlist.add(36); // Print arrlist System.out.println(\"Original arrlist: \" + arrlist); // Getting the subList // Using subList() method System.out.println(\"\\nEnd index value is out of range\"); List<Integer> arrlist2 = arrlist.subList(2, 7); // Print the subList System.out.println(\"Sublist of arrlist: \" + arrlist2); } // Exception try-catch block catch (IndexOutOfBoundsException e) { System.out.println(\"Exception thrown : \" + e); } // Exception try-catch block catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } } }",
"e": 33188,
"s": 31914,
"text": null
},
{
"code": null,
"e": 33196,
"s": 33188,
"text": "Output:"
},
{
"code": null,
"e": 33334,
"s": 33196,
"text": "Original arrlist: [1, 4, 9, 25, 36]\n\nEnd index value is out of range\nException thrown : java.lang.IndexOutOfBoundsException: toIndex = 7\n"
},
{
"code": null,
"e": 33344,
"s": 33334,
"text": "java-list"
},
{
"code": null,
"e": 33363,
"s": 33344,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 33370,
"s": 33363,
"text": "Picked"
},
{
"code": null,
"e": 33375,
"s": 33370,
"text": "Java"
},
{
"code": null,
"e": 33389,
"s": 33375,
"text": "Java Programs"
},
{
"code": null,
"e": 33394,
"s": 33389,
"text": "Java"
},
{
"code": null,
"e": 33492,
"s": 33394,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33507,
"s": 33492,
"text": "Stream In Java"
},
{
"code": null,
"e": 33528,
"s": 33507,
"text": "Constructors in Java"
},
{
"code": null,
"e": 33547,
"s": 33528,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 33577,
"s": 33547,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 33623,
"s": 33577,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 33649,
"s": 33623,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 33683,
"s": 33649,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 33730,
"s": 33683,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 33762,
"s": 33730,
"text": "How to Iterate HashMap in Java?"
}
] |
Bin Size in Matplotlib Histogram - GeeksforGeeks | 03 Jan, 2021
Prerequisites: Matplotlib
A histogram is a graphical representation of the distribution of data given by the user. Its appearance is similar to Bar-Graph except it is continuous.
The towers or bars of a histogram are called bins. The height of each bin shows how many values from that data fall into that range.
Width of each bin is = (max value of data – min value of data) / total number of bins
The default value of the number of bins to be created in a histogram is 10. However, we can change the size of bins using the parameter bins in matplotlib.pyplot.hist().
We can pass an integer in bins stating how many bins/towers to be created in the histogram and the width of each bin is then changed accordingly.
Example 1 :
Python3
import matplotlib.pyplot as plt height = [189, 185, 195, 149, 189, 147, 154, 174, 169, 195, 159, 192, 155, 191, 153, 157, 140, 144, 172, 157, 181, 182, 166, 167] plt.hist(height, edgecolor="red", bins=5)plt.show()
Output :
Here, the bins = 5, i.e the number of bins to be created is 5. Setting bins to an integer creates bins of equal size or width. As the bin size is changed so then the bin width would be changed accordingly as :
width = (195 – 140 ) / 5 = 11
Example 2 :
Python3
import matplotlib.pyplot as plt values = [87, 53, 66, 61, 67, 68, 62, 110, 104, 61, 111, 123, 117, 119, 116, 104, 92, 111, 90, 103, 81, 80, 101, 51, 79, 107, 110, 129, 145, 139, 110] plt.hist(values, bins=7, edgecolor="yellow", color="green")plt.show()
Output :
In the above graph, the width of each bin is :
width = ( 145 – 51 ) / 7 = 13.4
We can also pass a sequence of int or float in the parameter bins. In which the elements of the sequence are the edges/boundaries of the bins. In this method, the bin width may vary for each bin.
Suppose a sequence [1,2,3,4,5] is assigned to bins and then the number of bins made will be 4 i.e the first bin will be [1,2) (including 1, but excluding 2) second bin will be [2,3) (including 2, but excluding 3) third bin will be [3,4) (including 3, but excluding 4). However, in the last bin [4,5] both 4 and 5 are included.
Hence, all the bins are half-open [a, b) but the last bin is closed [a, b]. For such cases, the width of each bin is equal.
If the difference between each element of the sequence assigned to bins is not equal then the width of each bin is different, hence the bin width depends on the sequence.
Example 1 : Equal bin width
Python3
import matplotlib.pyplot as plt marks = [1, 2, 3, 2, 1, 2, 3, 2, 1, 4, 5, 4, 3, 2, 5, 4, 5, 4, 5, 3, 2, 1, 5] plt.hist(marks, bins=[1, 2, 3, 4, 5], edgecolor="black")plt.show()
Output :
Example 2 : Unequal bin width
Python3
import matplotlib.pyplot as plt data = [189, 185, 195, 149, 189, 147, 154, 174, 169, 195, 159, 192, 155, 191, 153, 157, 140, 144, 172, 157, 181, 182, 166, 167] plt.hist(data, bins=[140, 150, 160, 175, 185, 200], edgecolor="yellow", color="grey") plt.show()
Output:
For passing a sequence in the bins parameter, we may also use the range function for equally distributed bins. Within range(), the starting point is the minimum of data, the endpoint is the maximum of data + the bin width mentioned, as in range(), the endpoint is not included and the step is bin width.
As the step is fixed in range(), we get equally sized bins in the histogram.
Example :
Python3
import matplotlib.pyplot as plt data = [87, 53, 66, 61, 67, 68, 62, 110, 104, 61, 111, 123, 117, 119, 116, 104, 92, 111, 90, 103, 81, 80, 101, 51, 79, 107, 110, 129, 145, 128, 132, 135, 131, 126, 139, 110] binwidth = 8plt.hist(data, bins=range(min(data), max(data) + binwidth, binwidth), edgecolor="yellow", color="brown") plt.show()
Output :
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe | [
{
"code": null,
"e": 31547,
"s": 31519,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 31573,
"s": 31547,
"text": "Prerequisites: Matplotlib"
},
{
"code": null,
"e": 31726,
"s": 31573,
"text": "A histogram is a graphical representation of the distribution of data given by the user. Its appearance is similar to Bar-Graph except it is continuous."
},
{
"code": null,
"e": 31860,
"s": 31726,
"text": "The towers or bars of a histogram are called bins. The height of each bin shows how many values from that data fall into that range. "
},
{
"code": null,
"e": 31947,
"s": 31860,
"text": "Width of each bin is = (max value of data – min value of data) / total number of bins "
},
{
"code": null,
"e": 32118,
"s": 31947,
"text": "The default value of the number of bins to be created in a histogram is 10. However, we can change the size of bins using the parameter bins in matplotlib.pyplot.hist(). "
},
{
"code": null,
"e": 32264,
"s": 32118,
"text": "We can pass an integer in bins stating how many bins/towers to be created in the histogram and the width of each bin is then changed accordingly."
},
{
"code": null,
"e": 32276,
"s": 32264,
"text": "Example 1 :"
},
{
"code": null,
"e": 32284,
"s": 32276,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt height = [189, 185, 195, 149, 189, 147, 154, 174, 169, 195, 159, 192, 155, 191, 153, 157, 140, 144, 172, 157, 181, 182, 166, 167] plt.hist(height, edgecolor=\"red\", bins=5)plt.show()",
"e": 32530,
"s": 32284,
"text": null
},
{
"code": null,
"e": 32539,
"s": 32530,
"text": "Output :"
},
{
"code": null,
"e": 32749,
"s": 32539,
"text": "Here, the bins = 5, i.e the number of bins to be created is 5. Setting bins to an integer creates bins of equal size or width. As the bin size is changed so then the bin width would be changed accordingly as :"
},
{
"code": null,
"e": 32779,
"s": 32749,
"text": "width = (195 – 140 ) / 5 = 11"
},
{
"code": null,
"e": 32791,
"s": 32779,
"text": "Example 2 :"
},
{
"code": null,
"e": 32799,
"s": 32791,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt values = [87, 53, 66, 61, 67, 68, 62, 110, 104, 61, 111, 123, 117, 119, 116, 104, 92, 111, 90, 103, 81, 80, 101, 51, 79, 107, 110, 129, 145, 139, 110] plt.hist(values, bins=7, edgecolor=\"yellow\", color=\"green\")plt.show()",
"e": 33090,
"s": 32799,
"text": null
},
{
"code": null,
"e": 33099,
"s": 33090,
"text": "Output :"
},
{
"code": null,
"e": 33146,
"s": 33099,
"text": "In the above graph, the width of each bin is :"
},
{
"code": null,
"e": 33179,
"s": 33146,
"text": "width = ( 145 – 51 ) / 7 = 13.4"
},
{
"code": null,
"e": 33375,
"s": 33179,
"text": "We can also pass a sequence of int or float in the parameter bins. In which the elements of the sequence are the edges/boundaries of the bins. In this method, the bin width may vary for each bin."
},
{
"code": null,
"e": 33703,
"s": 33375,
"text": "Suppose a sequence [1,2,3,4,5] is assigned to bins and then the number of bins made will be 4 i.e the first bin will be [1,2) (including 1, but excluding 2) second bin will be [2,3) (including 2, but excluding 3) third bin will be [3,4) (including 3, but excluding 4). However, in the last bin [4,5] both 4 and 5 are included. "
},
{
"code": null,
"e": 33827,
"s": 33703,
"text": "Hence, all the bins are half-open [a, b) but the last bin is closed [a, b]. For such cases, the width of each bin is equal."
},
{
"code": null,
"e": 33998,
"s": 33827,
"text": "If the difference between each element of the sequence assigned to bins is not equal then the width of each bin is different, hence the bin width depends on the sequence."
},
{
"code": null,
"e": 34026,
"s": 33998,
"text": "Example 1 : Equal bin width"
},
{
"code": null,
"e": 34034,
"s": 34026,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt marks = [1, 2, 3, 2, 1, 2, 3, 2, 1, 4, 5, 4, 3, 2, 5, 4, 5, 4, 5, 3, 2, 1, 5] plt.hist(marks, bins=[1, 2, 3, 4, 5], edgecolor=\"black\")plt.show()",
"e": 34231,
"s": 34034,
"text": null
},
{
"code": null,
"e": 34240,
"s": 34231,
"text": "Output :"
},
{
"code": null,
"e": 34270,
"s": 34240,
"text": "Example 2 : Unequal bin width"
},
{
"code": null,
"e": 34278,
"s": 34270,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt data = [189, 185, 195, 149, 189, 147, 154, 174, 169, 195, 159, 192, 155, 191, 153, 157, 140, 144, 172, 157, 181, 182, 166, 167] plt.hist(data, bins=[140, 150, 160, 175, 185, 200], edgecolor=\"yellow\", color=\"grey\") plt.show()",
"e": 34568,
"s": 34278,
"text": null
},
{
"code": null,
"e": 34576,
"s": 34568,
"text": "Output:"
},
{
"code": null,
"e": 34881,
"s": 34576,
"text": "For passing a sequence in the bins parameter, we may also use the range function for equally distributed bins. Within range(), the starting point is the minimum of data, the endpoint is the maximum of data + the bin width mentioned, as in range(), the endpoint is not included and the step is bin width. "
},
{
"code": null,
"e": 34958,
"s": 34881,
"text": "As the step is fixed in range(), we get equally sized bins in the histogram."
},
{
"code": null,
"e": 34968,
"s": 34958,
"text": "Example :"
},
{
"code": null,
"e": 34976,
"s": 34968,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt data = [87, 53, 66, 61, 67, 68, 62, 110, 104, 61, 111, 123, 117, 119, 116, 104, 92, 111, 90, 103, 81, 80, 101, 51, 79, 107, 110, 129, 145, 128, 132, 135, 131, 126, 139, 110] binwidth = 8plt.hist(data, bins=range(min(data), max(data) + binwidth, binwidth), edgecolor=\"yellow\", color=\"brown\") plt.show()",
"e": 35350,
"s": 34976,
"text": null
},
{
"code": null,
"e": 35359,
"s": 35350,
"text": "Output :"
},
{
"code": null,
"e": 35366,
"s": 35359,
"text": "Picked"
},
{
"code": null,
"e": 35384,
"s": 35366,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 35408,
"s": 35384,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 35415,
"s": 35408,
"text": "Python"
},
{
"code": null,
"e": 35434,
"s": 35415,
"text": "Technical Scripter"
},
{
"code": null,
"e": 35532,
"s": 35434,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35560,
"s": 35532,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 35610,
"s": 35560,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 35632,
"s": 35610,
"text": "Python map() function"
},
{
"code": null,
"e": 35676,
"s": 35632,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 35694,
"s": 35676,
"text": "Python Dictionary"
},
{
"code": null,
"e": 35717,
"s": 35694,
"text": "Taking input in Python"
},
{
"code": null,
"e": 35752,
"s": 35717,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 35784,
"s": 35752,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 35806,
"s": 35784,
"text": "Enumerate() in Python"
}
] |
Introduction to Natural Language Processing - GeeksforGeeks | 16 Nov, 2018
The essence of Natural Language Processing lies in making computers understand the natural language. That’s not an easy task though. Computers can understand the structured form of data like spreadsheets and the tables in the database, but human languages, texts, and voices form an unstructured category of data, and it gets difficult for the computer to understand it, and there arises the need for Natural Language Processing.
There’s a lot of natural language data out there in various forms and it would get very easy if computers can understand and process that data. We can train the models in accordance with expected output in different ways. Humans have been writing for thousands of years, there are a lot of literature pieces available, and it would be great if we make computers understand that. But the task is never going to be easy. There are various challenges floating out there like understanding the correct meaning of the sentence, correct Named-Entity Recognition(NER), correct prediction of various parts of speech, coreference resolution(the most challenging thing in my opinion).
Computers can’t truly understand the human language. If we feed enough data and train a model properly, it can distinguish and try categorizing various parts of speech(noun, verb, adjective, supporter, etc...) based on previously fed data and experiences. If it encounters a new word it tried making the nearest guess which can be embarrassingly wrong few times.
It’s very difficult for a computer to extract the exact meaning from a sentence. For example – The boy radiated fire like vibes. The boy had a very motivating personality or he actually radiated fire? As you see over here, parsing English with a computer is going to be complicated.
There are various stages involved in training a model. Solving a complex problem in Machine Learning means building a pipeline. In simple terms, it means breaking a complex problem into a number of small problems, making models for each of them and then integrating these models. A similar thing is done in NLP. We can break down the process of understanding English for a model into a number of small pieces.
It would be really great if a computer could understand that San Pedro is an island in Belize district in Central America with a population of 16, 444 and it is the second largest town in Belize. But to make the computer understand this, we need to teach computer very basic concepts of written language.
So let’s start by creating an NLP pipeline. It has various steps which will give us the desired output(maybe not in a few rare cases) at the end.
Step #1: Sentence SegmentationBreaking the piece of text in various sentences.Input : San Pedro is a town on the southern part of the island of Ambergris Caye in the Belize District of the nation of Belize, in Central America. According to 2015 mid-year estimates, the town has a population of about 16, 444. It is the second-largest town in the Belize District and largest in the Belize Rural South constituency.Output : San Pedro is a town on the southern part of the island of Ambergris Caye in the 2.Belize District of the nation of Belize, in Central America.According to 2015 mid-year estimates, the town has a population of about 16, 444.It is the second-largest town in the Belize District and largest in the Belize Rural South constituency.For coding a sentence segmentation model, we can consider splitting a sentence when it encounters any punctuation mark. But modern NLP pipelines have techniques to split even if the document isn’t formatted properly.
Breaking the piece of text in various sentences.
Input : San Pedro is a town on the southern part of the island of Ambergris Caye in the Belize District of the nation of Belize, in Central America. According to 2015 mid-year estimates, the town has a population of about 16, 444. It is the second-largest town in the Belize District and largest in the Belize Rural South constituency.
Output : San Pedro is a town on the southern part of the island of Ambergris Caye in the 2.Belize District of the nation of Belize, in Central America.According to 2015 mid-year estimates, the town has a population of about 16, 444.It is the second-largest town in the Belize District and largest in the Belize Rural South constituency.For coding a sentence segmentation model, we can consider splitting a sentence when it encounters any punctuation mark. But modern NLP pipelines have techniques to split even if the document isn’t formatted properly.
Step #2: Word TokenizationBreaking the sentence into individual words called as tokens. We can tokenize them whenever we encounter a space, we can train a model in that way. Even punctuations are considered as individual tokens as they have some meaning.Input : San Pedro is a town on the southern part of the island of Ambergris Caye in the Belize District of the nation of Belize, in Central America. According to 2015 mid-year estimates, the town has a population of about 16, 444. It is the second-largest town in the Belize District and largest in the Belize Rural South constituency.Output : ‘San Pedro’, ’ is’, ’a’, ’town’ and so.
Breaking the sentence into individual words called as tokens. We can tokenize them whenever we encounter a space, we can train a model in that way. Even punctuations are considered as individual tokens as they have some meaning.
Input : San Pedro is a town on the southern part of the island of Ambergris Caye in the Belize District of the nation of Belize, in Central America. According to 2015 mid-year estimates, the town has a population of about 16, 444. It is the second-largest town in the Belize District and largest in the Belize Rural South constituency.
Output : ‘San Pedro’, ’ is’, ’a’, ’town’ and so.
Step #3: Predicting Parts of Speech for each tokenPredicting whether the word is a noun, verb, adjective, adverb, pronoun, etc. This will help to understand what the sentence is talking about. This can be achieved by feeding the tokens( and the words around it) to a pre-trained part-of-speech classification model. This model was fed a lot of English words with various parts of speech tagged to them so that it classifies the similar words it encounters in future in various parts of speech. Again, the models don’t really understand the ‘sense’ of the words, it just classifies them on the basis of its previous experience. It’s pure statistics.The process will look like this:Input : Part of speech classification model
Output : Town - common noun
Is - verb
The - determiner
And similarly, it will classify various tokens.
Predicting whether the word is a noun, verb, adjective, adverb, pronoun, etc. This will help to understand what the sentence is talking about. This can be achieved by feeding the tokens( and the words around it) to a pre-trained part-of-speech classification model. This model was fed a lot of English words with various parts of speech tagged to them so that it classifies the similar words it encounters in future in various parts of speech. Again, the models don’t really understand the ‘sense’ of the words, it just classifies them on the basis of its previous experience. It’s pure statistics.
The process will look like this:
Input : Part of speech classification model
Output : Town - common noun
Is - verb
The - determiner
And similarly, it will classify various tokens.
Step #4: LemmatizationFeeding the model with the root word.For example –There’s a Buffalo grazing in the field.
There are Buffaloes grazing in the field. Here, both Buffalo and Buffaloes mean the same. But, the computer can confuse it as two different terms as it doesn’t know anything. So we have to teach the computer that both terms mean the same. We have to tell a computer that both sentences are talking about the same concept. So we need to find out the most basic form or root form or lemma of the word and feed it to the model accordingly.In a similar fashion, we can use it for verbs too. ‘Play’ and ‘Playing’ should be considered as same.
Feeding the model with the root word.For example –
There’s a Buffalo grazing in the field.
There are Buffaloes grazing in the field.
Here, both Buffalo and Buffaloes mean the same. But, the computer can confuse it as two different terms as it doesn’t know anything. So we have to teach the computer that both terms mean the same. We have to tell a computer that both sentences are talking about the same concept. So we need to find out the most basic form or root form or lemma of the word and feed it to the model accordingly.
In a similar fashion, we can use it for verbs too. ‘Play’ and ‘Playing’ should be considered as same.
Step #5: Identifying stop wordsThere are various words in the English language that are used very frequently like ‘a’, ‘and’, ‘the’ etc. These words make a lot of noise while doing statistical analysis. We can take these words out. Some NLP pipelines will categorize these words as stop words, they will be filtered out while doing some statistical analysis. Definitely, they are needed to understand the dependency between various tokens to get the exact sense of the sentence. The list of stop words varies and depends on what kind of output are you expecting.
There are various words in the English language that are used very frequently like ‘a’, ‘and’, ‘the’ etc. These words make a lot of noise while doing statistical analysis. We can take these words out. Some NLP pipelines will categorize these words as stop words, they will be filtered out while doing some statistical analysis. Definitely, they are needed to understand the dependency between various tokens to get the exact sense of the sentence. The list of stop words varies and depends on what kind of output are you expecting.
Step 6.1: Dependency ParsingThis means finding out the relationship between the words in the sentence and how they are related to each other. We create a parse tree in dependency parsing, with root as the main verb in the sentence. If we talk about the first sentence in our example, then ‘is’ is the main verb and it will be the root of the parse tree. We can construct a parse tree of every sentence with one root word(main verb) associated with it. We can also identify the kind of relationship that exists between the two words. In our example, ‘San Pedro’ is the subject and ‘island’ is the attribute. Thus, the relationship between ‘San Pedro’ and ‘is’, and ‘island’ and ‘is’ can be established.Just like we trained a Machine Learning model to identify various parts of speech, we can train a model to identify the dependency between words by feeding many words. It’s a complex task though. In 2016, Google released a new dependency parser Parsey McParseface which used a deep learning approach.
This means finding out the relationship between the words in the sentence and how they are related to each other. We create a parse tree in dependency parsing, with root as the main verb in the sentence. If we talk about the first sentence in our example, then ‘is’ is the main verb and it will be the root of the parse tree. We can construct a parse tree of every sentence with one root word(main verb) associated with it. We can also identify the kind of relationship that exists between the two words. In our example, ‘San Pedro’ is the subject and ‘island’ is the attribute. Thus, the relationship between ‘San Pedro’ and ‘is’, and ‘island’ and ‘is’ can be established.
Just like we trained a Machine Learning model to identify various parts of speech, we can train a model to identify the dependency between words by feeding many words. It’s a complex task though. In 2016, Google released a new dependency parser Parsey McParseface which used a deep learning approach.
Step 6.2: Finding Noun PhrasesWe can group the words that represent the same idea. For example – It is the second-largest town in the Belize District and largest in the Belize Rural South constituency. Here, tokens ‘second’, ‘largest’ and ‘town’ can be grouped together as they together represent the same thing ‘Belize’. We can use the output of dependency parsing to combine such words. Whether to do this step or not completely depends on the end goal, but it’s always quick to do this if we don’t want much information about which words are adjective, rather focus on other important details.
We can group the words that represent the same idea. For example – It is the second-largest town in the Belize District and largest in the Belize Rural South constituency. Here, tokens ‘second’, ‘largest’ and ‘town’ can be grouped together as they together represent the same thing ‘Belize’. We can use the output of dependency parsing to combine such words. Whether to do this step or not completely depends on the end goal, but it’s always quick to do this if we don’t want much information about which words are adjective, rather focus on other important details.
Step #7: Named Entity Recognition(NER)San Pedro is a town on the southern part of the island of Ambergris Caye in the 2. Belize District of the nation of Belize, in Central America.Here, the NER maps the words with the real world places. The places that actually exist in the physical world. We can automatically extract the real world places present in the document using NLP.If the above sentence is the input, NER will map it like this way:San Pedro - Geographic Entity
Ambergris Caye - Geographic Entity
Belize - Geographic Entity
Central America - Geographic EntityNER systems look for how a word is placed in a sentence and make use of other statistical models to identify what kind of word actually it is. For example – ‘Washington’ can be a geographical location as well as the last name of any person. A good NER system can identify this.Kinds of objects that a typical NER system can tag:People’s names.
Company names.
Geographical locations
Product names.
Date and time.
Amount of money.
Events.
San Pedro is a town on the southern part of the island of Ambergris Caye in the 2. Belize District of the nation of Belize, in Central America.Here, the NER maps the words with the real world places. The places that actually exist in the physical world. We can automatically extract the real world places present in the document using NLP.
If the above sentence is the input, NER will map it like this way:
San Pedro - Geographic Entity
Ambergris Caye - Geographic Entity
Belize - Geographic Entity
Central America - Geographic Entity
NER systems look for how a word is placed in a sentence and make use of other statistical models to identify what kind of word actually it is. For example – ‘Washington’ can be a geographical location as well as the last name of any person. A good NER system can identify this.
Kinds of objects that a typical NER system can tag:
People’s names.
Company names.
Geographical locations
Product names.
Date and time.
Amount of money.
Events.
Step #8: Coreference Resolution:San Pedro is a town on the southern part of the island of Ambergris Caye in the Belize District of the nation of Belize, in Central America. According to 2015 mid-year estimates, the town has a population of about 16, 444. It is the second-largest town in the Belize District and largest in the Belize Rural South constituency.Here, we know that ‘it’ in the sentence 6 stands for San Pedro, but for a computer, it isn’t possible to understand that both the tokens are same because it treats both the sentences as two different things while it’s processing them. Pronouns are used with a high frequency in English literature and it becomes difficult for a computer to understand that both things are same.
San Pedro is a town on the southern part of the island of Ambergris Caye in the Belize District of the nation of Belize, in Central America. According to 2015 mid-year estimates, the town has a population of about 16, 444. It is the second-largest town in the Belize District and largest in the Belize Rural South constituency.
Here, we know that ‘it’ in the sentence 6 stands for San Pedro, but for a computer, it isn’t possible to understand that both the tokens are same because it treats both the sentences as two different things while it’s processing them. Pronouns are used with a high frequency in English literature and it becomes difficult for a computer to understand that both things are same.
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Activation functions in Neural Networks
Decision Tree Introduction with example
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Python | Decision tree implementation
Search Algorithms in AI
ML | Underfitting and Overfitting
Clustering in Machine Learning
Intuition of Adam Optimizer | [
{
"code": null,
"e": 25689,
"s": 25661,
"text": "\n16 Nov, 2018"
},
{
"code": null,
"e": 26119,
"s": 25689,
"text": "The essence of Natural Language Processing lies in making computers understand the natural language. That’s not an easy task though. Computers can understand the structured form of data like spreadsheets and the tables in the database, but human languages, texts, and voices form an unstructured category of data, and it gets difficult for the computer to understand it, and there arises the need for Natural Language Processing."
},
{
"code": null,
"e": 26794,
"s": 26119,
"text": "There’s a lot of natural language data out there in various forms and it would get very easy if computers can understand and process that data. We can train the models in accordance with expected output in different ways. Humans have been writing for thousands of years, there are a lot of literature pieces available, and it would be great if we make computers understand that. But the task is never going to be easy. There are various challenges floating out there like understanding the correct meaning of the sentence, correct Named-Entity Recognition(NER), correct prediction of various parts of speech, coreference resolution(the most challenging thing in my opinion)."
},
{
"code": null,
"e": 27157,
"s": 26794,
"text": "Computers can’t truly understand the human language. If we feed enough data and train a model properly, it can distinguish and try categorizing various parts of speech(noun, verb, adjective, supporter, etc...) based on previously fed data and experiences. If it encounters a new word it tried making the nearest guess which can be embarrassingly wrong few times."
},
{
"code": null,
"e": 27440,
"s": 27157,
"text": "It’s very difficult for a computer to extract the exact meaning from a sentence. For example – The boy radiated fire like vibes. The boy had a very motivating personality or he actually radiated fire? As you see over here, parsing English with a computer is going to be complicated."
},
{
"code": null,
"e": 27850,
"s": 27440,
"text": "There are various stages involved in training a model. Solving a complex problem in Machine Learning means building a pipeline. In simple terms, it means breaking a complex problem into a number of small problems, making models for each of them and then integrating these models. A similar thing is done in NLP. We can break down the process of understanding English for a model into a number of small pieces."
},
{
"code": null,
"e": 28155,
"s": 27850,
"text": "It would be really great if a computer could understand that San Pedro is an island in Belize district in Central America with a population of 16, 444 and it is the second largest town in Belize. But to make the computer understand this, we need to teach computer very basic concepts of written language."
},
{
"code": null,
"e": 28301,
"s": 28155,
"text": "So let’s start by creating an NLP pipeline. It has various steps which will give us the desired output(maybe not in a few rare cases) at the end."
},
{
"code": null,
"e": 29267,
"s": 28301,
"text": "Step #1: Sentence SegmentationBreaking the piece of text in various sentences.Input : San Pedro is a town on the southern part of the island of Ambergris Caye in the Belize District of the nation of Belize, in Central America. According to 2015 mid-year estimates, the town has a population of about 16, 444. It is the second-largest town in the Belize District and largest in the Belize Rural South constituency.Output : San Pedro is a town on the southern part of the island of Ambergris Caye in the 2.Belize District of the nation of Belize, in Central America.According to 2015 mid-year estimates, the town has a population of about 16, 444.It is the second-largest town in the Belize District and largest in the Belize Rural South constituency.For coding a sentence segmentation model, we can consider splitting a sentence when it encounters any punctuation mark. But modern NLP pipelines have techniques to split even if the document isn’t formatted properly."
},
{
"code": null,
"e": 29316,
"s": 29267,
"text": "Breaking the piece of text in various sentences."
},
{
"code": null,
"e": 29652,
"s": 29316,
"text": "Input : San Pedro is a town on the southern part of the island of Ambergris Caye in the Belize District of the nation of Belize, in Central America. According to 2015 mid-year estimates, the town has a population of about 16, 444. It is the second-largest town in the Belize District and largest in the Belize Rural South constituency."
},
{
"code": null,
"e": 30205,
"s": 29652,
"text": "Output : San Pedro is a town on the southern part of the island of Ambergris Caye in the 2.Belize District of the nation of Belize, in Central America.According to 2015 mid-year estimates, the town has a population of about 16, 444.It is the second-largest town in the Belize District and largest in the Belize Rural South constituency.For coding a sentence segmentation model, we can consider splitting a sentence when it encounters any punctuation mark. But modern NLP pipelines have techniques to split even if the document isn’t formatted properly."
},
{
"code": null,
"e": 30843,
"s": 30205,
"text": "Step #2: Word TokenizationBreaking the sentence into individual words called as tokens. We can tokenize them whenever we encounter a space, we can train a model in that way. Even punctuations are considered as individual tokens as they have some meaning.Input : San Pedro is a town on the southern part of the island of Ambergris Caye in the Belize District of the nation of Belize, in Central America. According to 2015 mid-year estimates, the town has a population of about 16, 444. It is the second-largest town in the Belize District and largest in the Belize Rural South constituency.Output : ‘San Pedro’, ’ is’, ’a’, ’town’ and so."
},
{
"code": null,
"e": 31072,
"s": 30843,
"text": "Breaking the sentence into individual words called as tokens. We can tokenize them whenever we encounter a space, we can train a model in that way. Even punctuations are considered as individual tokens as they have some meaning."
},
{
"code": null,
"e": 31408,
"s": 31072,
"text": "Input : San Pedro is a town on the southern part of the island of Ambergris Caye in the Belize District of the nation of Belize, in Central America. According to 2015 mid-year estimates, the town has a population of about 16, 444. It is the second-largest town in the Belize District and largest in the Belize Rural South constituency."
},
{
"code": null,
"e": 31457,
"s": 31408,
"text": "Output : ‘San Pedro’, ’ is’, ’a’, ’town’ and so."
},
{
"code": null,
"e": 32304,
"s": 31457,
"text": "Step #3: Predicting Parts of Speech for each tokenPredicting whether the word is a noun, verb, adjective, adverb, pronoun, etc. This will help to understand what the sentence is talking about. This can be achieved by feeding the tokens( and the words around it) to a pre-trained part-of-speech classification model. This model was fed a lot of English words with various parts of speech tagged to them so that it classifies the similar words it encounters in future in various parts of speech. Again, the models don’t really understand the ‘sense’ of the words, it just classifies them on the basis of its previous experience. It’s pure statistics.The process will look like this:Input : Part of speech classification model \nOutput : Town - common noun\n Is - verb \n The - determiner\nAnd similarly, it will classify various tokens."
},
{
"code": null,
"e": 32903,
"s": 32304,
"text": "Predicting whether the word is a noun, verb, adjective, adverb, pronoun, etc. This will help to understand what the sentence is talking about. This can be achieved by feeding the tokens( and the words around it) to a pre-trained part-of-speech classification model. This model was fed a lot of English words with various parts of speech tagged to them so that it classifies the similar words it encounters in future in various parts of speech. Again, the models don’t really understand the ‘sense’ of the words, it just classifies them on the basis of its previous experience. It’s pure statistics."
},
{
"code": null,
"e": 32936,
"s": 32903,
"text": "The process will look like this:"
},
{
"code": null,
"e": 33056,
"s": 32936,
"text": "Input : Part of speech classification model \nOutput : Town - common noun\n Is - verb \n The - determiner\n"
},
{
"code": null,
"e": 33104,
"s": 33056,
"text": "And similarly, it will classify various tokens."
},
{
"code": null,
"e": 33755,
"s": 33104,
"text": "Step #4: LemmatizationFeeding the model with the root word.For example –There’s a Buffalo grazing in the field. \nThere are Buffaloes grazing in the field. Here, both Buffalo and Buffaloes mean the same. But, the computer can confuse it as two different terms as it doesn’t know anything. So we have to teach the computer that both terms mean the same. We have to tell a computer that both sentences are talking about the same concept. So we need to find out the most basic form or root form or lemma of the word and feed it to the model accordingly.In a similar fashion, we can use it for verbs too. ‘Play’ and ‘Playing’ should be considered as same."
},
{
"code": null,
"e": 33806,
"s": 33755,
"text": "Feeding the model with the root word.For example –"
},
{
"code": null,
"e": 33890,
"s": 33806,
"text": "There’s a Buffalo grazing in the field. \nThere are Buffaloes grazing in the field. "
},
{
"code": null,
"e": 34285,
"s": 33890,
"text": "Here, both Buffalo and Buffaloes mean the same. But, the computer can confuse it as two different terms as it doesn’t know anything. So we have to teach the computer that both terms mean the same. We have to tell a computer that both sentences are talking about the same concept. So we need to find out the most basic form or root form or lemma of the word and feed it to the model accordingly."
},
{
"code": null,
"e": 34387,
"s": 34285,
"text": "In a similar fashion, we can use it for verbs too. ‘Play’ and ‘Playing’ should be considered as same."
},
{
"code": null,
"e": 34950,
"s": 34387,
"text": "Step #5: Identifying stop wordsThere are various words in the English language that are used very frequently like ‘a’, ‘and’, ‘the’ etc. These words make a lot of noise while doing statistical analysis. We can take these words out. Some NLP pipelines will categorize these words as stop words, they will be filtered out while doing some statistical analysis. Definitely, they are needed to understand the dependency between various tokens to get the exact sense of the sentence. The list of stop words varies and depends on what kind of output are you expecting."
},
{
"code": null,
"e": 35482,
"s": 34950,
"text": "There are various words in the English language that are used very frequently like ‘a’, ‘and’, ‘the’ etc. These words make a lot of noise while doing statistical analysis. We can take these words out. Some NLP pipelines will categorize these words as stop words, they will be filtered out while doing some statistical analysis. Definitely, they are needed to understand the dependency between various tokens to get the exact sense of the sentence. The list of stop words varies and depends on what kind of output are you expecting."
},
{
"code": null,
"e": 36484,
"s": 35482,
"text": "Step 6.1: Dependency ParsingThis means finding out the relationship between the words in the sentence and how they are related to each other. We create a parse tree in dependency parsing, with root as the main verb in the sentence. If we talk about the first sentence in our example, then ‘is’ is the main verb and it will be the root of the parse tree. We can construct a parse tree of every sentence with one root word(main verb) associated with it. We can also identify the kind of relationship that exists between the two words. In our example, ‘San Pedro’ is the subject and ‘island’ is the attribute. Thus, the relationship between ‘San Pedro’ and ‘is’, and ‘island’ and ‘is’ can be established.Just like we trained a Machine Learning model to identify various parts of speech, we can train a model to identify the dependency between words by feeding many words. It’s a complex task though. In 2016, Google released a new dependency parser Parsey McParseface which used a deep learning approach."
},
{
"code": null,
"e": 37158,
"s": 36484,
"text": "This means finding out the relationship between the words in the sentence and how they are related to each other. We create a parse tree in dependency parsing, with root as the main verb in the sentence. If we talk about the first sentence in our example, then ‘is’ is the main verb and it will be the root of the parse tree. We can construct a parse tree of every sentence with one root word(main verb) associated with it. We can also identify the kind of relationship that exists between the two words. In our example, ‘San Pedro’ is the subject and ‘island’ is the attribute. Thus, the relationship between ‘San Pedro’ and ‘is’, and ‘island’ and ‘is’ can be established."
},
{
"code": null,
"e": 37459,
"s": 37158,
"text": "Just like we trained a Machine Learning model to identify various parts of speech, we can train a model to identify the dependency between words by feeding many words. It’s a complex task though. In 2016, Google released a new dependency parser Parsey McParseface which used a deep learning approach."
},
{
"code": null,
"e": 38056,
"s": 37459,
"text": "Step 6.2: Finding Noun PhrasesWe can group the words that represent the same idea. For example – It is the second-largest town in the Belize District and largest in the Belize Rural South constituency. Here, tokens ‘second’, ‘largest’ and ‘town’ can be grouped together as they together represent the same thing ‘Belize’. We can use the output of dependency parsing to combine such words. Whether to do this step or not completely depends on the end goal, but it’s always quick to do this if we don’t want much information about which words are adjective, rather focus on other important details."
},
{
"code": null,
"e": 38623,
"s": 38056,
"text": "We can group the words that represent the same idea. For example – It is the second-largest town in the Belize District and largest in the Belize Rural South constituency. Here, tokens ‘second’, ‘largest’ and ‘town’ can be grouped together as they together represent the same thing ‘Belize’. We can use the output of dependency parsing to combine such words. Whether to do this step or not completely depends on the end goal, but it’s always quick to do this if we don’t want much information about which words are adjective, rather focus on other important details."
},
{
"code": null,
"e": 39635,
"s": 38623,
"text": "Step #7: Named Entity Recognition(NER)San Pedro is a town on the southern part of the island of Ambergris Caye in the 2. Belize District of the nation of Belize, in Central America.Here, the NER maps the words with the real world places. The places that actually exist in the physical world. We can automatically extract the real world places present in the document using NLP.If the above sentence is the input, NER will map it like this way:San Pedro - Geographic Entity\nAmbergris Caye - Geographic Entity\nBelize - Geographic Entity\nCentral America - Geographic EntityNER systems look for how a word is placed in a sentence and make use of other statistical models to identify what kind of word actually it is. For example – ‘Washington’ can be a geographical location as well as the last name of any person. A good NER system can identify this.Kinds of objects that a typical NER system can tag:People’s names. \nCompany names. \nGeographical locations\nProduct names. \nDate and time. \nAmount of money. \nEvents."
},
{
"code": null,
"e": 39975,
"s": 39635,
"text": "San Pedro is a town on the southern part of the island of Ambergris Caye in the 2. Belize District of the nation of Belize, in Central America.Here, the NER maps the words with the real world places. The places that actually exist in the physical world. We can automatically extract the real world places present in the document using NLP."
},
{
"code": null,
"e": 40042,
"s": 39975,
"text": "If the above sentence is the input, NER will map it like this way:"
},
{
"code": null,
"e": 40170,
"s": 40042,
"text": "San Pedro - Geographic Entity\nAmbergris Caye - Geographic Entity\nBelize - Geographic Entity\nCentral America - Geographic Entity"
},
{
"code": null,
"e": 40448,
"s": 40170,
"text": "NER systems look for how a word is placed in a sentence and make use of other statistical models to identify what kind of word actually it is. For example – ‘Washington’ can be a geographical location as well as the last name of any person. A good NER system can identify this."
},
{
"code": null,
"e": 40500,
"s": 40448,
"text": "Kinds of objects that a typical NER system can tag:"
},
{
"code": null,
"e": 40614,
"s": 40500,
"text": "People’s names. \nCompany names. \nGeographical locations\nProduct names. \nDate and time. \nAmount of money. \nEvents."
},
{
"code": null,
"e": 41351,
"s": 40614,
"text": "Step #8: Coreference Resolution:San Pedro is a town on the southern part of the island of Ambergris Caye in the Belize District of the nation of Belize, in Central America. According to 2015 mid-year estimates, the town has a population of about 16, 444. It is the second-largest town in the Belize District and largest in the Belize Rural South constituency.Here, we know that ‘it’ in the sentence 6 stands for San Pedro, but for a computer, it isn’t possible to understand that both the tokens are same because it treats both the sentences as two different things while it’s processing them. Pronouns are used with a high frequency in English literature and it becomes difficult for a computer to understand that both things are same."
},
{
"code": null,
"e": 41679,
"s": 41351,
"text": "San Pedro is a town on the southern part of the island of Ambergris Caye in the Belize District of the nation of Belize, in Central America. According to 2015 mid-year estimates, the town has a population of about 16, 444. It is the second-largest town in the Belize District and largest in the Belize Rural South constituency."
},
{
"code": null,
"e": 42057,
"s": 41679,
"text": "Here, we know that ‘it’ in the sentence 6 stands for San Pedro, but for a computer, it isn’t possible to understand that both the tokens are same because it treats both the sentences as two different things while it’s processing them. Pronouns are used with a high frequency in English literature and it becomes difficult for a computer to understand that both things are same."
},
{
"code": null,
"e": 42074,
"s": 42057,
"text": "Machine Learning"
},
{
"code": null,
"e": 42091,
"s": 42074,
"text": "Machine Learning"
},
{
"code": null,
"e": 42189,
"s": 42091,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42212,
"s": 42189,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 42252,
"s": 42212,
"text": "Activation functions in Neural Networks"
},
{
"code": null,
"e": 42292,
"s": 42252,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 42333,
"s": 42292,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 42366,
"s": 42333,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 42404,
"s": 42366,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 42428,
"s": 42404,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 42462,
"s": 42428,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 42493,
"s": 42462,
"text": "Clustering in Machine Learning"
}
] |
JavaScript string.replace() Method - GeeksforGeeks | 06 Oct, 2021
Below is the example of the string.replace() Method.
Example:
javascript
<script> var string = 'GeeksForGeeks'; var newstring = string.replace(/GeeksForGeeks/, 'GfG'); document.write(newstring);</script>
Output:
GfG
The string.replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged.Syntax:
str.replace(A, B)
Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string. Return Values: It returns a new string with replaced items.JavaScript code to show the working of this method: Code #1: Here the contents of the string GeeksForGeeks will be replaced with gfg.
javascript
<script> // Assigning a string var string = 'GeeksForGeeks is a CS portal'; // Calling replace() methodvar newstring = string.replace(/GeeksForGeeks/, 'gfg'); // Printing replaced stringdocument.write(newstring); </script>
Output:
gfg is a CS portal
Code #2:
javascript
<script> // Taking a regular expression var re = /GeeksForGeeks/; // Taking a string as inputvar string = 'GeeksForGeeks is a CS portal'; // Calling replace() method to replace// GeeksForGeeks from string with gfgvar newstring = string.replace(re, 'gfg'); // Printing new string with replaced itemsdocument.write(newstring); </script>
Output:
gfg is a CS portal
Supported Browsers:
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 5.5 and above
Opera 4 and above
Safari 1 and above
ysachin2314
JavaScript-Methods
javascript-string
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 ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26296,
"s": 26268,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 26351,
"s": 26296,
"text": "Below is the example of the string.replace() Method. "
},
{
"code": null,
"e": 26362,
"s": 26351,
"text": "Example: "
},
{
"code": null,
"e": 26373,
"s": 26362,
"text": "javascript"
},
{
"code": "<script> var string = 'GeeksForGeeks'; var newstring = string.replace(/GeeksForGeeks/, 'GfG'); document.write(newstring);</script>",
"e": 26514,
"s": 26373,
"text": null
},
{
"code": null,
"e": 26524,
"s": 26514,
"text": "Output: "
},
{
"code": null,
"e": 26528,
"s": 26524,
"text": "GfG"
},
{
"code": null,
"e": 26738,
"s": 26528,
"text": "The string.replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged.Syntax: "
},
{
"code": null,
"e": 26756,
"s": 26738,
"text": "str.replace(A, B)"
},
{
"code": null,
"e": 27076,
"s": 26756,
"text": "Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string. Return Values: It returns a new string with replaced items.JavaScript code to show the working of this method: Code #1: Here the contents of the string GeeksForGeeks will be replaced with gfg. "
},
{
"code": null,
"e": 27087,
"s": 27076,
"text": "javascript"
},
{
"code": "<script> // Assigning a string var string = 'GeeksForGeeks is a CS portal'; // Calling replace() methodvar newstring = string.replace(/GeeksForGeeks/, 'gfg'); // Printing replaced stringdocument.write(newstring); </script>",
"e": 27317,
"s": 27087,
"text": null
},
{
"code": null,
"e": 27327,
"s": 27317,
"text": "Output: "
},
{
"code": null,
"e": 27346,
"s": 27327,
"text": "gfg is a CS portal"
},
{
"code": null,
"e": 27357,
"s": 27346,
"text": "Code #2: "
},
{
"code": null,
"e": 27368,
"s": 27357,
"text": "javascript"
},
{
"code": "<script> // Taking a regular expression var re = /GeeksForGeeks/; // Taking a string as inputvar string = 'GeeksForGeeks is a CS portal'; // Calling replace() method to replace// GeeksForGeeks from string with gfgvar newstring = string.replace(re, 'gfg'); // Printing new string with replaced itemsdocument.write(newstring); </script>",
"e": 27710,
"s": 27368,
"text": null
},
{
"code": null,
"e": 27720,
"s": 27710,
"text": "Output: "
},
{
"code": null,
"e": 27739,
"s": 27720,
"text": "gfg is a CS portal"
},
{
"code": null,
"e": 27761,
"s": 27739,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 27787,
"s": 27761,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 27805,
"s": 27787,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 27825,
"s": 27805,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 27857,
"s": 27825,
"text": "Internet Explorer 5.5 and above"
},
{
"code": null,
"e": 27875,
"s": 27857,
"text": "Opera 4 and above"
},
{
"code": null,
"e": 27894,
"s": 27875,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 27908,
"s": 27896,
"text": "ysachin2314"
},
{
"code": null,
"e": 27927,
"s": 27908,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 27945,
"s": 27927,
"text": "javascript-string"
},
{
"code": null,
"e": 27956,
"s": 27945,
"text": "JavaScript"
},
{
"code": null,
"e": 27973,
"s": 27956,
"text": "Web Technologies"
},
{
"code": null,
"e": 28071,
"s": 27973,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28111,
"s": 28071,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28156,
"s": 28111,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28217,
"s": 28156,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28289,
"s": 28217,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28341,
"s": 28289,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28381,
"s": 28341,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28414,
"s": 28381,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28459,
"s": 28414,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28502,
"s": 28459,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to get keyboard input in PyGame ? - GeeksforGeeks | 30 Aug, 2021
While using pygame module of Python, we sometimes need to use the keyboard input for various operations such as moving a character in a certain direction. To achieve this, we have to see all the events happening. Pygame keeps track of events that occur, which we can see with the events.get() function. In this article, we are going to discuss how we can get and use various keyboard inputs in pygame.
Whenever a key is pressed or released, pygame.event() queue methods pygame.KEYDOWN and pygame.KEYUP events respectively.
For example, if we want to detect if a key was pressed, we will track if any event of pygame.KEYDOWN occurred or not and, accordingly, we will get to know if any key was pressed or not. The code for detecting if any key was pressed or not can be written as:
Python
# importing pygame moduleimport pygame # importing sys moduleimport sys # initialising pygamepygame.init() # creating displaydisplay = pygame.display.set_mode((300, 300)) # creating a running loopwhile True: # creating a loop to check events that # are occuring for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # checking if keydown event happened or not if event.type == pygame.KEYDOWN: # if keydown event happened # than printing a string to output print("A key has been pressed")
Output:
After running this code, it is seen that whenever a key has pressed a string “A key has been pressed” is printed on the terminal
To know which key was pressed, we have to check the event.key variable corresponds to which pygame keys. For example, the pygame key for the letter “A” is “K_a” then we will compare event.Key with K a and if it comes to be same that means the key “A” was pressed.
The various keyboard key and corresponding pygame keys are:
For example, let’s create a code to check if key “A” or “J” or “P” or “M” was pressed or not. The code for checking will be:
Python
# importing pygame moduleimport pygame # importing sys moduleimport sys # initialising pygamepygame.init() # creating displaydisplay = pygame.display.set_mode((300, 300)) # creating a running loopwhile True: # creating a loop to check events that # are occuring for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # checking if keydown event happened or not if event.type == pygame.KEYDOWN: # checking if key "A" was pressed if event.key == pygame.K_a: print("Key A has been pressed") # checking if key "J" was pressed if event.key == pygame.K_j: print("Key J has been pressed") # checking if key "P" was pressed if event.key == pygame.K_p: print("Key P has been pressed") # checking if key "M" was pressed if event.key == pygame.K_m: print("Key M has been pressed")
Output:
When we run this code and press the given keys the corresponding strings will be printed on the terminal.
adnanirshad158
saurabh1990aror
Picked
Python-PyGame
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 | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n30 Aug, 2021"
},
{
"code": null,
"e": 25939,
"s": 25537,
"text": "While using pygame module of Python, we sometimes need to use the keyboard input for various operations such as moving a character in a certain direction. To achieve this, we have to see all the events happening. Pygame keeps track of events that occur, which we can see with the events.get() function. In this article, we are going to discuss how we can get and use various keyboard inputs in pygame."
},
{
"code": null,
"e": 26060,
"s": 25939,
"text": "Whenever a key is pressed or released, pygame.event() queue methods pygame.KEYDOWN and pygame.KEYUP events respectively."
},
{
"code": null,
"e": 26318,
"s": 26060,
"text": "For example, if we want to detect if a key was pressed, we will track if any event of pygame.KEYDOWN occurred or not and, accordingly, we will get to know if any key was pressed or not. The code for detecting if any key was pressed or not can be written as:"
},
{
"code": null,
"e": 26325,
"s": 26318,
"text": "Python"
},
{
"code": "# importing pygame moduleimport pygame # importing sys moduleimport sys # initialising pygamepygame.init() # creating displaydisplay = pygame.display.set_mode((300, 300)) # creating a running loopwhile True: # creating a loop to check events that # are occuring for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # checking if keydown event happened or not if event.type == pygame.KEYDOWN: # if keydown event happened # than printing a string to output print(\"A key has been pressed\")",
"e": 26959,
"s": 26325,
"text": null
},
{
"code": null,
"e": 26970,
"s": 26962,
"text": "Output:"
},
{
"code": null,
"e": 27101,
"s": 26972,
"text": "After running this code, it is seen that whenever a key has pressed a string “A key has been pressed” is printed on the terminal"
},
{
"code": null,
"e": 27365,
"s": 27101,
"text": "To know which key was pressed, we have to check the event.key variable corresponds to which pygame keys. For example, the pygame key for the letter “A” is “K_a” then we will compare event.Key with K a and if it comes to be same that means the key “A” was pressed."
},
{
"code": null,
"e": 27427,
"s": 27367,
"text": "The various keyboard key and corresponding pygame keys are:"
},
{
"code": null,
"e": 27555,
"s": 27429,
"text": "For example, let’s create a code to check if key “A” or “J” or “P” or “M” was pressed or not. The code for checking will be: "
},
{
"code": null,
"e": 27562,
"s": 27555,
"text": "Python"
},
{
"code": "# importing pygame moduleimport pygame # importing sys moduleimport sys # initialising pygamepygame.init() # creating displaydisplay = pygame.display.set_mode((300, 300)) # creating a running loopwhile True: # creating a loop to check events that # are occuring for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # checking if keydown event happened or not if event.type == pygame.KEYDOWN: # checking if key \"A\" was pressed if event.key == pygame.K_a: print(\"Key A has been pressed\") # checking if key \"J\" was pressed if event.key == pygame.K_j: print(\"Key J has been pressed\") # checking if key \"P\" was pressed if event.key == pygame.K_p: print(\"Key P has been pressed\") # checking if key \"M\" was pressed if event.key == pygame.K_m: print(\"Key M has been pressed\")",
"e": 28639,
"s": 27562,
"text": null
},
{
"code": null,
"e": 28647,
"s": 28639,
"text": "Output:"
},
{
"code": null,
"e": 28753,
"s": 28647,
"text": "When we run this code and press the given keys the corresponding strings will be printed on the terminal."
},
{
"code": null,
"e": 28768,
"s": 28753,
"text": "adnanirshad158"
},
{
"code": null,
"e": 28784,
"s": 28768,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28791,
"s": 28784,
"text": "Picked"
},
{
"code": null,
"e": 28805,
"s": 28791,
"text": "Python-PyGame"
},
{
"code": null,
"e": 28812,
"s": 28805,
"text": "Python"
},
{
"code": null,
"e": 28910,
"s": 28812,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28942,
"s": 28910,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28984,
"s": 28942,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29026,
"s": 28984,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29082,
"s": 29026,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29109,
"s": 29082,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29140,
"s": 29109,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29179,
"s": 29140,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29208,
"s": 29179,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29230,
"s": 29208,
"text": "Defaultdict in Python"
}
] |
Scala List size() method with example - GeeksforGeeks | 26 Jul, 2019
The size() method is utilized to find the number of elements in the stated list.
Method Definition: def size(): Int
Return Type: It returns the number of elements in the stated list.
Example #1:
// Scala program of size()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 2, 3, 4, 5) // Applying size method val result = m1.size // Displays output println(result) }}
5
Example #2:
// Scala program of size()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 0) // Applying size method val result = m1.size // Displays output println(result) }}
2
Scala
Scala-list
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 Tutorial – Learn Scala with Step By Step Guide
Inheritance in Scala
Operators in Scala
Scala Constructors
Scala String substring() method with example
Lambda Expression in Scala
How to get the first element of List in Scala
Break statement in Scala | [
{
"code": null,
"e": 25167,
"s": 25139,
"text": "\n26 Jul, 2019"
},
{
"code": null,
"e": 25248,
"s": 25167,
"text": "The size() method is utilized to find the number of elements in the stated list."
},
{
"code": null,
"e": 25283,
"s": 25248,
"text": "Method Definition: def size(): Int"
},
{
"code": null,
"e": 25350,
"s": 25283,
"text": "Return Type: It returns the number of elements in the stated list."
},
{
"code": null,
"e": 25362,
"s": 25350,
"text": "Example #1:"
},
{
"code": "// Scala program of size()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 2, 3, 4, 5) // Applying size method val result = m1.size // Displays output println(result) }}",
"e": 25695,
"s": 25362,
"text": null
},
{
"code": null,
"e": 25698,
"s": 25695,
"text": "5\n"
},
{
"code": null,
"e": 25710,
"s": 25698,
"text": "Example #2:"
},
{
"code": "// Scala program of size()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 0) // Applying size method val result = m1.size // Displays output println(result) }}",
"e": 26034,
"s": 25710,
"text": null
},
{
"code": null,
"e": 26037,
"s": 26034,
"text": "2\n"
},
{
"code": null,
"e": 26043,
"s": 26037,
"text": "Scala"
},
{
"code": null,
"e": 26054,
"s": 26043,
"text": "Scala-list"
},
{
"code": null,
"e": 26067,
"s": 26054,
"text": "Scala-Method"
},
{
"code": null,
"e": 26073,
"s": 26067,
"text": "Scala"
},
{
"code": null,
"e": 26171,
"s": 26073,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26193,
"s": 26171,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 26219,
"s": 26193,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 26272,
"s": 26219,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 26293,
"s": 26272,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 26312,
"s": 26293,
"text": "Operators in Scala"
},
{
"code": null,
"e": 26331,
"s": 26312,
"text": "Scala Constructors"
},
{
"code": null,
"e": 26376,
"s": 26331,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 26403,
"s": 26376,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 26449,
"s": 26403,
"text": "How to get the first element of List in Scala"
}
] |
How to Install Katoolin on Linux Mint? - GeeksforGeeks | 06 Jun, 2019
When the question comes which Linux Distro is best for ethical hacking then this becomes typical to choose with. Everyone likes the different environment, looks and feel. At last, they find that there is no perfect Distro. There is one way that we can add all Kali Linux Hacking tools in any other Linux Debian based Distro using Katoolin. Katoolin is a script which helps to install all Kali Linux Hacking tools in any other Linux Debian based Distribution.
Step 1: To install Katoolin we need to clone a git hub repository using git command. In some OS (Linux based) Git is not pre-installed so we can install it by using the following command:
sudo apt-get install git
Step 2: After installing git we need to clone the git hub repository, copy the link from below
git clone https://github.com/LionSec/katoolin.git && cp katoolin/katoolin.py /usr/bin/katoolin
Step 3: After cloning the repository we need to give it executable permissions using the following command:
chmod +x /usr/bin/katoolin
Step 4: After completing all the steps just below command to confirm the installation.
katoolin
Using katoolin is very simple. You can enjoy all kali Linux repositories and install all hacking tools you need. Please note that before installing anything from katoolin you should remove previously added manual repositories from other sources to avoid errors.
Linux-Unix
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
Top Programming Languages for Android App Development
How to Run a Python Script using Docker?
Setting up the environment in Java | [
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n06 Jun, 2019"
},
{
"code": null,
"e": 26110,
"s": 25651,
"text": "When the question comes which Linux Distro is best for ethical hacking then this becomes typical to choose with. Everyone likes the different environment, looks and feel. At last, they find that there is no perfect Distro. There is one way that we can add all Kali Linux Hacking tools in any other Linux Debian based Distro using Katoolin. Katoolin is a script which helps to install all Kali Linux Hacking tools in any other Linux Debian based Distribution."
},
{
"code": null,
"e": 26298,
"s": 26110,
"text": "Step 1: To install Katoolin we need to clone a git hub repository using git command. In some OS (Linux based) Git is not pre-installed so we can install it by using the following command:"
},
{
"code": null,
"e": 26323,
"s": 26298,
"text": "sudo apt-get install git"
},
{
"code": null,
"e": 26418,
"s": 26323,
"text": "Step 2: After installing git we need to clone the git hub repository, copy the link from below"
},
{
"code": null,
"e": 26513,
"s": 26418,
"text": "git clone https://github.com/LionSec/katoolin.git && cp katoolin/katoolin.py /usr/bin/katoolin"
},
{
"code": null,
"e": 26621,
"s": 26513,
"text": "Step 3: After cloning the repository we need to give it executable permissions using the following command:"
},
{
"code": null,
"e": 26648,
"s": 26621,
"text": "chmod +x /usr/bin/katoolin"
},
{
"code": null,
"e": 26735,
"s": 26648,
"text": "Step 4: After completing all the steps just below command to confirm the installation."
},
{
"code": null,
"e": 26744,
"s": 26735,
"text": "katoolin"
},
{
"code": null,
"e": 27006,
"s": 26744,
"text": "Using katoolin is very simple. You can enjoy all kali Linux repositories and install all hacking tools you need. Please note that before installing anything from katoolin you should remove previously added manual repositories from other sources to avoid errors."
},
{
"code": null,
"e": 27017,
"s": 27006,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27026,
"s": 27017,
"text": "TechTips"
},
{
"code": null,
"e": 27124,
"s": 27026,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27159,
"s": 27124,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27193,
"s": 27159,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27219,
"s": 27193,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27248,
"s": 27219,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27285,
"s": 27248,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27338,
"s": 27285,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 27364,
"s": 27338,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27418,
"s": 27364,
"text": "Top Programming Languages for Android App Development"
},
{
"code": null,
"e": 27459,
"s": 27418,
"text": "How to Run a Python Script using Docker?"
}
] |
Hello World in R Programming - GeeksforGeeks | 22 Jul, 2021
When we start to learn any programming languages we do follow a tradition to begin HelloWorld as our first basic program. Here we are going to learn that tradition. An interesting thing about R programming is that we can get our things done with very little code.
Before we start to learn to code, let’s see the process of where to download the needed Softwares and programs.
Go to the official site of R programming and download R for windows(or Mac).
Install IDE like Rstudio, RTVS, StatET for running programs(you can download Rstudio here).We can write and run programs in IDE, but you have to download R before installing IDE.
For the HelloWorld program, we just need a print function. No need of any packages or main functions, just a simple print function is enough.
print("HelloWorld")
Output:
"HelloWorld"
print() is a function which is used to print the values on to the output screen. It also has arguments, we can use it if needed. For example, in the above program, the output is printed with quotes by default we can remove it if needed.
print("HelloWorld", quote=FALSE)
Output:
HelloWorld
We passed the argument named quote in print function which value is set to be false to remove the quotes.
There are many ways to run an R program:
Method 1: Using command prompt or terminalWrite your code in notepad or any text editor, save it as “helloworld.r”, Run it in command prompt or terminal using the command “Rscript helloworld.r”.
Write your code in notepad or any text editor, save it as “helloworld.r”,
Run it in command prompt or terminal using the command “Rscript helloworld.r”.
Method 2: Using an online IDEThere are many online IDEs(click here) available. We can use that without the need of installing or downloading anything.
Method 3: Using IDE like Rstudio, RTVS, StatETYou can download and install these IDE in your system and can write and run the program there. Rstudio & statET(Eclipse software)is available for Windows, Mac, and Linux. RTVS presently available only on windows.
Picked
R-basics
R-Input/Output
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Convert Factor to Numeric and Numeric to Factor in R Programming
Group by function in R using Dplyr
How to Change Axis Scales in R Plots? | [
{
"code": null,
"e": 30289,
"s": 30261,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 30553,
"s": 30289,
"text": "When we start to learn any programming languages we do follow a tradition to begin HelloWorld as our first basic program. Here we are going to learn that tradition. An interesting thing about R programming is that we can get our things done with very little code."
},
{
"code": null,
"e": 30665,
"s": 30553,
"text": "Before we start to learn to code, let’s see the process of where to download the needed Softwares and programs."
},
{
"code": null,
"e": 30742,
"s": 30665,
"text": "Go to the official site of R programming and download R for windows(or Mac)."
},
{
"code": null,
"e": 30921,
"s": 30742,
"text": "Install IDE like Rstudio, RTVS, StatET for running programs(you can download Rstudio here).We can write and run programs in IDE, but you have to download R before installing IDE."
},
{
"code": null,
"e": 31063,
"s": 30921,
"text": "For the HelloWorld program, we just need a print function. No need of any packages or main functions, just a simple print function is enough."
},
{
"code": "print(\"HelloWorld\")",
"e": 31083,
"s": 31063,
"text": null
},
{
"code": null,
"e": 31091,
"s": 31083,
"text": "Output:"
},
{
"code": null,
"e": 31106,
"s": 31091,
"text": "\"HelloWorld\" \n"
},
{
"code": null,
"e": 31343,
"s": 31106,
"text": "print() is a function which is used to print the values on to the output screen. It also has arguments, we can use it if needed. For example, in the above program, the output is printed with quotes by default we can remove it if needed."
},
{
"code": "print(\"HelloWorld\", quote=FALSE)",
"e": 31376,
"s": 31343,
"text": null
},
{
"code": null,
"e": 31384,
"s": 31376,
"text": "Output:"
},
{
"code": null,
"e": 31398,
"s": 31384,
"text": "HelloWorld \n"
},
{
"code": null,
"e": 31504,
"s": 31398,
"text": "We passed the argument named quote in print function which value is set to be false to remove the quotes."
},
{
"code": null,
"e": 31545,
"s": 31504,
"text": "There are many ways to run an R program:"
},
{
"code": null,
"e": 31740,
"s": 31545,
"text": "Method 1: Using command prompt or terminalWrite your code in notepad or any text editor, save it as “helloworld.r”, Run it in command prompt or terminal using the command “Rscript helloworld.r”."
},
{
"code": null,
"e": 31814,
"s": 31740,
"text": "Write your code in notepad or any text editor, save it as “helloworld.r”,"
},
{
"code": null,
"e": 31894,
"s": 31814,
"text": " Run it in command prompt or terminal using the command “Rscript helloworld.r”."
},
{
"code": null,
"e": 32045,
"s": 31894,
"text": "Method 2: Using an online IDEThere are many online IDEs(click here) available. We can use that without the need of installing or downloading anything."
},
{
"code": null,
"e": 32304,
"s": 32045,
"text": "Method 3: Using IDE like Rstudio, RTVS, StatETYou can download and install these IDE in your system and can write and run the program there. Rstudio & statET(Eclipse software)is available for Windows, Mac, and Linux. RTVS presently available only on windows."
},
{
"code": null,
"e": 32311,
"s": 32304,
"text": "Picked"
},
{
"code": null,
"e": 32320,
"s": 32311,
"text": "R-basics"
},
{
"code": null,
"e": 32335,
"s": 32320,
"text": "R-Input/Output"
},
{
"code": null,
"e": 32346,
"s": 32335,
"text": "R Language"
},
{
"code": null,
"e": 32444,
"s": 32346,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32489,
"s": 32444,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 32547,
"s": 32489,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 32599,
"s": 32547,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 32631,
"s": 32599,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 32694,
"s": 32631,
"text": "Adding elements in a vector in R programming - append() method"
},
{
"code": null,
"e": 32738,
"s": 32694,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 32790,
"s": 32738,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 32855,
"s": 32790,
"text": "Convert Factor to Numeric and Numeric to Factor in R Programming"
},
{
"code": null,
"e": 32890,
"s": 32855,
"text": "Group by function in R using Dplyr"
}
] |
Union of two arrays | Practice | GeeksforGeeks | Given two arrays a[] and b[] of size n and m respectively. The task is to find union between these two arrays.
Union of the two arrays can be defined as the set containing distinct elements from both the arrays. If there are repetitions, then only one occurrence of element should be printed in the union.
Example 1:
Input:
5 3
1 2 3 4 5
1 2 3
Output:
5
Explanation:
1, 2, 3, 4 and 5 are the
elements which comes in the union set
of both arrays. So count is 5.
Example 2:
Input:
6 2
85 25 1 32 54 6
85 2
Output:
7
Explanation:
85, 25, 1, 32, 54, 6, and
2 are the elements which comes in the
union set of both arrays. So count is 7.
Your Task:
Complete doUnion funciton that takes a, n, b, m as parameters and returns the count of union elements of the two arrays. The printing is done by the driver code.
Constraints:
1 ≤ n, m ≤ 105
0 ≤ a[i], b[i] < 105
Expected Time Complexity : O((n+m)log(n+m))
Expected Auxilliary Space : O(n+m)
0
ranabirchakraborty21819 hours ago
Use Hashset, which doesn't allow duplicate elements.class Solution{ public static int doUnion(int a[], int n, int b[], int m) { int count = 0; Set<Integer> set = new HashSet<Integer>(); for(int i=0; i<n; i++){ if(set.add(a[i])){ ++count; } } for(int j=0; j<m; j++){ if(set.add(b[j])){ ++count; } } return count; }}
+1
harshscode2 days ago
set contains unique elements......
set<int> s;
for(int i=0;i<n;i++)
s.insert(a[i]);
for(int i=0;i<m;i++)
s.insert(b[i]);
return s.size();
0
neetikat1662 days ago
int doUnion(int a[], int n, int b[], int m) { //code here set<int> s; for(int i=0;i<n;i++){ s.insert(a[i]); } for(int i=0;i<m;i++){ s.insert(b[i]); } return s.size(); }
0
niravramotiya0034 days ago
def doUnion(self,a,n,b,m):
a.extend(b)
temp=set(a)
return(len(temp))
0
shubham211019974 days ago
public static int doUnion(int a[], int n, int b[], int m)
{
HashSet<Integer>h=new HashSet<>();
for(int i:a)
h.add(i);
for(int i:b)
h.add(i);
return h.size();
}
0
vikashdas7704 days ago
def doUnion(self,a,n,b,m): out = a[:] + b[:] final_list = list(set(out)) return len(final_list)
0
adityapratapsinghaps3335 days ago
int doUnion(int a[], int n, int b[], int m) {
map<int,int>freq;
int i;
for(i=0;i<n;i++){
freq[a[i]]++;
}
for(i=0;i<m;i++){
freq[b[i]]++;
}
return freq.size();
}
0
yashshivhare5 days ago
doUnion(a, n, b, m){ let freq={}, count=0; for(let num of a) freq[num]?freq[num]++:freq[num]=1; for(let num of b) freq[num]?freq[num]++:freq[num]=1; for(let key in freq) count++; return count; }
0
anmolbansal25 days ago
//Java code
public static int doUnion(int a[], int n, int b[], int m) { Set<Integer>set=new HashSet<>(); for(int i:a){ set.add(i); } for(int i:b){ set.add(i); } return set.size(); }
0
aishaparween5461 week ago
//we can do this by using Hashset HashSet<Integer> set=new HashSet<>(); for(int i=0;i<n;i++) { set.add(a[i]); } for(int i=0;i<m;i++) { set.add(b[i]); } return set.size();//which return the count of element ofunion of two arrays }
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": 350,
"s": 238,
"text": "Given two arrays a[] and b[] of size n and m respectively. The task is to find union between these two arrays. "
},
{
"code": null,
"e": 545,
"s": 350,
"text": "Union of the two arrays can be defined as the set containing distinct elements from both the arrays. If there are repetitions, then only one occurrence of element should be printed in the union."
},
{
"code": null,
"e": 556,
"s": 545,
"text": "Example 1:"
},
{
"code": null,
"e": 703,
"s": 556,
"text": "Input:\n5 3\n1 2 3 4 5\n1 2 3\nOutput: \n5\nExplanation: \n1, 2, 3, 4 and 5 are the\nelements which comes in the union set\nof both arrays. So count is 5.\n"
},
{
"code": null,
"e": 714,
"s": 703,
"text": "Example 2:"
},
{
"code": null,
"e": 878,
"s": 714,
"text": "Input:\n6 2 \n85 25 1 32 54 6\n85 2 \nOutput: \n7\nExplanation: \n85, 25, 1, 32, 54, 6, and\n2 are the elements which comes in the\nunion set of both arrays. So count is 7."
},
{
"code": null,
"e": 1051,
"s": 878,
"text": "Your Task:\nComplete doUnion funciton that takes a, n, b, m as parameters and returns the count of union elements of the two arrays. The printing is done by the driver code."
},
{
"code": null,
"e": 1100,
"s": 1051,
"text": "Constraints:\n1 ≤ n, m ≤ 105\n0 ≤ a[i], b[i] < 105"
},
{
"code": null,
"e": 1179,
"s": 1100,
"text": "Expected Time Complexity : O((n+m)log(n+m))\nExpected Auxilliary Space : O(n+m)"
},
{
"code": null,
"e": 1181,
"s": 1179,
"text": "0"
},
{
"code": null,
"e": 1215,
"s": 1181,
"text": "ranabirchakraborty21819 hours ago"
},
{
"code": null,
"e": 1654,
"s": 1215,
"text": "Use Hashset, which doesn't allow duplicate elements.class Solution{ public static int doUnion(int a[], int n, int b[], int m) { int count = 0; Set<Integer> set = new HashSet<Integer>(); for(int i=0; i<n; i++){ if(set.add(a[i])){ ++count; } } for(int j=0; j<m; j++){ if(set.add(b[j])){ ++count; } } return count; }}"
},
{
"code": null,
"e": 1657,
"s": 1654,
"text": "+1"
},
{
"code": null,
"e": 1678,
"s": 1657,
"text": "harshscode2 days ago"
},
{
"code": null,
"e": 1863,
"s": 1678,
"text": " set contains unique elements......\n set<int> s;\n for(int i=0;i<n;i++)\n s.insert(a[i]);\n for(int i=0;i<m;i++)\n s.insert(b[i]);\n return s.size();"
},
{
"code": null,
"e": 1865,
"s": 1863,
"text": "0"
},
{
"code": null,
"e": 1887,
"s": 1865,
"text": "neetikat1662 days ago"
},
{
"code": null,
"e": 2128,
"s": 1887,
"text": "int doUnion(int a[], int n, int b[], int m) { //code here set<int> s; for(int i=0;i<n;i++){ s.insert(a[i]); } for(int i=0;i<m;i++){ s.insert(b[i]); } return s.size(); }"
},
{
"code": null,
"e": 2130,
"s": 2128,
"text": "0"
},
{
"code": null,
"e": 2157,
"s": 2130,
"text": "niravramotiya0034 days ago"
},
{
"code": null,
"e": 2247,
"s": 2157,
"text": "def doUnion(self,a,n,b,m):\n a.extend(b)\n temp=set(a)\n return(len(temp))"
},
{
"code": null,
"e": 2249,
"s": 2247,
"text": "0"
},
{
"code": null,
"e": 2275,
"s": 2249,
"text": "shubham211019974 days ago"
},
{
"code": null,
"e": 2497,
"s": 2275,
"text": "public static int doUnion(int a[], int n, int b[], int m) \n {\n HashSet<Integer>h=new HashSet<>();\n for(int i:a)\n h.add(i);\n for(int i:b)\n h.add(i);\n \n return h.size();\n }"
},
{
"code": null,
"e": 2499,
"s": 2497,
"text": "0"
},
{
"code": null,
"e": 2522,
"s": 2499,
"text": "vikashdas7704 days ago"
},
{
"code": null,
"e": 2639,
"s": 2522,
"text": " def doUnion(self,a,n,b,m): out = a[:] + b[:] final_list = list(set(out)) return len(final_list)"
},
{
"code": null,
"e": 2641,
"s": 2639,
"text": "0"
},
{
"code": null,
"e": 2675,
"s": 2641,
"text": "adityapratapsinghaps3335 days ago"
},
{
"code": null,
"e": 2948,
"s": 2675,
"text": "int doUnion(int a[], int n, int b[], int m) {\n map<int,int>freq;\n int i;\n \n for(i=0;i<n;i++){\n freq[a[i]]++;\n }\n \n for(i=0;i<m;i++){\n freq[b[i]]++;\n }\n \n return freq.size();\n }"
},
{
"code": null,
"e": 2950,
"s": 2948,
"text": "0"
},
{
"code": null,
"e": 2973,
"s": 2950,
"text": "yashshivhare5 days ago"
},
{
"code": null,
"e": 3189,
"s": 2973,
"text": " doUnion(a, n, b, m){ let freq={}, count=0; for(let num of a) freq[num]?freq[num]++:freq[num]=1; for(let num of b) freq[num]?freq[num]++:freq[num]=1; for(let key in freq) count++; return count; }"
},
{
"code": null,
"e": 3191,
"s": 3189,
"text": "0"
},
{
"code": null,
"e": 3214,
"s": 3191,
"text": "anmolbansal25 days ago"
},
{
"code": null,
"e": 3226,
"s": 3214,
"text": "//Java code"
},
{
"code": null,
"e": 3450,
"s": 3226,
"text": "public static int doUnion(int a[], int n, int b[], int m) { Set<Integer>set=new HashSet<>(); for(int i:a){ set.add(i); } for(int i:b){ set.add(i); } return set.size(); }"
},
{
"code": null,
"e": 3452,
"s": 3450,
"text": "0"
},
{
"code": null,
"e": 3478,
"s": 3452,
"text": "aishaparween5461 week ago"
},
{
"code": null,
"e": 3808,
"s": 3478,
"text": " //we can do this by using Hashset HashSet<Integer> set=new HashSet<>(); for(int i=0;i<n;i++) { set.add(a[i]); } for(int i=0;i<m;i++) { set.add(b[i]); } return set.size();//which return the count of element ofunion of two arrays }"
},
{
"code": null,
"e": 3954,
"s": 3808,
"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": 3990,
"s": 3954,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4000,
"s": 3990,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4010,
"s": 4000,
"text": "\nContest\n"
},
{
"code": null,
"e": 4073,
"s": 4010,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4221,
"s": 4073,
"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": 4429,
"s": 4221,
"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": 4535,
"s": 4429,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
What is the RemoveAt method in C# lists? | The RemoveAt() method in C# is used to remove an element in a list at a position you set.
Firstly, set elements in the list −
var subjects = new List();
subjects.Add("Physics");
subjects.Add("Chemistry");
subjects.Add("Biology");
subjects.Add("Science");
To remove an element, set the index from where you want to eliminate the element. The following is to remove an element from the 3rd position −
subjects.RemoveAt(2);
Let us see the complete code −
Live Demo
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(string[] args) {
var subjects = new List();
subjects.Add("Physics");
subjects.Add("Chemistry");
subjects.Add("Biology");
subjects.Add("Science");
Console.WriteLine("ELEMENTS:");
foreach (var sub in subjects) {
Console.WriteLine(sub);
}
// remove element at 3rd position
subjects.RemoveAt(2);
Console.WriteLine("After removing an element:");
foreach (var sub in subjects) {
Console.WriteLine(sub);
}
}
}
ELEMENTS:
Physics
Chemistry
Biology
Science
After removing an element:
Physics
Chemistry
Science | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "The RemoveAt() method in C# is used to remove an element in a list at a position you set."
},
{
"code": null,
"e": 1188,
"s": 1152,
"text": "Firstly, set elements in the list −"
},
{
"code": null,
"e": 1317,
"s": 1188,
"text": "var subjects = new List();\nsubjects.Add(\"Physics\");\nsubjects.Add(\"Chemistry\");\nsubjects.Add(\"Biology\");\nsubjects.Add(\"Science\");"
},
{
"code": null,
"e": 1461,
"s": 1317,
"text": "To remove an element, set the index from where you want to eliminate the element. The following is to remove an element from the 3rd position −"
},
{
"code": null,
"e": 1483,
"s": 1461,
"text": "subjects.RemoveAt(2);"
},
{
"code": null,
"e": 1514,
"s": 1483,
"text": "Let us see the complete code −"
},
{
"code": null,
"e": 1525,
"s": 1514,
"text": " Live Demo"
},
{
"code": null,
"e": 2126,
"s": 1525,
"text": "using System;\nusing System.Collections.Generic;\n\npublic class Demo {\n public static void Main(string[] args) {\n var subjects = new List();\n subjects.Add(\"Physics\");\n subjects.Add(\"Chemistry\");\n subjects.Add(\"Biology\");\n subjects.Add(\"Science\");\n\n Console.WriteLine(\"ELEMENTS:\");\n foreach (var sub in subjects) {\n Console.WriteLine(sub);\n }\n\n // remove element at 3rd position\n subjects.RemoveAt(2);\n Console.WriteLine(\"After removing an element:\");\n\n foreach (var sub in subjects) {\n Console.WriteLine(sub);\n }\n }\n}"
},
{
"code": null,
"e": 2223,
"s": 2126,
"text": "ELEMENTS:\nPhysics\nChemistry\nBiology\nScience\nAfter removing an element:\nPhysics\nChemistry\nScience"
}
] |
Minimum number of days required to complete the work - GeeksforGeeks | 03 Jun, 2021
Given N works numbered from 1 to N. Given two arrays, D1[] and D2[] of N elements each. Also, each work number W(i) is assigned days, D1[i] and D2[i] (Such that, D2[i] < D1[i]) either of which can be completed. Also, it is mentioned that each work has to be completed according to the non-decreasing date of the array D1[].The task is to find the minimum number of days required to complete the work in non-decreasing order of days in D1[].
Examples:
Input : N = 3 D1[] = {5, 3, 4} D2[] = {2, 1, 2} Output : 2Explanation: 3 works are to be completed. The first value on Line(i) is D1(i) and the second value is D2(i) where D2(i) < D1(i). The smart worker can finish the second work on Day 1 and then both third work and first work in Day 2, thus maintaining the non-decreasing order of D1[], [3 4 5].
Input : N = 6 D1[] = {3, 3, 4, 4, 5, 5} D2[] = {1, 2, 1, 2, 4, 4} Output : 4
Approach: The solution is greedy. The work(i) can be sorted by increasing D1[i], breaking the ties by increasing D2[i]. If we consider the works in this order, we can try to finish the works as early as possible. First of all complete the first work on D2[1]. Move to the second work. If we can complete it on day D2[2] such that (D2[1]<=D2[2]), do it. Otherwise, do the work on day D[2]. Repeat the process until we complete the N-th work, keeping the day of the latest work. Below is the implementation of the above approach.
C++
Java
Javascript
// C++ program to find the minimum// number days required #include <bits/stdc++.h>using namespace std;#define inf INT_MAX // Function to find the minimum// number days requiredint minimumDays(int N, int D1[], int D2[]){ // initialising ans to least value possible int ans = -inf; // vector to store the pair of D1(i) and D2(i) vector<pair<int, int> > vect; for (int i = 0; i < N; i++) vect.push_back(make_pair(D1[i], D2[i])); // sort by first i.e D(i) sort(vect.begin(), vect.end()); // Calculate the minimum possible days for (int i = 0; i < N; i++) { if (vect[i].second >= ans) ans = vect[i].second; else ans = vect[i].first; } // return the answer return ans;} // Driver Codeint main(){ // Number of works int N = 3; // D1[i] int D1[] = { 6, 5, 4 }; // D2[i] int D2[] = { 1, 2, 3 }; cout<<minimumDays(N, D1, D2); return 0;}
// Java program to find the minimum// number days requiredimport java.util.*;import java.lang.*;import java.io.*; // pair class for number of daysclass Pair{ int x, y; Pair(int a, int b) { this.x = a; this.y = b; }} class GFG{static int inf = Integer.MIN_VALUE; // Function to find the minimum// number days requiredpublic static int minimumDays(int N, int D1[], int D2[]){ // initialising ans to // least value possible int ans = -inf; ArrayList<Pair> list = new ArrayList<Pair>(); for (int i = 0; i < N; i++) list.add(new Pair(D1[i], D2[i])); // sort by first i.e D(i) Collections.sort(list, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { return p1.x - p2.x; } }); // Calculate the minimum possible daysfor (int i = 0; i < N; i++){ if (list.get(i).y >= ans) ans = list.get(i).y; else ans = list.get(i).x;} return ans;} // Driver Codepublic static void main (String[] args){ // Number of works int N = 3; // D1[i] int D1[] = new int[]{6, 5, 4}; // D2[i] int D2[] = new int[]{1, 2, 3}; System.out.print(minimumDays(N, D1, D2));}} // This code is contributed by Kirti_Mangal
<script> // Javascript program to find the minimum// number days required // Function to find the minimum// number days requiredfunction minimumDays(N, D1, D2){ // initialising ans to least value possible var ans = -1000000000; // vector to store the pair of D1(i) and D2(i) var vect = []; for (var i = 0; i < N; i++) vect.push([D1[i], D2[i]]); // sort by first i.e D(i) vect.sort((a,b)=>a-b) // Calculate the minimum possible days for (var i = 0; i < N; i++) { if (vect[i][1] >= ans) ans = vect[i][1]; else ans = vect[i][0]; } // return the answer return ans;} // Driver Code// Number of worksvar N = 3; // D1[i]var D1 = [6, 5, 4 ]; // D2[i]var D2 = [1, 2, 3 ];document.write( minimumDays(N, D1, D2)); </script>
6
Kirti_Mangal
noob2000
Constructive Algorithms
cpp-vector
Greedy Algorithms
Greedy
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Huffman Coding | Greedy Algo-3
Coin Change | DP-7
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Fractional Knapsack Problem
Difference between Prim's and Kruskal's algorithm for MST
Program for Least Recently Used (LRU) Page Replacement algorithm
Program for Shortest Job First (SJF) scheduling | Set 2 (Preemptive)
Graph Coloring | Set 2 (Greedy Algorithm)
Max Flow Problem Introduction
Program for Page Replacement Algorithms | Set 2 (FIFO) | [
{
"code": null,
"e": 24657,
"s": 24629,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 25098,
"s": 24657,
"text": "Given N works numbered from 1 to N. Given two arrays, D1[] and D2[] of N elements each. Also, each work number W(i) is assigned days, D1[i] and D2[i] (Such that, D2[i] < D1[i]) either of which can be completed. Also, it is mentioned that each work has to be completed according to the non-decreasing date of the array D1[].The task is to find the minimum number of days required to complete the work in non-decreasing order of days in D1[]."
},
{
"code": null,
"e": 25109,
"s": 25098,
"text": "Examples: "
},
{
"code": null,
"e": 25459,
"s": 25109,
"text": "Input : N = 3 D1[] = {5, 3, 4} D2[] = {2, 1, 2} Output : 2Explanation: 3 works are to be completed. The first value on Line(i) is D1(i) and the second value is D2(i) where D2(i) < D1(i). The smart worker can finish the second work on Day 1 and then both third work and first work in Day 2, thus maintaining the non-decreasing order of D1[], [3 4 5]."
},
{
"code": null,
"e": 25537,
"s": 25459,
"text": "Input : N = 6 D1[] = {3, 3, 4, 4, 5, 5} D2[] = {1, 2, 1, 2, 4, 4} Output : 4 "
},
{
"code": null,
"e": 26066,
"s": 25537,
"text": "Approach: The solution is greedy. The work(i) can be sorted by increasing D1[i], breaking the ties by increasing D2[i]. If we consider the works in this order, we can try to finish the works as early as possible. First of all complete the first work on D2[1]. Move to the second work. If we can complete it on day D2[2] such that (D2[1]<=D2[2]), do it. Otherwise, do the work on day D[2]. Repeat the process until we complete the N-th work, keeping the day of the latest work. Below is the implementation of the above approach. "
},
{
"code": null,
"e": 26070,
"s": 26066,
"text": "C++"
},
{
"code": null,
"e": 26075,
"s": 26070,
"text": "Java"
},
{
"code": null,
"e": 26086,
"s": 26075,
"text": "Javascript"
},
{
"code": "// C++ program to find the minimum// number days required #include <bits/stdc++.h>using namespace std;#define inf INT_MAX // Function to find the minimum// number days requiredint minimumDays(int N, int D1[], int D2[]){ // initialising ans to least value possible int ans = -inf; // vector to store the pair of D1(i) and D2(i) vector<pair<int, int> > vect; for (int i = 0; i < N; i++) vect.push_back(make_pair(D1[i], D2[i])); // sort by first i.e D(i) sort(vect.begin(), vect.end()); // Calculate the minimum possible days for (int i = 0; i < N; i++) { if (vect[i].second >= ans) ans = vect[i].second; else ans = vect[i].first; } // return the answer return ans;} // Driver Codeint main(){ // Number of works int N = 3; // D1[i] int D1[] = { 6, 5, 4 }; // D2[i] int D2[] = { 1, 2, 3 }; cout<<minimumDays(N, D1, D2); return 0;}",
"e": 27042,
"s": 26086,
"text": null
},
{
"code": "// Java program to find the minimum// number days requiredimport java.util.*;import java.lang.*;import java.io.*; // pair class for number of daysclass Pair{ int x, y; Pair(int a, int b) { this.x = a; this.y = b; }} class GFG{static int inf = Integer.MIN_VALUE; // Function to find the minimum// number days requiredpublic static int minimumDays(int N, int D1[], int D2[]){ // initialising ans to // least value possible int ans = -inf; ArrayList<Pair> list = new ArrayList<Pair>(); for (int i = 0; i < N; i++) list.add(new Pair(D1[i], D2[i])); // sort by first i.e D(i) Collections.sort(list, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { return p1.x - p2.x; } }); // Calculate the minimum possible daysfor (int i = 0; i < N; i++){ if (list.get(i).y >= ans) ans = list.get(i).y; else ans = list.get(i).x;} return ans;} // Driver Codepublic static void main (String[] args){ // Number of works int N = 3; // D1[i] int D1[] = new int[]{6, 5, 4}; // D2[i] int D2[] = new int[]{1, 2, 3}; System.out.print(minimumDays(N, D1, D2));}} // This code is contributed by Kirti_Mangal",
"e": 28356,
"s": 27042,
"text": null
},
{
"code": "<script> // Javascript program to find the minimum// number days required // Function to find the minimum// number days requiredfunction minimumDays(N, D1, D2){ // initialising ans to least value possible var ans = -1000000000; // vector to store the pair of D1(i) and D2(i) var vect = []; for (var i = 0; i < N; i++) vect.push([D1[i], D2[i]]); // sort by first i.e D(i) vect.sort((a,b)=>a-b) // Calculate the minimum possible days for (var i = 0; i < N; i++) { if (vect[i][1] >= ans) ans = vect[i][1]; else ans = vect[i][0]; } // return the answer return ans;} // Driver Code// Number of worksvar N = 3; // D1[i]var D1 = [6, 5, 4 ]; // D2[i]var D2 = [1, 2, 3 ];document.write( minimumDays(N, D1, D2)); </script>",
"e": 29160,
"s": 28356,
"text": null
},
{
"code": null,
"e": 29162,
"s": 29160,
"text": "6"
},
{
"code": null,
"e": 29177,
"s": 29164,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 29186,
"s": 29177,
"text": "noob2000"
},
{
"code": null,
"e": 29210,
"s": 29186,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 29221,
"s": 29210,
"text": "cpp-vector"
},
{
"code": null,
"e": 29239,
"s": 29221,
"text": "Greedy Algorithms"
},
{
"code": null,
"e": 29246,
"s": 29239,
"text": "Greedy"
},
{
"code": null,
"e": 29253,
"s": 29246,
"text": "Greedy"
},
{
"code": null,
"e": 29351,
"s": 29253,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29360,
"s": 29351,
"text": "Comments"
},
{
"code": null,
"e": 29373,
"s": 29360,
"text": "Old Comments"
},
{
"code": null,
"e": 29404,
"s": 29373,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 29423,
"s": 29404,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 29504,
"s": 29423,
"text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)"
},
{
"code": null,
"e": 29532,
"s": 29504,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 29590,
"s": 29532,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 29655,
"s": 29590,
"text": "Program for Least Recently Used (LRU) Page Replacement algorithm"
},
{
"code": null,
"e": 29724,
"s": 29655,
"text": "Program for Shortest Job First (SJF) scheduling | Set 2 (Preemptive)"
},
{
"code": null,
"e": 29766,
"s": 29724,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
},
{
"code": null,
"e": 29796,
"s": 29766,
"text": "Max Flow Problem Introduction"
}
] |
Imbalanced Classes: Part 2. Recently, I wrote this post about... | by Becca R | Towards Data Science | Recently, I wrote this post about imbalanced class sizes in classification models might lead to overestimation of a classification model’s performance. The post discussed a classification project I was developing using Airbnb first user booking data from Kaggle. The objective of the project was to predict whether a first-time Airbnb user would likely book a vacation home in the U.S.A./Canada or somewhere internationally. However, bookings within the U.S.A./Canada accounted for around 75 percent of the data, making it difficult to accurately estimate international bookings.
To account for the fact that nearly 100 percent of observations were predicted to be in the dominant class (in my case, travelers to the U.S.A./Canada), I used the Adaptive Synthetic (ADASYN) to oversample the minority class in my test set. Not satisfied with the results of the out-of-box logistic regression with default parameters, I decided to do some model selection and brute-force parameter tuning using GridSearchCV in scikit-learn. My features were engineered, my classes were balanced, and my shiny new AWS instance was compute-optimized. What could go wrong?
Data pre-processing
I was eager to fit some models and see how well I could classify user location based on the features I had acquired. I had split the dataframe into my target variable (y) and a matrix of features (X). I performed train-test-split on the data set (80% training, 20% testing) with stratification to ensure that the minority class were represented in the test set. I used a standard scalar transformation on the features sets (X_train and X_test). Finally, I used the the Adaptive Synthetic (ADASYN) method to perform oversampling of the minority class in the training data (see Imbalance Classes Part I for details).
from sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScalerfrom imblearn.over_sampling import ADASYNX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y,random_state = 88)std_scale = StandardScaler()X_train_scaled = std_scale.fit_transform(X_train)X_test_scaled = std_scale.transform(X_test)adasyn = ADASYN(random_state=88)X_adasyn, y_adasyn = adasyn.fit_resample(X_train_scaled, y_train)
GridSearchCV
I looped through five classifiers: Logistic Regression, K-Nearest Neighbors, Decision Tree, Random Forest, and Support Vector Classifier. I defined “models” to be a list of dictionaries for each classifier with the classifier object (random state set always to 88 for reproducibility, can you guess my favorite number?), and a grid of model-specific hyperparameters to be tuned.
from sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.svm import SVCmodels = [{'name': 'logreg','label': 'Logistic Regression', 'classifier': LogisticRegression(random_state=88), 'grid': {"C":np.logspace(-3,3,7), "penalty":["l1","l2"]}}, {'name': 'knn','label':'K Nearest Neighbors', 'classifier':KNeighborsClassifier(), 'grid': {"n_neighbors":np.arange(8)+1}}, {'name': 'dsc','label': 'Descision Tree', 'classifier': DecisionTreeClassifier(random_state=88), 'grid': {"max_depth":np.arange(8)+1}}, {'name': 'rf', 'label': 'Random Forest', 'classifier': RandomForestClassifier(random_state=88), 'grid': {'n_estimators': [200, 500],'max_features': ['auto', 'sqrt', 'log2'], 'max_depth' : [4,5,6,7,8],'criterion' :['gini', 'entropy']}}, {'name': 'svm_rbf', 'label': 'SVC (RBF)', 'classifier':SVC(random_state=88), 'grid': {'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['rbf']}}]
I defined the model_selection function below to perform a GridSearch to optimize hypterparameters across five cross-validation sets for a given model. I decided to use the Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) score to determine model performance so as to try and maximize true positives while minimizing false positives in model predictions. The function returns a dictionary that includes the classifier, optimal parameters from the GridSearch, and the best averaged ROC_AUC score from the validation sets.
from sklearn.metrics import roc_auc_scoredef model_selection(classifier, name, grid, X_train, y_train, scoring): gridsearch_cv=GridSearchCV(classifier, grid, cv=5, scoring = scoring) gridsearch_cv.fit(X_adasyn, y_adasyn) results_dict = {} results_dict['classifier_name'] = name results_dict['classifier'] = gridsearch_cv.best_estimator_ results_dict['best_params'] = gridsearch_cv.best_params_ results_dict['ROC_AUC'] = gridsearch_cv.best_score_ return(results_dict)results = []for m in models: print(m['name']) results.append(fit_first_model(m['classifier'], m['name'], m['grid'], X_adasyn, y_adasyn, 'roc_auc')) print('completed')
Finally, I had the results of each fitted classifier to compare! This process does not take a trivial amount of time, so be prepared to have some time to kill (my kitchen was spotless by the end of this process!).
I put the results into a dataframe for better viewability:
results_df = pd.DataFrame(results).sort_values(by='ROC_AUC', ascending = False)
Well, I was quite pleased with the first row, the Random Forest Classifier, achieving a 0.85 ROC_AUC score. This got me thinking about some grand plans for an XGBoost tree classifier. I was going to get a predictive model to rival the winners of the Kaggle competition...or was I?
Eager to confirm the performance of the Random Forest Classifier with tuned hyperparameters, I scored the predictive performance of the model on my test set. I was aghast when I saw that my the ROC_AUC score for the test set was only 0.525. In my experience test scores are typically lower than cross-validation scores, and I know that Random Forest can be prone to overfitting, but this was a performance decrease of 38 percent!
For good measure, I scored the performances of the remaining four classifiers on the test set. Sure enough, the ROC_AUC test scores were significantly lower than the cross validation ROC_AUC averages. Logistic regression was an exception, performing only slightly better than a random guess on both the validation and test sets.
Order matters
What was going on here? Well, remember that I oversampled with ADASYN before splitting my training data for cross-validation. So, my five-fold validation sets are NOT representative of a distribution in the real world. Rather, they contain “synthetic” data points representative of hard-to-classify observations in the minority class. Therefore, when I scored the model performance on the test set (with the target class proportions indicative of the real-world), the score dropped significantly.
Luckily, imbalanced-learn has a Pipeline class that will apply the ADASYN resampling only during the classifier fitting, thus allowing me to avoid some clunky for-loops and manual GridSearchCV.
Below is the code to build the pipeline for GridSearchCV hyperparameter tuning on the Random Forest Classifier with oversampling during cross-validation fitting. (Note the class__ prefix in the grid dictionary!)
from imblearn.pipeline import make_pipeline, Pipelinerf = RandomForestClassifier(random_state=88)adasyn = ADASYN(random_state=88)grid = {'class__n_estimators': [200, 500], 'class__max_features': ['auto', 'sqrt', 'log2'], 'class__max_depth' : [4,5,6,7,8], 'class__criterion' :['gini', 'entropy']}pipeline = Pipeline([('sampling', adasyn), ('class', rf)])grid_cv = GridSearchCV(pipeline, grid, scoring = 'roc_auc', cv = 5) grid_cv.fit(X_train_scaled, y_train)grid_cv.best_score_
Lo and behold, the cross-validation ROC_AUC was only 0.578, much more indicative of the model’s actual performance when applied to the test set. Once again, I looped through all models and saved optimal parameters, average validation scores, and test scores for completeness.
Key takeaways
The ROC-AUC curves for classification algorithms with synthetic data in the validation sets (left) demonstrate a clear overestimation of fit when compared to the ROC-AUC curves scored on a validation set with representative imbalanced classes (right). (Note: These algorithms were scored on a single validation set, rather than an average of three-folds, hence the difference in scores from the tables above).
While I am no closer to being able to confidently predict an Airbnb user’s vacation destination, this project illuminated the importance of paying attention to what’s happening “under the hood” of advanced machine learning algorithms. In particular, I built on my previous post about how imbalanced class sizes can lead to over-estimation of a classifier’s performance to discuss why order matters when fitting a classifier on re-sampled training data with cross-validation and hyperparameter tuning.
I hope that you found this series useful. Please feel free to provide any comments or additional insights in the comments below! | [
{
"code": null,
"e": 752,
"s": 172,
"text": "Recently, I wrote this post about imbalanced class sizes in classification models might lead to overestimation of a classification model’s performance. The post discussed a classification project I was developing using Airbnb first user booking data from Kaggle. The objective of the project was to predict whether a first-time Airbnb user would likely book a vacation home in the U.S.A./Canada or somewhere internationally. However, bookings within the U.S.A./Canada accounted for around 75 percent of the data, making it difficult to accurately estimate international bookings."
},
{
"code": null,
"e": 1322,
"s": 752,
"text": "To account for the fact that nearly 100 percent of observations were predicted to be in the dominant class (in my case, travelers to the U.S.A./Canada), I used the Adaptive Synthetic (ADASYN) to oversample the minority class in my test set. Not satisfied with the results of the out-of-box logistic regression with default parameters, I decided to do some model selection and brute-force parameter tuning using GridSearchCV in scikit-learn. My features were engineered, my classes were balanced, and my shiny new AWS instance was compute-optimized. What could go wrong?"
},
{
"code": null,
"e": 1342,
"s": 1322,
"text": "Data pre-processing"
},
{
"code": null,
"e": 1957,
"s": 1342,
"text": "I was eager to fit some models and see how well I could classify user location based on the features I had acquired. I had split the dataframe into my target variable (y) and a matrix of features (X). I performed train-test-split on the data set (80% training, 20% testing) with stratification to ensure that the minority class were represented in the test set. I used a standard scalar transformation on the features sets (X_train and X_test). Finally, I used the the Adaptive Synthetic (ADASYN) method to perform oversampling of the minority class in the training data (see Imbalance Classes Part I for details)."
},
{
"code": null,
"e": 2466,
"s": 1957,
"text": "from sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScalerfrom imblearn.over_sampling import ADASYNX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y,random_state = 88)std_scale = StandardScaler()X_train_scaled = std_scale.fit_transform(X_train)X_test_scaled = std_scale.transform(X_test)adasyn = ADASYN(random_state=88)X_adasyn, y_adasyn = adasyn.fit_resample(X_train_scaled, y_train)"
},
{
"code": null,
"e": 2479,
"s": 2466,
"text": "GridSearchCV"
},
{
"code": null,
"e": 2858,
"s": 2479,
"text": "I looped through five classifiers: Logistic Regression, K-Nearest Neighbors, Decision Tree, Random Forest, and Support Vector Classifier. I defined “models” to be a list of dictionaries for each classifier with the classifier object (random state set always to 88 for reproducibility, can you guess my favorite number?), and a grid of model-specific hyperparameters to be tuned."
},
{
"code": null,
"e": 4104,
"s": 2858,
"text": "from sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.svm import SVCmodels = [{'name': 'logreg','label': 'Logistic Regression', 'classifier': LogisticRegression(random_state=88), 'grid': {\"C\":np.logspace(-3,3,7), \"penalty\":[\"l1\",\"l2\"]}}, {'name': 'knn','label':'K Nearest Neighbors', 'classifier':KNeighborsClassifier(), 'grid': {\"n_neighbors\":np.arange(8)+1}}, {'name': 'dsc','label': 'Descision Tree', 'classifier': DecisionTreeClassifier(random_state=88), 'grid': {\"max_depth\":np.arange(8)+1}}, {'name': 'rf', 'label': 'Random Forest', 'classifier': RandomForestClassifier(random_state=88), 'grid': {'n_estimators': [200, 500],'max_features': ['auto', 'sqrt', 'log2'], 'max_depth' : [4,5,6,7,8],'criterion' :['gini', 'entropy']}}, {'name': 'svm_rbf', 'label': 'SVC (RBF)', 'classifier':SVC(random_state=88), 'grid': {'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['rbf']}}]"
},
{
"code": null,
"e": 4648,
"s": 4104,
"text": "I defined the model_selection function below to perform a GridSearch to optimize hypterparameters across five cross-validation sets for a given model. I decided to use the Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) score to determine model performance so as to try and maximize true positives while minimizing false positives in model predictions. The function returns a dictionary that includes the classifier, optimal parameters from the GridSearch, and the best averaged ROC_AUC score from the validation sets."
},
{
"code": null,
"e": 5617,
"s": 4648,
"text": "from sklearn.metrics import roc_auc_scoredef model_selection(classifier, name, grid, X_train, y_train, scoring): gridsearch_cv=GridSearchCV(classifier, grid, cv=5, scoring = scoring) gridsearch_cv.fit(X_adasyn, y_adasyn) results_dict = {} results_dict['classifier_name'] = name results_dict['classifier'] = gridsearch_cv.best_estimator_ results_dict['best_params'] = gridsearch_cv.best_params_ results_dict['ROC_AUC'] = gridsearch_cv.best_score_ return(results_dict)results = []for m in models: print(m['name']) results.append(fit_first_model(m['classifier'], m['name'], m['grid'], X_adasyn, y_adasyn, 'roc_auc')) print('completed')"
},
{
"code": null,
"e": 5831,
"s": 5617,
"text": "Finally, I had the results of each fitted classifier to compare! This process does not take a trivial amount of time, so be prepared to have some time to kill (my kitchen was spotless by the end of this process!)."
},
{
"code": null,
"e": 5890,
"s": 5831,
"text": "I put the results into a dataframe for better viewability:"
},
{
"code": null,
"e": 5970,
"s": 5890,
"text": "results_df = pd.DataFrame(results).sort_values(by='ROC_AUC', ascending = False)"
},
{
"code": null,
"e": 6251,
"s": 5970,
"text": "Well, I was quite pleased with the first row, the Random Forest Classifier, achieving a 0.85 ROC_AUC score. This got me thinking about some grand plans for an XGBoost tree classifier. I was going to get a predictive model to rival the winners of the Kaggle competition...or was I?"
},
{
"code": null,
"e": 6681,
"s": 6251,
"text": "Eager to confirm the performance of the Random Forest Classifier with tuned hyperparameters, I scored the predictive performance of the model on my test set. I was aghast when I saw that my the ROC_AUC score for the test set was only 0.525. In my experience test scores are typically lower than cross-validation scores, and I know that Random Forest can be prone to overfitting, but this was a performance decrease of 38 percent!"
},
{
"code": null,
"e": 7010,
"s": 6681,
"text": "For good measure, I scored the performances of the remaining four classifiers on the test set. Sure enough, the ROC_AUC test scores were significantly lower than the cross validation ROC_AUC averages. Logistic regression was an exception, performing only slightly better than a random guess on both the validation and test sets."
},
{
"code": null,
"e": 7024,
"s": 7010,
"text": "Order matters"
},
{
"code": null,
"e": 7521,
"s": 7024,
"text": "What was going on here? Well, remember that I oversampled with ADASYN before splitting my training data for cross-validation. So, my five-fold validation sets are NOT representative of a distribution in the real world. Rather, they contain “synthetic” data points representative of hard-to-classify observations in the minority class. Therefore, when I scored the model performance on the test set (with the target class proportions indicative of the real-world), the score dropped significantly."
},
{
"code": null,
"e": 7715,
"s": 7521,
"text": "Luckily, imbalanced-learn has a Pipeline class that will apply the ADASYN resampling only during the classifier fitting, thus allowing me to avoid some clunky for-loops and manual GridSearchCV."
},
{
"code": null,
"e": 7927,
"s": 7715,
"text": "Below is the code to build the pipeline for GridSearchCV hyperparameter tuning on the Random Forest Classifier with oversampling during cross-validation fitting. (Note the class__ prefix in the grid dictionary!)"
},
{
"code": null,
"e": 8427,
"s": 7927,
"text": "from imblearn.pipeline import make_pipeline, Pipelinerf = RandomForestClassifier(random_state=88)adasyn = ADASYN(random_state=88)grid = {'class__n_estimators': [200, 500], 'class__max_features': ['auto', 'sqrt', 'log2'], 'class__max_depth' : [4,5,6,7,8], 'class__criterion' :['gini', 'entropy']}pipeline = Pipeline([('sampling', adasyn), ('class', rf)])grid_cv = GridSearchCV(pipeline, grid, scoring = 'roc_auc', cv = 5) grid_cv.fit(X_train_scaled, y_train)grid_cv.best_score_"
},
{
"code": null,
"e": 8703,
"s": 8427,
"text": "Lo and behold, the cross-validation ROC_AUC was only 0.578, much more indicative of the model’s actual performance when applied to the test set. Once again, I looped through all models and saved optimal parameters, average validation scores, and test scores for completeness."
},
{
"code": null,
"e": 8717,
"s": 8703,
"text": "Key takeaways"
},
{
"code": null,
"e": 9127,
"s": 8717,
"text": "The ROC-AUC curves for classification algorithms with synthetic data in the validation sets (left) demonstrate a clear overestimation of fit when compared to the ROC-AUC curves scored on a validation set with representative imbalanced classes (right). (Note: These algorithms were scored on a single validation set, rather than an average of three-folds, hence the difference in scores from the tables above)."
},
{
"code": null,
"e": 9628,
"s": 9127,
"text": "While I am no closer to being able to confidently predict an Airbnb user’s vacation destination, this project illuminated the importance of paying attention to what’s happening “under the hood” of advanced machine learning algorithms. In particular, I built on my previous post about how imbalanced class sizes can lead to over-estimation of a classifier’s performance to discuss why order matters when fitting a classifier on re-sampled training data with cross-validation and hyperparameter tuning."
}
] |
XQuery - distinct-values Function | The distinct-values function is used to get the sequence containing unique items present in a given sequence.
distinct-values($seq as item()*)
$seq − provided sequence. A sequence can contain 0 or more items.
$seq − provided sequence. A sequence can contain 0 or more items.
let $items := (1,2,4,4,5,5)
let $unique-items := distinct-values($items)
return
<result>
<items>
{
for $item in $unique-items
return <item>{$item}</item>
}
</items>
</result>
<result>
<items>
<item>1</item>
<item>2</item>
<item>4</item>
<item>5</item>
</items>
</result>
In order to test the above-mentioned functionality, replace the contents of books.xqy (mentioned in Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program to verify the result.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1982,
"s": 1872,
"text": "The distinct-values function is used to get the sequence containing unique items present in a given sequence."
},
{
"code": null,
"e": 2015,
"s": 1982,
"text": "distinct-values($seq as item()*)"
},
{
"code": null,
"e": 2081,
"s": 2015,
"text": "$seq − provided sequence. A sequence can contain 0 or more items."
},
{
"code": null,
"e": 2147,
"s": 2081,
"text": "$seq − provided sequence. A sequence can contain 0 or more items."
},
{
"code": null,
"e": 2381,
"s": 2147,
"text": "let $items := (1,2,4,4,5,5)\nlet $unique-items := distinct-values($items)\nreturn\n <result> \n \n <items>\n {\n for $item in $unique-items\n return <item>{$item}</item>\n }\n </items>\n \n </result>"
},
{
"code": null,
"e": 2508,
"s": 2381,
"text": "<result>\n <items>\n <item>1</item>\n <item>2</item>\n <item>4</item>\n <item>5</item>\n </items>\n</result>\n"
},
{
"code": null,
"e": 2732,
"s": 2508,
"text": "In order to test the above-mentioned functionality, replace the contents of books.xqy (mentioned in Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program to verify the result."
},
{
"code": null,
"e": 2739,
"s": 2732,
"text": " Print"
},
{
"code": null,
"e": 2750,
"s": 2739,
"text": " Add Notes"
}
] |
Weight sum of a nested array in JavaScript | We are required to write a JavaScript function that takes in a nested array, arr (nested up to any
level) as the only argument.
The function should calculate the weighted sum of the nested array and return that sum.
For calculating nested sum, we multiply a specific element with its level of nesting and add
throughout the array.
For example, if the input to the function is −
const arr = [4, 7, [6, 1, [5, 2]]];
Then the output should be −
const output = 46;
The sum will be calculated like this −
(4 * 1) + ( 7 * 1) + (6 * 2) + (1 * 2) + (5 * 3) + (2 * 3) = 46
The code for this will be −
const arr = [4, 7, [6, 1, [5, 2]]];
const findWeightedSum = (arr = [], level = 1, res = 0) => {
for(let i = 0; i < arr.length; i++){
if(typeof arr[i] === 'number'){
res += (level * arr[i]);
}else if(Array.isArray(arr[i])){
return findWeightedSum(arr[i], level + 1, res);
};
};
return res;
};
console.log(findWeightedSum(arr));
And the output in the console will be −
46 | [
{
"code": null,
"e": 1190,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a nested array, arr (nested up to any\nlevel) as the only argument."
},
{
"code": null,
"e": 1278,
"s": 1190,
"text": "The function should calculate the weighted sum of the nested array and return that sum."
},
{
"code": null,
"e": 1393,
"s": 1278,
"text": "For calculating nested sum, we multiply a specific element with its level of nesting and add\nthroughout the array."
},
{
"code": null,
"e": 1440,
"s": 1393,
"text": "For example, if the input to the function is −"
},
{
"code": null,
"e": 1476,
"s": 1440,
"text": "const arr = [4, 7, [6, 1, [5, 2]]];"
},
{
"code": null,
"e": 1504,
"s": 1476,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1523,
"s": 1504,
"text": "const output = 46;"
},
{
"code": null,
"e": 1562,
"s": 1523,
"text": "The sum will be calculated like this −"
},
{
"code": null,
"e": 1626,
"s": 1562,
"text": "(4 * 1) + ( 7 * 1) + (6 * 2) + (1 * 2) + (5 * 3) + (2 * 3) = 46"
},
{
"code": null,
"e": 1654,
"s": 1626,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2026,
"s": 1654,
"text": "const arr = [4, 7, [6, 1, [5, 2]]];\nconst findWeightedSum = (arr = [], level = 1, res = 0) => {\n for(let i = 0; i < arr.length; i++){\n if(typeof arr[i] === 'number'){\n res += (level * arr[i]);\n }else if(Array.isArray(arr[i])){\n return findWeightedSum(arr[i], level + 1, res);\n };\n };\n return res;\n};\nconsole.log(findWeightedSum(arr));"
},
{
"code": null,
"e": 2066,
"s": 2026,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 2069,
"s": 2066,
"text": "46"
}
] |
How to implement a Singleton design pattern in C#? | Singleton Pattern belongs to Creational type pattern
Singleton design pattern is used when we need to ensure that only one object of a particular class is Instantiated. That single instance created is responsible to coordinate actions across the application.
As part of the Implementation guidelines we need to ensure that only one instance of the class exists by declaring all constructors of the class to be private. Also, to control the singleton access we need to provide a static property that returns a single instance of the object.
Sealed ensures the class being inherited and
object instantiation is restricted in the derived class
Private property initialized with null
ensures that only one instance of the object is created
based on the null condition
Private constructor ensures that object is not
instantiated other than with in the class itself
Public method which can be invoked through the singleton instance
Live Demo
public sealed class Singleton {
private static int counter = 0;
private static Singleton instance = null;
public static Singleton GetInstance {
get {
if (instance == null)
instance = new Singleton();
return instance;
}
}
private Singleton() {
counter++;
Console.WriteLine("Counter Value " + counter.ToString());
}
public void PrintDetails(string message) {
Console.WriteLine(message);
}
}
class Program {
static void Main() {
Singleton fromFacebook = Singleton.GetInstance;
fromFacebook.PrintDetails("From Facebook");
Singleton fromTwitter = Singleton.GetInstance;
fromTwitter.PrintDetails("From Twitter");
Console.ReadLine();
}
}
Counter Value 1
From Facebook
From Twitter | [
{
"code": null,
"e": 1115,
"s": 1062,
"text": "Singleton Pattern belongs to Creational type pattern"
},
{
"code": null,
"e": 1321,
"s": 1115,
"text": "Singleton design pattern is used when we need to ensure that only one object of a particular class is Instantiated. That single instance created is responsible to coordinate actions across the application."
},
{
"code": null,
"e": 1602,
"s": 1321,
"text": "As part of the Implementation guidelines we need to ensure that only one instance of the class exists by declaring all constructors of the class to be private. Also, to control the singleton access we need to provide a static property that returns a single instance of the object."
},
{
"code": null,
"e": 1703,
"s": 1602,
"text": "Sealed ensures the class being inherited and\nobject instantiation is restricted in the derived class"
},
{
"code": null,
"e": 1742,
"s": 1703,
"text": "Private property initialized with null"
},
{
"code": null,
"e": 1798,
"s": 1742,
"text": "ensures that only one instance of the object is created"
},
{
"code": null,
"e": 1826,
"s": 1798,
"text": "based on the null condition"
},
{
"code": null,
"e": 1922,
"s": 1826,
"text": "Private constructor ensures that object is not\ninstantiated other than with in the class itself"
},
{
"code": null,
"e": 1988,
"s": 1922,
"text": "Public method which can be invoked through the singleton instance"
},
{
"code": null,
"e": 1999,
"s": 1988,
"text": " Live Demo"
},
{
"code": null,
"e": 2747,
"s": 1999,
"text": "public sealed class Singleton {\n private static int counter = 0;\n private static Singleton instance = null;\n public static Singleton GetInstance {\n get {\n if (instance == null)\n instance = new Singleton();\n return instance;\n }\n }\n private Singleton() {\n counter++;\n Console.WriteLine(\"Counter Value \" + counter.ToString());\n }\n public void PrintDetails(string message) {\n Console.WriteLine(message);\n }\n}\nclass Program {\n static void Main() {\n Singleton fromFacebook = Singleton.GetInstance;\n fromFacebook.PrintDetails(\"From Facebook\");\n Singleton fromTwitter = Singleton.GetInstance;\n fromTwitter.PrintDetails(\"From Twitter\");\n Console.ReadLine();\n }\n}"
},
{
"code": null,
"e": 2790,
"s": 2747,
"text": "Counter Value 1\nFrom Facebook\nFrom Twitter"
}
] |
Python 3 - os.popen() Method | The method popen() opens a pipe to or from command.The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.The bufsize argument has the same meaning as in open() function.
Following is the syntax for popen() method −
os.popen(command[, mode[, bufsize]])
command − This is command used.
command − This is command used.
mode − This is the Mode can be 'r'(default) or 'w'.
mode − This is the Mode can be 'r'(default) or 'w'.
bufsize − If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
bufsize − If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
This method returns an open file object connected to the pipe.
The following example shows the usage of popen() method.
# !/usr/bin/python3
import os, sys
# using command mkdir
a = 'mkdir nwdir'
b = os.popen(a,'r',1)
print (b)
When we run the above program, it produces the following result −
<os._wrap_close object at 0x7fb599240b70>
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2598,
"s": 2340,
"text": "The method popen() opens a pipe to or from command.The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.The bufsize argument has the same meaning as in open() function."
},
{
"code": null,
"e": 2643,
"s": 2598,
"text": "Following is the syntax for popen() method −"
},
{
"code": null,
"e": 2681,
"s": 2643,
"text": "os.popen(command[, mode[, bufsize]])\n"
},
{
"code": null,
"e": 2713,
"s": 2681,
"text": "command − This is command used."
},
{
"code": null,
"e": 2745,
"s": 2713,
"text": "command − This is command used."
},
{
"code": null,
"e": 2797,
"s": 2745,
"text": "mode − This is the Mode can be 'r'(default) or 'w'."
},
{
"code": null,
"e": 2849,
"s": 2797,
"text": "mode − This is the Mode can be 'r'(default) or 'w'."
},
{
"code": null,
"e": 3219,
"s": 2849,
"text": "bufsize − If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior). "
},
{
"code": null,
"e": 3589,
"s": 3219,
"text": "bufsize − If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior). "
},
{
"code": null,
"e": 3652,
"s": 3589,
"text": "This method returns an open file object connected to the pipe."
},
{
"code": null,
"e": 3709,
"s": 3652,
"text": "The following example shows the usage of popen() method."
},
{
"code": null,
"e": 3818,
"s": 3709,
"text": "# !/usr/bin/python3\nimport os, sys\n\n# using command mkdir\na = 'mkdir nwdir'\nb = os.popen(a,'r',1)\n\nprint (b)"
},
{
"code": null,
"e": 3884,
"s": 3818,
"text": "When we run the above program, it produces the following result −"
},
{
"code": null,
"e": 3927,
"s": 3884,
"text": "<os._wrap_close object at 0x7fb599240b70>\n"
},
{
"code": null,
"e": 3964,
"s": 3927,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3980,
"s": 3964,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4013,
"s": 3980,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4032,
"s": 4013,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4067,
"s": 4032,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4089,
"s": 4067,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4123,
"s": 4089,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4151,
"s": 4123,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4186,
"s": 4151,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4200,
"s": 4186,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4233,
"s": 4200,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4250,
"s": 4233,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4257,
"s": 4250,
"text": " Print"
},
{
"code": null,
"e": 4268,
"s": 4257,
"text": " Add Notes"
}
] |
Apache Flink - Table API and SQL | Table API is a relational API with SQL like expression language. This API can do both batch and stream processing. It can be embedded with Java and Scala Dataset and Datastream APIs. You can create tables from existing Datasets and Datastreams or from external data sources. Through this relational API, you can perform operations like join, aggregate, select and filter. Whether the input is batch or stream, the semantics of the query remains the same.
Here is a sample Table API program −
// for batch programs use ExecutionEnvironment instead of StreamExecutionEnvironment
val env = StreamExecutionEnvironment.getExecutionEnvironment
// create a TableEnvironment
val tableEnv = TableEnvironment.getTableEnvironment(env)
// register a Table
tableEnv.registerTable("table1", ...) // or
tableEnv.registerTableSource("table2", ...) // or
tableEnv.registerExternalCatalog("extCat", ...)
// register an output Table
tableEnv.registerTableSink("outputTable", ...);
// create a Table from a Table API query
val tapiResult = tableEnv.scan("table1").select(...)
// Create a Table from a SQL query
val sqlResult = tableEnv.sqlQuery("SELECT ... FROM table2 ...")
// emit a Table API result Table to a TableSink, same for SQL result
tapiResult.insertInto("outputTable")
// execute
env.execute()
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": 2524,
"s": 2069,
"text": "Table API is a relational API with SQL like expression language. This API can do both batch and stream processing. It can be embedded with Java and Scala Dataset and Datastream APIs. You can create tables from existing Datasets and Datastreams or from external data sources. Through this relational API, you can perform operations like join, aggregate, select and filter. Whether the input is batch or stream, the semantics of the query remains the same."
},
{
"code": null,
"e": 2561,
"s": 2524,
"text": "Here is a sample Table API program −"
},
{
"code": null,
"e": 3360,
"s": 2561,
"text": "// for batch programs use ExecutionEnvironment instead of StreamExecutionEnvironment\nval env = StreamExecutionEnvironment.getExecutionEnvironment\n\n// create a TableEnvironment\nval tableEnv = TableEnvironment.getTableEnvironment(env)\n\n// register a Table\ntableEnv.registerTable(\"table1\", ...) // or\ntableEnv.registerTableSource(\"table2\", ...) // or\ntableEnv.registerExternalCatalog(\"extCat\", ...)\n\n// register an output Table\ntableEnv.registerTableSink(\"outputTable\", ...);\n// create a Table from a Table API query\nval tapiResult = tableEnv.scan(\"table1\").select(...)\n// Create a Table from a SQL query\nval sqlResult = tableEnv.sqlQuery(\"SELECT ... FROM table2 ...\")\n\n// emit a Table API result Table to a TableSink, same for SQL result\ntapiResult.insertInto(\"outputTable\")\n\n// execute\nenv.execute()"
},
{
"code": null,
"e": 3395,
"s": 3360,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3414,
"s": 3395,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3449,
"s": 3414,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3470,
"s": 3449,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 3503,
"s": 3470,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3516,
"s": 3503,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 3551,
"s": 3516,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3569,
"s": 3551,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3602,
"s": 3569,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3620,
"s": 3602,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3653,
"s": 3620,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3671,
"s": 3653,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3678,
"s": 3671,
"text": " Print"
},
{
"code": null,
"e": 3689,
"s": 3678,
"text": " Add Notes"
}
] |
How to change the button color after clicking it using AngularJS ? - GeeksforGeeks | 14 Oct, 2020
Created a HTML button and the task is to change the background color of the button when pressing it with the help of AngularJS.
Approach: In this approach, we will try to change the class or id of the button, and the CSS of those classes/IDs will change the background color of the button.
Example 1: In this example, the class is changed from red to green.
<!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.myButton = 'red'; $scope.changeCol = function () { $scope.myButton = "green"; }; }); </script> <style type="text/css"> .red { background: red; color: white; } .green { background: green; color: white; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to change the color of the button in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> <button ng-click="changeCol()" class="{{myButton}}"> Click to change </button> </div> </div></body> </html>
Output:
Example 2: In this example, the ID of the button is changed from blue to green.
<!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.ID = 'blue'; $scope.changeCol = function () { $scope.ID = "green"; }; }); </script> <style type="text/css"> #blue { background: blue; color: white; } #green { background: green; color: white; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to change the color of the button in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> <button ng-click="changeCol()" id="{{ID}}"> Click to change</button> </div> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
AngularJS-Misc
HTML-Misc
AngularJS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
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": 26464,
"s": 26436,
"text": "\n14 Oct, 2020"
},
{
"code": null,
"e": 26592,
"s": 26464,
"text": "Created a HTML button and the task is to change the background color of the button when pressing it with the help of AngularJS."
},
{
"code": null,
"e": 26754,
"s": 26592,
"text": "Approach: In this approach, we will try to change the class or id of the button, and the CSS of those classes/IDs will change the background color of the button."
},
{
"code": null,
"e": 26822,
"s": 26754,
"text": "Example 1: In this example, the class is changed from red to green."
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.myButton = 'red'; $scope.changeCol = function () { $scope.myButton = \"green\"; }; }); </script> <style type=\"text/css\"> .red { background: red; color: white; } .green { background: green; color: white; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to change the color of the button in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> <button ng-click=\"changeCol()\" class=\"{{myButton}}\"> Click to change </button> </div> </div></body> </html> ",
"e": 27838,
"s": 26822,
"text": null
},
{
"code": null,
"e": 27846,
"s": 27838,
"text": "Output:"
},
{
"code": null,
"e": 27926,
"s": 27846,
"text": "Example 2: In this example, the ID of the button is changed from blue to green."
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.ID = 'blue'; $scope.changeCol = function () { $scope.ID = \"green\"; }; }); </script> <style type=\"text/css\"> #blue { background: blue; color: white; } #green { background: green; color: white; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to change the color of the button in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> <button ng-click=\"changeCol()\" id=\"{{ID}}\"> Click to change</button> </div> </div></body> </html>",
"e": 28913,
"s": 27926,
"text": null
},
{
"code": null,
"e": 28921,
"s": 28913,
"text": "Output:"
},
{
"code": null,
"e": 29058,
"s": 28921,
"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": 29073,
"s": 29058,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 29083,
"s": 29073,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29093,
"s": 29083,
"text": "AngularJS"
},
{
"code": null,
"e": 29098,
"s": 29093,
"text": "HTML"
},
{
"code": null,
"e": 29115,
"s": 29098,
"text": "Web Technologies"
},
{
"code": null,
"e": 29120,
"s": 29115,
"text": "HTML"
},
{
"code": null,
"e": 29218,
"s": 29120,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29253,
"s": 29218,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 29288,
"s": 29253,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 29323,
"s": 29288,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 29347,
"s": 29323,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 29400,
"s": 29347,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 29450,
"s": 29400,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 29512,
"s": 29450,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29560,
"s": 29512,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29620,
"s": 29560,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
CALL Instructions and Stack in AVR Microcontroller - GeeksforGeeks | 17 Jan, 2022
CALL is a control transfer instruction that is used to call a particular subroutine. A subroutine is a block of instructions that need to be performed frequently.
In AVR, there are 4 instructions for the call subroutine as following.
CALL (call subroutine)RCALL (relative call subroutine)ICALL (indirect call to Z)EICALL (extended indirect call to Z)
CALL (call subroutine)
RCALL (relative call subroutine)
ICALL (indirect call to Z)
EICALL (extended indirect call to Z)
CALL :In this 4-byte instruction, 10 bits are used for the opcode and the other 22 bits are used for the address of the target subroutine just as in the JMP instruction. In this, 4M address space of 000000-$3FFFFF for AVR and can be used to call subroutines within the given range of address.
To make sure that the AVR knows where to come back after the execution of the subroutine, the microcontroller automatically saves the address of the instruction just below the CALL instruction on the stack. After finishing the execution of the subroutine, the RET instruction transfers control back to the caller. Hence, every subroutine has a RET instruction at the end.
Stack :Stack is the part in the RAM of CPU to store information temporarily. The CPU needs this storage because there is only a limited number of registers. The register used to access the stack is called the stack pointer (SP) register.In I/O memory space, there are 2 registers named SPL (the low byte of SP) and SPH (the high byte ofSP). The SP is implemented by these 2 registers.
In AVRs with more than 256 bytes of memory have two 8-bit registers. On the other hand, if the memory is less than 256 bytes, SP is made up of only SPL, as an 8-bit register can only address 256 bytes of memory.
The storing of the CPU information on the stack is called the PUSH operation, and the loading of the stack contents back into the CPU is known as POP operation.
Pushing onto the stack :The stack pointer (SP) points to the top of the stack. As we push the data onto the stack, the data is saved where the SP is pointing to and the SP is decremented by one.
To push a register onto a stack, we use PUSH instruction.
PUSH Rr;
Rr can be any general-purpose register (R0 - R31)
Popping from the stack :Popping the contents of the stack back into the register is the opposite function of pushing. When the POP instruction is executed, the SP is incremented by one and the top location of the stack is copied back to the register. This means that the stack is LIFO ( Last In First Out).
To retrieve back the data from the stack, we use POP instruction.
POP Rr;
Rr can be any general-purpose register (R0 - R31)
Initializing stack pointers :Different AVRs have different amounts of RAM. In the AVR assembler, RAMEND specifies the address of the last RAM location. So, if we want to initialize the SP so that it points to the last memory location, we can simply load RAMEND into the SP. Notice that SP is made up of 2 registers, SPH and SPL. So, we load the high byte of RAMEND into SPH and the low byte of RAMEND into SPL.
CALL instruction, RET instruction and the role of stack :When the CALL instruction is executed, the address of the instruction below the CALL instruction is pushed onto the stack. When the execution of that subroutine is finished and RET is executed, the address of the instruction below the CALL instruction is loaded in the program counter and it is executed.
tanwarsinghvaibhav
Computer Organization and Architecture
microprocessor
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Architecture of 8085 microprocessor
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Pin diagram of 8086 microprocessor
Difference between Hardwired and Micro-programmed Control Unit | Set 2
I2C Communication Protocol
Memory mapped I/O and Isolated I/O
Computer Architecture | Flynn's taxonomy
Computer Organization | Different Instruction Cycles
Introduction of Control Unit and its Design | [
{
"code": null,
"e": 26135,
"s": 26107,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 26298,
"s": 26135,
"text": "CALL is a control transfer instruction that is used to call a particular subroutine. A subroutine is a block of instructions that need to be performed frequently."
},
{
"code": null,
"e": 26369,
"s": 26298,
"text": "In AVR, there are 4 instructions for the call subroutine as following."
},
{
"code": null,
"e": 26486,
"s": 26369,
"text": "CALL (call subroutine)RCALL (relative call subroutine)ICALL (indirect call to Z)EICALL (extended indirect call to Z)"
},
{
"code": null,
"e": 26509,
"s": 26486,
"text": "CALL (call subroutine)"
},
{
"code": null,
"e": 26542,
"s": 26509,
"text": "RCALL (relative call subroutine)"
},
{
"code": null,
"e": 26569,
"s": 26542,
"text": "ICALL (indirect call to Z)"
},
{
"code": null,
"e": 26606,
"s": 26569,
"text": "EICALL (extended indirect call to Z)"
},
{
"code": null,
"e": 26899,
"s": 26606,
"text": "CALL :In this 4-byte instruction, 10 bits are used for the opcode and the other 22 bits are used for the address of the target subroutine just as in the JMP instruction. In this, 4M address space of 000000-$3FFFFF for AVR and can be used to call subroutines within the given range of address."
},
{
"code": null,
"e": 27271,
"s": 26899,
"text": "To make sure that the AVR knows where to come back after the execution of the subroutine, the microcontroller automatically saves the address of the instruction just below the CALL instruction on the stack. After finishing the execution of the subroutine, the RET instruction transfers control back to the caller. Hence, every subroutine has a RET instruction at the end."
},
{
"code": null,
"e": 27656,
"s": 27271,
"text": "Stack :Stack is the part in the RAM of CPU to store information temporarily. The CPU needs this storage because there is only a limited number of registers. The register used to access the stack is called the stack pointer (SP) register.In I/O memory space, there are 2 registers named SPL (the low byte of SP) and SPH (the high byte ofSP). The SP is implemented by these 2 registers."
},
{
"code": null,
"e": 27868,
"s": 27656,
"text": "In AVRs with more than 256 bytes of memory have two 8-bit registers. On the other hand, if the memory is less than 256 bytes, SP is made up of only SPL, as an 8-bit register can only address 256 bytes of memory."
},
{
"code": null,
"e": 28029,
"s": 27868,
"text": "The storing of the CPU information on the stack is called the PUSH operation, and the loading of the stack contents back into the CPU is known as POP operation."
},
{
"code": null,
"e": 28224,
"s": 28029,
"text": "Pushing onto the stack :The stack pointer (SP) points to the top of the stack. As we push the data onto the stack, the data is saved where the SP is pointing to and the SP is decremented by one."
},
{
"code": null,
"e": 28282,
"s": 28224,
"text": "To push a register onto a stack, we use PUSH instruction."
},
{
"code": null,
"e": 28344,
"s": 28282,
"text": "PUSH Rr; \nRr can be any general-purpose register (R0 - R31)\n"
},
{
"code": null,
"e": 28651,
"s": 28344,
"text": "Popping from the stack :Popping the contents of the stack back into the register is the opposite function of pushing. When the POP instruction is executed, the SP is incremented by one and the top location of the stack is copied back to the register. This means that the stack is LIFO ( Last In First Out)."
},
{
"code": null,
"e": 28717,
"s": 28651,
"text": "To retrieve back the data from the stack, we use POP instruction."
},
{
"code": null,
"e": 28778,
"s": 28717,
"text": "POP Rr; \nRr can be any general-purpose register (R0 - R31)\n"
},
{
"code": null,
"e": 29189,
"s": 28778,
"text": "Initializing stack pointers :Different AVRs have different amounts of RAM. In the AVR assembler, RAMEND specifies the address of the last RAM location. So, if we want to initialize the SP so that it points to the last memory location, we can simply load RAMEND into the SP. Notice that SP is made up of 2 registers, SPH and SPL. So, we load the high byte of RAMEND into SPH and the low byte of RAMEND into SPL."
},
{
"code": null,
"e": 29551,
"s": 29189,
"text": "CALL instruction, RET instruction and the role of stack :When the CALL instruction is executed, the address of the instruction below the CALL instruction is pushed onto the stack. When the execution of that subroutine is finished and RET is executed, the address of the instruction below the CALL instruction is loaded in the program counter and it is executed."
},
{
"code": null,
"e": 29570,
"s": 29551,
"text": "tanwarsinghvaibhav"
},
{
"code": null,
"e": 29609,
"s": 29570,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 29624,
"s": 29609,
"text": "microprocessor"
},
{
"code": null,
"e": 29661,
"s": 29624,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 29676,
"s": 29661,
"text": "microprocessor"
},
{
"code": null,
"e": 29774,
"s": 29676,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29836,
"s": 29774,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 29872,
"s": 29836,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 29963,
"s": 29872,
"text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)"
},
{
"code": null,
"e": 29998,
"s": 29963,
"text": "Pin diagram of 8086 microprocessor"
},
{
"code": null,
"e": 30069,
"s": 29998,
"text": "Difference between Hardwired and Micro-programmed Control Unit | Set 2"
},
{
"code": null,
"e": 30096,
"s": 30069,
"text": "I2C Communication Protocol"
},
{
"code": null,
"e": 30131,
"s": 30096,
"text": "Memory mapped I/O and Isolated I/O"
},
{
"code": null,
"e": 30172,
"s": 30131,
"text": "Computer Architecture | Flynn's taxonomy"
},
{
"code": null,
"e": 30225,
"s": 30172,
"text": "Computer Organization | Different Instruction Cycles"
}
] |
How to Collapse Toolbar Layout in Android? - GeeksforGeeks | 30 Dec, 2021
In this article, we are going to create the CollapsingToolbar app that is fascinating and much useful. CollapsingToolbarLayout gives the facility of adjusting the size of toolbar title text when it is expanded or contracted. A sample GIF is given below to get an idea about how CollapsingToolbarLayout looks like.
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.
Step 2: Add Design Support Library
Go to build.gradle file and add the below dependency if you are using an older version of Android Studio. A newer version of Android Studio contains this dependency as default, so you don’t need to add it if you are using the latest version.
implementation ‘com.android.support:design:29.0.0’
Step 3: Add Image
Copy the image that you want to use as a background image for the toolbar and paste it into the drawable folder. We will be using this image in activity_main.xml file.
Step 4: Working with strings.xml file
Navigate to res > values > strings.xml and add a long text that we will be using later in the activity_main.xml file. Here we are using a portion of Lorem Ipsum text. You can add the text whatever you want to use.
XML
<resources> <string name="app_name">GFG | CollapseToolbar</string> <string name="content">With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. In a short span, we have built a community of 1 Million+ Geeks around the world, 20,000+ Contributors and 500+ Campus Ambassadors in various colleges across the nation. Our success stories include a lot of students who benefitted in their placements and landed jobs at tech giants. Our vision is to build a gigantic network of geeks and we are only a fraction of it yet. </string></resources>
Step 5: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?> <!--first of all you have to change the layout as CoordinatorLayout. This is the first thing we need to do.--><androidx.coordinatorlayout.widget.CoordinatorLayout 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"> <!--AppBarLayout helps the toolbar and other components to react on scroll changes. I am using Dark theme for AppBarLayout. Inside this AppBarLayout i have used CollapsingToolbarLayout. --> <com.google.android.material.appbar.AppBarLayout android:id="@+id/appBarLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <!-- In CollapsingToolbarLayout sompe important attributes are: i) app:layout_scrollFlags which is used to specify how collapsing layout behaves when content is scrolled.I have used app:layout_scrollFlags="scroll|snap|exitUntilCollapsed" so it will scroll until it's is completely collapsed. ii) app:contentScrim="@color/green" that specifies the color of the collapsed toolbar --> <com.google.android.material.appbar.CollapsingToolbarLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:contentScrim="@color/green" app:layout_scrollFlags="scroll|snap|exitUntilCollapsed" app:title="@string/app_name"> <!--We are adding the image that we have added earlier in the drawable folder.The attribute app:layout_collapseMode="parallax" causes the image to move when user scrolls at a specific ratio. --> <ImageView android:layout_width="match_parent" android:layout_height="250dp" android:scaleType="centerCrop" android:src="@drawable/image" app:layout_collapseMode="parallax" /> <!-- The attribute app:layout_collapseMode="pin" is set so that sticks to the top when the user scrolls the view up--> <androidx.appcompat.widget.Toolbar android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" app:popupTheme="@style/ThemeOverlay.AppCompat.Dark" /> </com.google.android.material.appbar.CollapsingToolbarLayout> </com.google.android.material.appbar.AppBarLayout> <!--Now add the NestedScollView--> <androidx.core.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <!--In textview we will be adding the text that i have added earlier in strings.xml file.This is simply the the content to be scrolled --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:lineSpacingExtra="8sp" android:padding="16dp" android:text="@string/content" android:textSize="20sp" /> </androidx.core.widget.NestedScrollView> </androidx.coordinatorlayout.widget.CoordinatorLayout>
Output:
rkbhola5
Android
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?
Flexbox-Layout in Android
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example
How to Get Current Location in Android?
Fragment Lifecycle in Android
Difference Between a Fragment and an Activity in Android | [
{
"code": null,
"e": 26407,
"s": 26379,
"text": "\n30 Dec, 2021"
},
{
"code": null,
"e": 26722,
"s": 26407,
"text": "In this article, we are going to create the CollapsingToolbar app that is fascinating and much useful. CollapsingToolbarLayout gives the facility of adjusting the size of toolbar title text when it is expanded or contracted. A sample GIF is given below to get an idea about how CollapsingToolbarLayout looks like. "
},
{
"code": null,
"e": 26751,
"s": 26722,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26862,
"s": 26751,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio."
},
{
"code": null,
"e": 26897,
"s": 26862,
"text": "Step 2: Add Design Support Library"
},
{
"code": null,
"e": 27140,
"s": 26897,
"text": "Go to build.gradle file and add the below dependency if you are using an older version of Android Studio. A newer version of Android Studio contains this dependency as default, so you don’t need to add it if you are using the latest version. "
},
{
"code": null,
"e": 27191,
"s": 27140,
"text": "implementation ‘com.android.support:design:29.0.0’"
},
{
"code": null,
"e": 27210,
"s": 27191,
"text": "Step 3: Add Image "
},
{
"code": null,
"e": 27378,
"s": 27210,
"text": "Copy the image that you want to use as a background image for the toolbar and paste it into the drawable folder. We will be using this image in activity_main.xml file."
},
{
"code": null,
"e": 27416,
"s": 27378,
"text": "Step 4: Working with strings.xml file"
},
{
"code": null,
"e": 27631,
"s": 27416,
"text": "Navigate to res > values > strings.xml and add a long text that we will be using later in the activity_main.xml file. Here we are using a portion of Lorem Ipsum text. You can add the text whatever you want to use. "
},
{
"code": null,
"e": 27635,
"s": 27631,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">GFG | CollapseToolbar</string> <string name=\"content\">With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. In a short span, we have built a community of 1 Million+ Geeks around the world, 20,000+ Contributors and 500+ Campus Ambassadors in various colleges across the nation. Our success stories include a lot of students who benefitted in their placements and landed jobs at tech giants. Our vision is to build a gigantic network of geeks and we are only a fraction of it yet. </string></resources>",
"e": 28783,
"s": 27635,
"text": null
},
{
"code": null,
"e": 28832,
"s": 28783,
"text": " Step 5: Working with the activity_main.xml file"
},
{
"code": null,
"e": 28976,
"s": 28832,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 28980,
"s": 28976,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--first of all you have to change the layout as CoordinatorLayout. This is the first thing we need to do.--><androidx.coordinatorlayout.widget.CoordinatorLayout 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\"> <!--AppBarLayout helps the toolbar and other components to react on scroll changes. I am using Dark theme for AppBarLayout. Inside this AppBarLayout i have used CollapsingToolbarLayout. --> <com.google.android.material.appbar.AppBarLayout android:id=\"@+id/appBarLayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:theme=\"@style/ThemeOverlay.AppCompat.Dark.ActionBar\"> <!-- In CollapsingToolbarLayout sompe important attributes are: i) app:layout_scrollFlags which is used to specify how collapsing layout behaves when content is scrolled.I have used app:layout_scrollFlags=\"scroll|snap|exitUntilCollapsed\" so it will scroll until it's is completely collapsed. ii) app:contentScrim=\"@color/green\" that specifies the color of the collapsed toolbar --> <com.google.android.material.appbar.CollapsingToolbarLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:contentScrim=\"@color/green\" app:layout_scrollFlags=\"scroll|snap|exitUntilCollapsed\" app:title=\"@string/app_name\"> <!--We are adding the image that we have added earlier in the drawable folder.The attribute app:layout_collapseMode=\"parallax\" causes the image to move when user scrolls at a specific ratio. --> <ImageView android:layout_width=\"match_parent\" android:layout_height=\"250dp\" android:scaleType=\"centerCrop\" android:src=\"@drawable/image\" app:layout_collapseMode=\"parallax\" /> <!-- The attribute app:layout_collapseMode=\"pin\" is set so that sticks to the top when the user scrolls the view up--> <androidx.appcompat.widget.Toolbar android:layout_width=\"match_parent\" android:layout_height=\"?attr/actionBarSize\" app:layout_collapseMode=\"pin\" app:popupTheme=\"@style/ThemeOverlay.AppCompat.Dark\" /> </com.google.android.material.appbar.CollapsingToolbarLayout> </com.google.android.material.appbar.AppBarLayout> <!--Now add the NestedScollView--> <androidx.core.widget.NestedScrollView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:layout_behavior=\"@string/appbar_scrolling_view_behavior\"> <!--In textview we will be adding the text that i have added earlier in strings.xml file.This is simply the the content to be scrolled --> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:lineSpacingExtra=\"8sp\" android:padding=\"16dp\" android:text=\"@string/content\" android:textSize=\"20sp\" /> </androidx.core.widget.NestedScrollView> </androidx.coordinatorlayout.widget.CoordinatorLayout>",
"e": 32525,
"s": 28980,
"text": null
},
{
"code": null,
"e": 32535,
"s": 32525,
"text": " Output: "
},
{
"code": null,
"e": 32546,
"s": 32537,
"text": "rkbhola5"
},
{
"code": null,
"e": 32554,
"s": 32546,
"text": "Android"
},
{
"code": null,
"e": 32562,
"s": 32554,
"text": "Android"
},
{
"code": null,
"e": 32660,
"s": 32562,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32698,
"s": 32660,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 32737,
"s": 32698,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 32787,
"s": 32737,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 32813,
"s": 32787,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 32855,
"s": 32813,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32906,
"s": 32855,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 32944,
"s": 32906,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 32984,
"s": 32944,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 33014,
"s": 32984,
"text": "Fragment Lifecycle in Android"
}
] |
How to create a bouncing bubble effect using CSS ? - GeeksforGeeks | 30 Jun, 2020
One simple way of making a website more dynamic and attractive is to add some animations to it. One such animation is the bouncing bubble effect.
Approach: The basic idea is to create a section using <lspan> element, give it a round shape then by using the CSS animation property translateY the bubble can be moved up and down along the Y-axis. The following steps can be followed to obtain the desired result.
Create a few containers using span element as follow:<div class="dot"> <span></span> <span></span> <span></span> <span></span></div>To make the containers look spherical, the border radius must be changed as: border-radius :50%;To give the spheres a bubble like effect the opacity and background color can be changed as: background-color :#DF0101; opacity :0.8;The position must be set to absolute and the bubbles can be set to any position accordingly.To make the effect more realistic the dimension can be changed as the bubble reaches the surface (i.e. increase the width and decrease the height).To make the bubbles move in an unordered form the animation-delay can be varied for different bubbles and the size can also be varied.
Create a few containers using span element as follow:<div class="dot"> <span></span> <span></span> <span></span> <span></span></div>
<div class="dot"> <span></span> <span></span> <span></span> <span></span></div>
To make the containers look spherical, the border radius must be changed as: border-radius :50%;
To give the spheres a bubble like effect the opacity and background color can be changed as: background-color :#DF0101; opacity :0.8;
The position must be set to absolute and the bubbles can be set to any position accordingly.
To make the effect more realistic the dimension can be changed as the bubble reaches the surface (i.e. increase the width and decrease the height).
To make the bubbles move in an unordered form the animation-delay can be varied for different bubbles and the size can also be varied.
Example: This example implements the above approach.
<!DOCTYPE html><html> <head> <title> How to create a bouncing bubble effect using CSS? </title> <style> * { margin: 0; padding: 0; } /* To give the containers in spherical shape */ .dot { border-radius: 50%; } .dot span { position: absolute; display: block; border: 5px; border-radius: 50%; animation: animate 3s ease-in-out infinite; } /*the animation*/ @keyframes animate { 0% { transform: translateY(-300px); } 50% { transform: translateY(190px); width: -100px; height: +100px; } 100% { transform: translateY(-300px); } } /* Each bubble is defined in a separate section */ /* Set the color, opacity, delay and duration(i.e different speed) */ .dot span:nth-child(1) { top: 300px; left: 250px; height: 160px; width: 160px; background-color: yellow; opacity: 0.7; animation-delay: 0.3s; animation-direction: reverse; } .dot span:nth-child(2) { top: 310px; left: 400px; height: 190px; width: 190px; background-color: green; opacity: 0.9; animation-delay: 0.3s; animation-direction: reverse; animation-duration: 2.3s; } .dot span:nth-child(3) { top: 300px; left: 700px; height: 140px; width: 140px; background-color: #a97f58; opacity: 0.9; animation-delay: 0.5s; animation-direction: reverse; animation-duration: 2.6s; } .dot span:nth-child(4) { top: 300px; left: 1080px; height: 200px; width: 200px; background-color: #FA58AC; opacity: 0.9; animation-delay: 0.7s; animation-direction: reverse; animation-duration: 2.3s; } </style></head> <body> <div class="dot"> <span></span> <span></span> <span></span> <span></span> </div></body> </html>
Output:
This is just a simple animation, the more attractive things can be created by modifying or adding more animation effects to it.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
nidhi_biet
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
Write From Home
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
How to Upload Image into Database and Display it using PHP ?
Form validation using jQuery
How to set the default value for an HTML <select> element ?
HTML Cheat Sheet - A Basic Guide to HTML
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) | [
{
"code": null,
"e": 25212,
"s": 25184,
"text": "\n30 Jun, 2020"
},
{
"code": null,
"e": 25358,
"s": 25212,
"text": "One simple way of making a website more dynamic and attractive is to add some animations to it. One such animation is the bouncing bubble effect."
},
{
"code": null,
"e": 25623,
"s": 25358,
"text": "Approach: The basic idea is to create a section using <lspan> element, give it a round shape then by using the CSS animation property translateY the bubble can be moved up and down along the Y-axis. The following steps can be followed to obtain the desired result."
},
{
"code": null,
"e": 26370,
"s": 25623,
"text": "Create a few containers using span element as follow:<div class=\"dot\"> <span></span> <span></span> <span></span> <span></span></div>To make the containers look spherical, the border radius must be changed as: border-radius :50%;To give the spheres a bubble like effect the opacity and background color can be changed as: background-color :#DF0101; opacity :0.8;The position must be set to absolute and the bubbles can be set to any position accordingly.To make the effect more realistic the dimension can be changed as the bubble reaches the surface (i.e. increase the width and decrease the height).To make the bubbles move in an unordered form the animation-delay can be varied for different bubbles and the size can also be varied."
},
{
"code": null,
"e": 26515,
"s": 26370,
"text": "Create a few containers using span element as follow:<div class=\"dot\"> <span></span> <span></span> <span></span> <span></span></div>"
},
{
"code": "<div class=\"dot\"> <span></span> <span></span> <span></span> <span></span></div>",
"e": 26607,
"s": 26515,
"text": null
},
{
"code": null,
"e": 26704,
"s": 26607,
"text": "To make the containers look spherical, the border radius must be changed as: border-radius :50%;"
},
{
"code": null,
"e": 26838,
"s": 26704,
"text": "To give the spheres a bubble like effect the opacity and background color can be changed as: background-color :#DF0101; opacity :0.8;"
},
{
"code": null,
"e": 26931,
"s": 26838,
"text": "The position must be set to absolute and the bubbles can be set to any position accordingly."
},
{
"code": null,
"e": 27079,
"s": 26931,
"text": "To make the effect more realistic the dimension can be changed as the bubble reaches the surface (i.e. increase the width and decrease the height)."
},
{
"code": null,
"e": 27214,
"s": 27079,
"text": "To make the bubbles move in an unordered form the animation-delay can be varied for different bubbles and the size can also be varied."
},
{
"code": null,
"e": 27267,
"s": 27214,
"text": "Example: This example implements the above approach."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to create a bouncing bubble effect using CSS? </title> <style> * { margin: 0; padding: 0; } /* To give the containers in spherical shape */ .dot { border-radius: 50%; } .dot span { position: absolute; display: block; border: 5px; border-radius: 50%; animation: animate 3s ease-in-out infinite; } /*the animation*/ @keyframes animate { 0% { transform: translateY(-300px); } 50% { transform: translateY(190px); width: -100px; height: +100px; } 100% { transform: translateY(-300px); } } /* Each bubble is defined in a separate section */ /* Set the color, opacity, delay and duration(i.e different speed) */ .dot span:nth-child(1) { top: 300px; left: 250px; height: 160px; width: 160px; background-color: yellow; opacity: 0.7; animation-delay: 0.3s; animation-direction: reverse; } .dot span:nth-child(2) { top: 310px; left: 400px; height: 190px; width: 190px; background-color: green; opacity: 0.9; animation-delay: 0.3s; animation-direction: reverse; animation-duration: 2.3s; } .dot span:nth-child(3) { top: 300px; left: 700px; height: 140px; width: 140px; background-color: #a97f58; opacity: 0.9; animation-delay: 0.5s; animation-direction: reverse; animation-duration: 2.6s; } .dot span:nth-child(4) { top: 300px; left: 1080px; height: 200px; width: 200px; background-color: #FA58AC; opacity: 0.9; animation-delay: 0.7s; animation-direction: reverse; animation-duration: 2.3s; } </style></head> <body> <div class=\"dot\"> <span></span> <span></span> <span></span> <span></span> </div></body> </html>",
"e": 29684,
"s": 27267,
"text": null
},
{
"code": null,
"e": 29692,
"s": 29684,
"text": "Output:"
},
{
"code": null,
"e": 29820,
"s": 29692,
"text": "This is just a simple animation, the more attractive things can be created by modifying or adding more animation effects to it."
},
{
"code": null,
"e": 29957,
"s": 29820,
"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": 29968,
"s": 29957,
"text": "nidhi_biet"
},
{
"code": null,
"e": 29977,
"s": 29968,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29987,
"s": 29977,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29991,
"s": 29987,
"text": "CSS"
},
{
"code": null,
"e": 29996,
"s": 29991,
"text": "HTML"
},
{
"code": null,
"e": 30013,
"s": 29996,
"text": "Web Technologies"
},
{
"code": null,
"e": 30040,
"s": 30013,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30056,
"s": 30040,
"text": "Write From Home"
},
{
"code": null,
"e": 30061,
"s": 30056,
"text": "HTML"
},
{
"code": null,
"e": 30159,
"s": 30061,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30198,
"s": 30159,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30235,
"s": 30198,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30276,
"s": 30235,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 30337,
"s": 30276,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 30366,
"s": 30337,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30426,
"s": 30366,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30467,
"s": 30426,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 30520,
"s": 30467,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 30581,
"s": 30520,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Prime Number | Practice | GeeksforGeeks | For a given number N check if it is prime or not. A prime number is a number which is only divisible by 1 and itself.
Example 1:
Input:
N = 5
Output:
1
Explanation:
5 has 2 factors 1 and 5 only.
Example 2:
Input:
N = 25
Output:
0
Explanation:
25 has 3 factors 1, 5, 25
Your Task:
You don't need to read input or print anything. Your task is to complete the function isPrime() which takes an integer N as input parameters and returns an integer, 1 if N is a prime number or 0 otherwise.
Expected Time Complexity: O(sqrt(N))
Expected Space Complexity: O(1)
Constraints:
1 <= N <= 109
0
sarkarchitra67Premiumin 7 hours
int isPrime(int N){
// code here
if(N<=1){
return 0;
}
for(int i=2;i*i<=N;i++){
if(N%i==0)
return 0;
}
return 1;
}
0
sarkarchitra67
This comment was deleted.
0
rohitpandey484Premium3 days ago
what is wrong is this program
class Solution{ static int isPrime(int N){ // code here int i; for( i=2;i<=N-1;i++) break; if(i==N) return 1; else return 0; }}
-1
anmolbansal26 days ago
if(N<=1){ return 0; } for(int i=2;i*i<=N;i++){ if(N%i == 0){ return 0; } } return 1; }
0
nourintasnim1
This comment was deleted.
+2
sumitishere33 weeks ago
if(N<=1){ return 0; } for(int i=2;i<=sqrt(N);i++){ if(N%i == 0){ return 0; } } return 1;
Is there a better solution for this question?
0
kartik21gr
This comment was deleted.
0
kartik21gr1 month ago
class Solution{ static int isPrime(int N){ int c,count =0; for(int i = 2; i<N; i++){ c=N%i; if(c==0){ count+=1; } } if(count==0){ return 1; }else{ return 0; } }}
+1
adityapratyush1 month ago
Python Solution:
def isPrime (self, N): factor = 0 num = int(N**(1/2) + 1) if N == 1: return 0 else: for i in range(2, num): if N % i == 0: factor += 1 if factor == 0: return 1 else: return 0
0
princejee20192 months ago
C++ 0(Sqrt(n)) || Easy To undstand
int isPrime(int N){ if(N<=1) return 0; if(N==2 || N==3) return 1; if(N%2==0 || N%3==0)return 0; for(int i =5;i*i<=N;i+=6){ if(N%i==0 || N%(i+2)==0){ return 0; } } return 1; }
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": 358,
"s": 238,
"text": "For a given number N check if it is prime or not. A prime number is a number which is only divisible by 1 and itself.\n "
},
{
"code": null,
"e": 369,
"s": 358,
"text": "Example 1:"
},
{
"code": null,
"e": 435,
"s": 369,
"text": "Input:\nN = 5\nOutput:\n1\nExplanation:\n5 has 2 factors 1 and 5 only."
},
{
"code": null,
"e": 446,
"s": 435,
"text": "Example 2:"
},
{
"code": null,
"e": 510,
"s": 446,
"text": "Input:\nN = 25\nOutput:\n0\nExplanation:\n25 has 3 factors 1, 5, 25\n"
},
{
"code": null,
"e": 730,
"s": 510,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isPrime() which takes an integer N as input parameters and returns an integer, 1 if N is a prime number or 0 otherwise.\n "
},
{
"code": null,
"e": 801,
"s": 730,
"text": "Expected Time Complexity: O(sqrt(N))\nExpected Space Complexity: O(1)\n "
},
{
"code": null,
"e": 828,
"s": 801,
"text": "Constraints:\n1 <= N <= 109"
},
{
"code": null,
"e": 830,
"s": 828,
"text": "0"
},
{
"code": null,
"e": 862,
"s": 830,
"text": "sarkarchitra67Premiumin 7 hours"
},
{
"code": null,
"e": 1067,
"s": 862,
"text": "int isPrime(int N){\n // code here\n if(N<=1){\n return 0;\n }\n for(int i=2;i*i<=N;i++){\n if(N%i==0)\n return 0;\n }\n return 1;\n }"
},
{
"code": null,
"e": 1069,
"s": 1067,
"text": "0"
},
{
"code": null,
"e": 1084,
"s": 1069,
"text": "sarkarchitra67"
},
{
"code": null,
"e": 1110,
"s": 1084,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1112,
"s": 1110,
"text": "0"
},
{
"code": null,
"e": 1144,
"s": 1112,
"text": "rohitpandey484Premium3 days ago"
},
{
"code": null,
"e": 1174,
"s": 1144,
"text": "what is wrong is this program"
},
{
"code": null,
"e": 1357,
"s": 1174,
"text": "class Solution{ static int isPrime(int N){ // code here int i; for( i=2;i<=N-1;i++) break; if(i==N) return 1; else return 0; }}"
},
{
"code": null,
"e": 1360,
"s": 1357,
"text": "-1"
},
{
"code": null,
"e": 1383,
"s": 1360,
"text": "anmolbansal26 days ago"
},
{
"code": null,
"e": 1532,
"s": 1383,
"text": "if(N<=1){ return 0; } for(int i=2;i*i<=N;i++){ if(N%i == 0){ return 0; } } return 1; }"
},
{
"code": null,
"e": 1534,
"s": 1532,
"text": "0"
},
{
"code": null,
"e": 1548,
"s": 1534,
"text": "nourintasnim1"
},
{
"code": null,
"e": 1574,
"s": 1548,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1577,
"s": 1574,
"text": "+2"
},
{
"code": null,
"e": 1601,
"s": 1577,
"text": "sumitishere33 weeks ago"
},
{
"code": null,
"e": 1759,
"s": 1601,
"text": " if(N<=1){ return 0; } for(int i=2;i<=sqrt(N);i++){ if(N%i == 0){ return 0; } } return 1;"
},
{
"code": null,
"e": 1809,
"s": 1763,
"text": "Is there a better solution for this question?"
},
{
"code": null,
"e": 1811,
"s": 1809,
"text": "0"
},
{
"code": null,
"e": 1822,
"s": 1811,
"text": "kartik21gr"
},
{
"code": null,
"e": 1848,
"s": 1822,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1850,
"s": 1848,
"text": "0"
},
{
"code": null,
"e": 1872,
"s": 1850,
"text": "kartik21gr1 month ago"
},
{
"code": null,
"e": 2138,
"s": 1872,
"text": "class Solution{ static int isPrime(int N){ int c,count =0; for(int i = 2; i<N; i++){ c=N%i; if(c==0){ count+=1; } } if(count==0){ return 1; }else{ return 0; } }}"
},
{
"code": null,
"e": 2141,
"s": 2138,
"text": "+1"
},
{
"code": null,
"e": 2167,
"s": 2141,
"text": "adityapratyush1 month ago"
},
{
"code": null,
"e": 2184,
"s": 2167,
"text": "Python Solution:"
},
{
"code": null,
"e": 2483,
"s": 2184,
"text": "def isPrime (self, N): factor = 0 num = int(N**(1/2) + 1) if N == 1: return 0 else: for i in range(2, num): if N % i == 0: factor += 1 if factor == 0: return 1 else: return 0"
},
{
"code": null,
"e": 2485,
"s": 2483,
"text": "0"
},
{
"code": null,
"e": 2511,
"s": 2485,
"text": "princejee20192 months ago"
},
{
"code": null,
"e": 2546,
"s": 2511,
"text": "C++ 0(Sqrt(n)) || Easy To undstand"
},
{
"code": null,
"e": 2802,
"s": 2546,
"text": " int isPrime(int N){ if(N<=1) return 0; if(N==2 || N==3) return 1; if(N%2==0 || N%3==0)return 0; for(int i =5;i*i<=N;i+=6){ if(N%i==0 || N%(i+2)==0){ return 0; } } return 1; }"
},
{
"code": null,
"e": 2948,
"s": 2802,
"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": 2984,
"s": 2948,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2994,
"s": 2984,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3004,
"s": 2994,
"text": "\nContest\n"
},
{
"code": null,
"e": 3067,
"s": 3004,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3215,
"s": 3067,
"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": 3423,
"s": 3215,
"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": 3529,
"s": 3423,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Reading Environment Variables From Node.js - GeeksforGeeks | 12 Oct, 2021
Environment Variable: The two fundamental concepts of any programming language are variables and constants. As we know that constants and variables both represent the unique memory locations that contain data the program uses in its calculations.
The variable which exists outside your code is a part of your server environment and can help you by both streamlining and making more secure the process of running your script and applications.
During the application initialization, these are loaded into the process.env and accessed by suffixing the name of the variable.
Environment variables in backend applications relies on the commands of the operating system to define the environment variables along with their value. A system administrator may define it through a shell-script instead of a CLI interface. Environment variables typically aren’t globally accessible across the operating system, they are usually session-specific.
Reading Environment Variable: Node.js provides the env property under the core module i.e process which hosts all the environment variables that were set at the moment when the process was started.
The following example covers how to accesses the NODE_ENV environment variable, which is set to development by default.
Note: The process module does not require a require() method because it is automatically available on it.
process.env.NODE_ENV // "development"
Now setting this into Production before the script runs it will tell Node.js which is the production environment. Here we can access any type of custom variable which was set by us or already set in the environment.
How to set our own Environment variable in Node.js?
We can set our own environment variable in Node.js using the following simple steps:
Step 1: Build our own .env file which will include all the environment variables in one place. Just be sure not to put them in source control, otherwise, your history will contain references to your files.
NODE_ENV=development
PORT=8626 // You can add port no. as your preferences
# Set your database/API connection information here
API_KEY=**************************
API_URL=**************************
Step 2: Now create our own .gitignore file and add .env to it as shown in the following image and .gitignore will tell source control to ignore the files (or file patterns) which we will list.
Step 2: Now create our own .gitignore file and add .env to it as shown in the following image and .gitignore will tell source control to ignore the files (or file patterns) which we will list.
Note: Be careful while adding .env to your .gitignore file and that changes before you add your .env file otherwise you run into the risk of committing an early version of your .env source control.
varshagumber28
Node.js
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": 38611,
"s": 38583,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 38859,
"s": 38611,
"text": "Environment Variable: The two fundamental concepts of any programming language are variables and constants. As we know that constants and variables both represent the unique memory locations that contain data the program uses in its calculations."
},
{
"code": null,
"e": 39054,
"s": 38859,
"text": "The variable which exists outside your code is a part of your server environment and can help you by both streamlining and making more secure the process of running your script and applications."
},
{
"code": null,
"e": 39183,
"s": 39054,
"text": "During the application initialization, these are loaded into the process.env and accessed by suffixing the name of the variable."
},
{
"code": null,
"e": 39547,
"s": 39183,
"text": "Environment variables in backend applications relies on the commands of the operating system to define the environment variables along with their value. A system administrator may define it through a shell-script instead of a CLI interface. Environment variables typically aren’t globally accessible across the operating system, they are usually session-specific."
},
{
"code": null,
"e": 39745,
"s": 39547,
"text": "Reading Environment Variable: Node.js provides the env property under the core module i.e process which hosts all the environment variables that were set at the moment when the process was started."
},
{
"code": null,
"e": 39865,
"s": 39745,
"text": "The following example covers how to accesses the NODE_ENV environment variable, which is set to development by default."
},
{
"code": null,
"e": 39972,
"s": 39865,
"text": "Note: The process module does not require a require() method because it is automatically available on it. "
},
{
"code": null,
"e": 40010,
"s": 39972,
"text": "process.env.NODE_ENV // \"development\""
},
{
"code": null,
"e": 40226,
"s": 40010,
"text": "Now setting this into Production before the script runs it will tell Node.js which is the production environment. Here we can access any type of custom variable which was set by us or already set in the environment."
},
{
"code": null,
"e": 40278,
"s": 40226,
"text": "How to set our own Environment variable in Node.js?"
},
{
"code": null,
"e": 40363,
"s": 40278,
"text": "We can set our own environment variable in Node.js using the following simple steps:"
},
{
"code": null,
"e": 40569,
"s": 40363,
"text": "Step 1: Build our own .env file which will include all the environment variables in one place. Just be sure not to put them in source control, otherwise, your history will contain references to your files."
},
{
"code": null,
"e": 40773,
"s": 40575,
"text": "NODE_ENV=development\nPORT=8626 // You can add port no. as your preferences\n# Set your database/API connection information here\nAPI_KEY=**************************\nAPI_URL=**************************"
},
{
"code": null,
"e": 40969,
"s": 40775,
"text": "Step 2: Now create our own .gitignore file and add .env to it as shown in the following image and .gitignore will tell source control to ignore the files (or file patterns) which we will list. "
},
{
"code": null,
"e": 41162,
"s": 40969,
"text": "Step 2: Now create our own .gitignore file and add .env to it as shown in the following image and .gitignore will tell source control to ignore the files (or file patterns) which we will list."
},
{
"code": null,
"e": 41366,
"s": 41168,
"text": "Note: Be careful while adding .env to your .gitignore file and that changes before you add your .env file otherwise you run into the risk of committing an early version of your .env source control."
},
{
"code": null,
"e": 41383,
"s": 41368,
"text": "varshagumber28"
},
{
"code": null,
"e": 41391,
"s": 41383,
"text": "Node.js"
},
{
"code": null,
"e": 41399,
"s": 41391,
"text": "Node.js"
},
{
"code": null,
"e": 41416,
"s": 41399,
"text": "Web Technologies"
},
{
"code": null,
"e": 41514,
"s": 41416,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41562,
"s": 41514,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 41595,
"s": 41562,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 41625,
"s": 41595,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 41645,
"s": 41625,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 41699,
"s": 41645,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 41739,
"s": 41699,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 41784,
"s": 41739,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 41827,
"s": 41784,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 41877,
"s": 41827,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Java - Packages | Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access protection and namespace management.
Some of the existing packages in Java are −
java.lang − bundles the fundamental classes
java.lang − bundles the fundamental classes
java.io − classes for input , output functions are bundled in this package
java.io − classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, and annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes.
While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package.
To compile the Java programs with package statements, you have to use -d option as shown below.
javac -d Destination_folder file_name.java
Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder.
Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces.
Following package example contains interface named animals −
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
Now, let us implement the above interface in the same package animals −
package animals;
/* File name : MammalInt.java */
public class MammalInt implements Animal {
public void eat() {
System.out.println("Mammal eats");
}
public void travel() {
System.out.println("Mammal travels");
}
public int noOfLegs() {
return 0;
}
public static void main(String args[]) {
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Now compile the java files as shown below −
$ javac -d . Animal.java
$ javac -d . MammalInt.java
Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as shown below.
You can execute the class file within the package and get the result as shown below.
Mammal eats
Mammal travels
If a class wants to use another class in the same package, the package name need not be used. Classes in the same package find each other without any special syntax.
Here, a class named Boss is added to the payroll package that already contains Employee. The Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by the following Boss class.
package payroll;
public class Boss {
public void payEmployee(Employee e) {
e.mailCheck();
}
}
What happens if the Employee class is not in the payroll package? The Boss class must then use one of the following techniques for referring to a class in a different package.
The fully qualified name of the class can be used. For example −
payroll.Employee
The package can be imported using the import keyword and the wild card (*). For example −
The package can be imported using the import keyword and the wild card (*). For example −
import payroll.*;
The class itself can be imported using the import keyword. For example −
import payroll.Employee;
Note − A class file can contain any number of import statements. The import statements must appear after the package statement and before the class declaration.
Two major results occur when a class is placed in a package −
The name of the package becomes a part of the name of the class, as we just discussed in the previous section.
The name of the package becomes a part of the name of the class, as we just discussed in the previous section.
The name of the package must match the directory structure where the corresponding bytecode resides.
The name of the package must match the directory structure where the corresponding bytecode resides.
Here is simple way of managing your files in Java −
Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the type and whose extension is .java.
For example −
// File Name : Car.java
package vehicle;
public class Car {
// Class implementation.
}
Now, put the source file in a directory whose name reflects the name of the package to which the class belongs −
....\vehicle\Car.java
Now, the qualified class name and pathname would be as follows −
Class name → vehicle.Car
Path name → vehicle\Car.java (in windows)
In general, a company uses its reversed Internet domain name for its package names.
Example − A company's Internet domain name is apple.com, then all its package names would start with com.apple. Each component of the package name corresponds to a subdirectory.
Example − The company had a com.apple.computers package that contained a Dell.java source file, it would be contained in a series of subdirectories like this −
....\com\apple\computers\Dell.java
At the time of compilation, the compiler creates a different output file for each class, interface and enumeration defined in it. The base name of the output file is the name of the type, and its extension is .class.
For example −
// File Name: Dell.java
package com.apple.computers;
public class Dell {
}
class Ups {
}
Now, compile this file as follows using -d option −
$javac -d . Dell.java
The files will be compiled as follows −
.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class
You can import all the classes or interfaces defined in \com\apple\computers\ as follows −
import com.apple.computers.*;
Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as −
<path-one>\sources\com\apple\computers\Dell.java
<path-two>\classes\com\apple\computers\Dell.class
By doing this, it is possible to give access to the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses.
The full path to the classes directory, <path-two>\classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path.
Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the compiler and JVM will look for .class files in <path-two>\classes\com\apple\computers.
A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in the class path.
To display the current CLASSPATH variable, use the following commands in Windows and UNIX (Bourne shell) −
In Windows → C:\> set CLASSPATH
In UNIX → % echo $CLASSPATH
To delete the current contents of the CLASSPATH variable, use −
In Windows → C:\> set CLASSPATH =
In UNIX → % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable −
In Windows → set CLASSPATH = C:\users\jack\java\classes
In UNIX → % CLASSPATH = /home/jack/java/classes; export CLASSPATH
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2563,
"s": 2377,
"text": "Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc."
},
{
"code": null,
"e": 2726,
"s": 2563,
"text": "A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access protection and namespace management."
},
{
"code": null,
"e": 2770,
"s": 2726,
"text": "Some of the existing packages in Java are −"
},
{
"code": null,
"e": 2814,
"s": 2770,
"text": "java.lang − bundles the fundamental classes"
},
{
"code": null,
"e": 2858,
"s": 2814,
"text": "java.lang − bundles the fundamental classes"
},
{
"code": null,
"e": 2933,
"s": 2858,
"text": "java.io − classes for input , output functions are bundled in this package"
},
{
"code": null,
"e": 3008,
"s": 2933,
"text": "java.io − classes for input , output functions are bundled in this package"
},
{
"code": null,
"e": 3275,
"s": 3008,
"text": "Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, and annotations are related."
},
{
"code": null,
"e": 3489,
"s": 3275,
"text": "Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes."
},
{
"code": null,
"e": 3756,
"s": 3489,
"text": "While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package."
},
{
"code": null,
"e": 3925,
"s": 3756,
"text": "The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file."
},
{
"code": null,
"e": 4070,
"s": 3925,
"text": "If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package."
},
{
"code": null,
"e": 4166,
"s": 4070,
"text": "To compile the Java programs with package statements, you have to use -d option as shown below."
},
{
"code": null,
"e": 4209,
"s": 4166,
"text": "javac -d Destination_folder file_name.java"
},
{
"code": null,
"e": 4352,
"s": 4209,
"text": "Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder."
},
{
"code": null,
"e": 4553,
"s": 4352,
"text": "Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces."
},
{
"code": null,
"e": 4614,
"s": 4553,
"text": "Following package example contains interface named animals −"
},
{
"code": null,
"e": 4730,
"s": 4614,
"text": "/* File name : Animal.java */\npackage animals;\n\ninterface Animal {\n public void eat();\n public void travel();\n}"
},
{
"code": null,
"e": 4802,
"s": 4730,
"text": "Now, let us implement the above interface in the same package animals −"
},
{
"code": null,
"e": 5215,
"s": 4802,
"text": "package animals;\n/* File name : MammalInt.java */\n\npublic class MammalInt implements Animal {\n\n public void eat() {\n System.out.println(\"Mammal eats\");\n }\n\n public void travel() {\n System.out.println(\"Mammal travels\");\n } \n\n public int noOfLegs() {\n return 0;\n }\n\n public static void main(String args[]) {\n MammalInt m = new MammalInt();\n m.eat();\n m.travel();\n }\n} "
},
{
"code": null,
"e": 5259,
"s": 5215,
"text": "Now compile the java files as shown below −"
},
{
"code": null,
"e": 5314,
"s": 5259,
"text": "$ javac -d . Animal.java \n$ javac -d . MammalInt.java\n"
},
{
"code": null,
"e": 5457,
"s": 5314,
"text": "Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as shown below."
},
{
"code": null,
"e": 5542,
"s": 5457,
"text": "You can execute the class file within the package and get the result as shown below."
},
{
"code": null,
"e": 5570,
"s": 5542,
"text": "Mammal eats\nMammal travels\n"
},
{
"code": null,
"e": 5736,
"s": 5570,
"text": "If a class wants to use another class in the same package, the package name need not be used. Classes in the same package find each other without any special syntax."
},
{
"code": null,
"e": 5950,
"s": 5736,
"text": "Here, a class named Boss is added to the payroll package that already contains Employee. The Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by the following Boss class."
},
{
"code": null,
"e": 6056,
"s": 5950,
"text": "package payroll;\npublic class Boss {\n public void payEmployee(Employee e) {\n e.mailCheck();\n }\n}"
},
{
"code": null,
"e": 6232,
"s": 6056,
"text": "What happens if the Employee class is not in the payroll package? The Boss class must then use one of the following techniques for referring to a class in a different package."
},
{
"code": null,
"e": 6297,
"s": 6232,
"text": "The fully qualified name of the class can be used. For example −"
},
{
"code": null,
"e": 6314,
"s": 6297,
"text": "payroll.Employee"
},
{
"code": null,
"e": 6404,
"s": 6314,
"text": "The package can be imported using the import keyword and the wild card (*). For example −"
},
{
"code": null,
"e": 6494,
"s": 6404,
"text": "The package can be imported using the import keyword and the wild card (*). For example −"
},
{
"code": null,
"e": 6512,
"s": 6494,
"text": "import payroll.*;"
},
{
"code": null,
"e": 6585,
"s": 6512,
"text": "The class itself can be imported using the import keyword. For example −"
},
{
"code": null,
"e": 6610,
"s": 6585,
"text": "import payroll.Employee;"
},
{
"code": null,
"e": 6771,
"s": 6610,
"text": "Note − A class file can contain any number of import statements. The import statements must appear after the package statement and before the class declaration."
},
{
"code": null,
"e": 6833,
"s": 6771,
"text": "Two major results occur when a class is placed in a package −"
},
{
"code": null,
"e": 6944,
"s": 6833,
"text": "The name of the package becomes a part of the name of the class, as we just discussed in the previous section."
},
{
"code": null,
"e": 7055,
"s": 6944,
"text": "The name of the package becomes a part of the name of the class, as we just discussed in the previous section."
},
{
"code": null,
"e": 7156,
"s": 7055,
"text": "The name of the package must match the directory structure where the corresponding bytecode resides."
},
{
"code": null,
"e": 7257,
"s": 7156,
"text": "The name of the package must match the directory structure where the corresponding bytecode resides."
},
{
"code": null,
"e": 7309,
"s": 7257,
"text": "Here is simple way of managing your files in Java −"
},
{
"code": null,
"e": 7472,
"s": 7309,
"text": "Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the type and whose extension is .java."
},
{
"code": null,
"e": 7486,
"s": 7472,
"text": "For example −"
},
{
"code": null,
"e": 7581,
"s": 7486,
"text": "// File Name : Car.java\npackage vehicle;\n\npublic class Car {\n // Class implementation. \n}"
},
{
"code": null,
"e": 7694,
"s": 7581,
"text": "Now, put the source file in a directory whose name reflects the name of the package to which the class belongs −"
},
{
"code": null,
"e": 7717,
"s": 7694,
"text": "....\\vehicle\\Car.java\n"
},
{
"code": null,
"e": 7782,
"s": 7717,
"text": "Now, the qualified class name and pathname would be as follows −"
},
{
"code": null,
"e": 7807,
"s": 7782,
"text": "Class name → vehicle.Car"
},
{
"code": null,
"e": 7849,
"s": 7807,
"text": "Path name → vehicle\\Car.java (in windows)"
},
{
"code": null,
"e": 7933,
"s": 7849,
"text": "In general, a company uses its reversed Internet domain name for its package names."
},
{
"code": null,
"e": 8111,
"s": 7933,
"text": "Example − A company's Internet domain name is apple.com, then all its package names would start with com.apple. Each component of the package name corresponds to a subdirectory."
},
{
"code": null,
"e": 8271,
"s": 8111,
"text": "Example − The company had a com.apple.computers package that contained a Dell.java source file, it would be contained in a series of subdirectories like this −"
},
{
"code": null,
"e": 8307,
"s": 8271,
"text": "....\\com\\apple\\computers\\Dell.java\n"
},
{
"code": null,
"e": 8524,
"s": 8307,
"text": "At the time of compilation, the compiler creates a different output file for each class, interface and enumeration defined in it. The base name of the output file is the name of the type, and its extension is .class."
},
{
"code": null,
"e": 8538,
"s": 8524,
"text": "For example −"
},
{
"code": null,
"e": 8629,
"s": 8538,
"text": "// File Name: Dell.java\npackage com.apple.computers;\n\npublic class Dell {\n}\n\nclass Ups {\n}"
},
{
"code": null,
"e": 8681,
"s": 8629,
"text": "Now, compile this file as follows using -d option −"
},
{
"code": null,
"e": 8704,
"s": 8681,
"text": "$javac -d . Dell.java\n"
},
{
"code": null,
"e": 8744,
"s": 8704,
"text": "The files will be compiled as follows −"
},
{
"code": null,
"e": 8810,
"s": 8744,
"text": ".\\com\\apple\\computers\\Dell.class\n.\\com\\apple\\computers\\Ups.class\n"
},
{
"code": null,
"e": 8901,
"s": 8810,
"text": "You can import all the classes or interfaces defined in \\com\\apple\\computers\\ as follows −"
},
{
"code": null,
"e": 8932,
"s": 8901,
"text": "import com.apple.computers.*;\n"
},
{
"code": null,
"e": 9229,
"s": 8932,
"text": "Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as − "
},
{
"code": null,
"e": 9330,
"s": 9229,
"text": "<path-one>\\sources\\com\\apple\\computers\\Dell.java\n\n<path-two>\\classes\\com\\apple\\computers\\Dell.class\n"
},
{
"code": null,
"e": 9613,
"s": 9330,
"text": "By doing this, it is possible to give access to the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses."
},
{
"code": null,
"e": 9862,
"s": 9613,
"text": "The full path to the classes directory, <path-two>\\classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path."
},
{
"code": null,
"e": 10045,
"s": 9862,
"text": "Say <path-two>\\classes is the class path, and the package name is com.apple.computers, then the compiler and JVM will look for .class files in <path-two>\\classes\\com\\apple\\computers."
},
{
"code": null,
"e": 10345,
"s": 10045,
"text": "A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in the class path."
},
{
"code": null,
"e": 10452,
"s": 10345,
"text": "To display the current CLASSPATH variable, use the following commands in Windows and UNIX (Bourne shell) −"
},
{
"code": null,
"e": 10484,
"s": 10452,
"text": "In Windows → C:\\> set CLASSPATH"
},
{
"code": null,
"e": 10512,
"s": 10484,
"text": "In UNIX → % echo $CLASSPATH"
},
{
"code": null,
"e": 10576,
"s": 10512,
"text": "To delete the current contents of the CLASSPATH variable, use −"
},
{
"code": null,
"e": 10610,
"s": 10576,
"text": "In Windows → C:\\> set CLASSPATH ="
},
{
"code": null,
"e": 10656,
"s": 10610,
"text": "In UNIX → % unset CLASSPATH; export CLASSPATH"
},
{
"code": null,
"e": 10688,
"s": 10656,
"text": "To set the CLASSPATH variable −"
},
{
"code": null,
"e": 10744,
"s": 10688,
"text": "In Windows → set CLASSPATH = C:\\users\\jack\\java\\classes"
},
{
"code": null,
"e": 10810,
"s": 10744,
"text": "In UNIX → % CLASSPATH = /home/jack/java/classes; export CLASSPATH"
},
{
"code": null,
"e": 10843,
"s": 10810,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10859,
"s": 10843,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 10892,
"s": 10859,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 10908,
"s": 10892,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 10943,
"s": 10908,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10957,
"s": 10943,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 10991,
"s": 10957,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 11005,
"s": 10991,
"text": " Tushar Kale"
},
{
"code": null,
"e": 11042,
"s": 11005,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 11057,
"s": 11042,
"text": " Monica Mittal"
},
{
"code": null,
"e": 11090,
"s": 11057,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 11109,
"s": 11090,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 11116,
"s": 11109,
"text": " Print"
},
{
"code": null,
"e": 11127,
"s": 11116,
"text": " Add Notes"
}
] |
It’s official: time doesn’t exist | by Gonzalo Ferreiro Volpi | Towards Data Science | [IMPORTANT]: some people left the article thinking it was about phyisics. If you’re interested only in the ML part about how to treat time features, feel free to skip over the first part of the story and go straight to ‘Dealing with time features in our dataset’.
In December my girlfriend and I went back to Uruguay and Argentina, from where we are from. Over there, her grandfather, a man I personally find fascinating -in the best possible way-, recommended me a book peppering it telling me it was one of the hardest books he had ever read in his life. Let me explain myself: we’re talking about a super clever man who reads in between two and three books at the same time. He himself probably read more books than we can possibly imagine. But it didn’t stop there: before we left, he bought the book for me, so I left Buenos Aires around Christmas with a short book of around 150 pages in my hand called ‘The Order of Time’ by an Italian physicist called Carlo Rovelli.
He asked me to give him my opinion once I finish the book, so I read it consciously. I made sure I had understood every chapter and I highlighted all the book to read the most important parts again once I finish. I’m not ashamed of saying out loud that I had to read all chapters at least twice to get some understanding of them. The book starts by stating that if two twin brothers meet again after ten years, where one lived in the mountain and the other one in the plain, the former would be older since time passes faster in the mountain and slower in the plain. And this my friends, is no fairy tale: time indeed goes slower in places closer to the centre of the earth.
In short, the book explains that time as we know it and we have learnt to understand it doesn’t exist. And what really is time. Reading about all this, from a professional studying the subject since he was a college student, got me meditating about lots of stuff. I’m not going to bore you with self-reflection kind of thoughts, but the book caught me thinking also about who do we usually use time in machine learning and data science. Since in his book, Carlo states that time itself it’s nothing. What we perceive as the time it’s a human construction invented to measure how much time takes it to the earth to go around the sun. And that measure is done by metrics also invented by us like seconds, milliseconds, hours, minutes, etc.
Given this, for someone who doesn’t know what the concept of ‘minutes’ or ‘seconds’ is, who doesn’t know what day is today, and even worse, doesn’t know what ‘days’ or ‘months’, saying that now it’s 22:48 pm does not indicate anything at all. I know what you’re thinking: that kind of person just doesn’t exist. Well, even though that’s true, guess who doesn’t know all that: your machine learning algorithm. So the way we treat and feed time data to our model is key.
For all the curious minds, first I’m going to spend a few paragraphs to give a summary of the book. If you’re interested enough go ahead and read it. Otherwise, you can just skip over it. However, if you read it and you want to learn more, here a Ted Talk Carlo Rovelli gave 8 years ago, and the book it’s only around six pounds in Amazon.
As I said before, the book states that the concept of time as we know it doesn’t exist. Neither the metrics we use to measure it. And they don’t exist, because in the world of physics they don’t exist. The fundamental equations of the world do not have a variable for time. What does exist is a physical time, whose elapsing is not uniform but depends on many factors.
This physical time seems to not be a continuous-time, but a granular time, that goes jumping in-between values instead of elapsing. Where the notion of time under a specific value doesn’t exist in its more basic concept of time. Following this understanding of physical time, at a microscopic level time it’s made up of crashing atoms. Atoms that are scattered in a cloud of probabilities and we don’t have a precise way of knowing where are they going to appear. They appear and crash in between where the probabilities are good enough for it to happen. But when it does happen, that fraction of the universe goes from some specific somehow basic configuration to a more complex one. However, these particular configurations which allow that kind of microscopic events, depend explicitly on a blur or unfocused vision we have of the world. But this unfocused vision does not depend on some mental perception we might have, but instead, it’s a relative property. It is a property of an object in relation to another object. The concept of temporality then is deeply connected to this blur or unfocused vision of the world, where we ignore the most microscopic details of it. Therefore, this physical time is, ultimately, the expression of our ignorance about the world.
Regarding this last idea, it helped a lot to understand it a chapter which talks about the fact that a cat it’s not part of the elemental ingredients of the universe. It’s something more complex than that, that constantly appears in several parts of our planet. In a similar way, at the top of a mountain, we look at a valley covered with a blue sea of white clouds. If we climb the mountain, while we do it, the clouds stop being white; we find ourself in the middle of a fog. But the change is not instantaneous, it is gradual. The same happens with any kind of surface. A marble table would look like fog if could make ourselves small enough. In these examples, a real thing appears, things we are able to see and even sometimes touch. They appear from a world where at the most basic level there are no cats. In the same way, time arises from a world without time.
The world without time then, says the book, is nothing more than a network of interconnected events. Where the absence of time doesn’t mean that it’s frozen or static; it means that the happening it’s not sorted by a linear temporal line. If by time we understand only the happening, then everything is time. But at the same time, to my understanding, nothing is too. Or at least, nothing is past and nothing is future. We’re just a tiny happening of interconnected events in a universe that’s much bigger than we know and understand about it.
What we understand as the past and the future are within ourselves. We are the stories that live in our brain. Lines drawn from footprints of this constantly crashing of atoms. Lines that allow us to predict future events. Like for example, in which direction is going a ball that has been thrown to me and how to move our hand in order to catch it. This space, our memory, together with the constant practice of anticipation, is the source of our perception of time and of ourselves.
Now, as I said before, apart from all the self-reflection and deep kind of thoughts all this can spark, let’s take this down to the world of machine learning. We do have a memory to predict things like the example of the ball above. We do know that after January it comes February, that last year was 2019, or what minute comes after 23:59 pm. Also, industry-wise, our memory allows us to know, for example, that after the spring it comes the summer and that if I’m working for a company that sells beer, summer is probably a seasonal period for us, and therefore, we should see an increase in sales. At Ravelin, where I work, we might know that for some industries, certain hours or times of the day are more fraudulent than others. However, our machine learning model doesn’t know all that. And even if we feed it with the months of the year in a one-hot-encoding sort of way, the algorithm wouldn’t know that after December, it comes January. Or that after midnight the hour starts again from zero.
How should we treat timestamps then? Well, as I read in a Stackoverflow question a while ago:
You don’t really use timestamps as features because they wouldn’t be useful during the classification of unseen data. Imagine training a model with data obtained in 2018, and trying to classify data for 2019. The information is not on the dates but in the values of the other features!
Can you see the resemblance with what Carlo says in his book? As in real life, where time itself is nothing apart from references we might have in our memory to give context to it, the same happens with our machine learning model. Our time features only have value in relation with some other dates that might be relevant for whatever we are trying to predict.
According to this, values as the following wouldn’t make any sense for a machine learning model:
Datetimes like: 2019–12–24T10:25:11.577Z,
Or timestamps like: 1578830817’
How can we translate this into something useful for our algorithm? Well, at first we could make some simple transformation to give our model a better reference of how to compare in between rows or events happening at different datetimes or timestamps. For example, we could obtain:
month_of_the_year
day_of_the_year
day_of_the_week
hour_of_the_day
minute_of_the_day
Minute_of_hour
Pandas provides us with a neat table with lots of options from its documentation about Time series/date functionality:
By doing this, our model would know that August, the eigth month of the year, comes after July and before September. Or that in 2020 the 9th of May comes one hundred days after the 30th of January and one hundred days before the 17th of August.
We could even go further and do some other kinds of things. For example, we might know that Christmas is a sensible date for our business, and in fact, our model itself might be even able to find out that datetimes like ‘2019–12–24 08:57:04.927’ have something special/weird/peculiar going on while predicting. However, how can the model know that some other datetime comes exactly one day or twenty-four hours after that datetime? We need to make it easier for the algorithm to understand that. For this, we could set up features like:
is_christmas
days_since_christmas
weeks_since_christmas
Or if we are an online delivery company and we know that sales-wise our strongest moment of the week is Friday at 20:30 pm, we could create features like:
minutes_till_peak
minutes_since_peak
Again, we’re trying to give our machine learning model the same kind of context we have thanks to our memory and our understanding of time. However, I know what you might be thinking: ok, cool, but how am I supposed to deal with these features once I created them? Cause we would be transforming our timestamp into categorical features. And since we covered in a previous story of mine about categorical variables encoding, some algorithms don’t particularly enjoy dealing with this kind of features if we don’t feed them rightly. So what do we do?
Well, as mention before, we don’t want to do any sort of one-hot-encoding or similar transformation. If we do that we would be losing any value we might have in the continuity of the feature. In other words, the model would stop recognizing such things like that the sixth month of the year, June, comes after May and before July. However leaving them as they are presents another challenge: how can the model know that once December finishes, it comes January once again? Or that after the 23rd hour of the day it starts all over again from zero?
Lucky for us, there’s a very simple way of solving this: we could transform each variable into a two dimensions feature, using a sine and cosine transformation. Let’s go through an example.
Suppose you have a dataset with the feature ‘OriginalClientEventTime’ in it. At first, you would like to transform the type of the feature into Pandas Datetime, in order to afterwards obtain the hour of the day. You can do this as follows:
train[‘OriginalClientEventTime’] = pd.to_datetime(train[‘OriginalClientEventTime’])train[‘hour’] = [x.hour for x in train[‘OriginalClientEventTime’]]
In a similar way, you could do the same to obtain any of the properties listed above in the table from Panda’s documentation about Time series/date functionality.
Once we do this, these features would look the following way:
Now that we have the hour of the day, we can transform it into a two-dimensional feature in order for the model to pick up the nature of the original. We can easily do this in just two lines:
import numpy as nptrain[‘sin_hour’] = np.sin(2*np.pi*train.hour/24)train[‘cos_hour’] = np.cos(2*np.pi*train.hour/24)
And this is how our dataset would like now with the new features:
train[[‘OriginalClientEventTime’,’hour’,’sin_hour’,’cos_hour’]]
If we plot the sine or cosine features independently we wouldn’t notice much, but that’s because we need both variables to catch the proper nature of the feature. See now what happens when we plot both features at the same time on the Y and X-axis:
train.plot.scatter(‘sin_hour’,’cos_hour’)
Neat, right? The behaviour of time as we know it seems to be reflected in a perfect circle that loops in between the values of the hours in a day. We could do the same with any other time feature! The month of year, minutes of the day, day of the year, days till Christmas, etc.
As I told my girlfriend’s grandfather in my review of Rovelli’s book, surely there are tons of things from the text I didn’t understand. But I did get that if somehow we can remember stuff about the past, and predict things of the future -like where should I move my hand in order to catch a ball someone threw towards me-, is thanks to our memory and the concept of time we’ve built. A concept of time made up of metrics that only describe the distance in between events, like how long it takes for the earth to spin around the sun (which by the way, it’s 365.256 days).
So if we want our machine learning models to really learn, let’s try to teach them what we ourselves have learned over time.
Well, that’s all for today. Stay tuned for future stories featuring other kinds of techniques for dealing with categorical features. Meanwhile, the year is just starting, will you be looking for a job in 2020? Well, then you can’t miss my story about practical tips for landing your first data job. Or perhaps you’re still looking for the perfect Christmas gift to give yourself? Then check out this story about 9 data science-related books to read. If none of this is your case, feel free to visit my profile on Medium and check any other of my stories.
And if you want to receive my latest articles directly on your email, just subscribe to my newsletter :)
See you around! And thanks for reading! | [
{
"code": null,
"e": 436,
"s": 172,
"text": "[IMPORTANT]: some people left the article thinking it was about phyisics. If you’re interested only in the ML part about how to treat time features, feel free to skip over the first part of the story and go straight to ‘Dealing with time features in our dataset’."
},
{
"code": null,
"e": 1147,
"s": 436,
"text": "In December my girlfriend and I went back to Uruguay and Argentina, from where we are from. Over there, her grandfather, a man I personally find fascinating -in the best possible way-, recommended me a book peppering it telling me it was one of the hardest books he had ever read in his life. Let me explain myself: we’re talking about a super clever man who reads in between two and three books at the same time. He himself probably read more books than we can possibly imagine. But it didn’t stop there: before we left, he bought the book for me, so I left Buenos Aires around Christmas with a short book of around 150 pages in my hand called ‘The Order of Time’ by an Italian physicist called Carlo Rovelli."
},
{
"code": null,
"e": 1822,
"s": 1147,
"text": "He asked me to give him my opinion once I finish the book, so I read it consciously. I made sure I had understood every chapter and I highlighted all the book to read the most important parts again once I finish. I’m not ashamed of saying out loud that I had to read all chapters at least twice to get some understanding of them. The book starts by stating that if two twin brothers meet again after ten years, where one lived in the mountain and the other one in the plain, the former would be older since time passes faster in the mountain and slower in the plain. And this my friends, is no fairy tale: time indeed goes slower in places closer to the centre of the earth."
},
{
"code": null,
"e": 2560,
"s": 1822,
"text": "In short, the book explains that time as we know it and we have learnt to understand it doesn’t exist. And what really is time. Reading about all this, from a professional studying the subject since he was a college student, got me meditating about lots of stuff. I’m not going to bore you with self-reflection kind of thoughts, but the book caught me thinking also about who do we usually use time in machine learning and data science. Since in his book, Carlo states that time itself it’s nothing. What we perceive as the time it’s a human construction invented to measure how much time takes it to the earth to go around the sun. And that measure is done by metrics also invented by us like seconds, milliseconds, hours, minutes, etc."
},
{
"code": null,
"e": 3029,
"s": 2560,
"text": "Given this, for someone who doesn’t know what the concept of ‘minutes’ or ‘seconds’ is, who doesn’t know what day is today, and even worse, doesn’t know what ‘days’ or ‘months’, saying that now it’s 22:48 pm does not indicate anything at all. I know what you’re thinking: that kind of person just doesn’t exist. Well, even though that’s true, guess who doesn’t know all that: your machine learning algorithm. So the way we treat and feed time data to our model is key."
},
{
"code": null,
"e": 3369,
"s": 3029,
"text": "For all the curious minds, first I’m going to spend a few paragraphs to give a summary of the book. If you’re interested enough go ahead and read it. Otherwise, you can just skip over it. However, if you read it and you want to learn more, here a Ted Talk Carlo Rovelli gave 8 years ago, and the book it’s only around six pounds in Amazon."
},
{
"code": null,
"e": 3738,
"s": 3369,
"text": "As I said before, the book states that the concept of time as we know it doesn’t exist. Neither the metrics we use to measure it. And they don’t exist, because in the world of physics they don’t exist. The fundamental equations of the world do not have a variable for time. What does exist is a physical time, whose elapsing is not uniform but depends on many factors."
},
{
"code": null,
"e": 5008,
"s": 3738,
"text": "This physical time seems to not be a continuous-time, but a granular time, that goes jumping in-between values instead of elapsing. Where the notion of time under a specific value doesn’t exist in its more basic concept of time. Following this understanding of physical time, at a microscopic level time it’s made up of crashing atoms. Atoms that are scattered in a cloud of probabilities and we don’t have a precise way of knowing where are they going to appear. They appear and crash in between where the probabilities are good enough for it to happen. But when it does happen, that fraction of the universe goes from some specific somehow basic configuration to a more complex one. However, these particular configurations which allow that kind of microscopic events, depend explicitly on a blur or unfocused vision we have of the world. But this unfocused vision does not depend on some mental perception we might have, but instead, it’s a relative property. It is a property of an object in relation to another object. The concept of temporality then is deeply connected to this blur or unfocused vision of the world, where we ignore the most microscopic details of it. Therefore, this physical time is, ultimately, the expression of our ignorance about the world."
},
{
"code": null,
"e": 5877,
"s": 5008,
"text": "Regarding this last idea, it helped a lot to understand it a chapter which talks about the fact that a cat it’s not part of the elemental ingredients of the universe. It’s something more complex than that, that constantly appears in several parts of our planet. In a similar way, at the top of a mountain, we look at a valley covered with a blue sea of white clouds. If we climb the mountain, while we do it, the clouds stop being white; we find ourself in the middle of a fog. But the change is not instantaneous, it is gradual. The same happens with any kind of surface. A marble table would look like fog if could make ourselves small enough. In these examples, a real thing appears, things we are able to see and even sometimes touch. They appear from a world where at the most basic level there are no cats. In the same way, time arises from a world without time."
},
{
"code": null,
"e": 6421,
"s": 5877,
"text": "The world without time then, says the book, is nothing more than a network of interconnected events. Where the absence of time doesn’t mean that it’s frozen or static; it means that the happening it’s not sorted by a linear temporal line. If by time we understand only the happening, then everything is time. But at the same time, to my understanding, nothing is too. Or at least, nothing is past and nothing is future. We’re just a tiny happening of interconnected events in a universe that’s much bigger than we know and understand about it."
},
{
"code": null,
"e": 6906,
"s": 6421,
"text": "What we understand as the past and the future are within ourselves. We are the stories that live in our brain. Lines drawn from footprints of this constantly crashing of atoms. Lines that allow us to predict future events. Like for example, in which direction is going a ball that has been thrown to me and how to move our hand in order to catch it. This space, our memory, together with the constant practice of anticipation, is the source of our perception of time and of ourselves."
},
{
"code": null,
"e": 7908,
"s": 6906,
"text": "Now, as I said before, apart from all the self-reflection and deep kind of thoughts all this can spark, let’s take this down to the world of machine learning. We do have a memory to predict things like the example of the ball above. We do know that after January it comes February, that last year was 2019, or what minute comes after 23:59 pm. Also, industry-wise, our memory allows us to know, for example, that after the spring it comes the summer and that if I’m working for a company that sells beer, summer is probably a seasonal period for us, and therefore, we should see an increase in sales. At Ravelin, where I work, we might know that for some industries, certain hours or times of the day are more fraudulent than others. However, our machine learning model doesn’t know all that. And even if we feed it with the months of the year in a one-hot-encoding sort of way, the algorithm wouldn’t know that after December, it comes January. Or that after midnight the hour starts again from zero."
},
{
"code": null,
"e": 8002,
"s": 7908,
"text": "How should we treat timestamps then? Well, as I read in a Stackoverflow question a while ago:"
},
{
"code": null,
"e": 8288,
"s": 8002,
"text": "You don’t really use timestamps as features because they wouldn’t be useful during the classification of unseen data. Imagine training a model with data obtained in 2018, and trying to classify data for 2019. The information is not on the dates but in the values of the other features!"
},
{
"code": null,
"e": 8649,
"s": 8288,
"text": "Can you see the resemblance with what Carlo says in his book? As in real life, where time itself is nothing apart from references we might have in our memory to give context to it, the same happens with our machine learning model. Our time features only have value in relation with some other dates that might be relevant for whatever we are trying to predict."
},
{
"code": null,
"e": 8746,
"s": 8649,
"text": "According to this, values as the following wouldn’t make any sense for a machine learning model:"
},
{
"code": null,
"e": 8788,
"s": 8746,
"text": "Datetimes like: 2019–12–24T10:25:11.577Z,"
},
{
"code": null,
"e": 8820,
"s": 8788,
"text": "Or timestamps like: 1578830817’"
},
{
"code": null,
"e": 9102,
"s": 8820,
"text": "How can we translate this into something useful for our algorithm? Well, at first we could make some simple transformation to give our model a better reference of how to compare in between rows or events happening at different datetimes or timestamps. For example, we could obtain:"
},
{
"code": null,
"e": 9120,
"s": 9102,
"text": "month_of_the_year"
},
{
"code": null,
"e": 9136,
"s": 9120,
"text": "day_of_the_year"
},
{
"code": null,
"e": 9152,
"s": 9136,
"text": "day_of_the_week"
},
{
"code": null,
"e": 9168,
"s": 9152,
"text": "hour_of_the_day"
},
{
"code": null,
"e": 9186,
"s": 9168,
"text": "minute_of_the_day"
},
{
"code": null,
"e": 9201,
"s": 9186,
"text": "Minute_of_hour"
},
{
"code": null,
"e": 9320,
"s": 9201,
"text": "Pandas provides us with a neat table with lots of options from its documentation about Time series/date functionality:"
},
{
"code": null,
"e": 9565,
"s": 9320,
"text": "By doing this, our model would know that August, the eigth month of the year, comes after July and before September. Or that in 2020 the 9th of May comes one hundred days after the 30th of January and one hundred days before the 17th of August."
},
{
"code": null,
"e": 10102,
"s": 9565,
"text": "We could even go further and do some other kinds of things. For example, we might know that Christmas is a sensible date for our business, and in fact, our model itself might be even able to find out that datetimes like ‘2019–12–24 08:57:04.927’ have something special/weird/peculiar going on while predicting. However, how can the model know that some other datetime comes exactly one day or twenty-four hours after that datetime? We need to make it easier for the algorithm to understand that. For this, we could set up features like:"
},
{
"code": null,
"e": 10115,
"s": 10102,
"text": "is_christmas"
},
{
"code": null,
"e": 10136,
"s": 10115,
"text": "days_since_christmas"
},
{
"code": null,
"e": 10158,
"s": 10136,
"text": "weeks_since_christmas"
},
{
"code": null,
"e": 10313,
"s": 10158,
"text": "Or if we are an online delivery company and we know that sales-wise our strongest moment of the week is Friday at 20:30 pm, we could create features like:"
},
{
"code": null,
"e": 10331,
"s": 10313,
"text": "minutes_till_peak"
},
{
"code": null,
"e": 10350,
"s": 10331,
"text": "minutes_since_peak"
},
{
"code": null,
"e": 10899,
"s": 10350,
"text": "Again, we’re trying to give our machine learning model the same kind of context we have thanks to our memory and our understanding of time. However, I know what you might be thinking: ok, cool, but how am I supposed to deal with these features once I created them? Cause we would be transforming our timestamp into categorical features. And since we covered in a previous story of mine about categorical variables encoding, some algorithms don’t particularly enjoy dealing with this kind of features if we don’t feed them rightly. So what do we do?"
},
{
"code": null,
"e": 11447,
"s": 10899,
"text": "Well, as mention before, we don’t want to do any sort of one-hot-encoding or similar transformation. If we do that we would be losing any value we might have in the continuity of the feature. In other words, the model would stop recognizing such things like that the sixth month of the year, June, comes after May and before July. However leaving them as they are presents another challenge: how can the model know that once December finishes, it comes January once again? Or that after the 23rd hour of the day it starts all over again from zero?"
},
{
"code": null,
"e": 11637,
"s": 11447,
"text": "Lucky for us, there’s a very simple way of solving this: we could transform each variable into a two dimensions feature, using a sine and cosine transformation. Let’s go through an example."
},
{
"code": null,
"e": 11877,
"s": 11637,
"text": "Suppose you have a dataset with the feature ‘OriginalClientEventTime’ in it. At first, you would like to transform the type of the feature into Pandas Datetime, in order to afterwards obtain the hour of the day. You can do this as follows:"
},
{
"code": null,
"e": 12027,
"s": 11877,
"text": "train[‘OriginalClientEventTime’] = pd.to_datetime(train[‘OriginalClientEventTime’])train[‘hour’] = [x.hour for x in train[‘OriginalClientEventTime’]]"
},
{
"code": null,
"e": 12190,
"s": 12027,
"text": "In a similar way, you could do the same to obtain any of the properties listed above in the table from Panda’s documentation about Time series/date functionality."
},
{
"code": null,
"e": 12252,
"s": 12190,
"text": "Once we do this, these features would look the following way:"
},
{
"code": null,
"e": 12444,
"s": 12252,
"text": "Now that we have the hour of the day, we can transform it into a two-dimensional feature in order for the model to pick up the nature of the original. We can easily do this in just two lines:"
},
{
"code": null,
"e": 12561,
"s": 12444,
"text": "import numpy as nptrain[‘sin_hour’] = np.sin(2*np.pi*train.hour/24)train[‘cos_hour’] = np.cos(2*np.pi*train.hour/24)"
},
{
"code": null,
"e": 12627,
"s": 12561,
"text": "And this is how our dataset would like now with the new features:"
},
{
"code": null,
"e": 12691,
"s": 12627,
"text": "train[[‘OriginalClientEventTime’,’hour’,’sin_hour’,’cos_hour’]]"
},
{
"code": null,
"e": 12940,
"s": 12691,
"text": "If we plot the sine or cosine features independently we wouldn’t notice much, but that’s because we need both variables to catch the proper nature of the feature. See now what happens when we plot both features at the same time on the Y and X-axis:"
},
{
"code": null,
"e": 12982,
"s": 12940,
"text": "train.plot.scatter(‘sin_hour’,’cos_hour’)"
},
{
"code": null,
"e": 13261,
"s": 12982,
"text": "Neat, right? The behaviour of time as we know it seems to be reflected in a perfect circle that loops in between the values of the hours in a day. We could do the same with any other time feature! The month of year, minutes of the day, day of the year, days till Christmas, etc."
},
{
"code": null,
"e": 13833,
"s": 13261,
"text": "As I told my girlfriend’s grandfather in my review of Rovelli’s book, surely there are tons of things from the text I didn’t understand. But I did get that if somehow we can remember stuff about the past, and predict things of the future -like where should I move my hand in order to catch a ball someone threw towards me-, is thanks to our memory and the concept of time we’ve built. A concept of time made up of metrics that only describe the distance in between events, like how long it takes for the earth to spin around the sun (which by the way, it’s 365.256 days)."
},
{
"code": null,
"e": 13958,
"s": 13833,
"text": "So if we want our machine learning models to really learn, let’s try to teach them what we ourselves have learned over time."
},
{
"code": null,
"e": 14513,
"s": 13958,
"text": "Well, that’s all for today. Stay tuned for future stories featuring other kinds of techniques for dealing with categorical features. Meanwhile, the year is just starting, will you be looking for a job in 2020? Well, then you can’t miss my story about practical tips for landing your first data job. Or perhaps you’re still looking for the perfect Christmas gift to give yourself? Then check out this story about 9 data science-related books to read. If none of this is your case, feel free to visit my profile on Medium and check any other of my stories."
},
{
"code": null,
"e": 14618,
"s": 14513,
"text": "And if you want to receive my latest articles directly on your email, just subscribe to my newsletter :)"
}
] |
Bootstrap .tooltip("destroy") method | Use the tooltip(“destroy”) method in Bootstrap to detroy the tooltip −
$(".btn-default").click(function(){
$("[data-toggle='tooltip']").tooltip('destroy');
});
The following example has two buttons, one for “Show Tooltip” and another for “Destroy Tooltip” −
$(".btn-primary").click(function(){
$("[data-toggle='tooltip']").tooltip('show');
});
$(".btn-default").click(function(){
$("[data-toggle='tooltip']").tooltip('destroy');
});
Here is the complete code to implement the tooltip(“destroy”) method −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h3>Demo</h3>
<a href="#" data-toggle="tooltip" title="Tooltip is visible!">Tooltip will be visible here</a>
<div>
<button type="button" class="btn btn-primary">Show Tooltip</button>
<button type="button" class="btn btn-default">Destroy Tooltip</button>
</div>
</div>
<script>
$(document).ready(function(){
$(".btn-primary").click(function(){
$("[data-toggle='tooltip']").tooltip('show');
});
$(".btn-default").click(function(){
$("[data-toggle='tooltip']").tooltip('destroy');
});
});
</script>
</body>
</html> | [
{
"code": null,
"e": 1133,
"s": 1062,
"text": "Use the tooltip(“destroy”) method in Bootstrap to detroy the tooltip −"
},
{
"code": null,
"e": 1224,
"s": 1133,
"text": "$(\".btn-default\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('destroy');\n});"
},
{
"code": null,
"e": 1322,
"s": 1224,
"text": "The following example has two buttons, one for “Show Tooltip” and another for “Destroy Tooltip” −"
},
{
"code": null,
"e": 1410,
"s": 1322,
"text": "$(\".btn-primary\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('show');\n});"
},
{
"code": null,
"e": 1501,
"s": 1410,
"text": "$(\".btn-default\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('destroy');\n});"
},
{
"code": null,
"e": 1572,
"s": 1501,
"text": "Here is the complete code to implement the tooltip(“destroy”) method −"
},
{
"code": null,
"e": 1582,
"s": 1572,
"text": "Live Demo"
},
{
"code": null,
"e": 2671,
"s": 1582,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n <div class=\"container\">\n <h3>Demo</h3>\n <a href=\"#\" data-toggle=\"tooltip\" title=\"Tooltip is visible!\">Tooltip will be visible here</a>\n <div>\n <button type=\"button\" class=\"btn btn-primary\">Show Tooltip</button>\n <button type=\"button\" class=\"btn btn-default\">Destroy Tooltip</button>\n </div> \n </div>\n\n<script>\n $(document).ready(function(){\n $(\".btn-primary\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('show');\n });\n $(\".btn-default\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('destroy');\n });\n });\n</script>\n\n</body>\n</html>"
}
] |
Tune Your Scikit-learn Model Using Evolutionary Algorithms | by Rodrigo Arenas | Towards Data Science | Hyperparameter tuning is an essential part of the machine learning pipeline—most common implementations use a grid search (random or not) to choose between a set of combinations.
This article will use evolutionary algorithms with the python package sklearn-genetic-opt to find the set of parameters that optimizes our defined cross-validation metric. This package has some functionalities that can make this process easier:
Hyperparameters search by using several evolutionary algorithms.
Callbacks to stop the optimization when you meet a criterion, log objects into a local system, or customize your logic.
Logging capabilities into a Logbook object or with MLflow build-in integration.
Utils plots to understand the optimization process.
As a demonstration dataset, we’ll use the digits data from Scikit-learn; the idea is to classify handwritten digits of images of 8x8 pixels. A sample of the data is as follow:
Most of the evolutionary algorithms start with a population of individuals; each represents a set of hyperparameters to use in our machine learning model.
Using some mechanisms that try to emulate the way populations evolve, the algorithm reproduces, mutates, and selects new hyperparameters based on the results of the already tested parameters, using some metric to define its fitness (for example, the cross-validation accuracy) and repeats this process over several generations of individuals, here is an extended explanation of the process. Visually, it could look like this:
If you want a more in-depth explanation, you can check my other medium post explaining the theoretical aspects of this process.
The way the algorithm works may sound a bit confusing, but there are already some packages as DEAP in Python which already have optimized routines for this algorithm.
In this case, we will use sklearn-genetic-opt, a python package built on top of DEAP and scikit-learn to make this optimization process more straightforward.
First, let’s install it:
pip install sklearn-genetic-opt
Now, let’s import the data, split it in our train and test set, and create an instance of any scikit-learn classifier; for this example, I will use a Random Forest Classifier.
Now, we can use sklearn-genetic-opt to tune our classifier based on a metric; in this case, I will choose the accuracy score from stratified cross-validation with three splits.
The param_grid is similar to scikit-learn, but we must use the space classes to let sklearn-genetic-opt know which type of data to use to sample the parameters.
To define this and others options, we must use the principal class of the package called GASearchCV.
At the end of this article, I’ll explain the parameters shown so you can change them if you want.
The estimator must be a sckit-learn classifier or regressor, cv is the number of splits in the cross-validation or a cross-validation generator, and scoring is the metric chosen to optimize—it must be one of the sklearn metrics that are compatible with the estimator.
Now we can fit our model and use it in our test data; by default, it will use the best set of hyperparameters found:
evolved_estimator.fit(X_train,y_train)y_predicy_ga = evolved_estimator.predict(X_test)accuracy_score(y_test,y_predicy_ga)
You should see something like this:
While the algorithm is running, it shows us the metrics it’s achieving at each generation; the “fitness” refers to the metric we chose, in this case, the accuracy. As the algorithm uses more than one set of hyperparameters per generation, it shows the average accuracy, standard deviation, and maximum and minimum individual values.
In this particular run, we got an accuracy in the test set of 0.93 with this set of hyperparameters:
We can also see the evolution of the optimization routine, using the command:
plot_fitness_evolution(evolved_estimator)plt.show()
As you can see, the algorithm started with an accuracy around 0.8 in generation 0, which generated hyperparameters randomly. But the accuracy improves while the algorithm chooses a new set of hyperparameters using evolutionary strategies. The algorithm probably hasn’t wholly converged to its best fitness value but already got up to 0.94, so you can leave it running some extra generations to see if you can get better accuracy.
We can also have the log of all the hyperparameters that the model used and its cross-validation score.
For example, you can use those logs to plot the distribution of the parameters that the algorithm is selecting to see how its exploration and exploitation strategy were.
plot_search_space(evolved_estimator)plt.show()
The k (keep_top_k=4) best set of hyperparameters combinations:
So that is it! As you can see, it is pretty straightforward to make this optimization routine using evolutionary algorithms with sklearn-genetic-opt; this is an open-source project that can help you to choose your hyperparameters as an alternative to methods such as scikit-learn’s RandomizedSearchCV or GridSearch, which depends on pre-defined combinations of hyperparameters to try.
As the author of the package, any suggestion, contribution, or comment is very welcome. Here you can see more examples and the source code used:
sklearn-genetic-opt.readthedocs.io
Define the search space with the parameter ‘param_grid’; it takes a dictionary with some of these classes:
Categorical: Represents categorical variables, expects a list of options it can sample, and optionally the probability of sampling each option
Integer: Represents integer variables, expects a lower and upper bound of the variable
Continuous: Represents real-valued variables, expects a lower and upper bound of the variable, optionally can sample the values from a log-uniform distribution if the variable is positively defined
population: It’s the initial amount of hyperparameters candidates to generate randomly.
generations: How many iterations the algorithm will make, it creates a new population every generation
elitism: If true, it uses a tournament selection keeping the best k individuals; if false, it uses a roulette selection mechanism.
tournament size: How many individuals to select utilizing a tournament operator, only used if elitism=True.
crossover_probability: The probability that a crossover occurs in a particular mating.
mutation_probability: The probability that an already fixed individual, suffers a random change in some of its hyperparameters values.
param_grid: dictionary with the keys as the names of the hyperparameters, and the values some of the Categorical, Continuous, or Integer from sklearn_genetic.space
Defines the possible values that this parameter can take.
criteria: ‘max’ if the ‘scoring’ metric choose, it’s considered better as its value increases, ‘min’ otherwise.
algorithm: The specific evolutionary algorithm from the package deap to use, version 0.5.0 of sklearn-genetic-opt supports eaSimple, eaMuPlusLambda, and eaMuCommaLambda.
n_jobs: How many concurrent jobs to launch over the cross-validation step
verbose: If True, it displays some metrics over the optimization while the algorithm runs.
keep_top_k: Based on its final cross-validation score, how many sets of hyperparameters to return at the end of the optimization. This parameter determines the size of the hof.
log_config: If you set this parameter with the MLflowConfig, the metrics, hyperparameters, and models get logged into an MLflow server. | [
{
"code": null,
"e": 351,
"s": 172,
"text": "Hyperparameter tuning is an essential part of the machine learning pipeline—most common implementations use a grid search (random or not) to choose between a set of combinations."
},
{
"code": null,
"e": 596,
"s": 351,
"text": "This article will use evolutionary algorithms with the python package sklearn-genetic-opt to find the set of parameters that optimizes our defined cross-validation metric. This package has some functionalities that can make this process easier:"
},
{
"code": null,
"e": 661,
"s": 596,
"text": "Hyperparameters search by using several evolutionary algorithms."
},
{
"code": null,
"e": 781,
"s": 661,
"text": "Callbacks to stop the optimization when you meet a criterion, log objects into a local system, or customize your logic."
},
{
"code": null,
"e": 861,
"s": 781,
"text": "Logging capabilities into a Logbook object or with MLflow build-in integration."
},
{
"code": null,
"e": 913,
"s": 861,
"text": "Utils plots to understand the optimization process."
},
{
"code": null,
"e": 1089,
"s": 913,
"text": "As a demonstration dataset, we’ll use the digits data from Scikit-learn; the idea is to classify handwritten digits of images of 8x8 pixels. A sample of the data is as follow:"
},
{
"code": null,
"e": 1244,
"s": 1089,
"text": "Most of the evolutionary algorithms start with a population of individuals; each represents a set of hyperparameters to use in our machine learning model."
},
{
"code": null,
"e": 1670,
"s": 1244,
"text": "Using some mechanisms that try to emulate the way populations evolve, the algorithm reproduces, mutates, and selects new hyperparameters based on the results of the already tested parameters, using some metric to define its fitness (for example, the cross-validation accuracy) and repeats this process over several generations of individuals, here is an extended explanation of the process. Visually, it could look like this:"
},
{
"code": null,
"e": 1798,
"s": 1670,
"text": "If you want a more in-depth explanation, you can check my other medium post explaining the theoretical aspects of this process."
},
{
"code": null,
"e": 1965,
"s": 1798,
"text": "The way the algorithm works may sound a bit confusing, but there are already some packages as DEAP in Python which already have optimized routines for this algorithm."
},
{
"code": null,
"e": 2123,
"s": 1965,
"text": "In this case, we will use sklearn-genetic-opt, a python package built on top of DEAP and scikit-learn to make this optimization process more straightforward."
},
{
"code": null,
"e": 2148,
"s": 2123,
"text": "First, let’s install it:"
},
{
"code": null,
"e": 2180,
"s": 2148,
"text": "pip install sklearn-genetic-opt"
},
{
"code": null,
"e": 2356,
"s": 2180,
"text": "Now, let’s import the data, split it in our train and test set, and create an instance of any scikit-learn classifier; for this example, I will use a Random Forest Classifier."
},
{
"code": null,
"e": 2533,
"s": 2356,
"text": "Now, we can use sklearn-genetic-opt to tune our classifier based on a metric; in this case, I will choose the accuracy score from stratified cross-validation with three splits."
},
{
"code": null,
"e": 2694,
"s": 2533,
"text": "The param_grid is similar to scikit-learn, but we must use the space classes to let sklearn-genetic-opt know which type of data to use to sample the parameters."
},
{
"code": null,
"e": 2795,
"s": 2694,
"text": "To define this and others options, we must use the principal class of the package called GASearchCV."
},
{
"code": null,
"e": 2893,
"s": 2795,
"text": "At the end of this article, I’ll explain the parameters shown so you can change them if you want."
},
{
"code": null,
"e": 3161,
"s": 2893,
"text": "The estimator must be a sckit-learn classifier or regressor, cv is the number of splits in the cross-validation or a cross-validation generator, and scoring is the metric chosen to optimize—it must be one of the sklearn metrics that are compatible with the estimator."
},
{
"code": null,
"e": 3278,
"s": 3161,
"text": "Now we can fit our model and use it in our test data; by default, it will use the best set of hyperparameters found:"
},
{
"code": null,
"e": 3400,
"s": 3278,
"text": "evolved_estimator.fit(X_train,y_train)y_predicy_ga = evolved_estimator.predict(X_test)accuracy_score(y_test,y_predicy_ga)"
},
{
"code": null,
"e": 3436,
"s": 3400,
"text": "You should see something like this:"
},
{
"code": null,
"e": 3769,
"s": 3436,
"text": "While the algorithm is running, it shows us the metrics it’s achieving at each generation; the “fitness” refers to the metric we chose, in this case, the accuracy. As the algorithm uses more than one set of hyperparameters per generation, it shows the average accuracy, standard deviation, and maximum and minimum individual values."
},
{
"code": null,
"e": 3870,
"s": 3769,
"text": "In this particular run, we got an accuracy in the test set of 0.93 with this set of hyperparameters:"
},
{
"code": null,
"e": 3948,
"s": 3870,
"text": "We can also see the evolution of the optimization routine, using the command:"
},
{
"code": null,
"e": 4000,
"s": 3948,
"text": "plot_fitness_evolution(evolved_estimator)plt.show()"
},
{
"code": null,
"e": 4430,
"s": 4000,
"text": "As you can see, the algorithm started with an accuracy around 0.8 in generation 0, which generated hyperparameters randomly. But the accuracy improves while the algorithm chooses a new set of hyperparameters using evolutionary strategies. The algorithm probably hasn’t wholly converged to its best fitness value but already got up to 0.94, so you can leave it running some extra generations to see if you can get better accuracy."
},
{
"code": null,
"e": 4534,
"s": 4430,
"text": "We can also have the log of all the hyperparameters that the model used and its cross-validation score."
},
{
"code": null,
"e": 4704,
"s": 4534,
"text": "For example, you can use those logs to plot the distribution of the parameters that the algorithm is selecting to see how its exploration and exploitation strategy were."
},
{
"code": null,
"e": 4751,
"s": 4704,
"text": "plot_search_space(evolved_estimator)plt.show()"
},
{
"code": null,
"e": 4814,
"s": 4751,
"text": "The k (keep_top_k=4) best set of hyperparameters combinations:"
},
{
"code": null,
"e": 5199,
"s": 4814,
"text": "So that is it! As you can see, it is pretty straightforward to make this optimization routine using evolutionary algorithms with sklearn-genetic-opt; this is an open-source project that can help you to choose your hyperparameters as an alternative to methods such as scikit-learn’s RandomizedSearchCV or GridSearch, which depends on pre-defined combinations of hyperparameters to try."
},
{
"code": null,
"e": 5344,
"s": 5199,
"text": "As the author of the package, any suggestion, contribution, or comment is very welcome. Here you can see more examples and the source code used:"
},
{
"code": null,
"e": 5379,
"s": 5344,
"text": "sklearn-genetic-opt.readthedocs.io"
},
{
"code": null,
"e": 5486,
"s": 5379,
"text": "Define the search space with the parameter ‘param_grid’; it takes a dictionary with some of these classes:"
},
{
"code": null,
"e": 5629,
"s": 5486,
"text": "Categorical: Represents categorical variables, expects a list of options it can sample, and optionally the probability of sampling each option"
},
{
"code": null,
"e": 5716,
"s": 5629,
"text": "Integer: Represents integer variables, expects a lower and upper bound of the variable"
},
{
"code": null,
"e": 5914,
"s": 5716,
"text": "Continuous: Represents real-valued variables, expects a lower and upper bound of the variable, optionally can sample the values from a log-uniform distribution if the variable is positively defined"
},
{
"code": null,
"e": 6002,
"s": 5914,
"text": "population: It’s the initial amount of hyperparameters candidates to generate randomly."
},
{
"code": null,
"e": 6105,
"s": 6002,
"text": "generations: How many iterations the algorithm will make, it creates a new population every generation"
},
{
"code": null,
"e": 6236,
"s": 6105,
"text": "elitism: If true, it uses a tournament selection keeping the best k individuals; if false, it uses a roulette selection mechanism."
},
{
"code": null,
"e": 6344,
"s": 6236,
"text": "tournament size: How many individuals to select utilizing a tournament operator, only used if elitism=True."
},
{
"code": null,
"e": 6431,
"s": 6344,
"text": "crossover_probability: The probability that a crossover occurs in a particular mating."
},
{
"code": null,
"e": 6566,
"s": 6431,
"text": "mutation_probability: The probability that an already fixed individual, suffers a random change in some of its hyperparameters values."
},
{
"code": null,
"e": 6730,
"s": 6566,
"text": "param_grid: dictionary with the keys as the names of the hyperparameters, and the values some of the Categorical, Continuous, or Integer from sklearn_genetic.space"
},
{
"code": null,
"e": 6788,
"s": 6730,
"text": "Defines the possible values that this parameter can take."
},
{
"code": null,
"e": 6900,
"s": 6788,
"text": "criteria: ‘max’ if the ‘scoring’ metric choose, it’s considered better as its value increases, ‘min’ otherwise."
},
{
"code": null,
"e": 7070,
"s": 6900,
"text": "algorithm: The specific evolutionary algorithm from the package deap to use, version 0.5.0 of sklearn-genetic-opt supports eaSimple, eaMuPlusLambda, and eaMuCommaLambda."
},
{
"code": null,
"e": 7144,
"s": 7070,
"text": "n_jobs: How many concurrent jobs to launch over the cross-validation step"
},
{
"code": null,
"e": 7235,
"s": 7144,
"text": "verbose: If True, it displays some metrics over the optimization while the algorithm runs."
},
{
"code": null,
"e": 7412,
"s": 7235,
"text": "keep_top_k: Based on its final cross-validation score, how many sets of hyperparameters to return at the end of the optimization. This parameter determines the size of the hof."
}
] |
Count of larger elements on right side of each element in an array - GeeksforGeeks | 17 Dec, 2021
Given an array arr[] consisting of N integers, the task is to count the number of greater elements on the right side of each array element.
Examples:
Input: arr[] = {3, 7, 1, 5, 9, 2}Output: {3, 1, 3, 1, 0, 0}Explanation:For arr[0], the elements greater than it on the right are {7, 5, 9}.For arr[1], the only element greater than it on the right is {9}.For arr[2], the elements greater than it on the right are {5, 9, 2}.For arr[3], the only element greater than it on the right is {9}.For arr[4] and arr[5], no greater elements exist on the right.
Input: arr[] = {5, 4, 3, 2}Output: {0, 0, 0, 0}
Naive Approach: The simplest approach is to iterate all array elements using two loops and for each array element, count the number of elements greater than it on its right side and then print it.Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: The problem can be solved using the concept of Merge Sort in descending order. Follow the steps given below to solve the problem:
Initialize an array count[] where count[i] store the respective count of greater elements on the right for every arr[i]
Take the indexes i and j, and compare the elements in an array.
If higher index element is greater than the lower index element then, all the higher index element will be greater than all the elements after that lower index.
Since the left part is already sorted, add the count of elements after the lower index element to the count[] array for the lower index.
Repeat the above steps until the entire array is sorted.
Finally print the values of count[] array.
Below is the implementation of the above approach:
Java
// Java program for the above approach import java.util.*; public class GFG { // Stores the index & value pairs static class Item { int val; int index; public Item(int val, int index) { this.val = val; this.index = index; } } // Function to count the number of // greater elements on the right // of every array element public static ArrayList<Integer> countLarge(int[] a) { // Length of the array int len = a.length; // Stores the index-value pairs Item[] items = new Item[len]; for (int i = 0; i < len; i++) { items[i] = new Item(a[i], i); } // Stores the count of greater // elements on right int[] count = new int[len]; // Perform MergeSort operation mergeSort(items, 0, len - 1, count); ArrayList<Integer> res = new ArrayList<>(); for (int i : count) { res.add(i); } return res; } // Function to sort the array // using Merge Sort public static void mergeSort( Item[] items, int low int high, int[] count) { // Base Case if (low >= high) { return; } // Find Mid int mid = low + (high - low) / 2; mergeSort(items, low, mid, count); mergeSort(items, mid + 1, high, count); // Merging step merge(items, low, mid, mid + 1, high, count); } // Utility function to merge sorted // subarrays and find the count of // greater elements on the right public static void merge( Item[] items, int low, int lowEnd, int high, int highEnd, int[] count) { int m = highEnd - low + 1; // mid Item[] sorted = new Item[m]; int rightCounter = 0; int lowInd = low, highInd = high; int index = 0; // Loop to store the count of // larger elements on right side // when both array have elements while (lowInd <= lowEnd && highInd <= highEnd) { if (items[lowInd].val < items[highInd].val) { rightCounter++; sorted[index++] = items[highInd++]; } else { count[items[lowInd].index] += rightCounter; sorted[index++] = items[lowInd++]; } } // Loop to store the count of // larger elements in right side // when only left array have // some element while (lowInd <= lowEnd) { count[items[lowInd].index] += rightCounter; sorted[index++] = items[lowInd++]; } // Loop to store the count of // larger elements in right side // when only right array have // some element while (highInd <= highEnd) { sorted[index++] = items[highInd++]; } System.arraycopy(sorted, 0, items, low, m); } // Utility function that prints // the count of greater elements // on the right public static void printArray(ArrayList<Integer> countList) { for (Integer i : countList) System.out.print(i + " "); System.out.println(); } // Driver Code public static void main(String[] args) { // Given array int arr[] = { 3, 7, 1, 5, 9, 2 }; int n = arr.length; // Function Call ArrayList<Integer> countList = countLarge(arr); printArray(countList); }}
3 1 3 1 0 0
Time Complexity: O(N*log N)Auxiliary Space: O(N)
singghakshay
array-merge
Merge Sort
Arrays
Divide and Conquer
Sorting
Arrays
Divide and Conquer
Sorting
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
QuickSort
Merge Sort
Binary Search
Program for Tower of Hanoi
Divide and Conquer Algorithm | Introduction | [
{
"code": null,
"e": 24429,
"s": 24401,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 24569,
"s": 24429,
"text": "Given an array arr[] consisting of N integers, the task is to count the number of greater elements on the right side of each array element."
},
{
"code": null,
"e": 24579,
"s": 24569,
"text": "Examples:"
},
{
"code": null,
"e": 24979,
"s": 24579,
"text": "Input: arr[] = {3, 7, 1, 5, 9, 2}Output: {3, 1, 3, 1, 0, 0}Explanation:For arr[0], the elements greater than it on the right are {7, 5, 9}.For arr[1], the only element greater than it on the right is {9}.For arr[2], the elements greater than it on the right are {5, 9, 2}.For arr[3], the only element greater than it on the right is {9}.For arr[4] and arr[5], no greater elements exist on the right."
},
{
"code": null,
"e": 25027,
"s": 24979,
"text": "Input: arr[] = {5, 4, 3, 2}Output: {0, 0, 0, 0}"
},
{
"code": null,
"e": 25267,
"s": 25027,
"text": "Naive Approach: The simplest approach is to iterate all array elements using two loops and for each array element, count the number of elements greater than it on its right side and then print it.Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 25417,
"s": 25267,
"text": "Efficient Approach: The problem can be solved using the concept of Merge Sort in descending order. Follow the steps given below to solve the problem:"
},
{
"code": null,
"e": 25537,
"s": 25417,
"text": "Initialize an array count[] where count[i] store the respective count of greater elements on the right for every arr[i]"
},
{
"code": null,
"e": 25601,
"s": 25537,
"text": "Take the indexes i and j, and compare the elements in an array."
},
{
"code": null,
"e": 25762,
"s": 25601,
"text": "If higher index element is greater than the lower index element then, all the higher index element will be greater than all the elements after that lower index."
},
{
"code": null,
"e": 25899,
"s": 25762,
"text": "Since the left part is already sorted, add the count of elements after the lower index element to the count[] array for the lower index."
},
{
"code": null,
"e": 25956,
"s": 25899,
"text": "Repeat the above steps until the entire array is sorted."
},
{
"code": null,
"e": 25999,
"s": 25956,
"text": "Finally print the values of count[] array."
},
{
"code": null,
"e": 26050,
"s": 25999,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26055,
"s": 26050,
"text": "Java"
},
{
"code": "// Java program for the above approach import java.util.*; public class GFG { // Stores the index & value pairs static class Item { int val; int index; public Item(int val, int index) { this.val = val; this.index = index; } } // Function to count the number of // greater elements on the right // of every array element public static ArrayList<Integer> countLarge(int[] a) { // Length of the array int len = a.length; // Stores the index-value pairs Item[] items = new Item[len]; for (int i = 0; i < len; i++) { items[i] = new Item(a[i], i); } // Stores the count of greater // elements on right int[] count = new int[len]; // Perform MergeSort operation mergeSort(items, 0, len - 1, count); ArrayList<Integer> res = new ArrayList<>(); for (int i : count) { res.add(i); } return res; } // Function to sort the array // using Merge Sort public static void mergeSort( Item[] items, int low int high, int[] count) { // Base Case if (low >= high) { return; } // Find Mid int mid = low + (high - low) / 2; mergeSort(items, low, mid, count); mergeSort(items, mid + 1, high, count); // Merging step merge(items, low, mid, mid + 1, high, count); } // Utility function to merge sorted // subarrays and find the count of // greater elements on the right public static void merge( Item[] items, int low, int lowEnd, int high, int highEnd, int[] count) { int m = highEnd - low + 1; // mid Item[] sorted = new Item[m]; int rightCounter = 0; int lowInd = low, highInd = high; int index = 0; // Loop to store the count of // larger elements on right side // when both array have elements while (lowInd <= lowEnd && highInd <= highEnd) { if (items[lowInd].val < items[highInd].val) { rightCounter++; sorted[index++] = items[highInd++]; } else { count[items[lowInd].index] += rightCounter; sorted[index++] = items[lowInd++]; } } // Loop to store the count of // larger elements in right side // when only left array have // some element while (lowInd <= lowEnd) { count[items[lowInd].index] += rightCounter; sorted[index++] = items[lowInd++]; } // Loop to store the count of // larger elements in right side // when only right array have // some element while (highInd <= highEnd) { sorted[index++] = items[highInd++]; } System.arraycopy(sorted, 0, items, low, m); } // Utility function that prints // the count of greater elements // on the right public static void printArray(ArrayList<Integer> countList) { for (Integer i : countList) System.out.print(i + \" \"); System.out.println(); } // Driver Code public static void main(String[] args) { // Given array int arr[] = { 3, 7, 1, 5, 9, 2 }; int n = arr.length; // Function Call ArrayList<Integer> countList = countLarge(arr); printArray(countList); }}",
"e": 29714,
"s": 26055,
"text": null
},
{
"code": null,
"e": 29727,
"s": 29714,
"text": "3 1 3 1 0 0\n"
},
{
"code": null,
"e": 29776,
"s": 29727,
"text": "Time Complexity: O(N*log N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 29789,
"s": 29776,
"text": "singghakshay"
},
{
"code": null,
"e": 29801,
"s": 29789,
"text": "array-merge"
},
{
"code": null,
"e": 29812,
"s": 29801,
"text": "Merge Sort"
},
{
"code": null,
"e": 29819,
"s": 29812,
"text": "Arrays"
},
{
"code": null,
"e": 29838,
"s": 29819,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 29846,
"s": 29838,
"text": "Sorting"
},
{
"code": null,
"e": 29853,
"s": 29846,
"text": "Arrays"
},
{
"code": null,
"e": 29872,
"s": 29853,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 29880,
"s": 29872,
"text": "Sorting"
},
{
"code": null,
"e": 29891,
"s": 29880,
"text": "Merge Sort"
},
{
"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": 29998,
"s": 29989,
"text": "Comments"
},
{
"code": null,
"e": 30011,
"s": 29998,
"text": "Old Comments"
},
{
"code": null,
"e": 30032,
"s": 30011,
"text": "Next Greater Element"
},
{
"code": null,
"e": 30057,
"s": 30032,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 30084,
"s": 30057,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 30133,
"s": 30084,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30171,
"s": 30133,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 30181,
"s": 30171,
"text": "QuickSort"
},
{
"code": null,
"e": 30192,
"s": 30181,
"text": "Merge Sort"
},
{
"code": null,
"e": 30206,
"s": 30192,
"text": "Binary Search"
},
{
"code": null,
"e": 30233,
"s": 30206,
"text": "Program for Tower of Hanoi"
}
] |
Bernoulli Distribution with Python from Scratch | by Deniz Ağırdan | Towards Data Science | To solve a problem, the common ready libraries are used but we don’t search the function how to work and how to serve our purpose. More importantly, if we need to modify a function, we don’t know how to do that.
So, the purpose of this article is how to code bernoulli probability distributions and their some properties in a simple way, without using ready libraries like “SciPy” and gain some basic skills from scratch.
The bernoulli distribution is a discrete distribution that is used when a random experiment is performed and only two results are obtained such as good-bad, positive-negative, success-failure. Those statements are used to describe the probabilities of an event. Bernoulli trial is the simple way to represent an experiment like the outcome of a coin heads or tails, the result of an exam pass or failure, etc.
If X is a random variable and p is a probability of an event with this distribution, then:
Python Code:
#bernoulli probability mass function:def pmf(x,p): f = p**x*(1-p)**(1-x) return f
The mean or expected value E(x) of Bernoulli random variable X is:
Python Code:
# expected value of xdef mean(p): return p
The variance of random variable X is:
Python Code:
#variance of xdef var(p): return p*(1-p)#standard deviation is root of variancedef std(p): return var(p)**(1/2)
To generate random variates corresponding to Bernoulli distribution
Python Code
import numpy as np#size is a parameter that how many number generatesdef rvs(p,size=1): rvs = np.array([]) for i in range(0,size): if np.random.rand() <= p: a=1 rvs = np.append(rvs,a) else: a=0 rvs = np.append(rvs,a) return rvs
Let put them together
import numpy as np#created a bernoulli class class bernoulli(): def pmf(x,p): """ probability mass function """ f = p**x*(1-p)**(1-x) return f def mean(p): """ expected value of bernoulli random variable """ return p def var(p): """ variance of bernoulli random variable """ return p*(1-p) def std(p): """ standart deviation of bernoulli random variable """ return bernoulli.var(p)**(1/2) def rvs(p,size=1): """ random variates """ rvs = np.array([]) for i in range(0,size): if np.random.rand() <= p: a=1 rvs = np.append(rvs,a) else: a=0 rvs = np.append(rvs,a) return rvs
Suppose that a formula-1 racer has a 0.2 probability of having an accident. So that X = 1 if an accident occurs, and X = 0 otherwise. Find the expectation, variance and standart deviation of X and generate random variate 10 times.
p=0.2 # probability of having an accidentbernoulli.mean(p) # return -> 0.2bernoulli.var(p) # return -> 0.16bernoulli.std(p) # return -> 0.4#each execution generates random numbers, so array may be changebernoulli.rvs(p,size=10) #return-> array([0., 0., 0., 0., 1., 0., 1., 0., 0., 1.])
I hope this article is useful and gives you a different perspective.
Bernoulli Distribution https://www.wikiwand.com/en/Bernoulli_distribution
Probability Distribution https://www.wikiwand.com/en/Probability_distribution | [
{
"code": null,
"e": 384,
"s": 172,
"text": "To solve a problem, the common ready libraries are used but we don’t search the function how to work and how to serve our purpose. More importantly, if we need to modify a function, we don’t know how to do that."
},
{
"code": null,
"e": 594,
"s": 384,
"text": "So, the purpose of this article is how to code bernoulli probability distributions and their some properties in a simple way, without using ready libraries like “SciPy” and gain some basic skills from scratch."
},
{
"code": null,
"e": 1004,
"s": 594,
"text": "The bernoulli distribution is a discrete distribution that is used when a random experiment is performed and only two results are obtained such as good-bad, positive-negative, success-failure. Those statements are used to describe the probabilities of an event. Bernoulli trial is the simple way to represent an experiment like the outcome of a coin heads or tails, the result of an exam pass or failure, etc."
},
{
"code": null,
"e": 1095,
"s": 1004,
"text": "If X is a random variable and p is a probability of an event with this distribution, then:"
},
{
"code": null,
"e": 1108,
"s": 1095,
"text": "Python Code:"
},
{
"code": null,
"e": 1196,
"s": 1108,
"text": "#bernoulli probability mass function:def pmf(x,p): f = p**x*(1-p)**(1-x) return f"
},
{
"code": null,
"e": 1263,
"s": 1196,
"text": "The mean or expected value E(x) of Bernoulli random variable X is:"
},
{
"code": null,
"e": 1276,
"s": 1263,
"text": "Python Code:"
},
{
"code": null,
"e": 1322,
"s": 1276,
"text": "# expected value of xdef mean(p): return p"
},
{
"code": null,
"e": 1360,
"s": 1322,
"text": "The variance of random variable X is:"
},
{
"code": null,
"e": 1373,
"s": 1360,
"text": "Python Code:"
},
{
"code": null,
"e": 1491,
"s": 1373,
"text": "#variance of xdef var(p): return p*(1-p)#standard deviation is root of variancedef std(p): return var(p)**(1/2)"
},
{
"code": null,
"e": 1559,
"s": 1491,
"text": "To generate random variates corresponding to Bernoulli distribution"
},
{
"code": null,
"e": 1571,
"s": 1559,
"text": "Python Code"
},
{
"code": null,
"e": 1866,
"s": 1571,
"text": "import numpy as np#size is a parameter that how many number generatesdef rvs(p,size=1): rvs = np.array([]) for i in range(0,size): if np.random.rand() <= p: a=1 rvs = np.append(rvs,a) else: a=0 rvs = np.append(rvs,a) return rvs"
},
{
"code": null,
"e": 1888,
"s": 1866,
"text": "Let put them together"
},
{
"code": null,
"e": 2742,
"s": 1888,
"text": "import numpy as np#created a bernoulli class class bernoulli(): def pmf(x,p): \"\"\" probability mass function \"\"\" f = p**x*(1-p)**(1-x) return f def mean(p): \"\"\" expected value of bernoulli random variable \"\"\" return p def var(p): \"\"\" variance of bernoulli random variable \"\"\" return p*(1-p) def std(p): \"\"\" standart deviation of bernoulli random variable \"\"\" return bernoulli.var(p)**(1/2) def rvs(p,size=1): \"\"\" random variates \"\"\" rvs = np.array([]) for i in range(0,size): if np.random.rand() <= p: a=1 rvs = np.append(rvs,a) else: a=0 rvs = np.append(rvs,a) return rvs"
},
{
"code": null,
"e": 2973,
"s": 2742,
"text": "Suppose that a formula-1 racer has a 0.2 probability of having an accident. So that X = 1 if an accident occurs, and X = 0 otherwise. Find the expectation, variance and standart deviation of X and generate random variate 10 times."
},
{
"code": null,
"e": 3259,
"s": 2973,
"text": "p=0.2 # probability of having an accidentbernoulli.mean(p) # return -> 0.2bernoulli.var(p) # return -> 0.16bernoulli.std(p) # return -> 0.4#each execution generates random numbers, so array may be changebernoulli.rvs(p,size=10) #return-> array([0., 0., 0., 0., 1., 0., 1., 0., 0., 1.])"
},
{
"code": null,
"e": 3328,
"s": 3259,
"text": "I hope this article is useful and gives you a different perspective."
},
{
"code": null,
"e": 3402,
"s": 3328,
"text": "Bernoulli Distribution https://www.wikiwand.com/en/Bernoulli_distribution"
}
] |
Multi-class Classification: Extracting Performance Metrics From The Confusion Matrix | by Serafeim Loukas | Towards Data Science | In one of my previous posts, “ROC Curve explained using a COVID-19 hypothetical example: Binary & Multi-Class Classification tutorial”, I clearly explained what a ROC curve is and how it is connected to the famous Confusion Matrix. If you are not familiar with the term Confusion Matrix and True Positives, True Negatives etc., refer to the above article and learn everything in 6 minutes or continue reading for a quick 2 minutes recap.
Let’s imagine that we have a test that is able within seconds to tell us if one individual is affected by the virus or not. So the output of the test can be either Positive (affected) or Negative (not affected). So, in this hypothetical case we have a binary classification case.
True Positives (TP, blue distribution) are the people that truly have the virus.
True Negatives (TN, red distribution) are the people that truly DO NOT have the virus.
False Positives (FP) are the people that are truly NOT sick but based on the test, they were falsely (False) denoted as sick (Positives).
False Negatives (FN) are the people that are truly sick but based on the test, they were falsely (False) denoted as NOT sick (Negative).
To store all these measures of performance, the confusion matrix is usually used.
The confusion matrix of a classifier summarizes the TP, TN, FP, FN measures of performance of our model. The confusion matrix can be further used to extract more measures of performance such as: TPR, TNR, FPR, FNR and accuracy.
Using all the above terms, we can also construct the famous confusion matrix that consists of these metrics and then we can compute the True Positive Rate and the False Positive Rate as shown in the figure below for a binary classification case.
The confusion matrix can be well defined for any N-class classification problem. However, if we have more than 2 classes (N>2), then the above equations (in the confusion matrix figure) do not hold any more.
In this article, I show how to estimate all these measures for any number of classes (N).
In a previous post, I explained what an SVC model is so here we will use this as our classifier.
In the iris dataset, we have 3 classes of flowers and 4 features. So the classification problem is not a binary case anymore since we have 3 classes.
Let’s load the data and check how many classes and samples per class we have:
import numpy as npimport matplotlib.pyplot as pltfrom sklearn import svm, datasetsfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import plot_confusion_matrixfrom sklearn.metrics import confusion_matrix# import some data to play withiris = datasets.load_iris()X = iris.datay = iris.targetclass_names = iris.target_nameslabels, counts = np.unique(y, return_counts=True)plt.bar(labels, counts, align='center')plt.gca().set_xticks(labels)plt.show()
We can see that we have 3 classes/groups (labels: 0,1,2) and within each class/group we have 50 (i.e. the height of the bars) samples (examples/observations).
Next, we will split the data into training and test sets before model fitting:
# Split the data into a training set and a test setX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
Next, let’s create the classification model (linear SVC) and fit the model using the training set:
# Fit the classifierclassifier = svm.SVC(kernel='linear').fit(X_train, y_train)
Now, we will predict the labels of the test set samples and we will build the confusion matrix of our 3-class classification problem:
# Predict the labels of the test set samplespredicted_labels = classifier.predict(X_test)# Build the confusion matrix of our 3-class classification problemcnf_matrix = confusion_matrix(y_test, predicted_labels)print(cnf_matrix)#array([[13, 0, 0],# [ 0, 15, 1],# [ 0, 0, 9]])
To better read/understand the confusion matrix, let’s plot it:
disp = plot_confusion_matrix(classifier, X_test, y_test, display_labels=class_names, cmap=plt.cm.Blues)plt.show()
On the x-axis we have the predicted labels and on the y-axis we have the true labels of out test set’s samples (remember that the prediction was done using only the test set).
Ideally, a perfect classifier would result in a confusion matrix where we have values only on the diagonal i.e. in a case where we classify correctly all the test samples for all the 3 classes/groups that we have.
The values in the boxes are just counts. For instance, in our case, the upper left box has a value 13 inside and the next 2 boxes have 0 and 0. This means that we are able to correctly classify all 13 setosa test samples.
On the other hand, by looking at the second row that refers to the versicolor group, we can see that we classified correctly 15 versiolor test samples (out of the total of 16 that are in the test set) and missed 1 versicolor test samples that was wrongly predicted as “virginica”
Finally, here is the magic.
We will estimate the FP, FN, TP, TN, TPR (Sensitivity, hit rate, recall, or true positive rate), TNR (Specificity or True Negative Rate), PPV (Precision or Positive Predictive Value), NPV (Negative Predictive Value), FPR (Fall out or False Positive Rate), FNR (False Negative Rate), FDR (False Discovery Rate), and ACC (accurancy).
FP = cnf_matrix.sum(axis=0) - np.diag(cnf_matrix) FN = cnf_matrix.sum(axis=1) - np.diag(cnf_matrix)TP = np.diag(cnf_matrix)TN = cnf_matrix.sum() - (FP + FN + TP)FP = FP.astype(float)FN = FN.astype(float)TP = TP.astype(float)TN = TN.astype(float)# Sensitivity, hit rate, recall, or true positive rateTPR = TP/(TP+FN)# Specificity or true negative rateTNR = TN/(TN+FP) # Precision or positive predictive valuePPV = TP/(TP+FP)# Negative predictive valueNPV = TN/(TN+FN)# Fall out or false positive rateFPR = FP/(FP+TN)# False negative rateFNR = FN/(TP+FN)# False discovery rateFDR = FP/(TP+FP)# Overall accuracy for each classACC = (TP+TN)/(TP+FP+FN+TN)
That’s all folks ! Hope you liked this article!
[1] https://en.wikipedia.org/wiki/Confusion_matrix
[2] https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html
If you liked and found this article useful, follow me to be able to see all my new posts.
Questions? Post them as a comment and I will reply as soon as possible.
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
LinkedIn: https://www.linkedin.com/in/serafeim-loukas/
ResearchGate: https://www.researchgate.net/profile/Serafeim_Loukas
EPFL profile: https://people.epfl.ch/serafeim.loukas
Stack Overflow: https://stackoverflow.com/users/5025009/seralouk | [
{
"code": null,
"e": 610,
"s": 172,
"text": "In one of my previous posts, “ROC Curve explained using a COVID-19 hypothetical example: Binary & Multi-Class Classification tutorial”, I clearly explained what a ROC curve is and how it is connected to the famous Confusion Matrix. If you are not familiar with the term Confusion Matrix and True Positives, True Negatives etc., refer to the above article and learn everything in 6 minutes or continue reading for a quick 2 minutes recap."
},
{
"code": null,
"e": 890,
"s": 610,
"text": "Let’s imagine that we have a test that is able within seconds to tell us if one individual is affected by the virus or not. So the output of the test can be either Positive (affected) or Negative (not affected). So, in this hypothetical case we have a binary classification case."
},
{
"code": null,
"e": 971,
"s": 890,
"text": "True Positives (TP, blue distribution) are the people that truly have the virus."
},
{
"code": null,
"e": 1058,
"s": 971,
"text": "True Negatives (TN, red distribution) are the people that truly DO NOT have the virus."
},
{
"code": null,
"e": 1196,
"s": 1058,
"text": "False Positives (FP) are the people that are truly NOT sick but based on the test, they were falsely (False) denoted as sick (Positives)."
},
{
"code": null,
"e": 1333,
"s": 1196,
"text": "False Negatives (FN) are the people that are truly sick but based on the test, they were falsely (False) denoted as NOT sick (Negative)."
},
{
"code": null,
"e": 1415,
"s": 1333,
"text": "To store all these measures of performance, the confusion matrix is usually used."
},
{
"code": null,
"e": 1643,
"s": 1415,
"text": "The confusion matrix of a classifier summarizes the TP, TN, FP, FN measures of performance of our model. The confusion matrix can be further used to extract more measures of performance such as: TPR, TNR, FPR, FNR and accuracy."
},
{
"code": null,
"e": 1889,
"s": 1643,
"text": "Using all the above terms, we can also construct the famous confusion matrix that consists of these metrics and then we can compute the True Positive Rate and the False Positive Rate as shown in the figure below for a binary classification case."
},
{
"code": null,
"e": 2097,
"s": 1889,
"text": "The confusion matrix can be well defined for any N-class classification problem. However, if we have more than 2 classes (N>2), then the above equations (in the confusion matrix figure) do not hold any more."
},
{
"code": null,
"e": 2187,
"s": 2097,
"text": "In this article, I show how to estimate all these measures for any number of classes (N)."
},
{
"code": null,
"e": 2284,
"s": 2187,
"text": "In a previous post, I explained what an SVC model is so here we will use this as our classifier."
},
{
"code": null,
"e": 2434,
"s": 2284,
"text": "In the iris dataset, we have 3 classes of flowers and 4 features. So the classification problem is not a binary case anymore since we have 3 classes."
},
{
"code": null,
"e": 2512,
"s": 2434,
"text": "Let’s load the data and check how many classes and samples per class we have:"
},
{
"code": null,
"e": 2983,
"s": 2512,
"text": "import numpy as npimport matplotlib.pyplot as pltfrom sklearn import svm, datasetsfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import plot_confusion_matrixfrom sklearn.metrics import confusion_matrix# import some data to play withiris = datasets.load_iris()X = iris.datay = iris.targetclass_names = iris.target_nameslabels, counts = np.unique(y, return_counts=True)plt.bar(labels, counts, align='center')plt.gca().set_xticks(labels)plt.show()"
},
{
"code": null,
"e": 3142,
"s": 2983,
"text": "We can see that we have 3 classes/groups (labels: 0,1,2) and within each class/group we have 50 (i.e. the height of the bars) samples (examples/observations)."
},
{
"code": null,
"e": 3221,
"s": 3142,
"text": "Next, we will split the data into training and test sets before model fitting:"
},
{
"code": null,
"e": 3346,
"s": 3221,
"text": "# Split the data into a training set and a test setX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)"
},
{
"code": null,
"e": 3445,
"s": 3346,
"text": "Next, let’s create the classification model (linear SVC) and fit the model using the training set:"
},
{
"code": null,
"e": 3525,
"s": 3445,
"text": "# Fit the classifierclassifier = svm.SVC(kernel='linear').fit(X_train, y_train)"
},
{
"code": null,
"e": 3659,
"s": 3525,
"text": "Now, we will predict the labels of the test set samples and we will build the confusion matrix of our 3-class classification problem:"
},
{
"code": null,
"e": 3951,
"s": 3659,
"text": "# Predict the labels of the test set samplespredicted_labels = classifier.predict(X_test)# Build the confusion matrix of our 3-class classification problemcnf_matrix = confusion_matrix(y_test, predicted_labels)print(cnf_matrix)#array([[13, 0, 0],# [ 0, 15, 1],# [ 0, 0, 9]])"
},
{
"code": null,
"e": 4014,
"s": 3951,
"text": "To better read/understand the confusion matrix, let’s plot it:"
},
{
"code": null,
"e": 4192,
"s": 4014,
"text": "disp = plot_confusion_matrix(classifier, X_test, y_test, display_labels=class_names, cmap=plt.cm.Blues)plt.show()"
},
{
"code": null,
"e": 4368,
"s": 4192,
"text": "On the x-axis we have the predicted labels and on the y-axis we have the true labels of out test set’s samples (remember that the prediction was done using only the test set)."
},
{
"code": null,
"e": 4582,
"s": 4368,
"text": "Ideally, a perfect classifier would result in a confusion matrix where we have values only on the diagonal i.e. in a case where we classify correctly all the test samples for all the 3 classes/groups that we have."
},
{
"code": null,
"e": 4804,
"s": 4582,
"text": "The values in the boxes are just counts. For instance, in our case, the upper left box has a value 13 inside and the next 2 boxes have 0 and 0. This means that we are able to correctly classify all 13 setosa test samples."
},
{
"code": null,
"e": 5084,
"s": 4804,
"text": "On the other hand, by looking at the second row that refers to the versicolor group, we can see that we classified correctly 15 versiolor test samples (out of the total of 16 that are in the test set) and missed 1 versicolor test samples that was wrongly predicted as “virginica”"
},
{
"code": null,
"e": 5112,
"s": 5084,
"text": "Finally, here is the magic."
},
{
"code": null,
"e": 5444,
"s": 5112,
"text": "We will estimate the FP, FN, TP, TN, TPR (Sensitivity, hit rate, recall, or true positive rate), TNR (Specificity or True Negative Rate), PPV (Precision or Positive Predictive Value), NPV (Negative Predictive Value), FPR (Fall out or False Positive Rate), FNR (False Negative Rate), FDR (False Discovery Rate), and ACC (accurancy)."
},
{
"code": null,
"e": 6095,
"s": 5444,
"text": "FP = cnf_matrix.sum(axis=0) - np.diag(cnf_matrix) FN = cnf_matrix.sum(axis=1) - np.diag(cnf_matrix)TP = np.diag(cnf_matrix)TN = cnf_matrix.sum() - (FP + FN + TP)FP = FP.astype(float)FN = FN.astype(float)TP = TP.astype(float)TN = TN.astype(float)# Sensitivity, hit rate, recall, or true positive rateTPR = TP/(TP+FN)# Specificity or true negative rateTNR = TN/(TN+FP) # Precision or positive predictive valuePPV = TP/(TP+FP)# Negative predictive valueNPV = TN/(TN+FN)# Fall out or false positive rateFPR = FP/(FP+TN)# False negative rateFNR = FN/(TP+FN)# False discovery rateFDR = FP/(TP+FP)# Overall accuracy for each classACC = (TP+TN)/(TP+FP+FN+TN)"
},
{
"code": null,
"e": 6143,
"s": 6095,
"text": "That’s all folks ! Hope you liked this article!"
},
{
"code": null,
"e": 6194,
"s": 6143,
"text": "[1] https://en.wikipedia.org/wiki/Confusion_matrix"
},
{
"code": null,
"e": 6286,
"s": 6194,
"text": "[2] https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html"
},
{
"code": null,
"e": 6376,
"s": 6286,
"text": "If you liked and found this article useful, follow me to be able to see all my new posts."
},
{
"code": null,
"e": 6448,
"s": 6376,
"text": "Questions? Post them as a comment and I will reply as soon as possible."
},
{
"code": null,
"e": 6471,
"s": 6448,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6494,
"s": 6471,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6517,
"s": 6494,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6540,
"s": 6517,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6563,
"s": 6540,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6586,
"s": 6563,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6641,
"s": 6586,
"text": "LinkedIn: https://www.linkedin.com/in/serafeim-loukas/"
},
{
"code": null,
"e": 6708,
"s": 6641,
"text": "ResearchGate: https://www.researchgate.net/profile/Serafeim_Loukas"
},
{
"code": null,
"e": 6761,
"s": 6708,
"text": "EPFL profile: https://people.epfl.ch/serafeim.loukas"
}
] |
How can we use MySQL SELECT without FROM clause? | FROM clause after SELECT shows the references to a table. But if there is no reference to any table then we can use SELECT without the FROM clause. In other words, we can say that SELECT can be used to retrieve rows computed without reference to any table. Consider the following statements −
mysql> Select concat_ws(" ","Hello", "World");
+---------------------------------+
| concat_ws(" ","Hello", "World") |
+---------------------------------+
| Hello World |
+---------------------------------+
1 row in set (0.00 sec)
mysql> Set @var1=100;
Query OK, 0 rows affected (0.00 sec)
mysql> Select @var1;
+-------+
| @var1 |
+-------+
| 100 |
+-------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1355,
"s": 1062,
"text": "FROM clause after SELECT shows the references to a table. But if there is no reference to any table then we can use SELECT without the FROM clause. In other words, we can say that SELECT can be used to retrieve rows computed without reference to any table. Consider the following statements −"
},
{
"code": null,
"e": 1762,
"s": 1355,
"text": "mysql> Select concat_ws(\" \",\"Hello\", \"World\");\n+---------------------------------+\n| concat_ws(\" \",\"Hello\", \"World\") |\n+---------------------------------+\n| Hello World |\n+---------------------------------+\n1 row in set (0.00 sec)\n\nmysql> Set @var1=100;\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Select @var1;\n+-------+\n| @var1 |\n+-------+\n| 100 |\n+-------+\n1 row in set (0.00 sec)"
}
] |
Relative Positioning with CSS | Relative positioning changes the position of the HTML element relative to where it normally appears. So "left:20" adds 20 pixels to the element's LEFT position.
You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document.
Move Left - Use a negative value for left.
Move Right - Use a positive value for left.
Move Up - Use a negative value for top.
Move Down - Use a positive value for top.
You can try to run the following code to implement relative positioning −
<html>
<head>
</head>
<body>
<div style = "position:relative;left:80px;top:2px;background-color:yellow;">
This div has relative positioning.
</div>
</body>
</html> | [
{
"code": null,
"e": 1223,
"s": 1062,
"text": "Relative positioning changes the position of the HTML element relative to where it normally appears. So \"left:20\" adds 20 pixels to the element's LEFT position."
},
{
"code": null,
"e": 1347,
"s": 1223,
"text": "You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document."
},
{
"code": null,
"e": 1391,
"s": 1347,
"text": " Move Left - Use a negative value for left."
},
{
"code": null,
"e": 1436,
"s": 1391,
"text": " Move Right - Use a positive value for left."
},
{
"code": null,
"e": 1477,
"s": 1436,
"text": " Move Up - Use a negative value for top."
},
{
"code": null,
"e": 1520,
"s": 1477,
"text": " Move Down - Use a positive value for top."
},
{
"code": null,
"e": 1594,
"s": 1520,
"text": "You can try to run the following code to implement relative positioning −"
},
{
"code": null,
"e": 1806,
"s": 1594,
"text": "<html>\n <head>\n </head>\n <body>\n <div style = \"position:relative;left:80px;top:2px;background-color:yellow;\">\n This div has relative positioning.\n </div>\n </body>\n</html>"
}
] |
Summarising Data With SQL. In our previous look at SQL to analyse... | by Robert de Graaf | Towards Data Science | SQL can be used for more than simply transferring data from a database to your modelling environment. Learn more about how to analyse your data in situ to decide what is most useful
In our previous look at SQL to analyse data from a true data science perspective, we explored a little of how we can use SQL to understand the quality of a data set with respect to missingness, with a view to understanding which tables and fields are worthwhile to move to an enivornment preferred for modelling. In this installment we look at a classic tool for understanding the basic nature of distinct variables, and how it can be obtained in SQL.
John Tukey re-invigorated the practice of exploratory data analysis, and massively promoted the phrase itself with his book of the same name. One of the simplest yet most useful tools proposed by Tukey is the five number summary. In tribute to its usefulness, R has a single command to obtain this summary from any data set — fivenum() — which is in base R.
This consists very simply of the minimum, maximum, median, first quartile and third quartile of a variable. Given the maximum and minimum have always been standard aggregates, and there is no need to use tricky statistical distributions or matrix algebra to prepare any of the values, it might be supposed that this summary should be easily available from any SQL implementation.
However, as recently as the early 2000s, it was actually quite a rigmarole. Thankfully, while many things, such as popular music, have clearly deteriorated since then (I reached the age that entitled me to drive during the Clinton administration, which strongly correlates to the period when popular music sounded best to me), both standard SQL and the biggest implentations have introduced useful new features since then.
Window functions, added to ANSI SQL in the 2003 release provide a range of useful options. Of these, the PERCENTILE_CONT and PERCENTILE_DISC make it far simpler than previously to get the full set of the five number summary.
The basic syntax for these fuctions is:
PERCENTILE_DISC(int) WITHIN GROUP (ORDER BY numeric)OVER (PARTITION BY variable)
These functions are typically intended for someone to use when the intent is to divide the data set into subsets defined by a categorical variable within the dataset. Somewhat implicit in the idea of a five number summary is that at least in the first pass, we will want to use run it for the whole data set. To do this, we simply leave the OVER clause empty — e.g. ‘OVER (PARTITION BY variable)’ becomes ‘OVER ()’.
Hence, a complete query to get the 1st quartile, median and 3rd quartile on any single numeric variable looks like this:
SELECT DISTINCT PERCENTILE_DISC(25) WITHIN GROUP (ORDER BY numeric) OVER () as Q1_Var, PERCENTILE_DISC(50) WITHIN GROUP (ORDER BY numeric) OVER () as median_var, PERCENTILE_DISC(75) WITHIN GROUP (ORDER BY numeric) OVER () as Q3_varFROM db.tbl
This query obviously returns three values — the maximum and minimum, the more basic of the five number summary to obtain are missing. However, as the PERCENTILE values are not aggregate functions, SQL will throw a syntax error if we simply add min(var) and/or max(var) to our Select statement.
Instead, we need to create a second table using a common table expression that can contain the aggregate values as scalars, and join the two together. Given we are joining to single rows together, we can do a full Cartesian join and expect only a single row in return.
WITH extreme_table (var_min,var_max)AS (SELECT min(var) , max(var) FROM table)SELECT DISTINCT var_min, PERCENTILE_DISC(25) WITHIN GROUP (ORDER BY numeric) OVER () as Q1_Var, PERCENTILE_DISC(50) WITHIN GROUP (ORDER BY numeric) OVER () as median_var, PERCENTILE_DISC(75) WITHIN GROUP (ORDER BY numeric) OVER () as Q3_var, var_maxFROM db.table JOIN extreme_table on 1=1
This query returns a single row of five values representing the five number summary. However, we mentioned above that the SQL PERCENTILE functions are more frequently used with a partition variable to be applied to datasets subsetted with a particular categorical variable and the same can be said for the more run of the mill aggregate functions min() and max() which are usually found in conjunction with a Group By variable.
Intuitively, many analysts will want to apply the five number summary to different subsets of the data also. Extending the above query, this is achieved in a straight forward manner by adding the categorical variable both as a Group By clause and within the select clause to the extreme_table, and by adding in the PARTITION clause, before joining on the category. The result will be as follows.
WITH extreme_table (var_min,var_max,category)AS(SELECT min(var) , max(var) , category FROM table GROUP BY category)SELECT DISTINCT var_min, PERCENTILE_DISC(25) WITHIN GROUP (ORDER BY numeric) OVER (PARTITION BY category) as Q1_Var, PERCENTILE_DISC(50) WITHIN GROUP (ORDER BY numeric) OVER (PARTITION BY category) as median_var, PERCENTILE_DISC(75) WITHIN GROUP (ORDER BY numeric) OVER (PARTITION BY category) as Q3_var, var_max, table.categoryFROM db.table JOIN extreme_table on extreme_table.category=table.category
The usual analysis obtained from the five number summary is a sense of the skew — by seeing where the median is positioned within the 1st and 3rd quartile, and how the mininum and maximum relate to those quartiles also. Obviously, getting the same data on categorical subsets of the data is powerful in that it allows you to compare not just the location of the data in terms of the median, but also the shapes of each category’s distribution to get an understanding of how each category concentrates its underlying data.
Robert de Graaf is the author of the book in progress ‘The Lazy Data Scientist’, available via LeanPub Follow him on Twitter: https://twitter.com/RobertdeGraaf2 | [
{
"code": null,
"e": 354,
"s": 172,
"text": "SQL can be used for more than simply transferring data from a database to your modelling environment. Learn more about how to analyse your data in situ to decide what is most useful"
},
{
"code": null,
"e": 806,
"s": 354,
"text": "In our previous look at SQL to analyse data from a true data science perspective, we explored a little of how we can use SQL to understand the quality of a data set with respect to missingness, with a view to understanding which tables and fields are worthwhile to move to an enivornment preferred for modelling. In this installment we look at a classic tool for understanding the basic nature of distinct variables, and how it can be obtained in SQL."
},
{
"code": null,
"e": 1164,
"s": 806,
"text": "John Tukey re-invigorated the practice of exploratory data analysis, and massively promoted the phrase itself with his book of the same name. One of the simplest yet most useful tools proposed by Tukey is the five number summary. In tribute to its usefulness, R has a single command to obtain this summary from any data set — fivenum() — which is in base R."
},
{
"code": null,
"e": 1544,
"s": 1164,
"text": "This consists very simply of the minimum, maximum, median, first quartile and third quartile of a variable. Given the maximum and minimum have always been standard aggregates, and there is no need to use tricky statistical distributions or matrix algebra to prepare any of the values, it might be supposed that this summary should be easily available from any SQL implementation."
},
{
"code": null,
"e": 1967,
"s": 1544,
"text": "However, as recently as the early 2000s, it was actually quite a rigmarole. Thankfully, while many things, such as popular music, have clearly deteriorated since then (I reached the age that entitled me to drive during the Clinton administration, which strongly correlates to the period when popular music sounded best to me), both standard SQL and the biggest implentations have introduced useful new features since then."
},
{
"code": null,
"e": 2192,
"s": 1967,
"text": "Window functions, added to ANSI SQL in the 2003 release provide a range of useful options. Of these, the PERCENTILE_CONT and PERCENTILE_DISC make it far simpler than previously to get the full set of the five number summary."
},
{
"code": null,
"e": 2232,
"s": 2192,
"text": "The basic syntax for these fuctions is:"
},
{
"code": null,
"e": 2313,
"s": 2232,
"text": "PERCENTILE_DISC(int) WITHIN GROUP (ORDER BY numeric)OVER (PARTITION BY variable)"
},
{
"code": null,
"e": 2729,
"s": 2313,
"text": "These functions are typically intended for someone to use when the intent is to divide the data set into subsets defined by a categorical variable within the dataset. Somewhat implicit in the idea of a five number summary is that at least in the first pass, we will want to use run it for the whole data set. To do this, we simply leave the OVER clause empty — e.g. ‘OVER (PARTITION BY variable)’ becomes ‘OVER ()’."
},
{
"code": null,
"e": 2850,
"s": 2729,
"text": "Hence, a complete query to get the 1st quartile, median and 3rd quartile on any single numeric variable looks like this:"
},
{
"code": null,
"e": 3097,
"s": 2850,
"text": "SELECT DISTINCT PERCENTILE_DISC(25) WITHIN GROUP (ORDER BY numeric) OVER () as Q1_Var, PERCENTILE_DISC(50) WITHIN GROUP (ORDER BY numeric) OVER () as median_var, PERCENTILE_DISC(75) WITHIN GROUP (ORDER BY numeric) OVER () as Q3_varFROM db.tbl"
},
{
"code": null,
"e": 3391,
"s": 3097,
"text": "This query obviously returns three values — the maximum and minimum, the more basic of the five number summary to obtain are missing. However, as the PERCENTILE values are not aggregate functions, SQL will throw a syntax error if we simply add min(var) and/or max(var) to our Select statement."
},
{
"code": null,
"e": 3660,
"s": 3391,
"text": "Instead, we need to create a second table using a common table expression that can contain the aggregate values as scalars, and join the two together. Given we are joining to single rows together, we can do a full Cartesian join and expect only a single row in return."
},
{
"code": null,
"e": 4036,
"s": 3660,
"text": "WITH extreme_table (var_min,var_max)AS (SELECT min(var) , max(var) FROM table)SELECT DISTINCT var_min, PERCENTILE_DISC(25) WITHIN GROUP (ORDER BY numeric) OVER () as Q1_Var, PERCENTILE_DISC(50) WITHIN GROUP (ORDER BY numeric) OVER () as median_var, PERCENTILE_DISC(75) WITHIN GROUP (ORDER BY numeric) OVER () as Q3_var, var_maxFROM db.table JOIN extreme_table on 1=1"
},
{
"code": null,
"e": 4464,
"s": 4036,
"text": "This query returns a single row of five values representing the five number summary. However, we mentioned above that the SQL PERCENTILE functions are more frequently used with a partition variable to be applied to datasets subsetted with a particular categorical variable and the same can be said for the more run of the mill aggregate functions min() and max() which are usually found in conjunction with a Group By variable."
},
{
"code": null,
"e": 4860,
"s": 4464,
"text": "Intuitively, many analysts will want to apply the five number summary to different subsets of the data also. Extending the above query, this is achieved in a straight forward manner by adding the categorical variable both as a Group By clause and within the select clause to the extreme_table, and by adding in the PARTITION clause, before joining on the category. The result will be as follows."
},
{
"code": null,
"e": 5388,
"s": 4860,
"text": "WITH extreme_table (var_min,var_max,category)AS(SELECT min(var) , max(var) , category FROM table GROUP BY category)SELECT DISTINCT var_min, PERCENTILE_DISC(25) WITHIN GROUP (ORDER BY numeric) OVER (PARTITION BY category) as Q1_Var, PERCENTILE_DISC(50) WITHIN GROUP (ORDER BY numeric) OVER (PARTITION BY category) as median_var, PERCENTILE_DISC(75) WITHIN GROUP (ORDER BY numeric) OVER (PARTITION BY category) as Q3_var, var_max, table.categoryFROM db.table JOIN extreme_table on extreme_table.category=table.category"
},
{
"code": null,
"e": 5910,
"s": 5388,
"text": "The usual analysis obtained from the five number summary is a sense of the skew — by seeing where the median is positioned within the 1st and 3rd quartile, and how the mininum and maximum relate to those quartiles also. Obviously, getting the same data on categorical subsets of the data is powerful in that it allows you to compare not just the location of the data in terms of the median, but also the shapes of each category’s distribution to get an understanding of how each category concentrates its underlying data."
}
] |
Extract maximum numeric value from a given string | Set 1 (General approach) - GeeksforGeeks | 14 May, 2021
Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case. One approach to solving the problem is discussed here, other using Regular expressions is given in Set 2 Examples:
Input : 100klh564abc365bg
Output : 564
Maximum numeric value among 100, 564
and 365 is 564.
Input : abchsd0sdhs
Output : 0
Its solution is simple i.e. Start traversing the string and perform two operations:
If a numeric value is present at the current index then convert it into an integer num = num*10 + (str[i]-'0') Otherwise, update the maximum value and reset num = 0.
If a numeric value is present at the current index then convert it into an integer num = num*10 + (str[i]-'0')
num = num*10 + (str[i]-'0')
Otherwise, update the maximum value and reset num = 0.
Return the maximum value at the last.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to extract the maximum value#include<bits/stdc++.h>using namespace std; // Function to extract the maximum valueint extractMaximum(string str){ int num = 0, res = 0; // Start traversing the given string for (int i = 0; i<str.length(); i++) { // If a numeric value comes, start converting // it into an integer till there are consecutive // numeric digits if (str[i] >= '0' && str[i] <= '9') num = num * 10 + (str[i]-'0'); // Update maximum value else { res = max(res, num); // Reset the number num = 0; } } // Return maximum value return max(res, num);} // Driver programint main(){ string str = "100klh564abc365bg"; cout << extractMaximum(str); return 0;}
// Java program to extract the maximum value class GFG { // Method to extract the maximum value static int extractMaximum(String str) { int num = 0, res = 0; // Start traversing the given string for (int i = 0; i<str.length(); i++) { // If a numeric value comes, start converting // it into an integer till there are consecutive // numeric digits if (Character.isDigit(str.charAt(i))) num = num * 10 + (str.charAt(i)-'0'); // Update maximum value else { res = Math.max(res, num); // Reset the number num = 0; } } // Return maximum value return Math.max(res, num); } // Driver method public static void main(String[] args) { String str = "100klh564abc365bg"; System.out.println(extractMaximum(str)); } }
# Python 3 program to extract# the maximum valuedef extractMaximum(ss): num, res = 0, 0 # start traversing the given string for i in range(len(ss)): if ss[i] >= "0" and ss[i] <= "9": num = num * 10 + int(int(ss[i]) - 0) else: res = max(res, num) num = 0 return max(res, num) # Driver Codess = "100klh564abc365bg" print(extractMaximum(ss)) # This code is contributed# by mohit kumar 29
// C# program to extract the maximum valueusing System; class GFG { // Method to extract the maximum value static int extractMaximum(String str) { int num = 0, res = 0; // Start traversing the given string for (int i = 0; i < str.Length; i++) { // If a numeric value comes, start // converting it into an integer // till there are consecutive // numeric digits if (char.IsDigit(str[i])) num = num * 10 + (str[i]-'0'); // Update maximum value else { res = Math.Max(res, num); // Reset the number num = 0; } } // Return maximum value return Math.Max(res, num); } // Driver method public static void Main() { String str = "100klh564abc365bg"; Console.Write(extractMaximum(str)); } } // This code is contributed by nitin mittal.
<?php// PHP program to extract the maximum value // Function to extract the maximum valuefunction extractMaximum($str){ $num = 0; $res = 0; // Start traversing the given string for ($i = 0; $i<strlen($str); $i++) { // If a numeric value comes, // start converting it into // an integer till there are // consecutive numeric digits if ($str[$i] >= '0' && $str[$i] <= '9') $num = $num * 10 + ($str[$i]-'0'); // Update maximum value else { $res = max($res, $num); // Reset the number $num = 0; } } // Return maximum value return max($res, $num);} // Driver Code $str = "100klh564abc365bg"; echo extractMaximum($str); // This code is contributed by nitin mittal.?>
<script> // JavaScript program to extract// the maximum value // Method to extract the maximum valuefunction extractMaximum(str){ var num = 0, res = 0; // Start traversing the given string for (i = 0; i<str.length; i++) { // If a numeric value comes, // start converting // it into an integer till // there are consecutive // numeric digits if (isDigit(str.charAt(i))) num = num * 10 + (str.charAt(i).charCodeAt(0)- '0'.charCodeAt(0)); // Update maximum value else { res = Math.max(res, num); // Reset the number num = 0; } } // Return maximum value return Math.max(res, num);} function isDigit(c) { return c >= '0' && c <= '9'; } // Driver methodvar str = "100klh564abc365bg";document.write(extractMaximum(str)); // This code is contributed by Amit Katiyar </script>
Output:
564
But in the case of large numbers above program wouldn’t work because of the integer range in C and C++. So, to handle the case of large numbers we have to take each numeric value as a separate string and then find the maximum value.
1) Start traversing the given string.
Continue traversing if there are any
leading zeroes or any lowercase character.
b) Form a string of integer values.
c) Update the maximum string.
i) If the maximum string and current
string are having equal lengths then
on the basis of the first unmatched
value return maximum string.
ii) If both are having different lengths
then return the string with greater
length.
2) Return maximum string.
C++
Java
Python3
C#
PHP
Javascript
// C++ program for above implementation#include<bits/stdc++.h>using namespace std; // Utility function to find maximum stringstring maximumNum(string curr_num, string res){ int len1 = curr_num.length(); int len2 = res.length(); // If both having equal lengths if (len1 == len2) { // Reach first unmatched character / value int i = 0; while (curr_num[i]== res[i]) i++; // Return string with maximum value if (curr_num[i] < res[i]) return res; else return curr_num; } // If different lengths // return string with maximum length return len1 < len2 ? res: curr_num;} // Function to extract the maximum valuestring extractMaximum(string str){ int n = str.length(); string curr_num =""; string res; // Start traversing the string for (int i = 0; i<n; i++) { // Ignore leading zeroes while (i<n && str[i]=='0') i++; // Store numeric value into a string while (i<n && str[i]>='0' && str[i]<='9') { curr_num = curr_num + str[i]; i++; } if (i == n) break; if (curr_num.size() > 0) i--; // Update maximum string res = maximumNum(curr_num, res); curr_num = ""; } // To handle the case if there is only // 0 numeric value if (curr_num.size()== 0 && res.size()== 0) res = res + '0'; // Return maximum string return maximumNum(curr_num, res);} // Drivers programint main(){ string str ="100klh564abc365bg"; cout << extractMaximum(str) << endl; return 0;}
// Java program for above implementation class GFG { // Utility method to find maximum string static String maximumNum(String curr_num, String res) { int len1 = curr_num.length(); int len2 = res.length(); // If both having equal lengths if (len1 == len2) { // Reach first unmatched character / value int i = 0; while (curr_num.charAt(i) == res.charAt(i)) i++; // Return string with maximum value if (curr_num.charAt(i) < res.charAt(i)) return res; else return curr_num; } // If different lengths // return string with maximum length return len1 < len2 ? res: curr_num; } // Method to extract the maximum value static String extractMaximum(String str) { int n = str.length(); String curr_num =""; String res=""; // Start traversing the string for (int i = 0; i<n; i++) { // Ignore leading zeroes while (i<n && str.charAt(i)=='0') i++; // Store numeric value into a string while (i<n && Character.isDigit(str.charAt(i))) { curr_num = curr_num + str.charAt(i); i++; } if (i == n) break; if (curr_num.length() > 0) i--; // Update maximum string res = maximumNum(curr_num, res); curr_num = ""; } // To handle the case if there is only // 0 numeric value if (curr_num.length() == 0 && res.length() == 0) res = res + '0'; // Return maximum string return maximumNum(curr_num, res); } // Driver method public static void main(String[] args) { String str = "100klh564abc365bg"; System.out.println(extractMaximum(str)); } }
# Python3 program for above implementation # Utility function to find maximum stringdef maximumNum(curr_num, res): len1 = len(curr_num); len2 = len(res); # If both having equal lengths if (len1 == len2): # Reach first unmatched character / value i = 0; while (curr_num[i]== res[i]): i += 1; # Return string with maximum value if (curr_num[i] < res[i]): return res; else: return curr_num; # If different lengths # return string with maximum length return res if(len1 < len2) else curr_num; # Function to extract the maximum valuedef extractMaximum(str): n = len(str); curr_num = ""; res = ""; # Start traversing the string for i in range(n): # Ignore leading zeroes while (i < n and str[i]=='0'): i += 1; # Store numeric value into a string while (i < n and str[i] >= '0' and str[i] <= '9'): curr_num += str[i]; i += 1; if (i == n): break; if (len(curr_num) > 0): i -= 1; # Update maximum string res = maximumNum(curr_num, res); curr_num = ""; # To handle the case if there is only # 0 numeric value if (len(curr_num) == 0 and len(res) == 0): res += '0'; # Return maximum string return maximumNum(curr_num, res); # Driver Codestr ="100klh564abc365bg";print(extractMaximum(str)); # This code is contributed by mits
// C# program for above implementation using System;class GFG { // Utility method to find maximum string static String maximumNum(string curr_num, string res) { int len1 = curr_num.Length; int len2 = res.Length; // If both having equal lengths if (len1 == len2) { // Reach first unmatched character / value int i = 0; while (curr_num[i] == res[i]) i++; // Return string with maximum value if (curr_num[i] < res[i]) return res; else return curr_num; } // If different lengths // return string with maximum length return len1 < len2 ? res: curr_num; } // Method to extract the maximum value static string extractMaximum(string str) { int n = str.Length; string curr_num =""; string res=""; // Start traversing the string for (int i = 0; i<n; i++) { // Ignore leading zeroes while (i<n && str[i]=='0') i++; // Store numeric value into a string while (i<n && Char.IsDigit(str[i])) { curr_num = curr_num + str[i]; i++; } if (i == n) break; if (curr_num.Length > 0) i--; // Update maximum string res = maximumNum(curr_num, res); curr_num = ""; } // To handle the case if there is only // 0 numeric value if (curr_num.Length == 0 && res.Length == 0) res = res + '0'; // Return maximum string return maximumNum(curr_num, res); } // Driver method public static void Main() { string str = "100klh564abc365bg"; Console.WriteLine(extractMaximum(str)); } } // This code is contributed by mits
<?php// PHP program for above implementation // Utility function to find maximum stringfunction maximumNum($curr_num, $res){ $len1 = strlen($curr_num); $len2 = strlen($res); // If both having equal lengths if ($len1 == $len2) { // Reach first unmatched character / value $i = 0; while ($curr_num[$i]== $res[$i]) $i++; // Return string with maximum value if ($curr_num[$i] < $res[$i]) return $res; else return $curr_num; } // If different lengths // return string with maximum length return $len1 < $len2 ? $res: $curr_num;} // Function to extract the maximum valuefunction extractMaximum($str){ $n = strlen($str); $curr_num =""; $res=""; // Start traversing the string for ($i = 0; $i<$n; $i++) { // Ignore leading zeroes while ($i<$n && $str[$i]=='0') $i++; // Store numeric value into a string while ($i<$n && $str[$i]>='0' && $str[$i]<='9') { $curr_num .= $str[$i]; $i++; } if ($i == $n) break; if (strlen($curr_num) > 0) $i--; // Update maximum string $res = maximumNum($curr_num, $res); $curr_num = ""; } // To handle the case if there is only // 0 numeric value if (strlen($curr_num)== 0 && strlen($res)== 0) $res .= '0'; // Return maximum string return maximumNum($curr_num, $res);} // Drivers program $str ="100klh564abc365bg"; echo extractMaximum($str); // this code is contributed by mits?>
<script> // JavaScript program for above implementation // Utility method to find maximum string function maximumNum(curr_num,res) { let len1 = curr_num.length; let len2 = res.length; // If both having equal lengths if (len1 == len2) { // Reach first unmatched character / value let i = 0; while (curr_num[i] == res[i]) i++; // Return string with maximum value if (curr_num[i] < res[i]) return res; else return curr_num; } // If different lengths // return string with maximum length return len1 < len2 ? res: curr_num; } // Method to extract the maximum value function extractMaximum(str) { let n = str.length; let curr_num =""; let res=""; // Start traversing the string for (let i = 0; i<n; i++) { // Ignore leading zeroes while (i<n && str[i]=='0') i++; // Store numeric value into a string while (i<n && !isNaN(String(str[i]) * 1)) { curr_num = curr_num + str[i]; i++; } if (i == n) break; if (curr_num.length > 0) i--; // Update maximum string res = maximumNum(curr_num, res); curr_num = ""; } // To handle the case if there is only // 0 numeric value if (curr_num.length == 0 && res.length == 0) res = res + '0'; // Return maximum string return maximumNum(curr_num, res); } // Driver method let str = "100klh564abc365bg"; document.write(extractMaximum(str)); // This code is contributed by unknown2108 </script>
Output:
564
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
mohit kumar 29
Mithun Kumar
amit143katiyar
unknown2108
Amazon
Mathematical
Strings
Amazon
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Sieve of Eratosthenes
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 25029,
"s": 25001,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 25262,
"s": 25029,
"text": "Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case. One approach to solving the problem is discussed here, other using Regular expressions is given in Set 2 Examples: "
},
{
"code": null,
"e": 25387,
"s": 25262,
"text": "Input : 100klh564abc365bg\nOutput : 564\nMaximum numeric value among 100, 564 \nand 365 is 564.\n\nInput : abchsd0sdhs\nOutput : 0"
},
{
"code": null,
"e": 25475,
"s": 25389,
"text": "Its solution is simple i.e. Start traversing the string and perform two operations: "
},
{
"code": null,
"e": 25641,
"s": 25475,
"text": "If a numeric value is present at the current index then convert it into an integer num = num*10 + (str[i]-'0') Otherwise, update the maximum value and reset num = 0."
},
{
"code": null,
"e": 25753,
"s": 25641,
"text": "If a numeric value is present at the current index then convert it into an integer num = num*10 + (str[i]-'0') "
},
{
"code": null,
"e": 25783,
"s": 25753,
"text": " num = num*10 + (str[i]-'0') "
},
{
"code": null,
"e": 25838,
"s": 25783,
"text": "Otherwise, update the maximum value and reset num = 0."
},
{
"code": null,
"e": 25877,
"s": 25838,
"text": "Return the maximum value at the last. "
},
{
"code": null,
"e": 25881,
"s": 25877,
"text": "C++"
},
{
"code": null,
"e": 25886,
"s": 25881,
"text": "Java"
},
{
"code": null,
"e": 25894,
"s": 25886,
"text": "Python3"
},
{
"code": null,
"e": 25897,
"s": 25894,
"text": "C#"
},
{
"code": null,
"e": 25901,
"s": 25897,
"text": "PHP"
},
{
"code": null,
"e": 25912,
"s": 25901,
"text": "Javascript"
},
{
"code": "// C++ program to extract the maximum value#include<bits/stdc++.h>using namespace std; // Function to extract the maximum valueint extractMaximum(string str){ int num = 0, res = 0; // Start traversing the given string for (int i = 0; i<str.length(); i++) { // If a numeric value comes, start converting // it into an integer till there are consecutive // numeric digits if (str[i] >= '0' && str[i] <= '9') num = num * 10 + (str[i]-'0'); // Update maximum value else { res = max(res, num); // Reset the number num = 0; } } // Return maximum value return max(res, num);} // Driver programint main(){ string str = \"100klh564abc365bg\"; cout << extractMaximum(str); return 0;}",
"e": 26724,
"s": 25912,
"text": null
},
{
"code": "// Java program to extract the maximum value class GFG { // Method to extract the maximum value static int extractMaximum(String str) { int num = 0, res = 0; // Start traversing the given string for (int i = 0; i<str.length(); i++) { // If a numeric value comes, start converting // it into an integer till there are consecutive // numeric digits if (Character.isDigit(str.charAt(i))) num = num * 10 + (str.charAt(i)-'0'); // Update maximum value else { res = Math.max(res, num); // Reset the number num = 0; } } // Return maximum value return Math.max(res, num); } // Driver method public static void main(String[] args) { String str = \"100klh564abc365bg\"; System.out.println(extractMaximum(str)); } }",
"e": 27701,
"s": 26724,
"text": null
},
{
"code": "# Python 3 program to extract# the maximum valuedef extractMaximum(ss): num, res = 0, 0 # start traversing the given string for i in range(len(ss)): if ss[i] >= \"0\" and ss[i] <= \"9\": num = num * 10 + int(int(ss[i]) - 0) else: res = max(res, num) num = 0 return max(res, num) # Driver Codess = \"100klh564abc365bg\" print(extractMaximum(ss)) # This code is contributed# by mohit kumar 29",
"e": 28175,
"s": 27701,
"text": null
},
{
"code": "// C# program to extract the maximum valueusing System; class GFG { // Method to extract the maximum value static int extractMaximum(String str) { int num = 0, res = 0; // Start traversing the given string for (int i = 0; i < str.Length; i++) { // If a numeric value comes, start // converting it into an integer // till there are consecutive // numeric digits if (char.IsDigit(str[i])) num = num * 10 + (str[i]-'0'); // Update maximum value else { res = Math.Max(res, num); // Reset the number num = 0; } } // Return maximum value return Math.Max(res, num); } // Driver method public static void Main() { String str = \"100klh564abc365bg\"; Console.Write(extractMaximum(str)); } } // This code is contributed by nitin mittal.",
"e": 29211,
"s": 28175,
"text": null
},
{
"code": "<?php// PHP program to extract the maximum value // Function to extract the maximum valuefunction extractMaximum($str){ $num = 0; $res = 0; // Start traversing the given string for ($i = 0; $i<strlen($str); $i++) { // If a numeric value comes, // start converting it into // an integer till there are // consecutive numeric digits if ($str[$i] >= '0' && $str[$i] <= '9') $num = $num * 10 + ($str[$i]-'0'); // Update maximum value else { $res = max($res, $num); // Reset the number $num = 0; } } // Return maximum value return max($res, $num);} // Driver Code $str = \"100klh564abc365bg\"; echo extractMaximum($str); // This code is contributed by nitin mittal.?>",
"e": 30035,
"s": 29211,
"text": null
},
{
"code": "<script> // JavaScript program to extract// the maximum value // Method to extract the maximum valuefunction extractMaximum(str){ var num = 0, res = 0; // Start traversing the given string for (i = 0; i<str.length; i++) { // If a numeric value comes, // start converting // it into an integer till // there are consecutive // numeric digits if (isDigit(str.charAt(i))) num = num * 10 + (str.charAt(i).charCodeAt(0)- '0'.charCodeAt(0)); // Update maximum value else { res = Math.max(res, num); // Reset the number num = 0; } } // Return maximum value return Math.max(res, num);} function isDigit(c) { return c >= '0' && c <= '9'; } // Driver methodvar str = \"100klh564abc365bg\";document.write(extractMaximum(str)); // This code is contributed by Amit Katiyar </script>",
"e": 30991,
"s": 30035,
"text": null
},
{
"code": null,
"e": 31001,
"s": 30991,
"text": "Output: "
},
{
"code": null,
"e": 31005,
"s": 31001,
"text": "564"
},
{
"code": null,
"e": 31239,
"s": 31005,
"text": "But in the case of large numbers above program wouldn’t work because of the integer range in C and C++. So, to handle the case of large numbers we have to take each numeric value as a separate string and then find the maximum value. "
},
{
"code": null,
"e": 31737,
"s": 31239,
"text": " \n1) Start traversing the given string.\n Continue traversing if there are any \n leading zeroes or any lowercase character.\n b) Form a string of integer values.\n c) Update the maximum string.\n i) If the maximum string and current \n string are having equal lengths then \n on the basis of the first unmatched \n value return maximum string.\n ii) If both are having different lengths \n then return the string with greater \n length.\n\n2) Return maximum string."
},
{
"code": null,
"e": 31743,
"s": 31739,
"text": "C++"
},
{
"code": null,
"e": 31748,
"s": 31743,
"text": "Java"
},
{
"code": null,
"e": 31756,
"s": 31748,
"text": "Python3"
},
{
"code": null,
"e": 31759,
"s": 31756,
"text": "C#"
},
{
"code": null,
"e": 31763,
"s": 31759,
"text": "PHP"
},
{
"code": null,
"e": 31774,
"s": 31763,
"text": "Javascript"
},
{
"code": "// C++ program for above implementation#include<bits/stdc++.h>using namespace std; // Utility function to find maximum stringstring maximumNum(string curr_num, string res){ int len1 = curr_num.length(); int len2 = res.length(); // If both having equal lengths if (len1 == len2) { // Reach first unmatched character / value int i = 0; while (curr_num[i]== res[i]) i++; // Return string with maximum value if (curr_num[i] < res[i]) return res; else return curr_num; } // If different lengths // return string with maximum length return len1 < len2 ? res: curr_num;} // Function to extract the maximum valuestring extractMaximum(string str){ int n = str.length(); string curr_num =\"\"; string res; // Start traversing the string for (int i = 0; i<n; i++) { // Ignore leading zeroes while (i<n && str[i]=='0') i++; // Store numeric value into a string while (i<n && str[i]>='0' && str[i]<='9') { curr_num = curr_num + str[i]; i++; } if (i == n) break; if (curr_num.size() > 0) i--; // Update maximum string res = maximumNum(curr_num, res); curr_num = \"\"; } // To handle the case if there is only // 0 numeric value if (curr_num.size()== 0 && res.size()== 0) res = res + '0'; // Return maximum string return maximumNum(curr_num, res);} // Drivers programint main(){ string str =\"100klh564abc365bg\"; cout << extractMaximum(str) << endl; return 0;}",
"e": 33426,
"s": 31774,
"text": null
},
{
"code": "// Java program for above implementation class GFG { // Utility method to find maximum string static String maximumNum(String curr_num, String res) { int len1 = curr_num.length(); int len2 = res.length(); // If both having equal lengths if (len1 == len2) { // Reach first unmatched character / value int i = 0; while (curr_num.charAt(i) == res.charAt(i)) i++; // Return string with maximum value if (curr_num.charAt(i) < res.charAt(i)) return res; else return curr_num; } // If different lengths // return string with maximum length return len1 < len2 ? res: curr_num; } // Method to extract the maximum value static String extractMaximum(String str) { int n = str.length(); String curr_num =\"\"; String res=\"\"; // Start traversing the string for (int i = 0; i<n; i++) { // Ignore leading zeroes while (i<n && str.charAt(i)=='0') i++; // Store numeric value into a string while (i<n && Character.isDigit(str.charAt(i))) { curr_num = curr_num + str.charAt(i); i++; } if (i == n) break; if (curr_num.length() > 0) i--; // Update maximum string res = maximumNum(curr_num, res); curr_num = \"\"; } // To handle the case if there is only // 0 numeric value if (curr_num.length() == 0 && res.length() == 0) res = res + '0'; // Return maximum string return maximumNum(curr_num, res); } // Driver method public static void main(String[] args) { String str = \"100klh564abc365bg\"; System.out.println(extractMaximum(str)); } }",
"e": 35449,
"s": 33426,
"text": null
},
{
"code": "# Python3 program for above implementation # Utility function to find maximum stringdef maximumNum(curr_num, res): len1 = len(curr_num); len2 = len(res); # If both having equal lengths if (len1 == len2): # Reach first unmatched character / value i = 0; while (curr_num[i]== res[i]): i += 1; # Return string with maximum value if (curr_num[i] < res[i]): return res; else: return curr_num; # If different lengths # return string with maximum length return res if(len1 < len2) else curr_num; # Function to extract the maximum valuedef extractMaximum(str): n = len(str); curr_num = \"\"; res = \"\"; # Start traversing the string for i in range(n): # Ignore leading zeroes while (i < n and str[i]=='0'): i += 1; # Store numeric value into a string while (i < n and str[i] >= '0' and str[i] <= '9'): curr_num += str[i]; i += 1; if (i == n): break; if (len(curr_num) > 0): i -= 1; # Update maximum string res = maximumNum(curr_num, res); curr_num = \"\"; # To handle the case if there is only # 0 numeric value if (len(curr_num) == 0 and len(res) == 0): res += '0'; # Return maximum string return maximumNum(curr_num, res); # Driver Codestr =\"100klh564abc365bg\";print(extractMaximum(str)); # This code is contributed by mits",
"e": 36992,
"s": 35449,
"text": null
},
{
"code": "// C# program for above implementation using System;class GFG { // Utility method to find maximum string static String maximumNum(string curr_num, string res) { int len1 = curr_num.Length; int len2 = res.Length; // If both having equal lengths if (len1 == len2) { // Reach first unmatched character / value int i = 0; while (curr_num[i] == res[i]) i++; // Return string with maximum value if (curr_num[i] < res[i]) return res; else return curr_num; } // If different lengths // return string with maximum length return len1 < len2 ? res: curr_num; } // Method to extract the maximum value static string extractMaximum(string str) { int n = str.Length; string curr_num =\"\"; string res=\"\"; // Start traversing the string for (int i = 0; i<n; i++) { // Ignore leading zeroes while (i<n && str[i]=='0') i++; // Store numeric value into a string while (i<n && Char.IsDigit(str[i])) { curr_num = curr_num + str[i]; i++; } if (i == n) break; if (curr_num.Length > 0) i--; // Update maximum string res = maximumNum(curr_num, res); curr_num = \"\"; } // To handle the case if there is only // 0 numeric value if (curr_num.Length == 0 && res.Length == 0) res = res + '0'; // Return maximum string return maximumNum(curr_num, res); } // Driver method public static void Main() { string str = \"100klh564abc365bg\"; Console.WriteLine(extractMaximum(str)); } } // This code is contributed by mits",
"e": 39029,
"s": 36992,
"text": null
},
{
"code": "<?php// PHP program for above implementation // Utility function to find maximum stringfunction maximumNum($curr_num, $res){ $len1 = strlen($curr_num); $len2 = strlen($res); // If both having equal lengths if ($len1 == $len2) { // Reach first unmatched character / value $i = 0; while ($curr_num[$i]== $res[$i]) $i++; // Return string with maximum value if ($curr_num[$i] < $res[$i]) return $res; else return $curr_num; } // If different lengths // return string with maximum length return $len1 < $len2 ? $res: $curr_num;} // Function to extract the maximum valuefunction extractMaximum($str){ $n = strlen($str); $curr_num =\"\"; $res=\"\"; // Start traversing the string for ($i = 0; $i<$n; $i++) { // Ignore leading zeroes while ($i<$n && $str[$i]=='0') $i++; // Store numeric value into a string while ($i<$n && $str[$i]>='0' && $str[$i]<='9') { $curr_num .= $str[$i]; $i++; } if ($i == $n) break; if (strlen($curr_num) > 0) $i--; // Update maximum string $res = maximumNum($curr_num, $res); $curr_num = \"\"; } // To handle the case if there is only // 0 numeric value if (strlen($curr_num)== 0 && strlen($res)== 0) $res .= '0'; // Return maximum string return maximumNum($curr_num, $res);} // Drivers program $str =\"100klh564abc365bg\"; echo extractMaximum($str); // this code is contributed by mits?>",
"e": 40645,
"s": 39029,
"text": null
},
{
"code": "<script> // JavaScript program for above implementation // Utility method to find maximum string function maximumNum(curr_num,res) { let len1 = curr_num.length; let len2 = res.length; // If both having equal lengths if (len1 == len2) { // Reach first unmatched character / value let i = 0; while (curr_num[i] == res[i]) i++; // Return string with maximum value if (curr_num[i] < res[i]) return res; else return curr_num; } // If different lengths // return string with maximum length return len1 < len2 ? res: curr_num; } // Method to extract the maximum value function extractMaximum(str) { let n = str.length; let curr_num =\"\"; let res=\"\"; // Start traversing the string for (let i = 0; i<n; i++) { // Ignore leading zeroes while (i<n && str[i]=='0') i++; // Store numeric value into a string while (i<n && !isNaN(String(str[i]) * 1)) { curr_num = curr_num + str[i]; i++; } if (i == n) break; if (curr_num.length > 0) i--; // Update maximum string res = maximumNum(curr_num, res); curr_num = \"\"; } // To handle the case if there is only // 0 numeric value if (curr_num.length == 0 && res.length == 0) res = res + '0'; // Return maximum string return maximumNum(curr_num, res); } // Driver method let str = \"100klh564abc365bg\"; document.write(extractMaximum(str)); // This code is contributed by unknown2108 </script>",
"e": 42590,
"s": 40645,
"text": null
},
{
"code": null,
"e": 42600,
"s": 42590,
"text": "Output: "
},
{
"code": null,
"e": 42604,
"s": 42600,
"text": "564"
},
{
"code": null,
"e": 43026,
"s": 42604,
"text": "This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 43039,
"s": 43026,
"text": "nitin mittal"
},
{
"code": null,
"e": 43054,
"s": 43039,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 43067,
"s": 43054,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 43082,
"s": 43067,
"text": "amit143katiyar"
},
{
"code": null,
"e": 43094,
"s": 43082,
"text": "unknown2108"
},
{
"code": null,
"e": 43101,
"s": 43094,
"text": "Amazon"
},
{
"code": null,
"e": 43114,
"s": 43101,
"text": "Mathematical"
},
{
"code": null,
"e": 43122,
"s": 43114,
"text": "Strings"
},
{
"code": null,
"e": 43129,
"s": 43122,
"text": "Amazon"
},
{
"code": null,
"e": 43137,
"s": 43129,
"text": "Strings"
},
{
"code": null,
"e": 43150,
"s": 43137,
"text": "Mathematical"
},
{
"code": null,
"e": 43248,
"s": 43150,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43257,
"s": 43248,
"text": "Comments"
},
{
"code": null,
"e": 43270,
"s": 43257,
"text": "Old Comments"
},
{
"code": null,
"e": 43294,
"s": 43270,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 43336,
"s": 43294,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 43379,
"s": 43336,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 43393,
"s": 43379,
"text": "Prime Numbers"
},
{
"code": null,
"e": 43415,
"s": 43393,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 43440,
"s": 43415,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 43486,
"s": 43440,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 43520,
"s": 43486,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 43577,
"s": 43520,
"text": "Python program to check if a string is palindrome or not"
}
] |
Create a new user with password in MySQL 8? | You need to use CREATE command to create a new user with password in MySQL 8. Let us check the version
mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.12 |
+-----------+
1 row in set (0.14 sec)
The syntax is as follows to create a new user with password
CREATE USER 'yourUserName'@'localhost' IDENTIFIED BY 'yourPassword';
The following is the syntax to grant all privileges to the created user
GRANT ALL ON *.* TO 'yourUserName'@'localhost';
Now flush the privileges using flush command
flush privileges;
Let us create a new user with the help of the above syntax. The query is as follows
mysql> use MySQL;
Database changed
mysql> CREATE USER 'James'@'localhost' IDENTIFIED BY 'James123456';
Query OK, 0 rows affected (0.21 sec)
The following is the query to grant all privileges to the newly created user
mysql> GRANT ALL ON *.* TO 'James'@'localhost';
Query OK, 0 rows affected (0.18 sec)
Let us check the user has been created or not
mysql> select user from MySQL.user;
The following is the output displaying the new user we created above
+------------------+
| user |
+------------------+
| Bob |
| Manish |
| User2 |
| mysql.infoschema |
| mysql.session |
| mysql.sys |
| root |
| @UserName@ |
| Adam Smith |
| James |
| John |
| John Doe |
| User1 |
| am |
| hbstudent |
| mysql.infoschema |
| mysql.session |
+------------------+
17 rows in set (0.00 sec)
Look at the sample output, the user James has been created successfully. Now flush the privileges using a flush command. The query is as follows
mysql> flush privileges;
Query OK, 0 rows affected (0.04 sec) | [
{
"code": null,
"e": 1165,
"s": 1062,
"text": "You need to use CREATE command to create a new user with password in MySQL 8. Let us check the version"
},
{
"code": null,
"e": 1284,
"s": 1165,
"text": "mysql> select version();\n+-----------+\n| version() |\n+-----------+\n| 8.0.12 |\n+-----------+\n1 row in set (0.14 sec)"
},
{
"code": null,
"e": 1344,
"s": 1284,
"text": "The syntax is as follows to create a new user with password"
},
{
"code": null,
"e": 1413,
"s": 1344,
"text": "CREATE USER 'yourUserName'@'localhost' IDENTIFIED BY 'yourPassword';"
},
{
"code": null,
"e": 1485,
"s": 1413,
"text": "The following is the syntax to grant all privileges to the created user"
},
{
"code": null,
"e": 1533,
"s": 1485,
"text": "GRANT ALL ON *.* TO 'yourUserName'@'localhost';"
},
{
"code": null,
"e": 1578,
"s": 1533,
"text": "Now flush the privileges using flush command"
},
{
"code": null,
"e": 1597,
"s": 1578,
"text": "flush privileges;\n"
},
{
"code": null,
"e": 1681,
"s": 1597,
"text": "Let us create a new user with the help of the above syntax. The query is as follows"
},
{
"code": null,
"e": 1821,
"s": 1681,
"text": "mysql> use MySQL;\nDatabase changed\nmysql> CREATE USER 'James'@'localhost' IDENTIFIED BY 'James123456';\nQuery OK, 0 rows affected (0.21 sec)"
},
{
"code": null,
"e": 1898,
"s": 1821,
"text": "The following is the query to grant all privileges to the newly created user"
},
{
"code": null,
"e": 1983,
"s": 1898,
"text": "mysql> GRANT ALL ON *.* TO 'James'@'localhost';\nQuery OK, 0 rows affected (0.18 sec)"
},
{
"code": null,
"e": 2029,
"s": 1983,
"text": "Let us check the user has been created or not"
},
{
"code": null,
"e": 2065,
"s": 2029,
"text": "mysql> select user from MySQL.user;"
},
{
"code": null,
"e": 2134,
"s": 2065,
"text": "The following is the output displaying the new user we created above"
},
{
"code": null,
"e": 2601,
"s": 2134,
"text": "+------------------+\n| user |\n+------------------+\n| Bob |\n| Manish |\n| User2 |\n| mysql.infoschema |\n| mysql.session |\n| mysql.sys |\n| root |\n| @UserName@ |\n| Adam Smith |\n| James |\n| John |\n| John Doe |\n| User1 |\n| am |\n| hbstudent |\n| mysql.infoschema |\n| mysql.session |\n+------------------+\n17 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2746,
"s": 2601,
"text": "Look at the sample output, the user James has been created successfully. Now flush the privileges using a flush command. The query is as follows"
},
{
"code": null,
"e": 2808,
"s": 2746,
"text": "mysql> flush privileges;\nQuery OK, 0 rows affected (0.04 sec)"
}
] |
Exception Hierarchy in case of multiple catch blocks. | An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.
Whenever we have a code that may generate more than one exception and if you need to handle them specifically you can use multiple catch blocks on a single try.
try{
//code
} catch(Exception1 ex1) {
//
} catch(Exception2 ex2) {
//
}
Live Demo
import java.util.Arrays;
import java.util.Scanner;
public class MultipleCatchBlocks {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator (not 0) from this array (enter positions 0 to 5)");
int a = sc.nextInt();
int b = sc.nextInt();
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Warning: You have chosen a position which is not in the array");
}
catch(ArithmeticException e) {
System.out.println("Warning: You cannot divide a number with 0");
}
}
}
Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
2
8
Warning: You have chosen a position which is not in the array
Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator (not 0) from this array (enter positions 0 to 5)
1
4
Warning: You cannot divide a number with 0
If you have multiple catch blocks for a single try and if the exceptions classes of them belong to the same hierarchy, You need to make sure that the catch block that catches the exception class of higher-level is at last at the last in the order of catch blocks.
If not, all the exceptions of the subclasses will be handled in the higher level catch block making the remaining (catch) blocks unreachable leading to a compile-time exception.
In the following Java program, a single try block contains 4 catch blocks handling IndexOutOfBoundsException, ArrayIndexOutOfBoundsException, Exception and, ArithmeticException in the same order.
Since IndexOutOfBoundsException is a superclass of ArrayIndexOutOfBoundsException exceptions related to both classes are handled in the first catch block making the later one non-reachable.
Since Exception is the superclass of all the exception classes, if you place the catch block that catches it earlier to the catch blocks catching any other exceptions, all exceptions are handled in the Exception block itself making the remaining blocks unreachable.
Live Demo
import java.util.Arrays;
import java.util.Scanner;
public class ExceptionHierarchy {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator (positions 0 to 5)");
int a = sc.nextInt();
int b = sc.nextInt();
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(IndexOutOfBoundsException e) {
System.out.println("Warning: position chosen is not in the array");
}
catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
catch(ArithmeticException e) {
System.out.println("Warning: You cannot divide a number with 0");
}
}
}
Compile-time exception
ExceptionHierarchy.java:16: error: exception ArrayIndexOutOfBoundsException has already been caught
}catch(ArrayIndexOutOfBoundsException e) {
^
ExceptionHierarchy.java:20: error: exception ArithmeticException has already been caught
}catch(ArithmeticException e) {
^
2 errors
If you compile the above code in eclipse it generates the following errors −
Message1 −
Message2 −
To make the above code work,
The catch block that catches the IndexOutOfBoundsException should be placed after the catch block catching the ArrayIndexOutOfBoundsException.
The catch block that catches the IndexOutOfBoundsException should be placed after the catch block catching the ArrayIndexOutOfBoundsException.
The catch block catching the Exception object should be placed at last in the order of the catch blocks.
The catch block catching the Exception object should be placed at last in the order of the catch blocks.
Live Demo
import java.util.Arrays;
import java.util.Scanner;
public class ExceptionHierarchy {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator (enter positions 0 to 5)");
int a = sc.nextInt();
int b = sc.nextInt();
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
catch(IndexOutOfBoundsException e) {
System.out.println("Warning: You have chosen a position which is not in the array");
}
catch(ArithmeticException e) {
System.out.println("Warning: You cannot divide a number with 0");
}
catch(Exception e) {
e.printStackTrace();
}
}
} | [
{
"code": null,
"e": 1295,
"s": 1062,
"text": "An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed."
},
{
"code": null,
"e": 1456,
"s": 1295,
"text": "Whenever we have a code that may generate more than one exception and if you need to handle them specifically you can use multiple catch blocks on a single try."
},
{
"code": null,
"e": 1537,
"s": 1456,
"text": "try{\n //code\n} catch(Exception1 ex1) {\n //\n} catch(Exception2 ex2) {\n //\n}"
},
{
"code": null,
"e": 1548,
"s": 1537,
"text": " Live Demo"
},
{
"code": null,
"e": 2399,
"s": 1548,
"text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class MultipleCatchBlocks {\n public static void main(String [] args) {\n Scanner sc = new Scanner(System.in);\n int[] arr = {10, 20, 30, 2, 0, 8};\n System.out.println(\"Array: \"+Arrays.toString(arr));\n System.out.println(\"Choose numerator and denominator (not 0) from this array (enter positions 0 to 5)\");\n int a = sc.nextInt();\n int b = sc.nextInt();\n try {\n int result = (arr[a])/(arr[b]);\n System.out.println(\"Result of \"+arr[a]+\"/\"+arr[b]+\": \"+result);\n }\n catch(ArrayIndexOutOfBoundsException e) {\n System.out.println(\"Warning: You have chosen a position which is not in the array\");\n }\n catch(ArithmeticException e) {\n System.out.println(\"Warning: You cannot divide a number with 0\");\n }\n }\n}"
},
{
"code": null,
"e": 2610,
"s": 2399,
"text": "Enter 3 integer values one by one:\nArray: [10, 20, 30, 2, 0, 8]\nChoose numerator and denominator(not 0) from this array (enter positions 0 to 5)\n2\n8\nWarning: You have chosen a position which is not in the array"
},
{
"code": null,
"e": 2803,
"s": 2610,
"text": "Enter 3 integer values one by one:\nArray: [10, 20, 30, 2, 0, 8]\nChoose numerator and denominator (not 0) from this array (enter positions 0 to 5)\n1\n4\nWarning: You cannot divide a number with 0"
},
{
"code": null,
"e": 3067,
"s": 2803,
"text": "If you have multiple catch blocks for a single try and if the exceptions classes of them belong to the same hierarchy, You need to make sure that the catch block that catches the exception class of higher-level is at last at the last in the order of catch blocks."
},
{
"code": null,
"e": 3245,
"s": 3067,
"text": "If not, all the exceptions of the subclasses will be handled in the higher level catch block making the remaining (catch) blocks unreachable leading to a compile-time exception."
},
{
"code": null,
"e": 3441,
"s": 3245,
"text": "In the following Java program, a single try block contains 4 catch blocks handling IndexOutOfBoundsException, ArrayIndexOutOfBoundsException, Exception and, ArithmeticException in the same order."
},
{
"code": null,
"e": 3631,
"s": 3441,
"text": "Since IndexOutOfBoundsException is a superclass of ArrayIndexOutOfBoundsException exceptions related to both classes are handled in the first catch block making the later one non-reachable."
},
{
"code": null,
"e": 3897,
"s": 3631,
"text": "Since Exception is the superclass of all the exception classes, if you place the catch block that catches it earlier to the catch blocks catching any other exceptions, all exceptions are handled in the Exception block itself making the remaining blocks unreachable."
},
{
"code": null,
"e": 3908,
"s": 3897,
"text": " Live Demo"
},
{
"code": null,
"e": 4857,
"s": 3908,
"text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class ExceptionHierarchy {\n public static void main(String [] args) {\n Scanner sc = new Scanner(System.in);\n int[] arr = {10, 20, 30, 2, 0, 8};\n System.out.println(\"Array: \"+Arrays.toString(arr));\n System.out.println(\"Choose numerator and denominator (positions 0 to 5)\");\n int a = sc.nextInt();\n int b = sc.nextInt();\n try {\n int result = (arr[a])/(arr[b]);\n System.out.println(\"Result of \"+arr[a]+\"/\"+arr[b]+\": \"+result);\n }\n catch(IndexOutOfBoundsException e) {\n System.out.println(\"Warning: position chosen is not in the array\");\n }\n catch(ArrayIndexOutOfBoundsException e) {\n e.printStackTrace();\n }\n catch(Exception e) {\n e.printStackTrace();\n }\n catch(ArithmeticException e) {\n System.out.println(\"Warning: You cannot divide a number with 0\");\n }\n }\n}"
},
{
"code": null,
"e": 4880,
"s": 4857,
"text": "Compile-time exception"
},
{
"code": null,
"e": 5169,
"s": 4880,
"text": "ExceptionHierarchy.java:16: error: exception ArrayIndexOutOfBoundsException has already been caught\n }catch(ArrayIndexOutOfBoundsException e) {\n ^\nExceptionHierarchy.java:20: error: exception ArithmeticException has already been caught\n }catch(ArithmeticException e) {\n ^\n2 errors"
},
{
"code": null,
"e": 5246,
"s": 5169,
"text": "If you compile the above code in eclipse it generates the following errors −"
},
{
"code": null,
"e": 5257,
"s": 5246,
"text": "Message1 −"
},
{
"code": null,
"e": 5268,
"s": 5257,
"text": "Message2 −"
},
{
"code": null,
"e": 5297,
"s": 5268,
"text": "To make the above code work,"
},
{
"code": null,
"e": 5440,
"s": 5297,
"text": "The catch block that catches the IndexOutOfBoundsException should be placed after the catch block catching the ArrayIndexOutOfBoundsException."
},
{
"code": null,
"e": 5583,
"s": 5440,
"text": "The catch block that catches the IndexOutOfBoundsException should be placed after the catch block catching the ArrayIndexOutOfBoundsException."
},
{
"code": null,
"e": 5688,
"s": 5583,
"text": "The catch block catching the Exception object should be placed at last in the order of the catch blocks."
},
{
"code": null,
"e": 5793,
"s": 5688,
"text": "The catch block catching the Exception object should be placed at last in the order of the catch blocks."
},
{
"code": null,
"e": 5804,
"s": 5793,
"text": " Live Demo"
},
{
"code": null,
"e": 6773,
"s": 5804,
"text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class ExceptionHierarchy {\n public static void main(String [] args) {\n Scanner sc = new Scanner(System.in);\n int[] arr = {10, 20, 30, 2, 0, 8};\n System.out.println(\"Array: \"+Arrays.toString(arr));\n System.out.println(\"Choose numerator and denominator (enter positions 0 to 5)\");\n int a = sc.nextInt();\n int b = sc.nextInt();\n try {\n int result = (arr[a])/(arr[b]);\n System.out.println(\"Result of \"+arr[a]+\"/\"+arr[b]+\": \"+result);\n }\n catch(ArrayIndexOutOfBoundsException e) {\n e.printStackTrace();\n }\n catch(IndexOutOfBoundsException e) {\n System.out.println(\"Warning: You have chosen a position which is not in the array\");\n }\n catch(ArithmeticException e) {\n System.out.println(\"Warning: You cannot divide a number with 0\");\n }\n catch(Exception e) {\n e.printStackTrace();\n }\n }\n}"
}
] |
Perl - Special Variables | There are some variables which have a predefined and special meaning in Perl. They are the variables that use punctuation characters after the usual variable indicator ($, @, or %), such as $_ ( explained below ).
Most of the special variables have an english like long name, e.g., Operating System Error variable $! can be written as $OS_ERROR. But if you are going to use english like names, then you would have to put one line use English; at the top of your program file. This guides the interpreter to pickup exact meaning of the variable.
The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines −
#!/usr/bin/perl
foreach ('hickory','dickory','doc') {
print $_;
print "\n";
}
When executed, this will produce the following result −
hickory
dickory
doc
Again, let's check the same example without using $_ variable explicitly −
#!/usr/bin/perl
foreach ('hickory','dickory','doc') {
print;
print "\n";
}
When executed, this will also produce the following result −
hickory
dickory
doc
The first time the loop is executed, "hickory" is printed. The second time around, "dickory" is printed, and the third time, "doc" is printed. That's because in each iteration of the loop, the current string is placed in $_, and is used by default by print. Here are the places where Perl will assume $_ even if you don't specify it −
Various unary functions, including functions like ord and int, as well as the all file tests (-f, -d) except for -t, which defaults to STDIN.
Various unary functions, including functions like ord and int, as well as the all file tests (-f, -d) except for -t, which defaults to STDIN.
Various list functions like print and unlink.
Various list functions like print and unlink.
The pattern-matching operations m//, s///, and tr/// when used without an =~ operator.
The pattern-matching operations m//, s///, and tr/// when used without an =~ operator.
The default iterator variable in a foreach loop if no other variable is supplied.
The default iterator variable in a foreach loop if no other variable is supplied.
The implicit iterator variable in the grep and map functions.
The implicit iterator variable in the grep and map functions.
The default place to put an input record when a line-input operation's result is tested by itself as the sole criterion of a while test (i.e., ). Note that outside of a while test, this will not happen.
The default place to put an input record when a line-input operation's result is tested by itself as the sole criterion of a while test (i.e., ). Note that outside of a while test, this will not happen.
Based on the usage and nature of special variables, we can categorize them in the following categories −
Global Scalar Special Variables.
Global Array Special Variables.
Global Hash Special Variables.
Global Special Filehandles.
Global Special Constants.
Regular Expression Special Variables.
Filehandle Special Variables.
Here is the list of all the scalar special variables. We have listed corresponding english like names along with the symbolic names.
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": 2434,
"s": 2220,
"text": "There are some variables which have a predefined and special meaning in Perl. They are the variables that use punctuation characters after the usual variable indicator ($, @, or %), such as $_ ( explained below )."
},
{
"code": null,
"e": 2765,
"s": 2434,
"text": "Most of the special variables have an english like long name, e.g., Operating System Error variable $! can be written as $OS_ERROR. But if you are going to use english like names, then you would have to put one line use English; at the top of your program file. This guides the interpreter to pickup exact meaning of the variable."
},
{
"code": null,
"e": 2913,
"s": 2765,
"text": "The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines −"
},
{
"code": null,
"e": 2998,
"s": 2913,
"text": "#!/usr/bin/perl\n\nforeach ('hickory','dickory','doc') {\n print $_;\n print \"\\n\";\n}"
},
{
"code": null,
"e": 3054,
"s": 2998,
"text": "When executed, this will produce the following result −"
},
{
"code": null,
"e": 3075,
"s": 3054,
"text": "hickory\ndickory\ndoc\n"
},
{
"code": null,
"e": 3150,
"s": 3075,
"text": "Again, let's check the same example without using $_ variable explicitly −"
},
{
"code": null,
"e": 3232,
"s": 3150,
"text": "#!/usr/bin/perl\n\nforeach ('hickory','dickory','doc') {\n print;\n print \"\\n\";\n}"
},
{
"code": null,
"e": 3293,
"s": 3232,
"text": "When executed, this will also produce the following result −"
},
{
"code": null,
"e": 3314,
"s": 3293,
"text": "hickory\ndickory\ndoc\n"
},
{
"code": null,
"e": 3649,
"s": 3314,
"text": "The first time the loop is executed, \"hickory\" is printed. The second time around, \"dickory\" is printed, and the third time, \"doc\" is printed. That's because in each iteration of the loop, the current string is placed in $_, and is used by default by print. Here are the places where Perl will assume $_ even if you don't specify it −"
},
{
"code": null,
"e": 3791,
"s": 3649,
"text": "Various unary functions, including functions like ord and int, as well as the all file tests (-f, -d) except for -t, which defaults to STDIN."
},
{
"code": null,
"e": 3933,
"s": 3791,
"text": "Various unary functions, including functions like ord and int, as well as the all file tests (-f, -d) except for -t, which defaults to STDIN."
},
{
"code": null,
"e": 3979,
"s": 3933,
"text": "Various list functions like print and unlink."
},
{
"code": null,
"e": 4025,
"s": 3979,
"text": "Various list functions like print and unlink."
},
{
"code": null,
"e": 4112,
"s": 4025,
"text": "The pattern-matching operations m//, s///, and tr/// when used without an =~ operator."
},
{
"code": null,
"e": 4199,
"s": 4112,
"text": "The pattern-matching operations m//, s///, and tr/// when used without an =~ operator."
},
{
"code": null,
"e": 4281,
"s": 4199,
"text": "The default iterator variable in a foreach loop if no other variable is supplied."
},
{
"code": null,
"e": 4363,
"s": 4281,
"text": "The default iterator variable in a foreach loop if no other variable is supplied."
},
{
"code": null,
"e": 4425,
"s": 4363,
"text": "The implicit iterator variable in the grep and map functions."
},
{
"code": null,
"e": 4487,
"s": 4425,
"text": "The implicit iterator variable in the grep and map functions."
},
{
"code": null,
"e": 4690,
"s": 4487,
"text": "The default place to put an input record when a line-input operation's result is tested by itself as the sole criterion of a while test (i.e., ). Note that outside of a while test, this will not happen."
},
{
"code": null,
"e": 4893,
"s": 4690,
"text": "The default place to put an input record when a line-input operation's result is tested by itself as the sole criterion of a while test (i.e., ). Note that outside of a while test, this will not happen."
},
{
"code": null,
"e": 4998,
"s": 4893,
"text": "Based on the usage and nature of special variables, we can categorize them in the following categories −"
},
{
"code": null,
"e": 5031,
"s": 4998,
"text": "Global Scalar Special Variables."
},
{
"code": null,
"e": 5063,
"s": 5031,
"text": "Global Array Special Variables."
},
{
"code": null,
"e": 5094,
"s": 5063,
"text": "Global Hash Special Variables."
},
{
"code": null,
"e": 5122,
"s": 5094,
"text": "Global Special Filehandles."
},
{
"code": null,
"e": 5148,
"s": 5122,
"text": "Global Special Constants."
},
{
"code": null,
"e": 5186,
"s": 5148,
"text": "Regular Expression Special Variables."
},
{
"code": null,
"e": 5216,
"s": 5186,
"text": "Filehandle Special Variables."
},
{
"code": null,
"e": 5349,
"s": 5216,
"text": "Here is the list of all the scalar special variables. We have listed corresponding english like names along with the symbolic names."
},
{
"code": null,
"e": 5384,
"s": 5349,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5398,
"s": 5384,
"text": " Devi Killada"
},
{
"code": null,
"e": 5433,
"s": 5398,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5453,
"s": 5433,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 5486,
"s": 5453,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5502,
"s": 5486,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 5535,
"s": 5502,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5552,
"s": 5535,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 5585,
"s": 5552,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5608,
"s": 5585,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 5643,
"s": 5608,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5666,
"s": 5643,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 5673,
"s": 5666,
"text": " Print"
},
{
"code": null,
"e": 5684,
"s": 5673,
"text": " Add Notes"
}
] |
WebGL - Html5 Canvas Overview | To create graphical applications on the web, HTML-5 provides a rich set of features such as 2D Canvas, WebGL, SVG, 3D CSS transforms, and SMIL. To write WebGL applications, we use the existing canvas element of HTML-5. This chapter provides an overview of the HTML-5 2D canvas element.
HTML-5 <canvas> provides an easy and powerful option to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions, or do simple (and not so simple) animations.
Here is a simple <canvas> element having only two specific attributes width and height plus all the core HTML-5 attributes like id, name, and class.
The syntax of HTML canvas tag is given below. You have to mention the name of the canvas inside double quotations (“ ”).
<canvas id = "mycanvas" width = "100" height = "100"></canvas>
The canvas tag has three attributes namely, id, width, and height.
Id − Id represents the identifier of the canvas element in the Document Object Model (DOM).
Id − Id represents the identifier of the canvas element in the Document Object Model (DOM).
Width − Width represents the width of the canvas.
Width − Width represents the width of the canvas.
Height − Height represents the height of the canvas.
Height − Height represents the height of the canvas.
These attributes determine the size of the canvas. If a programmer is not specifying them under the canvas tag, then browsers such as Firefox, Chrome, and Web Kit, by default, provide a canvas element of size 300 × 150.
The following code shows how to create a canvas. We have used CSS to give a colored border to the canvas.
<html>
<head>
<style>
#mycanvas{border:1px solid red;}
</style>
</head>
<body>
<canvas id = "mycanvas" width = "100" height = "100"></canvas>
</body>
</html>
On executing, the above code will produce the following output −
The <canvas> is initially blank. To display something on the canvas element, we have to use a scripting language. This scripting language should access the rendering context and draw on it.
The canvas element has a DOM method called getContext(), which is used to obtain the rendering context and its drawing functions. This method takes one parameter, the type of context 2d.
The following code is to be written to get the required context. You can write this script inside the body tag as shown below.
<!DOCTYPE HTML>
<html>
<body>
<canvas id = "mycanvas" width = "600" height = "200"></canvas>
<script>
var canvas = document.getElementById('mycanvas');
var context = canvas.getContext('2d');
context.font = '20pt Calibri';
context.fillStyle = 'green';
context.fillText('Welcome to Tutorialspoint', 70, 70);
</script>
</body>
</html>
On executing, the above code will produce the following output −
For more example on HTML-5 2D Canvas, check out the following link HTML-5 Canvas.
HTML5 Canvas is also used to write WebGL applications. To create a WebGL rendering context on the canvas element, you should pass the string experimental-webgl, instead of 2d to the canvas.getContext() method. Some browsers support only 'webgl'.
<!DOCTYPE html>
<html>
<canvas id = 'my_canvas'></canvas>
<script>
var canvas = document.getElementById('my_canvas');
var gl = canvas.getContext('experimental-webgl');
gl.clearColor(0.9,0.9,0.8,1);
gl.clear(gl.COLOR_BUFFER_BIT);
</script>
</html>
On executing, the above code will produce the following output −
10 Lectures
1 hours
Frahaan Hussain
28 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2333,
"s": 2047,
"text": "To create graphical applications on the web, HTML-5 provides a rich set of features such as 2D Canvas, WebGL, SVG, 3D CSS transforms, and SMIL. To write WebGL applications, we use the existing canvas element of HTML-5. This chapter provides an overview of the HTML-5 2D canvas element."
},
{
"code": null,
"e": 2522,
"s": 2333,
"text": "HTML-5 <canvas> provides an easy and powerful option to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions, or do simple (and not so simple) animations."
},
{
"code": null,
"e": 2671,
"s": 2522,
"text": "Here is a simple <canvas> element having only two specific attributes width and height plus all the core HTML-5 attributes like id, name, and class."
},
{
"code": null,
"e": 2792,
"s": 2671,
"text": "The syntax of HTML canvas tag is given below. You have to mention the name of the canvas inside double quotations (“ ”)."
},
{
"code": null,
"e": 2856,
"s": 2792,
"text": "<canvas id = \"mycanvas\" width = \"100\" height = \"100\"></canvas>\n"
},
{
"code": null,
"e": 2923,
"s": 2856,
"text": "The canvas tag has three attributes namely, id, width, and height."
},
{
"code": null,
"e": 3015,
"s": 2923,
"text": "Id − Id represents the identifier of the canvas element in the Document Object Model (DOM)."
},
{
"code": null,
"e": 3107,
"s": 3015,
"text": "Id − Id represents the identifier of the canvas element in the Document Object Model (DOM)."
},
{
"code": null,
"e": 3157,
"s": 3107,
"text": "Width − Width represents the width of the canvas."
},
{
"code": null,
"e": 3207,
"s": 3157,
"text": "Width − Width represents the width of the canvas."
},
{
"code": null,
"e": 3260,
"s": 3207,
"text": "Height − Height represents the height of the canvas."
},
{
"code": null,
"e": 3313,
"s": 3260,
"text": "Height − Height represents the height of the canvas."
},
{
"code": null,
"e": 3533,
"s": 3313,
"text": "These attributes determine the size of the canvas. If a programmer is not specifying them under the canvas tag, then browsers such as Firefox, Chrome, and Web Kit, by default, provide a canvas element of size 300 × 150."
},
{
"code": null,
"e": 3639,
"s": 3533,
"text": "The following code shows how to create a canvas. We have used CSS to give a colored border to the canvas."
},
{
"code": null,
"e": 3836,
"s": 3639,
"text": "<html>\n <head>\n <style>\n #mycanvas{border:1px solid red;}\n </style>\n </head>\n <body>\n <canvas id = \"mycanvas\" width = \"100\" height = \"100\"></canvas>\n </body>\n</html>"
},
{
"code": null,
"e": 3901,
"s": 3836,
"text": "On executing, the above code will produce the following output −"
},
{
"code": null,
"e": 4091,
"s": 3901,
"text": "The <canvas> is initially blank. To display something on the canvas element, we have to use a scripting language. This scripting language should access the rendering context and draw on it."
},
{
"code": null,
"e": 4278,
"s": 4091,
"text": "The canvas element has a DOM method called getContext(), which is used to obtain the rendering context and its drawing functions. This method takes one parameter, the type of context 2d."
},
{
"code": null,
"e": 4405,
"s": 4278,
"text": "The following code is to be written to get the required context. You can write this script inside the body tag as shown below."
},
{
"code": null,
"e": 4811,
"s": 4405,
"text": "<!DOCTYPE HTML>\n<html>\n <body>\n <canvas id = \"mycanvas\" width = \"600\" height = \"200\"></canvas>\n\n <script>\n var canvas = document.getElementById('mycanvas');\n var context = canvas.getContext('2d');\n\t\t\t\n context.font = '20pt Calibri';\n context.fillStyle = 'green';\n context.fillText('Welcome to Tutorialspoint', 70, 70);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4876,
"s": 4811,
"text": "On executing, the above code will produce the following output −"
},
{
"code": null,
"e": 4958,
"s": 4876,
"text": "For more example on HTML-5 2D Canvas, check out the following link HTML-5 Canvas."
},
{
"code": null,
"e": 5204,
"s": 4958,
"text": "HTML5 Canvas is also used to write WebGL applications. To create a WebGL rendering context on the canvas element, you should pass the string experimental-webgl, instead of 2d to the canvas.getContext() method. Some browsers support only 'webgl'."
},
{
"code": null,
"e": 5486,
"s": 5204,
"text": "<!DOCTYPE html>\n<html>\n <canvas id = 'my_canvas'></canvas>\n\t\n <script>\n var canvas = document.getElementById('my_canvas');\n var gl = canvas.getContext('experimental-webgl');\n gl.clearColor(0.9,0.9,0.8,1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n </script>\n</html>"
},
{
"code": null,
"e": 5551,
"s": 5486,
"text": "On executing, the above code will produce the following output −"
},
{
"code": null,
"e": 5584,
"s": 5551,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5601,
"s": 5584,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5634,
"s": 5601,
"text": "\n 28 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5651,
"s": 5634,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5658,
"s": 5651,
"text": " Print"
},
{
"code": null,
"e": 5669,
"s": 5658,
"text": " Add Notes"
}
] |
Hosting your ML model on AWS Lambdas + API Gateway Part 1 | by Evan Miller | Towards Data Science | But now someone wants to use your model. That’s great news ain’t it?
It definitely is, but a whole new problem comes up. You’ve gotta put it somewhere and make it available to other people in the business.
I’ll show you how to do it easily and cheaply on AWS.
For my other articles on Model Deployment check out the link above the title.
This tutorial series will show you how to use AWS to do this. In specific we’ll be using the following components:
S3 buckets
Lambda functions
Lambda layers
API gateway (coming in part 2)
I’m not using Sagemaker because it can be quite expensive £100 p/m per model opposed to lambda functions where you just pay per request.
That can result in lambdas being 1/5th to 1/10th of the cost of running the same models on Sagemaker, especially if you’ve got a few models going to deployment with low traffic.
You’ll need a few things to complete this. You’ll need an installation of Python (scikit learn, pandas etc) and Docker installed. Docker will be needed to build the correct lambda layer files if you are on a Windows machine (I learned this the hard way).
So you’ll need a model first. I’m going to build my model off the UK house price dataset on Kaggle(the data can be found here and my code here).
Lambdas are small runtimes that do very specific tasks. They can take awhile to configure but they are fully managed by AWS so all you need to configure is the memory of your lambda.
They can have installations of Python on them but they won’t have the packages installed to run the model out of the box. To enable that functionality we need to use lambda layers.
Lambda layers are very similar to Docker images if you’re familiar with them. Each layer inherits the layer above’s functionality. But there’s a few things you’ll need to know about them.
Lambda layers need to be zip files
You can only have five lambda layers for a given lambda function
The lambda layers can’t be bigger than 250MB (in total, unzipped)
For this example we’ll need to use 4 lambda layers
Numpy / scipy layer as we’ll need these packages for later layers (pre-built by AWS)Pandas layer to allow us to use the ColumnTransformer used in our modelSklearn layer to enable use of the scikit-learn libraryModel layer where our model will reside
Numpy / scipy layer as we’ll need these packages for later layers (pre-built by AWS)
Pandas layer to allow us to use the ColumnTransformer used in our model
Sklearn layer to enable use of the scikit-learn library
Model layer where our model will reside
So next I’ll show you how to build your own AWS lambda layer to allow your lambda function to use Pandas
These steps will be the same between both Pandas/scikit-learn layers so we’ll focus on nailing them here and you can repeat the steps for the scikit-learn layer.
Next you’ll need open bash/Powershell and to change directory to the layers/Pandas directory.
Then run this command:
docker run --rm -it -v ${PWD}:/var/task lambci/lambda:build-python3.6 bash
NB: ${PWD} mounts the current working directory to the image in Windows environments in Powershell. If you’re using mac/linux $pwd should work fine.
This simple command does a few things:
Pulls down the docker image for lambci. This docker image emulates the runtime of the Python 3.6 lambda environment and allows us to build the files in the same environment as they will run in (this is hella important for Windows users)
Mounts the current directory as a volume so the docker image can output the lambda build files
Allows us to bash into the docker image directly
Now run the following script to build the python files for your lambda layer in the docker image bash (exactly the same for the sklearn layer too):
pip install -r requirements.txt --no-deps -t python/lib/python3.6/site-packages/
This builds the python required files for using Pandas in your lambda function. The main difference is all your file extensions in the __pycache__ should have .pyc file types. These files are needed to run the code on the lambda linux environment.
Next we need to create a zip file for the code to be used.
Lambda layers need to have a specific folder structure in the zip file:
- python - lib - python3.6 - site-packages - all your python package files will be included in here
So go through and run the code in zip_layers.py which will create zip files that will work as lambda layers.
Next steps are:
Upload your pandas_layer.zip to S3Copy the path of your pandas_lambda.zip file in the S3 bucketSelect Lambda on AWS servicesClick the left hand panel and select layersCreate a new layer
Upload your pandas_layer.zip to S3
Copy the path of your pandas_lambda.zip file in the S3 bucket
Select Lambda on AWS services
Click the left hand panel and select layers
Create a new layer
Viola, you’ve created your first lambda layer! But now we need to test that it works. To do this you’ll need to create a lambda function with a Python 3.6 runtime.
To add lambda layers you’ll need to click the Layers icon in the lambda function template and then click the Add a layer button.
Then you’ll select numpy/scipy from the list of runtime compatible layers and then select your Pandas layer you just built.
But be sure to put the numpy/scipy layer first. Otherwise the pandas layer won’t be able use the numpy dependency from the layer above it.
And don’t forget to click save!!
Next you’ll need to refresh your page and go through and edit the lambda function. Use the following code to test that the Pandas functionality is working as you’d expect:
import jsonimport pandas as pddef lambda_handler(event, context): print((pd.DataFrame(data={'col1': [1, 2, 3, 4]})))
Save your function and click test. You’ll need to create a test case but just give the sample a name as we don’t need it until we build the model layer.
If you see the below output then great success, you’ve got pandas working on your lambda funciton. Woooooo.
Now we’ll need to repeat the above steps to use docker to build the files for us to use sklearn. Repeat the above steps (with the sklearn resources.txt from my github) to create the new sklearn_lambda.zip and upload it to S3.
Now we’ll need to test that the sklearn installation is working on the lambda function. To use this we’ll just update the lambda function code from above to include references to sklearn.
import jsonimport pandas as pdimport sklearndef lambda_handler(event, context): print((pd.DataFrame(data={'col1': [1, 2, 3, 4]}))) print(sklearn.__version__)
If you see that 0.20.3 is added to the output of the lambda then you’ve done very well, almost all of the hard work is done!! Next we’ll add the model to the lambda function so we can start returning model predictions.
From running the build_model.py you’ll have a perfectly formatted zip for using the model on your lambdas.
To add this to your function you‘ll repeat the above steps and get use that zip file (upload the zip to S3, create a new model layer and then add the layer to your lambda function).
To test this we’ll need to do a bit more work. Firstly we’ll need to configure the JSON to allow for inputting the fields needed for the model.
If you didn’t change the basic test case in the lambdas your test JSON will look like this:
{ "key1": "value1", "key2": "value2", "key3": "value3"}
Now you’ll want to update that to work with our required model inputs.
{ "Property Type": "S", "Old/New": "Y", "Duration": "L"}
Once you’ve linked up your model lambda layer to your lambda function you should be ready to go.
Update your lambda function to this code and you’ll be able to return predictions from your model. The lambda function will have taken your model layer and saved your .pkl file to /opt/model_name.pkl in your lambda function.
import jsonimport pandas as pdfrom sklearn.externals import joblibmodel = joblib.load('/opt/house_price_model.pkl')def lambda_handler(event, context): df = pd.DataFrame([event]) # Returning the value from the list result = model.predict(df)[0] return result
And that’s it. If all the steps have worked then you should get a result. I get 164344.6062626412, but it’ll depend on your random seed, number of features etc.
But that’s it. It isn’t too scary, but it can take awhile if you don’t know the ins and outs.
Next I’ll hook this lambda into the API gateway so we can call our model API using the requests package in Python. | [
{
"code": null,
"e": 240,
"s": 171,
"text": "But now someone wants to use your model. That’s great news ain’t it?"
},
{
"code": null,
"e": 377,
"s": 240,
"text": "It definitely is, but a whole new problem comes up. You’ve gotta put it somewhere and make it available to other people in the business."
},
{
"code": null,
"e": 431,
"s": 377,
"text": "I’ll show you how to do it easily and cheaply on AWS."
},
{
"code": null,
"e": 509,
"s": 431,
"text": "For my other articles on Model Deployment check out the link above the title."
},
{
"code": null,
"e": 624,
"s": 509,
"text": "This tutorial series will show you how to use AWS to do this. In specific we’ll be using the following components:"
},
{
"code": null,
"e": 635,
"s": 624,
"text": "S3 buckets"
},
{
"code": null,
"e": 652,
"s": 635,
"text": "Lambda functions"
},
{
"code": null,
"e": 666,
"s": 652,
"text": "Lambda layers"
},
{
"code": null,
"e": 697,
"s": 666,
"text": "API gateway (coming in part 2)"
},
{
"code": null,
"e": 834,
"s": 697,
"text": "I’m not using Sagemaker because it can be quite expensive £100 p/m per model opposed to lambda functions where you just pay per request."
},
{
"code": null,
"e": 1012,
"s": 834,
"text": "That can result in lambdas being 1/5th to 1/10th of the cost of running the same models on Sagemaker, especially if you’ve got a few models going to deployment with low traffic."
},
{
"code": null,
"e": 1267,
"s": 1012,
"text": "You’ll need a few things to complete this. You’ll need an installation of Python (scikit learn, pandas etc) and Docker installed. Docker will be needed to build the correct lambda layer files if you are on a Windows machine (I learned this the hard way)."
},
{
"code": null,
"e": 1412,
"s": 1267,
"text": "So you’ll need a model first. I’m going to build my model off the UK house price dataset on Kaggle(the data can be found here and my code here)."
},
{
"code": null,
"e": 1595,
"s": 1412,
"text": "Lambdas are small runtimes that do very specific tasks. They can take awhile to configure but they are fully managed by AWS so all you need to configure is the memory of your lambda."
},
{
"code": null,
"e": 1776,
"s": 1595,
"text": "They can have installations of Python on them but they won’t have the packages installed to run the model out of the box. To enable that functionality we need to use lambda layers."
},
{
"code": null,
"e": 1964,
"s": 1776,
"text": "Lambda layers are very similar to Docker images if you’re familiar with them. Each layer inherits the layer above’s functionality. But there’s a few things you’ll need to know about them."
},
{
"code": null,
"e": 1999,
"s": 1964,
"text": "Lambda layers need to be zip files"
},
{
"code": null,
"e": 2064,
"s": 1999,
"text": "You can only have five lambda layers for a given lambda function"
},
{
"code": null,
"e": 2130,
"s": 2064,
"text": "The lambda layers can’t be bigger than 250MB (in total, unzipped)"
},
{
"code": null,
"e": 2181,
"s": 2130,
"text": "For this example we’ll need to use 4 lambda layers"
},
{
"code": null,
"e": 2431,
"s": 2181,
"text": "Numpy / scipy layer as we’ll need these packages for later layers (pre-built by AWS)Pandas layer to allow us to use the ColumnTransformer used in our modelSklearn layer to enable use of the scikit-learn libraryModel layer where our model will reside"
},
{
"code": null,
"e": 2516,
"s": 2431,
"text": "Numpy / scipy layer as we’ll need these packages for later layers (pre-built by AWS)"
},
{
"code": null,
"e": 2588,
"s": 2516,
"text": "Pandas layer to allow us to use the ColumnTransformer used in our model"
},
{
"code": null,
"e": 2644,
"s": 2588,
"text": "Sklearn layer to enable use of the scikit-learn library"
},
{
"code": null,
"e": 2684,
"s": 2644,
"text": "Model layer where our model will reside"
},
{
"code": null,
"e": 2789,
"s": 2684,
"text": "So next I’ll show you how to build your own AWS lambda layer to allow your lambda function to use Pandas"
},
{
"code": null,
"e": 2951,
"s": 2789,
"text": "These steps will be the same between both Pandas/scikit-learn layers so we’ll focus on nailing them here and you can repeat the steps for the scikit-learn layer."
},
{
"code": null,
"e": 3045,
"s": 2951,
"text": "Next you’ll need open bash/Powershell and to change directory to the layers/Pandas directory."
},
{
"code": null,
"e": 3068,
"s": 3045,
"text": "Then run this command:"
},
{
"code": null,
"e": 3143,
"s": 3068,
"text": "docker run --rm -it -v ${PWD}:/var/task lambci/lambda:build-python3.6 bash"
},
{
"code": null,
"e": 3292,
"s": 3143,
"text": "NB: ${PWD} mounts the current working directory to the image in Windows environments in Powershell. If you’re using mac/linux $pwd should work fine."
},
{
"code": null,
"e": 3331,
"s": 3292,
"text": "This simple command does a few things:"
},
{
"code": null,
"e": 3568,
"s": 3331,
"text": "Pulls down the docker image for lambci. This docker image emulates the runtime of the Python 3.6 lambda environment and allows us to build the files in the same environment as they will run in (this is hella important for Windows users)"
},
{
"code": null,
"e": 3663,
"s": 3568,
"text": "Mounts the current directory as a volume so the docker image can output the lambda build files"
},
{
"code": null,
"e": 3712,
"s": 3663,
"text": "Allows us to bash into the docker image directly"
},
{
"code": null,
"e": 3860,
"s": 3712,
"text": "Now run the following script to build the python files for your lambda layer in the docker image bash (exactly the same for the sklearn layer too):"
},
{
"code": null,
"e": 3941,
"s": 3860,
"text": "pip install -r requirements.txt --no-deps -t python/lib/python3.6/site-packages/"
},
{
"code": null,
"e": 4189,
"s": 3941,
"text": "This builds the python required files for using Pandas in your lambda function. The main difference is all your file extensions in the __pycache__ should have .pyc file types. These files are needed to run the code on the lambda linux environment."
},
{
"code": null,
"e": 4248,
"s": 4189,
"text": "Next we need to create a zip file for the code to be used."
},
{
"code": null,
"e": 4320,
"s": 4248,
"text": "Lambda layers need to have a specific folder structure in the zip file:"
},
{
"code": null,
"e": 4436,
"s": 4320,
"text": "- python - lib - python3.6 - site-packages - all your python package files will be included in here"
},
{
"code": null,
"e": 4545,
"s": 4436,
"text": "So go through and run the code in zip_layers.py which will create zip files that will work as lambda layers."
},
{
"code": null,
"e": 4561,
"s": 4545,
"text": "Next steps are:"
},
{
"code": null,
"e": 4747,
"s": 4561,
"text": "Upload your pandas_layer.zip to S3Copy the path of your pandas_lambda.zip file in the S3 bucketSelect Lambda on AWS servicesClick the left hand panel and select layersCreate a new layer"
},
{
"code": null,
"e": 4782,
"s": 4747,
"text": "Upload your pandas_layer.zip to S3"
},
{
"code": null,
"e": 4844,
"s": 4782,
"text": "Copy the path of your pandas_lambda.zip file in the S3 bucket"
},
{
"code": null,
"e": 4874,
"s": 4844,
"text": "Select Lambda on AWS services"
},
{
"code": null,
"e": 4918,
"s": 4874,
"text": "Click the left hand panel and select layers"
},
{
"code": null,
"e": 4937,
"s": 4918,
"text": "Create a new layer"
},
{
"code": null,
"e": 5101,
"s": 4937,
"text": "Viola, you’ve created your first lambda layer! But now we need to test that it works. To do this you’ll need to create a lambda function with a Python 3.6 runtime."
},
{
"code": null,
"e": 5230,
"s": 5101,
"text": "To add lambda layers you’ll need to click the Layers icon in the lambda function template and then click the Add a layer button."
},
{
"code": null,
"e": 5354,
"s": 5230,
"text": "Then you’ll select numpy/scipy from the list of runtime compatible layers and then select your Pandas layer you just built."
},
{
"code": null,
"e": 5493,
"s": 5354,
"text": "But be sure to put the numpy/scipy layer first. Otherwise the pandas layer won’t be able use the numpy dependency from the layer above it."
},
{
"code": null,
"e": 5526,
"s": 5493,
"text": "And don’t forget to click save!!"
},
{
"code": null,
"e": 5698,
"s": 5526,
"text": "Next you’ll need to refresh your page and go through and edit the lambda function. Use the following code to test that the Pandas functionality is working as you’d expect:"
},
{
"code": null,
"e": 5822,
"s": 5698,
"text": "import jsonimport pandas as pddef lambda_handler(event, context): print((pd.DataFrame(data={'col1': [1, 2, 3, 4]})))"
},
{
"code": null,
"e": 5975,
"s": 5822,
"text": "Save your function and click test. You’ll need to create a test case but just give the sample a name as we don’t need it until we build the model layer."
},
{
"code": null,
"e": 6083,
"s": 5975,
"text": "If you see the below output then great success, you’ve got pandas working on your lambda funciton. Woooooo."
},
{
"code": null,
"e": 6309,
"s": 6083,
"text": "Now we’ll need to repeat the above steps to use docker to build the files for us to use sklearn. Repeat the above steps (with the sklearn resources.txt from my github) to create the new sklearn_lambda.zip and upload it to S3."
},
{
"code": null,
"e": 6497,
"s": 6309,
"text": "Now we’ll need to test that the sklearn installation is working on the lambda function. To use this we’ll just update the lambda function code from above to include references to sklearn."
},
{
"code": null,
"e": 6665,
"s": 6497,
"text": "import jsonimport pandas as pdimport sklearndef lambda_handler(event, context): print((pd.DataFrame(data={'col1': [1, 2, 3, 4]}))) print(sklearn.__version__)"
},
{
"code": null,
"e": 6884,
"s": 6665,
"text": "If you see that 0.20.3 is added to the output of the lambda then you’ve done very well, almost all of the hard work is done!! Next we’ll add the model to the lambda function so we can start returning model predictions."
},
{
"code": null,
"e": 6991,
"s": 6884,
"text": "From running the build_model.py you’ll have a perfectly formatted zip for using the model on your lambdas."
},
{
"code": null,
"e": 7173,
"s": 6991,
"text": "To add this to your function you‘ll repeat the above steps and get use that zip file (upload the zip to S3, create a new model layer and then add the layer to your lambda function)."
},
{
"code": null,
"e": 7317,
"s": 7173,
"text": "To test this we’ll need to do a bit more work. Firstly we’ll need to configure the JSON to allow for inputting the fields needed for the model."
},
{
"code": null,
"e": 7409,
"s": 7317,
"text": "If you didn’t change the basic test case in the lambdas your test JSON will look like this:"
},
{
"code": null,
"e": 7470,
"s": 7409,
"text": "{ \"key1\": \"value1\", \"key2\": \"value2\", \"key3\": \"value3\"}"
},
{
"code": null,
"e": 7541,
"s": 7470,
"text": "Now you’ll want to update that to work with our required model inputs."
},
{
"code": null,
"e": 7609,
"s": 7541,
"text": "{ \"Property Type\": \"S\", \"Old/New\": \"Y\", \"Duration\": \"L\"}"
},
{
"code": null,
"e": 7706,
"s": 7609,
"text": "Once you’ve linked up your model lambda layer to your lambda function you should be ready to go."
},
{
"code": null,
"e": 7931,
"s": 7706,
"text": "Update your lambda function to this code and you’ll be able to return predictions from your model. The lambda function will have taken your model layer and saved your .pkl file to /opt/model_name.pkl in your lambda function."
},
{
"code": null,
"e": 8218,
"s": 7931,
"text": "import jsonimport pandas as pdfrom sklearn.externals import joblibmodel = joblib.load('/opt/house_price_model.pkl')def lambda_handler(event, context): df = pd.DataFrame([event]) # Returning the value from the list result = model.predict(df)[0] return result"
},
{
"code": null,
"e": 8379,
"s": 8218,
"text": "And that’s it. If all the steps have worked then you should get a result. I get 164344.6062626412, but it’ll depend on your random seed, number of features etc."
},
{
"code": null,
"e": 8473,
"s": 8379,
"text": "But that’s it. It isn’t too scary, but it can take awhile if you don’t know the ins and outs."
}
] |
MapStruct - Mapping Direct Fields | MapStruct handles direct fields mapping easily. For example, a Student with section as private property and StudentEntity with section as public property. To have both getter/setter mapping, a property should be public. In case of public final, only getter method will be present for mapping.
Now create a mapper interface. We'll use @InheritInverseConfiguration annotation to copy reverse configuration now.
@Mapper
public interface StudentMapper {
@Mapping(target="className", source="classVal")
@Mapping(target="subject", source="subject.name")
Student getModelFromEntity(StudentEntity studentEntity);
@InheritInverseConfiguration
StudentEntity getEntityFromModel(Student student);
}
Open project mapping as updated in Mapping Nested Objects chapter in Eclipse.
Update StudentEntity.java with following code −
StudentEntity.java
package com.tutorialspoint.entity;
public class StudentEntity {
private int id;
private String name;
private String classVal;
private SubjectEntity subject;
public String section;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassVal() {
return classVal;
}
public void setClassVal(String classVal) {
this.classVal = classVal;
}
public SubjectEntity getSubject() {
return subject;
}
public void setSubject(SubjectEntity subject) {
this.subject = subject;
}
}
Update Student.java with following code −
Student.java
package com.tutorialspoint.model;
public class Student {
private int id;
private String name;
private String className;
private String subject;
private String section;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
}
Update StudentMapper.java with following code −
StudentMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.model.Student;
@Mapper
public interface StudentMapper {
@Mapping(target="className", source="classVal")
@Mapping(target="subject", source="subject.name")
Student getModelFromEntity(StudentEntity studentEntity);
@InheritInverseConfiguration
StudentEntity getEntityFromModel(Student student);
}
Update StudentMapperTest.java with following code −
StudentMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.entity.SubjectEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;
public class StudentMapperTest {
private StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);
@Test
public void testEntityToModel() {
StudentEntity entity = new StudentEntity();
entity.setClassVal("X");
entity.setName("John");
entity.setId(1);
entity.section = "A";
SubjectEntity subject = new SubjectEntity();
subject.setName("Computer");
entity.setSubject(subject);
Student model = studentMapper.getModelFromEntity(entity);
assertEquals(entity.getClassVal(), model.getClassName());
assertEquals(entity.getName(), model.getName());
assertEquals(entity.getId(), model.getId());
assertEquals(entity.getSubject().getName(), model.getSubject());
assertEquals(entity.section, model.getSection());
}
@Test
public void testModelToEntity() {
Student model = new Student();
model.setId(1);
model.setName("John");
model.setClassName("X");
model.setSubject("Science");
model.setSection("A");
StudentEntity entity = studentMapper.getEntityFromModel(model);
assertEquals(entity.getClassVal(), model.getClassName());
assertEquals(entity.getName(), model.getName());
assertEquals(entity.getId(), model.getId());
assertEquals(entity.getSubject().getName(), model.getSubject());
assertEquals(entity.section, model.getSection());
}
}
Run the following command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec
Results :
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
...
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2553,
"s": 2260,
"text": "MapStruct handles direct fields mapping easily. For example, a Student with section as private property and StudentEntity with section as public property. To have both getter/setter mapping, a property should be public. In case of public final, only getter method will be present for mapping."
},
{
"code": null,
"e": 2669,
"s": 2553,
"text": "Now create a mapper interface. We'll use @InheritInverseConfiguration annotation to copy reverse configuration now."
},
{
"code": null,
"e": 2964,
"s": 2669,
"text": "@Mapper\npublic interface StudentMapper {\n @Mapping(target=\"className\", source=\"classVal\")\n @Mapping(target=\"subject\", source=\"subject.name\")\n Student getModelFromEntity(StudentEntity studentEntity);\n\t\n @InheritInverseConfiguration\n StudentEntity getEntityFromModel(Student student);\n}"
},
{
"code": null,
"e": 3042,
"s": 2964,
"text": "Open project mapping as updated in Mapping Nested Objects chapter in Eclipse."
},
{
"code": null,
"e": 3090,
"s": 3042,
"text": "Update StudentEntity.java with following code −"
},
{
"code": null,
"e": 3109,
"s": 3090,
"text": "StudentEntity.java"
},
{
"code": null,
"e": 3825,
"s": 3109,
"text": "package com.tutorialspoint.entity;\n\npublic class StudentEntity {\n private int id;\n private String name;\n private String classVal;\n private SubjectEntity subject;\n public String section;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassVal() {\n return classVal;\n }\n public void setClassVal(String classVal) {\n this.classVal = classVal;\n }\n public SubjectEntity getSubject() {\n return subject;\n }\n public void setSubject(SubjectEntity subject) {\n this.subject = subject;\n }\n}"
},
{
"code": null,
"e": 3867,
"s": 3825,
"text": "Update Student.java with following code −"
},
{
"code": null,
"e": 3880,
"s": 3867,
"text": "Student.java"
},
{
"code": null,
"e": 4714,
"s": 3880,
"text": "package com.tutorialspoint.model;\n\npublic class Student {\n private int id;\n private String name;\n private String className;\n private String subject;\n private String section;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassName() {\n return className;\n }\n public void setClassName(String className) {\n this.className = className;\n }\n public String getSubject() {\n return subject;\n }\n public void setSubject(String subject) {\n this.subject = subject;\n }\n public String getSection() {\n return section;\n }\n public void setSection(String section) {\n this.section = section;\n }\n}"
},
{
"code": null,
"e": 4762,
"s": 4714,
"text": "Update StudentMapper.java with following code −"
},
{
"code": null,
"e": 4781,
"s": 4762,
"text": "StudentMapper.java"
},
{
"code": null,
"e": 5310,
"s": 4781,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.InheritInverseConfiguration;\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.model.Student;\n\n@Mapper\npublic interface StudentMapper {\n @Mapping(target=\"className\", source=\"classVal\")\n @Mapping(target=\"subject\", source=\"subject.name\")\n Student getModelFromEntity(StudentEntity studentEntity);\n\n @InheritInverseConfiguration\n StudentEntity getEntityFromModel(Student student);\n}"
},
{
"code": null,
"e": 5362,
"s": 5310,
"text": "Update StudentMapperTest.java with following code −"
},
{
"code": null,
"e": 5385,
"s": 5362,
"text": "StudentMapperTest.java"
},
{
"code": null,
"e": 7157,
"s": 5385,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.entity.SubjectEntity;\nimport com.tutorialspoint.mapper.StudentMapper;\nimport com.tutorialspoint.model.Student;\n\npublic class StudentMapperTest {\n private StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);\n @Test\n public void testEntityToModel() {\n StudentEntity entity = new StudentEntity();\n entity.setClassVal(\"X\");\n entity.setName(\"John\");\n entity.setId(1);\n entity.section = \"A\";\n SubjectEntity subject = new SubjectEntity();\n subject.setName(\"Computer\");\n entity.setSubject(subject);\n Student model = studentMapper.getModelFromEntity(entity);\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n assertEquals(entity.getSubject().getName(), model.getSubject());\n assertEquals(entity.section, model.getSection());\t \n }\n @Test\n public void testModelToEntity() {\n Student model = new Student();\n model.setId(1);\n model.setName(\"John\");\n model.setClassName(\"X\");\n model.setSubject(\"Science\");\n model.setSection(\"A\");\n StudentEntity entity = studentMapper.getEntityFromModel(model);\n\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n assertEquals(entity.getSubject().getName(), model.getSubject());\n assertEquals(entity.section, model.getSection());\n }\n}"
},
{
"code": null,
"e": 7205,
"s": 7157,
"text": "Run the following command to test the mappings."
},
{
"code": null,
"e": 7221,
"s": 7205,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 7268,
"s": 7221,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 7916,
"s": 7268,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec\n\nResults :\n\nTests run: 3, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 7923,
"s": 7916,
"text": " Print"
},
{
"code": null,
"e": 7934,
"s": 7923,
"text": " Add Notes"
}
] |
C++ STL | Set 4 (stack) | Practice | GeeksforGeeks | Implement different operations on a stack s .
Input:
The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries .
A query can be of four types
1. a x (Pushes an element x to the stack s )
2. b (if stack is not empty pops top element and prints it, else prints -1)
3. c (prints the size of the stack )
4. d (if stack is not empty prints the top element of the stack, else prints -1)
Output:
The output for each test case will be space separated integers denoting the results of each query .
Constraints:
1<=T<=100
1<=Q<=100
Example:
Input
2
5
a 4 a 6 a 7 b c
3
a 55 a 11 d
Output
7 2
11
Explanation :
For the first test case
There are five queries. Queries are performed in this order
1. a 4 { stack s has 4 }
2. a 7 {stack s has 4,7 }
3. a 6 {stack s has 4,7,6}
4. b {pop 6 from stack s and prints it stack now has 4,7}
5. c {prints the size of the stack s}
For the sec test case
There are three queries. Queries are performed in this order
1. a 55 (stack s has 55}
2. a 11 (stack s has 55 ,11}
3. d (prints the top element of the stack s ie. 11 )
Note:The Input/Output format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
0
nishasingh005063 months ago
void push(stack<int> &s,int x){ s.push(x);}
/*pops the top element of thestack and returns it */int pop(stack<int> &s){ while(!s.empty()) { int item= s.top(); s.pop(); return item; } return -1;}
/*returns the size of the stack */int getSize(stack<int> &s){ int size= s.size(); return size;}
/*returns the top element of the stack */int getTop(stack<int> &s){ while(!s.empty()) { int t= s.top(); return t; } return -1;}
0
kumarnitesh884414 months ago
void push(stack<int> &s,int x){ //Your code here s.push(x);}
/*pops the top element of thestack and returns it */int pop(stack<int> &s){ //Your code here if(s.size()>0){ int res=s.top(); s.pop(); return res; } return -1;}
/*returns the size of the stack */int getSize(stack<int> &s){ //Your code here return s.size();}
/*returns the top element of the stack */int getTop(stack<int> &s){ //Your code here if(s.size()>0){ return s.top(); } return -1;}
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": 937,
"s": 226,
"text": "Implement different operations on a stack s .\n\nInput:\nThe first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries .\nA query can be of four types \n1. a x (Pushes an element x to the stack s )\n2. b (if stack is not empty pops top element and prints it, else prints -1)\n3. c (prints the size of the stack )\n4. d (if stack is not empty prints the top element of the stack, else prints -1)\n\nOutput:\nThe output for each test case will be space separated integers denoting the results of each query . \n\nConstraints:\n1<=T<=100\n1<=Q<=100\n\nExample:"
},
{
"code": null,
"e": 1781,
"s": 937,
"text": "Input\n2\n5\na 4 a 6 a 7 b c \n3\na 55 a 11 d \n \nOutput\n7 2\n11\n\nExplanation :\nFor the first test case\nThere are five queries. Queries are performed in this order\n1. a 4 { stack s has 4 }\n2. a 7 {stack s has 4,7 }\n3. a 6 {stack s has 4,7,6}\n4. b {pop 6 from stack s and prints it stack now has 4,7}\n5. c {prints the size of the stack s}\n\nFor the sec test case \nThere are three queries. Queries are performed in this order\n1. a 55 (stack s has 55}\n2. a 11 (stack s has 55 ,11}\n3. d (prints the top element of the stack s ie. 11 )\n\n\n\nNote:The Input/Output format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 1783,
"s": 1781,
"text": "0"
},
{
"code": null,
"e": 1811,
"s": 1783,
"text": "nishasingh005063 months ago"
},
{
"code": null,
"e": 1855,
"s": 1811,
"text": "void push(stack<int> &s,int x){ s.push(x);}"
},
{
"code": null,
"e": 2017,
"s": 1855,
"text": "/*pops the top element of thestack and returns it */int pop(stack<int> &s){ while(!s.empty()) { int item= s.top(); s.pop(); return item; } return -1;}"
},
{
"code": null,
"e": 2115,
"s": 2017,
"text": "/*returns the size of the stack */int getSize(stack<int> &s){ int size= s.size(); return size;}"
},
{
"code": null,
"e": 2254,
"s": 2115,
"text": "/*returns the top element of the stack */int getTop(stack<int> &s){ while(!s.empty()) { int t= s.top(); return t; } return -1;}"
},
{
"code": null,
"e": 2256,
"s": 2254,
"text": "0"
},
{
"code": null,
"e": 2285,
"s": 2256,
"text": "kumarnitesh884414 months ago"
},
{
"code": null,
"e": 2353,
"s": 2285,
"text": "void push(stack<int> &s,int x){ //Your code here s.push(x);}"
},
{
"code": null,
"e": 2540,
"s": 2353,
"text": "/*pops the top element of thestack and returns it */int pop(stack<int> &s){ //Your code here if(s.size()>0){ int res=s.top(); s.pop(); return res; } return -1;}"
},
{
"code": null,
"e": 2639,
"s": 2540,
"text": "/*returns the size of the stack */int getSize(stack<int> &s){ //Your code here return s.size();}"
},
{
"code": null,
"e": 2775,
"s": 2639,
"text": "/*returns the top element of the stack */int getTop(stack<int> &s){ //Your code here if(s.size()>0){ return s.top(); } return -1;}"
},
{
"code": null,
"e": 2921,
"s": 2775,
"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": 2957,
"s": 2921,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2967,
"s": 2957,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2977,
"s": 2967,
"text": "\nContest\n"
},
{
"code": null,
"e": 3040,
"s": 2977,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3188,
"s": 3040,
"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": 3396,
"s": 3188,
"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": 3502,
"s": 3396,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.