title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
R-squared Regression Analysis in R Programming - GeeksforGeeks
|
28 Jul, 2020
For the prediction of one variable’s value(dependent variable) through other variables (independent variables) some models are used that are called regression models. For further calculating the accuracy of this prediction another mathematical tool is used, which is R-squared Regression Analysis or the coefficient of determination. The value of R-squared is between 0 and 1. And if the coefficient of determination is 1 (or 100%) means that prediction of the dependent variable has been perfect and accurate.
R-square is a comparison of the residual sum of squares (SSres) with the total sum of squares(SStot). The residual sum of squares is calculated by the summation of squares of perpendicular distance between data points and the best-fitted line.
The total sum of squares is calculated by the summation of squares of perpendicular distance between data points and the average line.
The formula for R-squared Regression Analysis is given as follows,
where,: experimental values of the dependent variable: the average/mean: the fitted value
It is very easy to find out the Coefficient of Determination(R) in the R language. The steps to follow are:
Make a data frame in R.
Calculate the linear regression model and save it in a new variable.
The so calculated new variable’s summary has a coefficient of determination or R-squared parameter that needs to be extracted.
# Creating a data frame of exam marksexam <- data.frame(name = c("ravi", "shaily", "arsh", "monu"), math = c(87, 98, 67, 90), estimated = c(65, 87, 56, 100)) # Printing data frameexam # Calculating the linear regression modelmodel = lm(math~estimated, data = exam) # Extracting R-squared parameter from summarysummary(model)$r.squared
Output:
name math estimated
1 ravi 87 65
2 shaily 98 87
3 arsh 67 56
4 monu 90 100
[1] 0.5672797
Note: If the prediction is accurate the R-squared Regression value generated is 1.
# Creating a data frame of exam marksexam <- data.frame(name = c("ravi", "shaily", "arsh", "monu"), math = c(87, 98, 67, 90), estimated = c(87, 98, 67, 90)) # Printing data frameexam # Calculating the linear regression modelmodel = lm(math~estimated, data = exam) # Extracting R-squared parameter from summarysummary(model)$r.squared
Output:
name math estimated
1 ravi 87 87
2 shaily 98 98
3 arsh 67 67
4 monu 90 90
[1] 1
The value of r-square always increases or remains the same as new variables are added to the model, without detecting the significance of this newly added variable (i.e value of r-square never decreases on the addition of new attributes to the model). As a result, non-significant attributes can also be added to the model with an increase in r-square value.
This is because SStot is always constant and the regression model tries to decrease the value of SSres by finding some correlation with this new attribute and hence the overall value of r-square increases, which can lead to a poor regression model.
Picked
R Data-science
R regression
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Printing Output of an R Program
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
|
[
{
"code": null,
"e": 25971,
"s": 25943,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 26482,
"s": 25971,
"text": "For the prediction of one variable’s value(dependent variable) through other variables (independent variables) some models are used that are called regression models. For further calculating the accuracy of this prediction another mathematical tool is used, which is R-squared Regression Analysis or the coefficient of determination. The value of R-squared is between 0 and 1. And if the coefficient of determination is 1 (or 100%) means that prediction of the dependent variable has been perfect and accurate."
},
{
"code": null,
"e": 26726,
"s": 26482,
"text": "R-square is a comparison of the residual sum of squares (SSres) with the total sum of squares(SStot). The residual sum of squares is calculated by the summation of squares of perpendicular distance between data points and the best-fitted line."
},
{
"code": null,
"e": 26861,
"s": 26726,
"text": "The total sum of squares is calculated by the summation of squares of perpendicular distance between data points and the average line."
},
{
"code": null,
"e": 26928,
"s": 26861,
"text": "The formula for R-squared Regression Analysis is given as follows,"
},
{
"code": null,
"e": 27018,
"s": 26928,
"text": "where,: experimental values of the dependent variable: the average/mean: the fitted value"
},
{
"code": null,
"e": 27126,
"s": 27018,
"text": "It is very easy to find out the Coefficient of Determination(R) in the R language. The steps to follow are:"
},
{
"code": null,
"e": 27150,
"s": 27126,
"text": "Make a data frame in R."
},
{
"code": null,
"e": 27219,
"s": 27150,
"text": "Calculate the linear regression model and save it in a new variable."
},
{
"code": null,
"e": 27346,
"s": 27219,
"text": "The so calculated new variable’s summary has a coefficient of determination or R-squared parameter that needs to be extracted."
},
{
"code": "# Creating a data frame of exam marksexam <- data.frame(name = c(\"ravi\", \"shaily\", \"arsh\", \"monu\"), math = c(87, 98, 67, 90), estimated = c(65, 87, 56, 100)) # Printing data frameexam # Calculating the linear regression modelmodel = lm(math~estimated, data = exam) # Extracting R-squared parameter from summarysummary(model)$r.squared",
"e": 27748,
"s": 27346,
"text": null
},
{
"code": null,
"e": 27756,
"s": 27748,
"text": "Output:"
},
{
"code": null,
"e": 27896,
"s": 27756,
"text": " name math estimated\n1 ravi 87 65\n2 shaily 98 87\n3 arsh 67 56\n4 monu 90 100\n\n[1] 0.5672797\n"
},
{
"code": null,
"e": 27979,
"s": 27896,
"text": "Note: If the prediction is accurate the R-squared Regression value generated is 1."
},
{
"code": "# Creating a data frame of exam marksexam <- data.frame(name = c(\"ravi\", \"shaily\", \"arsh\", \"monu\"), math = c(87, 98, 67, 90), estimated = c(87, 98, 67, 90)) # Printing data frameexam # Calculating the linear regression modelmodel = lm(math~estimated, data = exam) # Extracting R-squared parameter from summarysummary(model)$r.squared",
"e": 28381,
"s": 27979,
"text": null
},
{
"code": null,
"e": 28389,
"s": 28381,
"text": "Output:"
},
{
"code": null,
"e": 28520,
"s": 28389,
"text": " name math estimated\n1 ravi 87 87\n2 shaily 98 98\n3 arsh 67 67\n4 monu 90 90\n\n[1] 1\n"
},
{
"code": null,
"e": 28879,
"s": 28520,
"text": "The value of r-square always increases or remains the same as new variables are added to the model, without detecting the significance of this newly added variable (i.e value of r-square never decreases on the addition of new attributes to the model). As a result, non-significant attributes can also be added to the model with an increase in r-square value."
},
{
"code": null,
"e": 29128,
"s": 28879,
"text": "This is because SStot is always constant and the regression model tries to decrease the value of SSres by finding some correlation with this new attribute and hence the overall value of r-square increases, which can lead to a poor regression model."
},
{
"code": null,
"e": 29135,
"s": 29128,
"text": "Picked"
},
{
"code": null,
"e": 29150,
"s": 29135,
"text": "R Data-science"
},
{
"code": null,
"e": 29163,
"s": 29150,
"text": "R regression"
},
{
"code": null,
"e": 29174,
"s": 29163,
"text": "R Language"
},
{
"code": null,
"e": 29272,
"s": 29174,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29330,
"s": 29272,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 29382,
"s": 29330,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 29414,
"s": 29382,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 29466,
"s": 29414,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29510,
"s": 29466,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 29545,
"s": 29510,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29583,
"s": 29545,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29615,
"s": 29583,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 29673,
"s": 29615,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
Sum of internal angles of a Polygon - GeeksforGeeks
|
08 Mar, 2022
Given an integer N, the task is to find the sum of interior angles of an N-sided polygon. A plane figure having a minimum of three sides and angles is called a polygon.Examples:
Input: N = 3 Output: 180 3-sided polygon is a triangle and the sum of the interior angles of a triangle is 180.Input: N = 6 Output: 720
Approach: The sum of internal angles of a polygon with N sides is given by (N – 2) * 180Below is the implementation of the above approach:
C++
Java
C#
Python
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of internal// angles of an n-sided polygonint sumOfInternalAngles(int n){ if (n < 3) return 0; return (n - 2) * 180;} // Driver codeint main(){ int n = 5; cout << sumOfInternalAngles(n); return 0;}
// Java implementation of the approachclass GFG { // Function to return the sum of internal // angles of an n-sided polygon static int sumOfInternalAngles(int n) { if (n < 3) return 0; return ((n - 2) * 180); } // Driver code public static void main(String args[]) { int n = 5; System.out.print(sumOfInternalAngles(n)); }}
// C# implementation of the approachusing System;class GFG { // Function to return the sum of internal // angles of an n-sided polygon static int sumOfInternalAngles(int n) { if (n < 3) return 0; return ((n - 2) * 180); } // Driver code public static void Main() { int n = 5; Console.Write(sumOfInternalAngles(n)); }}
# Python3 implementation of the approach # Function to return the sum of internal# angles of an n-sided polygondef sumOfInternalAngles(n): if(n < 3): return 0 return ((n - 2) * 180) # Driver coden = 5print(sumOfInternalAngles(n))
<?php// PHP implementation of the approach // Function to return the sum of internal// angles of an n-sided polygonfunction sumOfInternalAngles($n){ if($n < 3) return 0; return (($n - 2) * 180);} // Driver code$n = 5;echo(sumOfInternalAngles($n));?>
<script> // JavaScript implementation of the approach // Function to return the sum of internal// angles of an n-sided polygonfunction sumOfInternalAngles(n){ if (n < 3) return 0; return (n - 2) * 180;} // Driver code let n = 5; document.write(sumOfInternalAngles(n)); // This code is contributed by Mayank Tyagi </script>
540
Time Complexity: O(1)
Auxiliary Space: O(1)
mayanktyagi1709
subhammahato348
Geometric
Mathematical
Technical Scripter
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Convex Hull | Set 2 (Graham Scan)
Optimum location of point to minimize total distance
Program for Fibonacci numbers
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
C++ Data Types
Coin Change | DP-7
|
[
{
"code": null,
"e": 26417,
"s": 26389,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 26597,
"s": 26417,
"text": "Given an integer N, the task is to find the sum of interior angles of an N-sided polygon. A plane figure having a minimum of three sides and angles is called a polygon.Examples: "
},
{
"code": null,
"e": 26735,
"s": 26597,
"text": "Input: N = 3 Output: 180 3-sided polygon is a triangle and the sum of the interior angles of a triangle is 180.Input: N = 6 Output: 720 "
},
{
"code": null,
"e": 26877,
"s": 26737,
"text": "Approach: The sum of internal angles of a polygon with N sides is given by (N – 2) * 180Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26881,
"s": 26877,
"text": "C++"
},
{
"code": null,
"e": 26886,
"s": 26881,
"text": "Java"
},
{
"code": null,
"e": 26889,
"s": 26886,
"text": "C#"
},
{
"code": null,
"e": 26896,
"s": 26889,
"text": "Python"
},
{
"code": null,
"e": 26900,
"s": 26896,
"text": "PHP"
},
{
"code": null,
"e": 26911,
"s": 26900,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of internal// angles of an n-sided polygonint sumOfInternalAngles(int n){ if (n < 3) return 0; return (n - 2) * 180;} // Driver codeint main(){ int n = 5; cout << sumOfInternalAngles(n); return 0;}",
"e": 27245,
"s": 26911,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to return the sum of internal // angles of an n-sided polygon static int sumOfInternalAngles(int n) { if (n < 3) return 0; return ((n - 2) * 180); } // Driver code public static void main(String args[]) { int n = 5; System.out.print(sumOfInternalAngles(n)); }}",
"e": 27637,
"s": 27245,
"text": null
},
{
"code": "// C# implementation of the approachusing System;class GFG { // Function to return the sum of internal // angles of an n-sided polygon static int sumOfInternalAngles(int n) { if (n < 3) return 0; return ((n - 2) * 180); } // Driver code public static void Main() { int n = 5; Console.Write(sumOfInternalAngles(n)); }}",
"e": 28024,
"s": 27637,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the sum of internal# angles of an n-sided polygondef sumOfInternalAngles(n): if(n < 3): return 0 return ((n - 2) * 180) # Driver coden = 5print(sumOfInternalAngles(n))",
"e": 28267,
"s": 28024,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the sum of internal// angles of an n-sided polygonfunction sumOfInternalAngles($n){ if($n < 3) return 0; return (($n - 2) * 180);} // Driver code$n = 5;echo(sumOfInternalAngles($n));?>",
"e": 28530,
"s": 28267,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return the sum of internal// angles of an n-sided polygonfunction sumOfInternalAngles(n){ if (n < 3) return 0; return (n - 2) * 180;} // Driver code let n = 5; document.write(sumOfInternalAngles(n)); // This code is contributed by Mayank Tyagi </script>",
"e": 28875,
"s": 28530,
"text": null
},
{
"code": null,
"e": 28879,
"s": 28875,
"text": "540"
},
{
"code": null,
"e": 28903,
"s": 28881,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 28925,
"s": 28903,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28941,
"s": 28925,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 28957,
"s": 28941,
"text": "subhammahato348"
},
{
"code": null,
"e": 28967,
"s": 28957,
"text": "Geometric"
},
{
"code": null,
"e": 28980,
"s": 28967,
"text": "Mathematical"
},
{
"code": null,
"e": 28999,
"s": 28980,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29012,
"s": 28999,
"text": "Mathematical"
},
{
"code": null,
"e": 29022,
"s": 29012,
"text": "Geometric"
},
{
"code": null,
"e": 29120,
"s": 29022,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29169,
"s": 29120,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 29222,
"s": 29169,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 29273,
"s": 29222,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 29307,
"s": 29273,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 29360,
"s": 29307,
"text": "Optimum location of point to minimize total distance"
},
{
"code": null,
"e": 29390,
"s": 29360,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 29450,
"s": 29390,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 29493,
"s": 29450,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29508,
"s": 29493,
"text": "C++ Data Types"
}
] |
PHP Interview Questions and Answers - GeeksforGeeks
|
26 Apr, 2022
What is PHP ?PHP is the general-purpose programming language used to design a website or web application. It is server-side scripting language embedded with HTML to develop a Static website, Dynamic website or Web applications. It was created by Rasmus Lerdorf in 1994. What is the full form of PHP ?PHP is the abbreviation of Hypertext Preprocessor and earlier it was abbreviated as Personal Home Page. What was the old name of PHP ?The old name of PHP was Personal Home Page. What are the uses of PHP ?It is a server-side scripting language used to design dynamic websites or web applications.It receives data from forms to generate the dynamic page content.It can work with databases, sessions, send and receive cookies, send emails, etc.It can be used to add, delete, modify content within the database.It can be used to set the restriction to the user to access the web page. What is PEAR in PHP ?PEAR is a framework and distribution system for reusable PHP components. It stands for PHP Extension and Application Repository. It contains PHP snippets and a library to reuse the code. It provides a command-line interface to install packages. What is the difference between static and dynamic websites ?Static Website: The web pages are returned from the server which are prebuilt source code files built using simple languages such as HTML, CSS or JavaScript. There is no processing of content on the server in Static Websites.Dynamic Website: The web pages are returned from the server which is processed during runtime means they are not prebuilt web pages but they are built during runtime according to the user’s demand with the help of server-side scripting languages such as PHP, Node.js, ASP.NET and many more supported by the server. What is the correct and the two most common ways to start and finish a PHP block of code ?The PHP code always starts with <?php and ends with ?>. The block of PHP code are:<?php [ --Content of PHP code-- ] ?> How to execute a PHP script from the command line?Use the following steps to run PHP program using command line:Open terminal or command line window.Go to the specified folder or directory where PHP files are present.Then we can run PHP code using the command php file_name.phpStart the server for testing the php code using the command php -S localhost:port -t your_folder/ How to display text with a PHP script ?There are two methods echo and print to display the text. Is PHP a case sensitive language ?No, PHP is a partially case sensitive language. It means the variable names are case-sensitive and the function names are not case sensitive i.e. user-defined functions are not case sensitive. What is the main difference between PHP 4 and PHP 5 ?PHP 5 contains many additional OOP (object-oriented programming) features. What are the rules for naming a PHP variable ?Variables in a program are used to store some values or data that can be used later in a program. PHP has its own way of declaring and storing variables. The characteristics of the variables are listed below:A variable declared in PHP must begin with a dollar sign ($), followed by the variable name.A variable name contains alphanumeric characters and underscores (i.e. ‘a-z’, ‘A-Z’, ‘0-9’ and ‘_’) in their name.The variable name must start with a letter or underscore, not a number.PHP is a loosely typed language and we do not require to declare the data types of variables, rather PHP assumes it automatically by analyzing the values.PHP variables are case-sensitive i.e. $sum and $SUM are treated differently. How do you define a constant in PHP ?The define() function is used to create and retrieve the value of a constant. A PHP constant is an identifier whose value can not be change over the time (such as the domain name of a website eg. www.geeksforgeeks.org). If you have defined a constant, it can never be changed or undefined. The $ symbol is not used with a constant. What are the popular Content Management Systems (CMS) in PHP ?WordPress: WordPress is a free and open-source Content Management System(CMS) framework. It is the most widely used CMS framework of recent time.Joomla: It is a free and open-source content management system (CMS) for distributing web content. It follows the model-view-controller web application framework that can be used independently.Magento: It is an open-source and e-commerce platform to develop online business.Drupal: It is a content management system (CMS) platform developed in PHP and distributed under the GNU (General Public License). What is the purpose of break and continue statement ?break: The break statement immediately terminates the whole iteration of a loop and the program control resumes at the next statement following the loop.continue: The continue statement skips the current iteration and brings the next iteration early. The continue 2 acts as terminator for case and skips the current iteration of the loop. What are the popular frameworks in PHP ?LaravelCodeIgniterSymfonyCakePHPYiiZend FrameworkPhalconFuelPHPPHPixieSlim How to make single and multi-line comments in PHP ?Comments are used to prevent the execution of the statement. It is ignored by the compiler. In PHP, there are two types of comments: single-line comments and multi-line comments.Single-line comment: The comment is started with double forward-slash (//).Multi-line comment: The comments are enclosed within /* comment section */ What is the use of count() function in PHP ?The count() function in PHP is used to count the number of elements present in the array. The function might return 0 for the variable that has been set to an empty array. Also for the variable which is not set the function returns 0. What are the different types of loop in PHP ?PHP supports four different types of loop which are listed below:for loopwhile loopdo-while loopforeach loop What is the difference between for and foreach loop in PHP ?The for loop is considered to be openly executing the iteration whereas the foreach loop hides the iteration and visibly simplified.The performance of foreach loop is considered better in comparison with for loop.The foreach loop though iterates over an array of elements, the execution is simplified and finish the loop in less time comparing with for loop.The foreach loop allocates temporary memory for index iterations which makes the overall system redundant its performance in terms of memory allocation.
What is PHP ?PHP is the general-purpose programming language used to design a website or web application. It is server-side scripting language embedded with HTML to develop a Static website, Dynamic website or Web applications. It was created by Rasmus Lerdorf in 1994.
What is the full form of PHP ?PHP is the abbreviation of Hypertext Preprocessor and earlier it was abbreviated as Personal Home Page.
What was the old name of PHP ?The old name of PHP was Personal Home Page.
What are the uses of PHP ?It is a server-side scripting language used to design dynamic websites or web applications.It receives data from forms to generate the dynamic page content.It can work with databases, sessions, send and receive cookies, send emails, etc.It can be used to add, delete, modify content within the database.It can be used to set the restriction to the user to access the web page.
It is a server-side scripting language used to design dynamic websites or web applications.
It receives data from forms to generate the dynamic page content.
It can work with databases, sessions, send and receive cookies, send emails, etc.
It can be used to add, delete, modify content within the database.
It can be used to set the restriction to the user to access the web page.
What is PEAR in PHP ?PEAR is a framework and distribution system for reusable PHP components. It stands for PHP Extension and Application Repository. It contains PHP snippets and a library to reuse the code. It provides a command-line interface to install packages.
What is the difference between static and dynamic websites ?Static Website: The web pages are returned from the server which are prebuilt source code files built using simple languages such as HTML, CSS or JavaScript. There is no processing of content on the server in Static Websites.Dynamic Website: The web pages are returned from the server which is processed during runtime means they are not prebuilt web pages but they are built during runtime according to the user’s demand with the help of server-side scripting languages such as PHP, Node.js, ASP.NET and many more supported by the server.
Static Website: The web pages are returned from the server which are prebuilt source code files built using simple languages such as HTML, CSS or JavaScript. There is no processing of content on the server in Static Websites.
Dynamic Website: The web pages are returned from the server which is processed during runtime means they are not prebuilt web pages but they are built during runtime according to the user’s demand with the help of server-side scripting languages such as PHP, Node.js, ASP.NET and many more supported by the server.
What is the correct and the two most common ways to start and finish a PHP block of code ?The PHP code always starts with <?php and ends with ?>. The block of PHP code are:<?php [ --Content of PHP code-- ] ?>
<?php [ --Content of PHP code-- ] ?>
How to execute a PHP script from the command line?Use the following steps to run PHP program using command line:Open terminal or command line window.Go to the specified folder or directory where PHP files are present.Then we can run PHP code using the command php file_name.phpStart the server for testing the php code using the command php -S localhost:port -t your_folder/
Open terminal or command line window.
Go to the specified folder or directory where PHP files are present.
Then we can run PHP code using the command php file_name.php
Start the server for testing the php code using the command php -S localhost:port -t your_folder/
How to display text with a PHP script ?There are two methods echo and print to display the text.
Is PHP a case sensitive language ?No, PHP is a partially case sensitive language. It means the variable names are case-sensitive and the function names are not case sensitive i.e. user-defined functions are not case sensitive.
What is the main difference between PHP 4 and PHP 5 ?PHP 5 contains many additional OOP (object-oriented programming) features.
What are the rules for naming a PHP variable ?Variables in a program are used to store some values or data that can be used later in a program. PHP has its own way of declaring and storing variables. The characteristics of the variables are listed below:A variable declared in PHP must begin with a dollar sign ($), followed by the variable name.A variable name contains alphanumeric characters and underscores (i.e. ‘a-z’, ‘A-Z’, ‘0-9’ and ‘_’) in their name.The variable name must start with a letter or underscore, not a number.PHP is a loosely typed language and we do not require to declare the data types of variables, rather PHP assumes it automatically by analyzing the values.PHP variables are case-sensitive i.e. $sum and $SUM are treated differently.
A variable declared in PHP must begin with a dollar sign ($), followed by the variable name.
A variable name contains alphanumeric characters and underscores (i.e. ‘a-z’, ‘A-Z’, ‘0-9’ and ‘_’) in their name.
The variable name must start with a letter or underscore, not a number.
PHP is a loosely typed language and we do not require to declare the data types of variables, rather PHP assumes it automatically by analyzing the values.
PHP variables are case-sensitive i.e. $sum and $SUM are treated differently.
How do you define a constant in PHP ?The define() function is used to create and retrieve the value of a constant. A PHP constant is an identifier whose value can not be change over the time (such as the domain name of a website eg. www.geeksforgeeks.org). If you have defined a constant, it can never be changed or undefined. The $ symbol is not used with a constant.
What are the popular Content Management Systems (CMS) in PHP ?WordPress: WordPress is a free and open-source Content Management System(CMS) framework. It is the most widely used CMS framework of recent time.Joomla: It is a free and open-source content management system (CMS) for distributing web content. It follows the model-view-controller web application framework that can be used independently.Magento: It is an open-source and e-commerce platform to develop online business.Drupal: It is a content management system (CMS) platform developed in PHP and distributed under the GNU (General Public License).
WordPress: WordPress is a free and open-source Content Management System(CMS) framework. It is the most widely used CMS framework of recent time.
Joomla: It is a free and open-source content management system (CMS) for distributing web content. It follows the model-view-controller web application framework that can be used independently.
Magento: It is an open-source and e-commerce platform to develop online business.
Drupal: It is a content management system (CMS) platform developed in PHP and distributed under the GNU (General Public License).
What is the purpose of break and continue statement ?break: The break statement immediately terminates the whole iteration of a loop and the program control resumes at the next statement following the loop.continue: The continue statement skips the current iteration and brings the next iteration early. The continue 2 acts as terminator for case and skips the current iteration of the loop.
break: The break statement immediately terminates the whole iteration of a loop and the program control resumes at the next statement following the loop.
continue: The continue statement skips the current iteration and brings the next iteration early. The continue 2 acts as terminator for case and skips the current iteration of the loop.
What are the popular frameworks in PHP ?LaravelCodeIgniterSymfonyCakePHPYiiZend FrameworkPhalconFuelPHPPHPixieSlim
Laravel
CodeIgniter
Symfony
CakePHP
Yii
Zend Framework
Phalcon
FuelPHP
PHPixie
Slim
How to make single and multi-line comments in PHP ?Comments are used to prevent the execution of the statement. It is ignored by the compiler. In PHP, there are two types of comments: single-line comments and multi-line comments.Single-line comment: The comment is started with double forward-slash (//).Multi-line comment: The comments are enclosed within /* comment section */
Single-line comment: The comment is started with double forward-slash (//).
Multi-line comment: The comments are enclosed within /* comment section */
What is the use of count() function in PHP ?The count() function in PHP is used to count the number of elements present in the array. The function might return 0 for the variable that has been set to an empty array. Also for the variable which is not set the function returns 0.
What are the different types of loop in PHP ?PHP supports four different types of loop which are listed below:for loopwhile loopdo-while loopforeach loop
for loop
while loop
do-while loop
foreach loop
What is the difference between for and foreach loop in PHP ?The for loop is considered to be openly executing the iteration whereas the foreach loop hides the iteration and visibly simplified.The performance of foreach loop is considered better in comparison with for loop.The foreach loop though iterates over an array of elements, the execution is simplified and finish the loop in less time comparing with for loop.The foreach loop allocates temporary memory for index iterations which makes the overall system redundant its performance in terms of memory allocation.
The for loop is considered to be openly executing the iteration whereas the foreach loop hides the iteration and visibly simplified.
The performance of foreach loop is considered better in comparison with for loop.
The foreach loop though iterates over an array of elements, the execution is simplified and finish the loop in less time comparing with for loop.
The foreach loop allocates temporary memory for index iterations which makes the overall system redundant its performance in terms of memory allocation.
prabhat12pundeer
interview-preparation
PHP
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25604,
"s": 25576,
"text": "\n26 Apr, 2022"
},
{
"code": null,
"e": 32080,
"s": 25604,
"text": "What is PHP ?PHP is the general-purpose programming language used to design a website or web application. It is server-side scripting language embedded with HTML to develop a Static website, Dynamic website or Web applications. It was created by Rasmus Lerdorf in 1994. What is the full form of PHP ?PHP is the abbreviation of Hypertext Preprocessor and earlier it was abbreviated as Personal Home Page. What was the old name of PHP ?The old name of PHP was Personal Home Page. What are the uses of PHP ?It is a server-side scripting language used to design dynamic websites or web applications.It receives data from forms to generate the dynamic page content.It can work with databases, sessions, send and receive cookies, send emails, etc.It can be used to add, delete, modify content within the database.It can be used to set the restriction to the user to access the web page. What is PEAR in PHP ?PEAR is a framework and distribution system for reusable PHP components. It stands for PHP Extension and Application Repository. It contains PHP snippets and a library to reuse the code. It provides a command-line interface to install packages. What is the difference between static and dynamic websites ?Static Website: The web pages are returned from the server which are prebuilt source code files built using simple languages such as HTML, CSS or JavaScript. There is no processing of content on the server in Static Websites.Dynamic Website: The web pages are returned from the server which is processed during runtime means they are not prebuilt web pages but they are built during runtime according to the user’s demand with the help of server-side scripting languages such as PHP, Node.js, ASP.NET and many more supported by the server. What is the correct and the two most common ways to start and finish a PHP block of code ?The PHP code always starts with <?php and ends with ?>. The block of PHP code are:<?php [ --Content of PHP code-- ] ?> How to execute a PHP script from the command line?Use the following steps to run PHP program using command line:Open terminal or command line window.Go to the specified folder or directory where PHP files are present.Then we can run PHP code using the command php file_name.phpStart the server for testing the php code using the command php -S localhost:port -t your_folder/ How to display text with a PHP script ?There are two methods echo and print to display the text. Is PHP a case sensitive language ?No, PHP is a partially case sensitive language. It means the variable names are case-sensitive and the function names are not case sensitive i.e. user-defined functions are not case sensitive. What is the main difference between PHP 4 and PHP 5 ?PHP 5 contains many additional OOP (object-oriented programming) features. What are the rules for naming a PHP variable ?Variables in a program are used to store some values or data that can be used later in a program. PHP has its own way of declaring and storing variables. The characteristics of the variables are listed below:A variable declared in PHP must begin with a dollar sign ($), followed by the variable name.A variable name contains alphanumeric characters and underscores (i.e. ‘a-z’, ‘A-Z’, ‘0-9’ and ‘_’) in their name.The variable name must start with a letter or underscore, not a number.PHP is a loosely typed language and we do not require to declare the data types of variables, rather PHP assumes it automatically by analyzing the values.PHP variables are case-sensitive i.e. $sum and $SUM are treated differently. How do you define a constant in PHP ?The define() function is used to create and retrieve the value of a constant. A PHP constant is an identifier whose value can not be change over the time (such as the domain name of a website eg. www.geeksforgeeks.org). If you have defined a constant, it can never be changed or undefined. The $ symbol is not used with a constant. What are the popular Content Management Systems (CMS) in PHP ?WordPress: WordPress is a free and open-source Content Management System(CMS) framework. It is the most widely used CMS framework of recent time.Joomla: It is a free and open-source content management system (CMS) for distributing web content. It follows the model-view-controller web application framework that can be used independently.Magento: It is an open-source and e-commerce platform to develop online business.Drupal: It is a content management system (CMS) platform developed in PHP and distributed under the GNU (General Public License). What is the purpose of break and continue statement ?break: The break statement immediately terminates the whole iteration of a loop and the program control resumes at the next statement following the loop.continue: The continue statement skips the current iteration and brings the next iteration early. The continue 2 acts as terminator for case and skips the current iteration of the loop. What are the popular frameworks in PHP ?LaravelCodeIgniterSymfonyCakePHPYiiZend FrameworkPhalconFuelPHPPHPixieSlim How to make single and multi-line comments in PHP ?Comments are used to prevent the execution of the statement. It is ignored by the compiler. In PHP, there are two types of comments: single-line comments and multi-line comments.Single-line comment: The comment is started with double forward-slash (//).Multi-line comment: The comments are enclosed within /* comment section */ What is the use of count() function in PHP ?The count() function in PHP is used to count the number of elements present in the array. The function might return 0 for the variable that has been set to an empty array. Also for the variable which is not set the function returns 0. What are the different types of loop in PHP ?PHP supports four different types of loop which are listed below:for loopwhile loopdo-while loopforeach loop What is the difference between for and foreach loop in PHP ?The for loop is considered to be openly executing the iteration whereas the foreach loop hides the iteration and visibly simplified.The performance of foreach loop is considered better in comparison with for loop.The foreach loop though iterates over an array of elements, the execution is simplified and finish the loop in less time comparing with for loop.The foreach loop allocates temporary memory for index iterations which makes the overall system redundant its performance in terms of memory allocation."
},
{
"code": null,
"e": 32354,
"s": 32080,
"text": "What is PHP ?PHP is the general-purpose programming language used to design a website or web application. It is server-side scripting language embedded with HTML to develop a Static website, Dynamic website or Web applications. It was created by Rasmus Lerdorf in 1994. "
},
{
"code": null,
"e": 32497,
"s": 32359,
"text": "What is the full form of PHP ?PHP is the abbreviation of Hypertext Preprocessor and earlier it was abbreviated as Personal Home Page. "
},
{
"code": null,
"e": 32580,
"s": 32502,
"text": "What was the old name of PHP ?The old name of PHP was Personal Home Page. "
},
{
"code": null,
"e": 32992,
"s": 32585,
"text": "What are the uses of PHP ?It is a server-side scripting language used to design dynamic websites or web applications.It receives data from forms to generate the dynamic page content.It can work with databases, sessions, send and receive cookies, send emails, etc.It can be used to add, delete, modify content within the database.It can be used to set the restriction to the user to access the web page. "
},
{
"code": null,
"e": 33084,
"s": 32992,
"text": "It is a server-side scripting language used to design dynamic websites or web applications."
},
{
"code": null,
"e": 33150,
"s": 33084,
"text": "It receives data from forms to generate the dynamic page content."
},
{
"code": null,
"e": 33232,
"s": 33150,
"text": "It can work with databases, sessions, send and receive cookies, send emails, etc."
},
{
"code": null,
"e": 33299,
"s": 33232,
"text": "It can be used to add, delete, modify content within the database."
},
{
"code": null,
"e": 33373,
"s": 33299,
"text": "It can be used to set the restriction to the user to access the web page."
},
{
"code": null,
"e": 33648,
"s": 33378,
"text": "What is PEAR in PHP ?PEAR is a framework and distribution system for reusable PHP components. It stands for PHP Extension and Application Repository. It contains PHP snippets and a library to reuse the code. It provides a command-line interface to install packages. "
},
{
"code": null,
"e": 34257,
"s": 33653,
"text": "What is the difference between static and dynamic websites ?Static Website: The web pages are returned from the server which are prebuilt source code files built using simple languages such as HTML, CSS or JavaScript. There is no processing of content on the server in Static Websites.Dynamic Website: The web pages are returned from the server which is processed during runtime means they are not prebuilt web pages but they are built during runtime according to the user’s demand with the help of server-side scripting languages such as PHP, Node.js, ASP.NET and many more supported by the server. "
},
{
"code": null,
"e": 34483,
"s": 34257,
"text": "Static Website: The web pages are returned from the server which are prebuilt source code files built using simple languages such as HTML, CSS or JavaScript. There is no processing of content on the server in Static Websites."
},
{
"code": null,
"e": 34798,
"s": 34483,
"text": "Dynamic Website: The web pages are returned from the server which is processed during runtime means they are not prebuilt web pages but they are built during runtime according to the user’s demand with the help of server-side scripting languages such as PHP, Node.js, ASP.NET and many more supported by the server."
},
{
"code": null,
"e": 35020,
"s": 34803,
"text": "What is the correct and the two most common ways to start and finish a PHP block of code ?The PHP code always starts with <?php and ends with ?>. The block of PHP code are:<?php [ --Content of PHP code-- ] ?> "
},
{
"code": null,
"e": 35061,
"s": 35020,
"text": "<?php [ --Content of PHP code-- ] ?>"
},
{
"code": null,
"e": 35445,
"s": 35066,
"text": "How to execute a PHP script from the command line?Use the following steps to run PHP program using command line:Open terminal or command line window.Go to the specified folder or directory where PHP files are present.Then we can run PHP code using the command php file_name.phpStart the server for testing the php code using the command php -S localhost:port -t your_folder/ "
},
{
"code": null,
"e": 35483,
"s": 35445,
"text": "Open terminal or command line window."
},
{
"code": null,
"e": 35552,
"s": 35483,
"text": "Go to the specified folder or directory where PHP files are present."
},
{
"code": null,
"e": 35613,
"s": 35552,
"text": "Then we can run PHP code using the command php file_name.php"
},
{
"code": null,
"e": 35711,
"s": 35613,
"text": "Start the server for testing the php code using the command php -S localhost:port -t your_folder/"
},
{
"code": null,
"e": 35817,
"s": 35716,
"text": "How to display text with a PHP script ?There are two methods echo and print to display the text. "
},
{
"code": null,
"e": 36053,
"s": 35822,
"text": "Is PHP a case sensitive language ?No, PHP is a partially case sensitive language. It means the variable names are case-sensitive and the function names are not case sensitive i.e. user-defined functions are not case sensitive. "
},
{
"code": null,
"e": 36190,
"s": 36058,
"text": "What is the main difference between PHP 4 and PHP 5 ?PHP 5 contains many additional OOP (object-oriented programming) features. "
},
{
"code": null,
"e": 36961,
"s": 36195,
"text": "What are the rules for naming a PHP variable ?Variables in a program are used to store some values or data that can be used later in a program. PHP has its own way of declaring and storing variables. The characteristics of the variables are listed below:A variable declared in PHP must begin with a dollar sign ($), followed by the variable name.A variable name contains alphanumeric characters and underscores (i.e. ‘a-z’, ‘A-Z’, ‘0-9’ and ‘_’) in their name.The variable name must start with a letter or underscore, not a number.PHP is a loosely typed language and we do not require to declare the data types of variables, rather PHP assumes it automatically by analyzing the values.PHP variables are case-sensitive i.e. $sum and $SUM are treated differently. "
},
{
"code": null,
"e": 37054,
"s": 36961,
"text": "A variable declared in PHP must begin with a dollar sign ($), followed by the variable name."
},
{
"code": null,
"e": 37169,
"s": 37054,
"text": "A variable name contains alphanumeric characters and underscores (i.e. ‘a-z’, ‘A-Z’, ‘0-9’ and ‘_’) in their name."
},
{
"code": null,
"e": 37241,
"s": 37169,
"text": "The variable name must start with a letter or underscore, not a number."
},
{
"code": null,
"e": 37396,
"s": 37241,
"text": "PHP is a loosely typed language and we do not require to declare the data types of variables, rather PHP assumes it automatically by analyzing the values."
},
{
"code": null,
"e": 37473,
"s": 37396,
"text": "PHP variables are case-sensitive i.e. $sum and $SUM are treated differently."
},
{
"code": null,
"e": 37851,
"s": 37478,
"text": "How do you define a constant in PHP ?The define() function is used to create and retrieve the value of a constant. A PHP constant is an identifier whose value can not be change over the time (such as the domain name of a website eg. www.geeksforgeeks.org). If you have defined a constant, it can never be changed or undefined. The $ symbol is not used with a constant. "
},
{
"code": null,
"e": 38471,
"s": 37856,
"text": "What are the popular Content Management Systems (CMS) in PHP ?WordPress: WordPress is a free and open-source Content Management System(CMS) framework. It is the most widely used CMS framework of recent time.Joomla: It is a free and open-source content management system (CMS) for distributing web content. It follows the model-view-controller web application framework that can be used independently.Magento: It is an open-source and e-commerce platform to develop online business.Drupal: It is a content management system (CMS) platform developed in PHP and distributed under the GNU (General Public License). "
},
{
"code": null,
"e": 38617,
"s": 38471,
"text": "WordPress: WordPress is a free and open-source Content Management System(CMS) framework. It is the most widely used CMS framework of recent time."
},
{
"code": null,
"e": 38811,
"s": 38617,
"text": "Joomla: It is a free and open-source content management system (CMS) for distributing web content. It follows the model-view-controller web application framework that can be used independently."
},
{
"code": null,
"e": 38893,
"s": 38811,
"text": "Magento: It is an open-source and e-commerce platform to develop online business."
},
{
"code": null,
"e": 39023,
"s": 38893,
"text": "Drupal: It is a content management system (CMS) platform developed in PHP and distributed under the GNU (General Public License)."
},
{
"code": null,
"e": 39424,
"s": 39028,
"text": "What is the purpose of break and continue statement ?break: The break statement immediately terminates the whole iteration of a loop and the program control resumes at the next statement following the loop.continue: The continue statement skips the current iteration and brings the next iteration early. The continue 2 acts as terminator for case and skips the current iteration of the loop. "
},
{
"code": null,
"e": 39578,
"s": 39424,
"text": "break: The break statement immediately terminates the whole iteration of a loop and the program control resumes at the next statement following the loop."
},
{
"code": null,
"e": 39764,
"s": 39578,
"text": "continue: The continue statement skips the current iteration and brings the next iteration early. The continue 2 acts as terminator for case and skips the current iteration of the loop."
},
{
"code": null,
"e": 39888,
"s": 39769,
"text": "What are the popular frameworks in PHP ?LaravelCodeIgniterSymfonyCakePHPYiiZend FrameworkPhalconFuelPHPPHPixieSlim "
},
{
"code": null,
"e": 39896,
"s": 39888,
"text": "Laravel"
},
{
"code": null,
"e": 39908,
"s": 39896,
"text": "CodeIgniter"
},
{
"code": null,
"e": 39916,
"s": 39908,
"text": "Symfony"
},
{
"code": null,
"e": 39924,
"s": 39916,
"text": "CakePHP"
},
{
"code": null,
"e": 39928,
"s": 39924,
"text": "Yii"
},
{
"code": null,
"e": 39943,
"s": 39928,
"text": "Zend Framework"
},
{
"code": null,
"e": 39951,
"s": 39943,
"text": "Phalcon"
},
{
"code": null,
"e": 39959,
"s": 39951,
"text": "FuelPHP"
},
{
"code": null,
"e": 39967,
"s": 39959,
"text": "PHPixie"
},
{
"code": null,
"e": 39972,
"s": 39967,
"text": "Slim"
},
{
"code": null,
"e": 40360,
"s": 39977,
"text": "How to make single and multi-line comments in PHP ?Comments are used to prevent the execution of the statement. It is ignored by the compiler. In PHP, there are two types of comments: single-line comments and multi-line comments.Single-line comment: The comment is started with double forward-slash (//).Multi-line comment: The comments are enclosed within /* comment section */ "
},
{
"code": null,
"e": 40436,
"s": 40360,
"text": "Single-line comment: The comment is started with double forward-slash (//)."
},
{
"code": null,
"e": 40511,
"s": 40436,
"text": "Multi-line comment: The comments are enclosed within /* comment section */"
},
{
"code": null,
"e": 40799,
"s": 40516,
"text": "What is the use of count() function in PHP ?The count() function in PHP is used to count the number of elements present in the array. The function might return 0 for the variable that has been set to an empty array. Also for the variable which is not set the function returns 0. "
},
{
"code": null,
"e": 40962,
"s": 40804,
"text": "What are the different types of loop in PHP ?PHP supports four different types of loop which are listed below:for loopwhile loopdo-while loopforeach loop "
},
{
"code": null,
"e": 40971,
"s": 40962,
"text": "for loop"
},
{
"code": null,
"e": 40982,
"s": 40971,
"text": "while loop"
},
{
"code": null,
"e": 40996,
"s": 40982,
"text": "do-while loop"
},
{
"code": null,
"e": 41009,
"s": 40996,
"text": "foreach loop"
},
{
"code": null,
"e": 41585,
"s": 41014,
"text": "What is the difference between for and foreach loop in PHP ?The for loop is considered to be openly executing the iteration whereas the foreach loop hides the iteration and visibly simplified.The performance of foreach loop is considered better in comparison with for loop.The foreach loop though iterates over an array of elements, the execution is simplified and finish the loop in less time comparing with for loop.The foreach loop allocates temporary memory for index iterations which makes the overall system redundant its performance in terms of memory allocation."
},
{
"code": null,
"e": 41718,
"s": 41585,
"text": "The for loop is considered to be openly executing the iteration whereas the foreach loop hides the iteration and visibly simplified."
},
{
"code": null,
"e": 41800,
"s": 41718,
"text": "The performance of foreach loop is considered better in comparison with for loop."
},
{
"code": null,
"e": 41946,
"s": 41800,
"text": "The foreach loop though iterates over an array of elements, the execution is simplified and finish the loop in less time comparing with for loop."
},
{
"code": null,
"e": 42099,
"s": 41946,
"text": "The foreach loop allocates temporary memory for index iterations which makes the overall system redundant its performance in terms of memory allocation."
},
{
"code": null,
"e": 42116,
"s": 42099,
"text": "prabhat12pundeer"
},
{
"code": null,
"e": 42138,
"s": 42116,
"text": "interview-preparation"
},
{
"code": null,
"e": 42142,
"s": 42138,
"text": "PHP"
},
{
"code": null,
"e": 42159,
"s": 42142,
"text": "Web Technologies"
},
{
"code": null,
"e": 42186,
"s": 42159,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 42190,
"s": 42186,
"text": "PHP"
},
{
"code": null,
"e": 42288,
"s": 42190,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42338,
"s": 42288,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 42378,
"s": 42338,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 42439,
"s": 42378,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 42489,
"s": 42439,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 42534,
"s": 42489,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 42574,
"s": 42534,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 42607,
"s": 42574,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 42652,
"s": 42607,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42695,
"s": 42652,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
CSS Opacity / Transparency - GeeksforGeeks
|
05 Nov, 2021
The opacity in CSS is the property of an element that describes the transparency of the element. It is the opposite of transparency & represents the degree to which the content will be hidden behind an element.
We can apply the opacity with different styling properties to the elements. A few of them are discussed below:
Image Opacity: The opacity property is used in the image to describe the transparency of the image. The value of opacity lies between 0.0 to 1.0 where a low value represents high transparency and a high value represents low transparency. The percentage of opacity is calculated as Opacity% = Opacity * 100.
Example: This example describes the opacity property by applying it to the image.
HTML
<!DOCTYPE html><html> <head> <title>Opacity property</title> <style> .forest { opacity: 0.5; } p { font-size: 25px; font-weight: bold; margin-bottom: 5px; } .opacity { text-align: center; } </style></head> <body> <div class="opacity"> <p>Image with 100% opacity (original image)</p> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-10.png" class="forest1"> <br> <br> <p>Image with 50% opacity</p> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-10.png" class="forest"> </div></body> </html>
Output:
Image Hover Opacity: The hover opacity property is applied to the image when the mouse puts it over the image otherwise opacity property changes. The value of opacity can easily reverse the process by setting the opacity as a higher value at first and then lowering it when hovering over it like:
Syntax:
.hightolow {
opacity: 1.0;
}
.hightolow:hover {
opacity: 0.5;
}
Example: This example describes the opacity property by applying it to the image to generate opacity by hovering over it.
HTML
<!DOCTYPE html><html> <head> <title>Image Hover Opacity</title> <style> .gfg_opacity { opacity: 0.5; } .gfg_opacity:hover { opacity: 1.0; } .main { text-align: center; } </style></head> <body> <div class="main"> <h1>Image Hover Opacity:</h1> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-10.png" class="gfg_opacity"> <br> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-10.png" class="gfg_opacity"> <br> <br> </div></body> </html>
Output:
Transparency box and transparency using RGBA values: In the transparency box, child property inherit the property from the parent property but in the case of transparency using RGBA, only opacity property is used or applied to add transparency to the background of an element.
Example: This example describes the opacity property by applying transparency using RGBA values.
HTML
<!DOCTYPE html><html> <head> <title>Transparent box</title> <style> .geeks { background: rgb(0, 153, 0); padding: 15px; text-align: center; width: 300px; } #geek { padding: 15px; text-align: center; width: 300px; } .rgba1 { background: rgba(0, 153, 0, 0.1); } .rgba2 { background: rgba(0, 153, 0, 0.5); } .rgba3 { background: rgba(0, 153, 0, 0.8); } .rgba4 { background: rgba(0, 153, 0, 1.0); } .g1 { float: left; margin-left: 50px; } .g2 { margin-top: -40px; margin-left: 50px; float: left; } </style></head> <body> <div class="g1"> <p style="font-size:24px;font-weight:bold;">Transparent Box</p> <div class="geeks" style="opacity:0.1;"> <p>10% opacity</p> </div> <div class="geeks" style="opacity:0.5;"> <p>50% opacity</p> </div> <div class="geeks" style="opacity:0.8;"> <p>80% opacity</p> </div> <div class="geeks"> <p>100% opacity</p> </div> </div> <br> <br> <div class="g2"> <p style="font-size:24px;font-weight:bold;">RGBA color values</p> <div class="rgba1" id="geek"> <p>10% opacity</p> </div> <div class="rgba2" id="geek"> <p>50% opacity</p> </div> <div class="rgba3" id="geek"> <p>80% opacity</p> </div> <div class="rgba4" id="geek"> <p>100% opacity</p> </div> </div></body> </html>
Output:
Text In Transparent Box: The opacity property can be used to decrease or increase the opacity of a box and put text inside of it for making the most egregious posts.
Example: This example describes the opacity property by placing the text in a transparent box.
HTML
<!DOCTYPE html><html> <head> <style> div.bg { background: url("https: //media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-10.png"); width: 550px; height: 300px; border: 1px solid; } div.box { margin: 50px 20px; text-align: center; width: 500px; height: 150px; background-color: #000000; border: 3px solid white; opacity: 0.7; } div.box p { margin: 5%; font-family: Arial; color: #009900; font-weight: bold; font-size: 25px; } </style></head> <body> <div class="bg"> <div class="box"> <p>GeeksforGeeks</p> </div> </div></body> </html>
Output:
Supported Browsers:
Google Chrome 1.0
Microsoft Edge 12.0
Internet Explorer 9.0
Firefox 1.0
Opera 9.0
Safari 2.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
bhaskargeeksforgeeks
CSS-Basics
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 29315,
"s": 29287,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 29526,
"s": 29315,
"text": "The opacity in CSS is the property of an element that describes the transparency of the element. It is the opposite of transparency & represents the degree to which the content will be hidden behind an element."
},
{
"code": null,
"e": 29637,
"s": 29526,
"text": "We can apply the opacity with different styling properties to the elements. A few of them are discussed below:"
},
{
"code": null,
"e": 29944,
"s": 29637,
"text": "Image Opacity: The opacity property is used in the image to describe the transparency of the image. The value of opacity lies between 0.0 to 1.0 where a low value represents high transparency and a high value represents low transparency. The percentage of opacity is calculated as Opacity% = Opacity * 100."
},
{
"code": null,
"e": 30026,
"s": 29944,
"text": "Example: This example describes the opacity property by applying it to the image."
},
{
"code": null,
"e": 30031,
"s": 30026,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Opacity property</title> <style> .forest { opacity: 0.5; } p { font-size: 25px; font-weight: bold; margin-bottom: 5px; } .opacity { text-align: center; } </style></head> <body> <div class=\"opacity\"> <p>Image with 100% opacity (original image)</p> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-10.png\" class=\"forest1\"> <br> <br> <p>Image with 50% opacity</p> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-10.png\" class=\"forest\"> </div></body> </html>",
"e": 30751,
"s": 30031,
"text": null
},
{
"code": null,
"e": 30759,
"s": 30751,
"text": "Output:"
},
{
"code": null,
"e": 31056,
"s": 30759,
"text": "Image Hover Opacity: The hover opacity property is applied to the image when the mouse puts it over the image otherwise opacity property changes. The value of opacity can easily reverse the process by setting the opacity as a higher value at first and then lowering it when hovering over it like:"
},
{
"code": null,
"e": 31064,
"s": 31056,
"text": "Syntax:"
},
{
"code": null,
"e": 31137,
"s": 31064,
"text": ".hightolow {\n opacity: 1.0;\n}\n\n.hightolow:hover {\n opacity: 0.5;\n}"
},
{
"code": null,
"e": 31259,
"s": 31137,
"text": "Example: This example describes the opacity property by applying it to the image to generate opacity by hovering over it."
},
{
"code": null,
"e": 31264,
"s": 31259,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Image Hover Opacity</title> <style> .gfg_opacity { opacity: 0.5; } .gfg_opacity:hover { opacity: 1.0; } .main { text-align: center; } </style></head> <body> <div class=\"main\"> <h1>Image Hover Opacity:</h1> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-10.png\" class=\"gfg_opacity\"> <br> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-10.png\" class=\"gfg_opacity\"> <br> <br> </div></body> </html>",
"e": 31899,
"s": 31264,
"text": null
},
{
"code": null,
"e": 31907,
"s": 31899,
"text": "Output:"
},
{
"code": null,
"e": 32184,
"s": 31907,
"text": "Transparency box and transparency using RGBA values: In the transparency box, child property inherit the property from the parent property but in the case of transparency using RGBA, only opacity property is used or applied to add transparency to the background of an element."
},
{
"code": null,
"e": 32281,
"s": 32184,
"text": "Example: This example describes the opacity property by applying transparency using RGBA values."
},
{
"code": null,
"e": 32286,
"s": 32281,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Transparent box</title> <style> .geeks { background: rgb(0, 153, 0); padding: 15px; text-align: center; width: 300px; } #geek { padding: 15px; text-align: center; width: 300px; } .rgba1 { background: rgba(0, 153, 0, 0.1); } .rgba2 { background: rgba(0, 153, 0, 0.5); } .rgba3 { background: rgba(0, 153, 0, 0.8); } .rgba4 { background: rgba(0, 153, 0, 1.0); } .g1 { float: left; margin-left: 50px; } .g2 { margin-top: -40px; margin-left: 50px; float: left; } </style></head> <body> <div class=\"g1\"> <p style=\"font-size:24px;font-weight:bold;\">Transparent Box</p> <div class=\"geeks\" style=\"opacity:0.1;\"> <p>10% opacity</p> </div> <div class=\"geeks\" style=\"opacity:0.5;\"> <p>50% opacity</p> </div> <div class=\"geeks\" style=\"opacity:0.8;\"> <p>80% opacity</p> </div> <div class=\"geeks\"> <p>100% opacity</p> </div> </div> <br> <br> <div class=\"g2\"> <p style=\"font-size:24px;font-weight:bold;\">RGBA color values</p> <div class=\"rgba1\" id=\"geek\"> <p>10% opacity</p> </div> <div class=\"rgba2\" id=\"geek\"> <p>50% opacity</p> </div> <div class=\"rgba3\" id=\"geek\"> <p>80% opacity</p> </div> <div class=\"rgba4\" id=\"geek\"> <p>100% opacity</p> </div> </div></body> </html>",
"e": 33953,
"s": 32286,
"text": null
},
{
"code": null,
"e": 33961,
"s": 33953,
"text": "Output:"
},
{
"code": null,
"e": 34127,
"s": 33961,
"text": "Text In Transparent Box: The opacity property can be used to decrease or increase the opacity of a box and put text inside of it for making the most egregious posts."
},
{
"code": null,
"e": 34222,
"s": 34127,
"text": "Example: This example describes the opacity property by placing the text in a transparent box."
},
{
"code": null,
"e": 34227,
"s": 34222,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> div.bg { background: url(\"https: //media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-10.png\"); width: 550px; height: 300px; border: 1px solid; } div.box { margin: 50px 20px; text-align: center; width: 500px; height: 150px; background-color: #000000; border: 3px solid white; opacity: 0.7; } div.box p { margin: 5%; font-family: Arial; color: #009900; font-weight: bold; font-size: 25px; } </style></head> <body> <div class=\"bg\"> <div class=\"box\"> <p>GeeksforGeeks</p> </div> </div></body> </html>",
"e": 34952,
"s": 34227,
"text": null
},
{
"code": null,
"e": 34960,
"s": 34952,
"text": "Output:"
},
{
"code": null,
"e": 34980,
"s": 34960,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 34998,
"s": 34980,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 35018,
"s": 34998,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 35040,
"s": 35018,
"text": "Internet Explorer 9.0"
},
{
"code": null,
"e": 35052,
"s": 35040,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 35062,
"s": 35052,
"text": "Opera 9.0"
},
{
"code": null,
"e": 35073,
"s": 35062,
"text": "Safari 2.0"
},
{
"code": null,
"e": 35210,
"s": 35073,
"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": 35231,
"s": 35210,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 35242,
"s": 35231,
"text": "CSS-Basics"
},
{
"code": null,
"e": 35249,
"s": 35242,
"text": "Picked"
},
{
"code": null,
"e": 35253,
"s": 35249,
"text": "CSS"
},
{
"code": null,
"e": 35258,
"s": 35253,
"text": "HTML"
},
{
"code": null,
"e": 35275,
"s": 35258,
"text": "Web Technologies"
},
{
"code": null,
"e": 35280,
"s": 35275,
"text": "HTML"
},
{
"code": null,
"e": 35378,
"s": 35280,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35428,
"s": 35378,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35490,
"s": 35428,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35538,
"s": 35490,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 35596,
"s": 35538,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 35651,
"s": 35596,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 35701,
"s": 35651,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35763,
"s": 35701,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35811,
"s": 35763,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 35871,
"s": 35811,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
How To Work With Images in Bokeh - GeeksforGeeks
|
14 Sep, 2021
In this article, we are going to see how to work with images in Bokeh.
For this, we will use the ImageURL Glyph. This glyph renders images that are loaded from the given URLs.
Syntax: ImageURL(‘url’, ‘x’, ‘y’, ‘w’, ‘h’, ‘angle’, ‘dilate’)
Arguments:
url: The url from where the images needs to be retrieved.
x = NumberSpec(default=field(“x”), the x-coordinates to locate the image anchors.
y = NumberSpec(default=field(“y”), the y-coordinates to locate the image anchors.
w = NullDistanceSpec, the width of the plot region that the image will occupy in data space.The default value is “None“, in which case the image will be displayed at its actual image size.
h = NullDistanceSpec, the height of the plot region that the image will occupy in data space.The default value is “None“, in which case the image will be displayed at its actual image size (regardless of the units specified here).
angle = AngleSpec(default=0), the angles with which the images are to be rotated, as measured from the horizontal.
global_alpha = Float(1.0), an overall opacity that each image is rendered with.
dilate = Bool(False), Whether to always round fractional pixel locations in such a way as to make the images bigger.This setting may be useful if pixel rounding errors are causing images to have a gap between them, when they should appear flush.
anchor = Enum(Anchor), What position of the image should be anchored at the `x`, `y` coordinates.
retry_attempts = Int(0), number of attempts to retry loading the images from the specified URL. Default is zero.
retry_timeout = Int(0), timeout (in ms) between retry attempts to load the image from the specified URL. Default is zero ms.
In this example, we are loading the image from the URL given and then rendering the image on the plot. In this example, we are loading the image from the web which can also be loaded locally. Here, we are showing two images on the plot with different parameter values (such as x,y,w,h, etc). You can observe the output to better understand.
Python
# importing numpy package and other librariesimport numpy as npfrom bokeh.io import curdoc, showfrom bokeh.models import ColumnDataSource, Grid, ImageURL, LinearAxis, Plot, Range1dfrom bokeh.plotting import figure # url to load image fromurl = "https://media.geeksforgeeks.org/wp-content/\uploads/20210829161730/logo.png" N = 5 # creating columndatasourcesource = ColumnDataSource(dict( url=[url]*N, x1=np.arange(N), y1=np.arange(N), w1=[35]*N, h1=[64]*N,)) # creating x and y axis rangexdr = Range1d(start=-100, end=300)ydr = Range1d(start=-100, end=300) # creating a plot with above x and y axes rangeplot = Plot( title=None, x_range=xdr, y_range=ydr, plot_width=400, plot_height=400, min_border=0, toolbar_location=None) # loading the image using imageUrlimage = ImageURL(url=["https://media.geeksforgeeks.org/\wp-content/uploads/20210829161730/logo.png"], x=50, y=80, w=200, h=250, anchor="bottom_left")image1 = ImageURL(url="url", x="x1", y="y1", w="w1", h="h1", anchor="center") # rendering the images to the plotplot.add_glyph(source, image)plot.add_glyph(source, image1) xaxis = LinearAxis()plot.add_layout(xaxis, 'below') yaxis = LinearAxis()plot.add_layout(yaxis, 'left') # adding grid lines to the plotplot.add_layout(Grid(dimension=0, ticker=xaxis.ticker, grid_line_color='#00ff00')) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker, grid_line_color='#00ff00')) # creates output filecurdoc().add_root(plot)curdoc().theme = 'caliber' # showing the plot on output fileshow(plot)
Output:
We are creating ColumnDataSource which provides data to the Glyphs of our plot. Bokeh has its own data structure called ColumnDataSource which can be used as an input to any Bokeh object. We are creating the data with NumPy arrays.
Now create the x and y range using range1d which creates a range in a scalar dimension and then assign it to xdr and ydr which we will use while creating the plot.
We then create the plot with xdr and ydr as x_range and y_range and setting the height and width of the plot as 400.
We are then retrieving the image from the URL we declared before by setting the values of all the parameters as shown in the code. We are using two images over here by giving different values.
Now, we render the images to the plot.
Next, we add the grid lines to the plot using the Grid function and give it the color ‘green’.
Then, we add the plot to the app code curdoc which represents a new document and is sent to the bokehJs to show it to the user.
In this example, we are creating a figure with a circle glyph and then simply rendering the image from the given URL using the glyph ImageURL.
Python
# importing numpy package and other librariesimport numpy as npfrom bokeh.io import curdoc, showfrom bokeh.models import ColumnDataSource, Grid, ImageURL, LinearAxis, Plot, Range1dfrom bokeh.plotting import figure # create dict as basis for ColumnDataSourcedata = {'x1': [10, 20, 30, 40, 50], 'y1': [60, 70, 80, 90, 100]} # create ColumnDataSource based on dictsource = ColumnDataSource(data=data) # creating figurep = figure(plot_height=500, plot_width=500)p.circle(x="x1", y="y1", size=20, source=source) # rendering the image using imageUrlimage = ImageURL(url=["https://media.geeksforgeeks.org/\wp-content/uploads/20210902155548/imgurl2-200x112.jpg"], x=80, y=100, w=50, h=40, anchor="center", retry_attempts=2) # adding the images to the plotp.add_glyph(source, image) # creates output filecurdoc().add_root(p) # showing the plot on output fileshow(p)
Output:
Blogathon-2021
Python-Bokeh
Blogathon
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 26121,
"s": 26093,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 26193,
"s": 26121,
"text": "In this article, we are going to see how to work with images in Bokeh. "
},
{
"code": null,
"e": 26298,
"s": 26193,
"text": "For this, we will use the ImageURL Glyph. This glyph renders images that are loaded from the given URLs."
},
{
"code": null,
"e": 26361,
"s": 26298,
"text": "Syntax: ImageURL(‘url’, ‘x’, ‘y’, ‘w’, ‘h’, ‘angle’, ‘dilate’)"
},
{
"code": null,
"e": 26372,
"s": 26361,
"text": "Arguments:"
},
{
"code": null,
"e": 26430,
"s": 26372,
"text": "url: The url from where the images needs to be retrieved."
},
{
"code": null,
"e": 26512,
"s": 26430,
"text": "x = NumberSpec(default=field(“x”), the x-coordinates to locate the image anchors."
},
{
"code": null,
"e": 26595,
"s": 26512,
"text": "y = NumberSpec(default=field(“y”), the y-coordinates to locate the image anchors."
},
{
"code": null,
"e": 26784,
"s": 26595,
"text": "w = NullDistanceSpec, the width of the plot region that the image will occupy in data space.The default value is “None“, in which case the image will be displayed at its actual image size."
},
{
"code": null,
"e": 27015,
"s": 26784,
"text": "h = NullDistanceSpec, the height of the plot region that the image will occupy in data space.The default value is “None“, in which case the image will be displayed at its actual image size (regardless of the units specified here)."
},
{
"code": null,
"e": 27130,
"s": 27015,
"text": "angle = AngleSpec(default=0), the angles with which the images are to be rotated, as measured from the horizontal."
},
{
"code": null,
"e": 27210,
"s": 27130,
"text": "global_alpha = Float(1.0), an overall opacity that each image is rendered with."
},
{
"code": null,
"e": 27456,
"s": 27210,
"text": "dilate = Bool(False), Whether to always round fractional pixel locations in such a way as to make the images bigger.This setting may be useful if pixel rounding errors are causing images to have a gap between them, when they should appear flush."
},
{
"code": null,
"e": 27554,
"s": 27456,
"text": "anchor = Enum(Anchor), What position of the image should be anchored at the `x`, `y` coordinates."
},
{
"code": null,
"e": 27667,
"s": 27554,
"text": "retry_attempts = Int(0), number of attempts to retry loading the images from the specified URL. Default is zero."
},
{
"code": null,
"e": 27792,
"s": 27667,
"text": "retry_timeout = Int(0), timeout (in ms) between retry attempts to load the image from the specified URL. Default is zero ms."
},
{
"code": null,
"e": 28133,
"s": 27792,
"text": "In this example, we are loading the image from the URL given and then rendering the image on the plot. In this example, we are loading the image from the web which can also be loaded locally. Here, we are showing two images on the plot with different parameter values (such as x,y,w,h, etc). You can observe the output to better understand."
},
{
"code": null,
"e": 28140,
"s": 28133,
"text": "Python"
},
{
"code": "# importing numpy package and other librariesimport numpy as npfrom bokeh.io import curdoc, showfrom bokeh.models import ColumnDataSource, Grid, ImageURL, LinearAxis, Plot, Range1dfrom bokeh.plotting import figure # url to load image fromurl = \"https://media.geeksforgeeks.org/wp-content/\\uploads/20210829161730/logo.png\" N = 5 # creating columndatasourcesource = ColumnDataSource(dict( url=[url]*N, x1=np.arange(N), y1=np.arange(N), w1=[35]*N, h1=[64]*N,)) # creating x and y axis rangexdr = Range1d(start=-100, end=300)ydr = Range1d(start=-100, end=300) # creating a plot with above x and y axes rangeplot = Plot( title=None, x_range=xdr, y_range=ydr, plot_width=400, plot_height=400, min_border=0, toolbar_location=None) # loading the image using imageUrlimage = ImageURL(url=[\"https://media.geeksforgeeks.org/\\wp-content/uploads/20210829161730/logo.png\"], x=50, y=80, w=200, h=250, anchor=\"bottom_left\")image1 = ImageURL(url=\"url\", x=\"x1\", y=\"y1\", w=\"w1\", h=\"h1\", anchor=\"center\") # rendering the images to the plotplot.add_glyph(source, image)plot.add_glyph(source, image1) xaxis = LinearAxis()plot.add_layout(xaxis, 'below') yaxis = LinearAxis()plot.add_layout(yaxis, 'left') # adding grid lines to the plotplot.add_layout(Grid(dimension=0, ticker=xaxis.ticker, grid_line_color='#00ff00')) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker, grid_line_color='#00ff00')) # creates output filecurdoc().add_root(plot)curdoc().theme = 'caliber' # showing the plot on output fileshow(plot)",
"e": 29742,
"s": 28140,
"text": null
},
{
"code": null,
"e": 29750,
"s": 29742,
"text": "Output:"
},
{
"code": null,
"e": 29982,
"s": 29750,
"text": "We are creating ColumnDataSource which provides data to the Glyphs of our plot. Bokeh has its own data structure called ColumnDataSource which can be used as an input to any Bokeh object. We are creating the data with NumPy arrays."
},
{
"code": null,
"e": 30146,
"s": 29982,
"text": "Now create the x and y range using range1d which creates a range in a scalar dimension and then assign it to xdr and ydr which we will use while creating the plot."
},
{
"code": null,
"e": 30263,
"s": 30146,
"text": "We then create the plot with xdr and ydr as x_range and y_range and setting the height and width of the plot as 400."
},
{
"code": null,
"e": 30456,
"s": 30263,
"text": "We are then retrieving the image from the URL we declared before by setting the values of all the parameters as shown in the code. We are using two images over here by giving different values."
},
{
"code": null,
"e": 30495,
"s": 30456,
"text": "Now, we render the images to the plot."
},
{
"code": null,
"e": 30590,
"s": 30495,
"text": "Next, we add the grid lines to the plot using the Grid function and give it the color ‘green’."
},
{
"code": null,
"e": 30718,
"s": 30590,
"text": "Then, we add the plot to the app code curdoc which represents a new document and is sent to the bokehJs to show it to the user."
},
{
"code": null,
"e": 30861,
"s": 30718,
"text": "In this example, we are creating a figure with a circle glyph and then simply rendering the image from the given URL using the glyph ImageURL."
},
{
"code": null,
"e": 30868,
"s": 30861,
"text": "Python"
},
{
"code": "# importing numpy package and other librariesimport numpy as npfrom bokeh.io import curdoc, showfrom bokeh.models import ColumnDataSource, Grid, ImageURL, LinearAxis, Plot, Range1dfrom bokeh.plotting import figure # create dict as basis for ColumnDataSourcedata = {'x1': [10, 20, 30, 40, 50], 'y1': [60, 70, 80, 90, 100]} # create ColumnDataSource based on dictsource = ColumnDataSource(data=data) # creating figurep = figure(plot_height=500, plot_width=500)p.circle(x=\"x1\", y=\"y1\", size=20, source=source) # rendering the image using imageUrlimage = ImageURL(url=[\"https://media.geeksforgeeks.org/\\wp-content/uploads/20210902155548/imgurl2-200x112.jpg\"], x=80, y=100, w=50, h=40, anchor=\"center\", retry_attempts=2) # adding the images to the plotp.add_glyph(source, image) # creates output filecurdoc().add_root(p) # showing the plot on output fileshow(p)",
"e": 31772,
"s": 30868,
"text": null
},
{
"code": null,
"e": 31781,
"s": 31772,
"text": " Output:"
},
{
"code": null,
"e": 31796,
"s": 31781,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 31809,
"s": 31796,
"text": "Python-Bokeh"
},
{
"code": null,
"e": 31819,
"s": 31809,
"text": "Blogathon"
},
{
"code": null,
"e": 31826,
"s": 31819,
"text": "Python"
},
{
"code": null,
"e": 31924,
"s": 31826,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31981,
"s": 31924,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 32022,
"s": 31981,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 32052,
"s": 32022,
"text": "Stratified Sampling in Pandas"
},
{
"code": null,
"e": 32087,
"s": 32052,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 32131,
"s": 32087,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 32159,
"s": 32131,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 32209,
"s": 32159,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 32231,
"s": 32209,
"text": "Python map() function"
}
] |
Tridiagonal matrix in python - GeeksforGeeks
|
02 Feb, 2021
A tridiagonal matrix is a matrix that has non-zero elements only at the main diagonal, diagonal below and above it. All other elements are zero. For this reason tridiagonal matrices of dimension smaller than or equal to 3 seem meaningless.
Example 1:
[a11, a22, 0 , 0 , 0 , 0 ]
[a21, a22, a23, 0 , 0 , 0 ]
[0 , a32, a33, a34, 0 , 0 ]
[0 , 0 , a43, a44, a55, 0 ]
[0 , 0 , 0 , a54, a55, a56]
[0 , 0 , 0 , 0 , a65, a66]
Example 2:
[1, 1, 0, 0, 0, 0]
[1, 1, 1, 0, 0, 0]
[0, 1, 1, 1, 0, 0]
[0, 0, 1, 1, 1, 0]
[0, 0, 0, 1, 1, 1]
[0, 0, 0, 0, 1, 1]
Take the size of the matrix as input
Check if greater than 3if not, exitif yes, proceed further
if not, exit
if yes, proceed further
Take elements of the matrix as input
Now put zero everywhere except at main diagonal and diagonals below and above the main diagonal.
Program:
Python3
# if you enter number n it will automatically # be considered as a square matrix of size n by nsize_of_a_matrix = int(input("Enter size the matrix that you want : ")) if size_of_a_matrix <= 3: # since size should be greater than 3 print("Please enter the size that is greater than 3") exit() diagonal = []numbers1 = [[0 for j in range(0, size_of_a_matrix)] for i in range(0, size_of_a_matrix)] # created a loop to enter numbersfor a in range(size_of_a_matrix): numbers1 = int(input(f"Enter the numbers for the main diagonal for position[{a}][{a}] : ")) # appending the values to the list diagonal.append(numbers1) diagonalAbove = []print("*********") # created a loop to enter numbersfor k in range(size_of_a_matrix-1): numbers2 = int(input(f"Enter the numbers for diagonal above the main diagonal for position[{k}][{k+1}]: ")) # appending the values to the list diagonalAbove.append(numbers2) diagonalBelow = []print("*********") # created a loop to enter numbersfor z in range(size_of_a_matrix-1): numbers3 = int(input(f"Enter the numbers for diagonal below the main diagonal for position[{z+1}][{z}]: ")) # appending the values to the list diagonalBelow.append(numbers3)print("*********") def tridiagonal(size_of_a_matrix, diagonal, diagonalAbove, diagonalBelow): matrix = [[0 for j in range(size_of_a_matrix)] for i in range(size_of_a_matrix)] for k in range(size_of_a_matrix-1): matrix[k][k] = diagonal[k] matrix[k][k+1] = diagonalAbove[k] matrix[k+1][k] = diagonalBelow[k] matrix[size_of_a_matrix-1][size_of_a_matrix - 1] = diagonal[size_of_a_matrix-1] # so that the values will print row by row for row in matrix: print(row) return "this is the tridiagonal matrix" # printing final valuesprint(tridiagonal(size_of_a_matrix, diagonal, diagonalAbove, diagonalBelow))
Output:
output of our program
Python-Matrix
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 25801,
"s": 25561,
"text": "A tridiagonal matrix is a matrix that has non-zero elements only at the main diagonal, diagonal below and above it. All other elements are zero. For this reason tridiagonal matrices of dimension smaller than or equal to 3 seem meaningless."
},
{
"code": null,
"e": 25812,
"s": 25801,
"text": "Example 1:"
},
{
"code": null,
"e": 25851,
"s": 25812,
"text": "[a11, a22, 0 , 0 , 0 , 0 ] "
},
{
"code": null,
"e": 25887,
"s": 25851,
"text": "[a21, a22, a23, 0 , 0 , 0 ]"
},
{
"code": null,
"e": 25923,
"s": 25887,
"text": "[0 , a32, a33, a34, 0 , 0 ]"
},
{
"code": null,
"e": 25959,
"s": 25923,
"text": "[0 , 0 , a43, a44, a55, 0 ]"
},
{
"code": null,
"e": 25995,
"s": 25959,
"text": "[0 , 0 , 0 , a54, a55, a56]"
},
{
"code": null,
"e": 26031,
"s": 25995,
"text": "[0 , 0 , 0 , 0 , a65, a66]"
},
{
"code": null,
"e": 26042,
"s": 26031,
"text": "Example 2:"
},
{
"code": null,
"e": 26069,
"s": 26042,
"text": "[1, 1, 0, 0, 0, 0] "
},
{
"code": null,
"e": 26093,
"s": 26069,
"text": "[1, 1, 1, 0, 0, 0]"
},
{
"code": null,
"e": 26117,
"s": 26093,
"text": "[0, 1, 1, 1, 0, 0]"
},
{
"code": null,
"e": 26141,
"s": 26117,
"text": "[0, 0, 1, 1, 1, 0]"
},
{
"code": null,
"e": 26165,
"s": 26141,
"text": "[0, 0, 0, 1, 1, 1]"
},
{
"code": null,
"e": 26189,
"s": 26165,
"text": "[0, 0, 0, 0, 1, 1]"
},
{
"code": null,
"e": 26226,
"s": 26189,
"text": "Take the size of the matrix as input"
},
{
"code": null,
"e": 26285,
"s": 26226,
"text": "Check if greater than 3if not, exitif yes, proceed further"
},
{
"code": null,
"e": 26298,
"s": 26285,
"text": "if not, exit"
},
{
"code": null,
"e": 26322,
"s": 26298,
"text": "if yes, proceed further"
},
{
"code": null,
"e": 26359,
"s": 26322,
"text": "Take elements of the matrix as input"
},
{
"code": null,
"e": 26456,
"s": 26359,
"text": "Now put zero everywhere except at main diagonal and diagonals below and above the main diagonal."
},
{
"code": null,
"e": 26465,
"s": 26456,
"text": "Program:"
},
{
"code": null,
"e": 26473,
"s": 26465,
"text": "Python3"
},
{
"code": "# if you enter number n it will automatically # be considered as a square matrix of size n by nsize_of_a_matrix = int(input(\"Enter size the matrix that you want : \")) if size_of_a_matrix <= 3: # since size should be greater than 3 print(\"Please enter the size that is greater than 3\") exit() diagonal = []numbers1 = [[0 for j in range(0, size_of_a_matrix)] for i in range(0, size_of_a_matrix)] # created a loop to enter numbersfor a in range(size_of_a_matrix): numbers1 = int(input(f\"Enter the numbers for the main diagonal for position[{a}][{a}] : \")) # appending the values to the list diagonal.append(numbers1) diagonalAbove = []print(\"*********\") # created a loop to enter numbersfor k in range(size_of_a_matrix-1): numbers2 = int(input(f\"Enter the numbers for diagonal above the main diagonal for position[{k}][{k+1}]: \")) # appending the values to the list diagonalAbove.append(numbers2) diagonalBelow = []print(\"*********\") # created a loop to enter numbersfor z in range(size_of_a_matrix-1): numbers3 = int(input(f\"Enter the numbers for diagonal below the main diagonal for position[{z+1}][{z}]: \")) # appending the values to the list diagonalBelow.append(numbers3)print(\"*********\") def tridiagonal(size_of_a_matrix, diagonal, diagonalAbove, diagonalBelow): matrix = [[0 for j in range(size_of_a_matrix)] for i in range(size_of_a_matrix)] for k in range(size_of_a_matrix-1): matrix[k][k] = diagonal[k] matrix[k][k+1] = diagonalAbove[k] matrix[k+1][k] = diagonalBelow[k] matrix[size_of_a_matrix-1][size_of_a_matrix - 1] = diagonal[size_of_a_matrix-1] # so that the values will print row by row for row in matrix: print(row) return \"this is the tridiagonal matrix\" # printing final valuesprint(tridiagonal(size_of_a_matrix, diagonal, diagonalAbove, diagonalBelow))",
"e": 28413,
"s": 26473,
"text": null
},
{
"code": null,
"e": 28421,
"s": 28413,
"text": "Output:"
},
{
"code": null,
"e": 28443,
"s": 28421,
"text": "output of our program"
},
{
"code": null,
"e": 28457,
"s": 28443,
"text": "Python-Matrix"
},
{
"code": null,
"e": 28464,
"s": 28457,
"text": "Python"
},
{
"code": null,
"e": 28562,
"s": 28464,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28594,
"s": 28562,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28636,
"s": 28594,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28678,
"s": 28636,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28705,
"s": 28678,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28761,
"s": 28705,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28783,
"s": 28761,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28822,
"s": 28783,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28853,
"s": 28822,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28882,
"s": 28853,
"text": "Create a directory in Python"
}
] |
Central Tendency in R Programming - GeeksforGeeks
|
10 May, 2020
Central Tendency is one of the feature of descriptive statistics. Central tendency tells about how the group of data is clustered around the centre value of the distribution. Central tendency performs the following measures:
Arithmetic Mean
Geometric Mean
Harmonic Mean
Median
Mode
The arithmetic mean is simply called the average of the numbers which represents the central value of the data distribution. It is calculated by adding all the values and then dividing by the total number of observations.
Formula:
where,
X indicates the arithmetic mean indicates value in data vectorn indicates total number of observations
In R language, arithmetic mean can be calculated by mean() function.
Syntax: mean(x, trim, na.rm = FALSE)
Parameters:x: Represents objecttrim: Specifies number of values to be removed from each side of object before calculating the mean. The value is between 0 to 0.5na.rm: If TRUE then removes the NA value from x
Example:
# Defining vectorx <- c(3, 7, 5, 13, 20, 23, 39, 23, 40, 23, 14, 12, 56, 23) # Print meanprint(mean(x))
Output:
[1] 21.5
The geometric mean is a type of mean that is computed by multiplying all the data values and thus, shows the central tendency for given data distribution.
Formula:
where,
X indicates geometric mean indicates value in data vectorn indicates total number of observations
prod() and length() function helps in finding the geometric mean for given set of numbers as there is no direct function for geometric mean.
Syntax:
prod(x)^(1/length(x))
where,prod() function returns the product of all values present in vector xlength() function returns the length of vector x
Example:
# Defining vectorx <- c(1, 5, 9, 19, 25) # Print Geometric Meanprint(prod(x)^(1 / length(x)))
Output:
[1] 7.344821
Harmonic mean is another type of mean used as another measure of central tendency. It is computed as reciprocal of the arithmetic mean of reciprocals of the given set of values.
Formula:
where,
X indicates harmonic mean indicates value in data vectorn indicates total number of observations
Example:Modifying the code to find the harmonic mean of given set of values.
# Defining vectorx <- c(1, 5, 8, 10) # Print Harmonic Meanprint(1 / mean(1 / x))
Output:
[1] 2.807018
Median in statistics is another measure of central tendency which represents the middlemost value of a given set of values.
In R language, median can be calculated by median() function.
Syntax: median(x, na.rm = FALSE)
Parameters:x: It is the data vectorna.rm: If TRUE then removes the NA value from x
Example:
# Defining vectorx <- c(3, 7, 5, 13, 20, 23, 39, 23, 40, 23, 14, 12, 56, 23) # Print Medianmedian(x)
Output:
[1] 21.5
The mode of a given set of values is the value that is repeated most in the set. There can exist multiple mode values in case if there are two or more values with matching maximum frequency.
Example 1: Single-mode valueIn R language, there is no function to calculate mode. So, modifying the code to find out the mode for a given set of values.
# Defining vectorx <- c(3, 7, 5, 13, 20, 23, 39, 23, 40, 23, 14, 12, 56, 23, 29, 56, 37, 45, 1, 25, 8) # Generate frequency tabley <- table(x) # Print frequency tableprint(y) # Mode of xm <- names(y)[which(y == max(y))] # Print modeprint(m)
Output:
x
1 3 5 7 8 12 13 14 20 23 25 29 37 39 40 45 56
1 1 1 1 1 1 1 1 1 4 1 1 1 1 1 1 2
[1] "23"
Example 2: Multiple Mode values
# Defining vectorx <- c(3, 7, 5, 13, 20, 23, 39, 23, 40, 23, 14, 12, 56, 23, 29, 56, 37, 45, 1, 25, 8, 56, 56) # Generate frequency tabley <- table(x) # Print frequency tableprint(y) # Mode of xm <- names(y)[which(y == max(y))] # Print modeprint(m)
Output:
x
1 3 5 7 8 12 13 14 20 23 25 29 37 39 40 45 56
1 1 1 1 1 1 1 1 1 4 1 1 1 1 1 1 4
[1] "23" "56"
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
R Programming Language - Introduction
K-Means Clustering in R Programming
Replace Specific Characters in String in R
|
[
{
"code": null,
"e": 26105,
"s": 26077,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 26330,
"s": 26105,
"text": "Central Tendency is one of the feature of descriptive statistics. Central tendency tells about how the group of data is clustered around the centre value of the distribution. Central tendency performs the following measures:"
},
{
"code": null,
"e": 26346,
"s": 26330,
"text": "Arithmetic Mean"
},
{
"code": null,
"e": 26361,
"s": 26346,
"text": "Geometric Mean"
},
{
"code": null,
"e": 26375,
"s": 26361,
"text": "Harmonic Mean"
},
{
"code": null,
"e": 26382,
"s": 26375,
"text": "Median"
},
{
"code": null,
"e": 26387,
"s": 26382,
"text": "Mode"
},
{
"code": null,
"e": 26609,
"s": 26387,
"text": "The arithmetic mean is simply called the average of the numbers which represents the central value of the data distribution. It is calculated by adding all the values and then dividing by the total number of observations."
},
{
"code": null,
"e": 26618,
"s": 26609,
"text": "Formula:"
},
{
"code": null,
"e": 26625,
"s": 26618,
"text": "where,"
},
{
"code": null,
"e": 26729,
"s": 26625,
"text": "X indicates the arithmetic mean indicates value in data vectorn indicates total number of observations"
},
{
"code": null,
"e": 26798,
"s": 26729,
"text": "In R language, arithmetic mean can be calculated by mean() function."
},
{
"code": null,
"e": 26835,
"s": 26798,
"text": "Syntax: mean(x, trim, na.rm = FALSE)"
},
{
"code": null,
"e": 27044,
"s": 26835,
"text": "Parameters:x: Represents objecttrim: Specifies number of values to be removed from each side of object before calculating the mean. The value is between 0 to 0.5na.rm: If TRUE then removes the NA value from x"
},
{
"code": null,
"e": 27053,
"s": 27044,
"text": "Example:"
},
{
"code": "# Defining vectorx <- c(3, 7, 5, 13, 20, 23, 39, 23, 40, 23, 14, 12, 56, 23) # Print meanprint(mean(x))",
"e": 27158,
"s": 27053,
"text": null
},
{
"code": null,
"e": 27166,
"s": 27158,
"text": "Output:"
},
{
"code": null,
"e": 27176,
"s": 27166,
"text": "[1] 21.5\n"
},
{
"code": null,
"e": 27331,
"s": 27176,
"text": "The geometric mean is a type of mean that is computed by multiplying all the data values and thus, shows the central tendency for given data distribution."
},
{
"code": null,
"e": 27340,
"s": 27331,
"text": "Formula:"
},
{
"code": null,
"e": 27347,
"s": 27340,
"text": "where,"
},
{
"code": null,
"e": 27446,
"s": 27347,
"text": "X indicates geometric mean indicates value in data vectorn indicates total number of observations"
},
{
"code": null,
"e": 27587,
"s": 27446,
"text": "prod() and length() function helps in finding the geometric mean for given set of numbers as there is no direct function for geometric mean."
},
{
"code": null,
"e": 27595,
"s": 27587,
"text": "Syntax:"
},
{
"code": null,
"e": 27618,
"s": 27595,
"text": "prod(x)^(1/length(x))\n"
},
{
"code": null,
"e": 27742,
"s": 27618,
"text": "where,prod() function returns the product of all values present in vector xlength() function returns the length of vector x"
},
{
"code": null,
"e": 27751,
"s": 27742,
"text": "Example:"
},
{
"code": "# Defining vectorx <- c(1, 5, 9, 19, 25) # Print Geometric Meanprint(prod(x)^(1 / length(x)))",
"e": 27846,
"s": 27751,
"text": null
},
{
"code": null,
"e": 27854,
"s": 27846,
"text": "Output:"
},
{
"code": null,
"e": 27868,
"s": 27854,
"text": "[1] 7.344821\n"
},
{
"code": null,
"e": 28046,
"s": 27868,
"text": "Harmonic mean is another type of mean used as another measure of central tendency. It is computed as reciprocal of the arithmetic mean of reciprocals of the given set of values."
},
{
"code": null,
"e": 28055,
"s": 28046,
"text": "Formula:"
},
{
"code": null,
"e": 28062,
"s": 28055,
"text": "where,"
},
{
"code": null,
"e": 28160,
"s": 28062,
"text": "X indicates harmonic mean indicates value in data vectorn indicates total number of observations"
},
{
"code": null,
"e": 28237,
"s": 28160,
"text": "Example:Modifying the code to find the harmonic mean of given set of values."
},
{
"code": "# Defining vectorx <- c(1, 5, 8, 10) # Print Harmonic Meanprint(1 / mean(1 / x))",
"e": 28319,
"s": 28237,
"text": null
},
{
"code": null,
"e": 28327,
"s": 28319,
"text": "Output:"
},
{
"code": null,
"e": 28341,
"s": 28327,
"text": "[1] 2.807018\n"
},
{
"code": null,
"e": 28465,
"s": 28341,
"text": "Median in statistics is another measure of central tendency which represents the middlemost value of a given set of values."
},
{
"code": null,
"e": 28527,
"s": 28465,
"text": "In R language, median can be calculated by median() function."
},
{
"code": null,
"e": 28560,
"s": 28527,
"text": "Syntax: median(x, na.rm = FALSE)"
},
{
"code": null,
"e": 28643,
"s": 28560,
"text": "Parameters:x: It is the data vectorna.rm: If TRUE then removes the NA value from x"
},
{
"code": null,
"e": 28652,
"s": 28643,
"text": "Example:"
},
{
"code": "# Defining vectorx <- c(3, 7, 5, 13, 20, 23, 39, 23, 40, 23, 14, 12, 56, 23) # Print Medianmedian(x)",
"e": 28761,
"s": 28652,
"text": null
},
{
"code": null,
"e": 28769,
"s": 28761,
"text": "Output:"
},
{
"code": null,
"e": 28779,
"s": 28769,
"text": "[1] 21.5\n"
},
{
"code": null,
"e": 28970,
"s": 28779,
"text": "The mode of a given set of values is the value that is repeated most in the set. There can exist multiple mode values in case if there are two or more values with matching maximum frequency."
},
{
"code": null,
"e": 29124,
"s": 28970,
"text": "Example 1: Single-mode valueIn R language, there is no function to calculate mode. So, modifying the code to find out the mode for a given set of values."
},
{
"code": "# Defining vectorx <- c(3, 7, 5, 13, 20, 23, 39, 23, 40, 23, 14, 12, 56, 23, 29, 56, 37, 45, 1, 25, 8) # Generate frequency tabley <- table(x) # Print frequency tableprint(y) # Mode of xm <- names(y)[which(y == max(y))] # Print modeprint(m)",
"e": 29383,
"s": 29124,
"text": null
},
{
"code": null,
"e": 29391,
"s": 29383,
"text": "Output:"
},
{
"code": null,
"e": 29506,
"s": 29391,
"text": "x\n 1 3 5 7 8 12 13 14 20 23 25 29 37 39 40 45 56 \n 1 1 1 1 1 1 1 1 1 4 1 1 1 1 1 1 2\n[1] \"23\"\n"
},
{
"code": null,
"e": 29538,
"s": 29506,
"text": "Example 2: Multiple Mode values"
},
{
"code": "# Defining vectorx <- c(3, 7, 5, 13, 20, 23, 39, 23, 40, 23, 14, 12, 56, 23, 29, 56, 37, 45, 1, 25, 8, 56, 56) # Generate frequency tabley <- table(x) # Print frequency tableprint(y) # Mode of xm <- names(y)[which(y == max(y))] # Print modeprint(m)",
"e": 29804,
"s": 29538,
"text": null
},
{
"code": null,
"e": 29812,
"s": 29804,
"text": "Output:"
},
{
"code": null,
"e": 29933,
"s": 29812,
"text": "x\n 1 3 5 7 8 12 13 14 20 23 25 29 37 39 40 45 56 \n 1 1 1 1 1 1 1 1 1 4 1 1 1 1 1 1 4 \n[1] \"23\" \"56\"\n"
},
{
"code": null,
"e": 29946,
"s": 29933,
"text": "R-Statistics"
},
{
"code": null,
"e": 29957,
"s": 29946,
"text": "R Language"
},
{
"code": null,
"e": 30055,
"s": 29957,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30107,
"s": 30055,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 30139,
"s": 30107,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 30191,
"s": 30139,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30235,
"s": 30191,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 30270,
"s": 30235,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30308,
"s": 30270,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 30366,
"s": 30308,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30404,
"s": 30366,
"text": "R Programming Language - Introduction"
},
{
"code": null,
"e": 30440,
"s": 30404,
"text": "K-Means Clustering in R Programming"
}
] |
Check for balanced parentheses in an expression | O(1) space | O(N^2) time complexity - GeeksforGeeks
|
09 Sep, 2020
Given a string str containing characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, the task is to determine if brackets are balanced or not.Brackets are balanced if:
Open brackets must be closed by the same type of brackets.Open brackets must be closed in the correct order.
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Examples:
Input: str = “(())[]”Output: Yes
Input: str = “))(({}{”Output: No
Approach:
Keep two variables i and j to keep track of two brackets to be compared.
Maintain a count whose value increments on encountering opening bracket and decrements on encountering a closing bracket.
Set j = i, i = i + 1 and counter++ when opening brackets are encountered.
When Closing brackets are encountered decrement count and compare brackets at i and j,If brackets at i and j are a match, then substitute ‘#’ in string at ith and jth position. Increment i and decrement j until non ‘#’ value is encountered or j ≥ 0.If brackets at i and j are not a match then return false.
If brackets at i and j are a match, then substitute ‘#’ in string at ith and jth position. Increment i and decrement j until non ‘#’ value is encountered or j ≥ 0.
If brackets at i and j are not a match then return false.
If count != 0 then return false.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ implementation of the approach #include <iostream> using namespace std; // This helper function is called whenever // closing bracket is encountered. // Hence count is decremented // j and i points to opening and closing // brackets to be matched respectively // If brackets at i and j is a match // replace them with "#" character and decrement j // to point next opening bracket to * be matched // Similarly, increment i to point to next closing // bracket to be matched // If j is out of bound or brackets did not match return 0 bool helperFunc(int& count, string& s, int& i, int& j, char tocom) { count--; if (j > -1 && s[j] == tocom) { s[i] = '#'; s[j] = '#'; while (j >= 0 && s[j] == '#') j--; i++; return 1; } else return 0; } // Function that returns true if s is a // valid balanced bracket string bool isValid(string s) { // Empty string is considered balanced if (s.length() == 0) return true; else { int i = 0; // Increments for opening bracket and // decrements for closing bracket int count = 0; int j = -1; bool result; while (i < s.length()) { switch (s[i]) { case '}': result = helperFunc(count, s, i, j, '{'); if (result == 0) { return false; } break; case ')': result = helperFunc(count, s, i, j, '('); if (result == 0) { return false; } break; case ']': result = helperFunc(count, s, i, j, '['); if (result == 0) { return false; } break; default: j = i; i++; count++; } } // count != 0 indicates unbalanced parentheses // this check is required to handle cases where // count of opening brackets > closing brackets if (count != 0) return false; return true; } } // Driver code int main() { string str = "[[]][]()"; if (isValid(str)) cout << "Yes"; else cout << "No"; return 0; }
// Java implementation of the approach import java.util.*; class GFG { static String s = "[[]][]()"; static int count = 0; static int i = 0; static int j = -1; // This helper function is called whenever // closing bracket is encountered. // Hence count is decremented // j and i points to opening and closing // brackets to be matched respectively // If brackets at i and j is a match // replace them with "#" character and decrement j // to point next opening bracket to * be matched // Similarly, increment i to point to next closing // bracket to be matched // If j is out of bound or brackets did not match return 0 static int helperFunc(char tocom) { count--; char temp = s.charAt(j); if (j > -1 && temp == tocom) { s = s.replace(s.charAt(i),'#'); s = s.replace(s.charAt(j),'#'); temp = s.charAt(j); while (j >= 0 && temp == '#') j--; i++; return 1; } else return 0; } // Function that returns true if s is a // valid balanced bracket string static boolean isValid() { // Empty string is considered balanced if (s.length() == 0) return true; else { int result; while (i < s.length()) { char temp = s.charAt(i); if(temp=='}') { result = helperFunc('{'); if (result == 0) { return false; } } else if(temp == ')') { result = helperFunc('('); if (result == 0) { return false; } } else if(temp == ']') { result = helperFunc('['); if (result == 0) { return false; } } else { j = i; i++; count++; } } // count != 0 indicates unbalanced parentheses // this check is required to handle cases where // count of opening brackets > closing brackets if (count != 0) return false; return true; } } // Driver code public static void main(String args[]) { if (isValid()) System.out.println("No"); else System.out.println("Yes"); } } // This code is contributed by Surendra_Gangwar
# Python3 implementation of the approach # These are defined as global because they # are passed by reference count = 0i = 0j = -1 # This helper function is called whenever # closing bracket is encountered. # Hence count is decremented # j and i points to opening and closing # brackets to be matched respectively # If brackets at i and j is a match # replace them with "#" character and decrement j # to point next opening bracket to * be matched # Similarly, increment i to point to next closing # bracket to be matched # If j is out of bound or brackets # did not match return 0 def helperFunc(s, tocom): global i, j, count count -= 1 if j > -1 and s[j] == tocom: s[i] = '#' s[j] = '#' while j >= 0 and s[j] == '#': j -= 1 i += 1 return 1 else: return 0 # Function that returns true if s is a # valid balanced bracket string def isValid(s): global i, j, count # Empty string is considered balanced if len(s) == 0: return True else: # Increments for opening bracket and # decrements for closing bracket result = False while i < len(s): if s[i] == '}': result = helperFunc(s, '{') if result == 0: return False elif s[i] == ')': result = helperFunc(s, '(') if result == 0: return False elif s[i] == ']': result = helperFunc(s, '[') if result == 0: return False else: j = i i += 1 count += 1 # count != 0 indicates unbalanced parentheses # this check is required to handle cases where # count of opening brackets > closing brackets if count != 0: return False return True # Driver Code if __name__ == "__main__": string = "[[]][]()" string = list(string) print("Yes") if isValid(string) else print("No") # This code is contributed by # sanjeev2552
// C# implementation of the approachusing System; class GFG{ static string s = "[[]][]()";static int count = 0;static int i = 0;static int j = -1; // This helper function is called whenever// closing bracket is encountered. Hence // count is decremented j and i points to// opening and closing brackets to be matched // respectively. If brackets at i and j is a match// replace them with "#" character and decrement j// to point next opening bracket to * be matched// Similarly, increment i to point to next closing// bracket to be matched. If j is out of bound or// brackets did not match return 0static int helperFunc(char tocom){ count--; char temp = s[j]; if (j > -1 && temp == tocom) { s = s.Replace(s[i],'#'); s = s.Replace(s[j],'#'); temp = s[j]; while (j >= 0 && temp == '#') j--; i++; return 1; } else return 0;} // Function that returns true if s is a// valid balanced bracket stringstatic bool isValid(){ // Empty string is considered balanced if (s.Length == 0) return true; else { int result; while (i < s.Length) { char temp = s[i]; if(temp == '}') { result = helperFunc('{'); if (result == 0) { return false; } } else if(temp == ')') { result = helperFunc('('); if (result == 0) { return false; } } else if(temp == ']') { result = helperFunc('['); if (result == 0) { return false; } } else { j = i; i++; count++; } } // count != 0 indicates unbalanced // parentheses this check is required // to handle cases where count of opening // brackets > closing brackets if (count != 0) return false; return true; }} // Driver codepublic static void Main(string []args){ if (isValid()) { Console.Write("No"); } else { Console.Write("Yes"); }}} // This code is contributed by rutvik_56
Yes
sanjeev2552
SURENDRA_GANGWAR
rutvik_56
Constructive Algorithms
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 25963,
"s": 25935,
"text": "\n09 Sep, 2020"
},
{
"code": null,
"e": 26120,
"s": 25963,
"text": "Given a string str containing characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, the task is to determine if brackets are balanced or not.Brackets are balanced if:"
},
{
"code": null,
"e": 26229,
"s": 26120,
"text": "Open brackets must be closed by the same type of brackets.Open brackets must be closed in the correct order."
},
{
"code": null,
"e": 26288,
"s": 26229,
"text": "Open brackets must be closed by the same type of brackets."
},
{
"code": null,
"e": 26339,
"s": 26288,
"text": "Open brackets must be closed in the correct order."
},
{
"code": null,
"e": 26349,
"s": 26339,
"text": "Examples:"
},
{
"code": null,
"e": 26382,
"s": 26349,
"text": "Input: str = “(())[]”Output: Yes"
},
{
"code": null,
"e": 26415,
"s": 26382,
"text": "Input: str = “))(({}{”Output: No"
},
{
"code": null,
"e": 26425,
"s": 26415,
"text": "Approach:"
},
{
"code": null,
"e": 26498,
"s": 26425,
"text": "Keep two variables i and j to keep track of two brackets to be compared."
},
{
"code": null,
"e": 26620,
"s": 26498,
"text": "Maintain a count whose value increments on encountering opening bracket and decrements on encountering a closing bracket."
},
{
"code": null,
"e": 26694,
"s": 26620,
"text": "Set j = i, i = i + 1 and counter++ when opening brackets are encountered."
},
{
"code": null,
"e": 27001,
"s": 26694,
"text": "When Closing brackets are encountered decrement count and compare brackets at i and j,If brackets at i and j are a match, then substitute ‘#’ in string at ith and jth position. Increment i and decrement j until non ‘#’ value is encountered or j ≥ 0.If brackets at i and j are not a match then return false."
},
{
"code": null,
"e": 27165,
"s": 27001,
"text": "If brackets at i and j are a match, then substitute ‘#’ in string at ith and jth position. Increment i and decrement j until non ‘#’ value is encountered or j ≥ 0."
},
{
"code": null,
"e": 27223,
"s": 27165,
"text": "If brackets at i and j are not a match then return false."
},
{
"code": null,
"e": 27256,
"s": 27223,
"text": "If count != 0 then return false."
},
{
"code": null,
"e": 27307,
"s": 27256,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27311,
"s": 27307,
"text": "C++"
},
{
"code": null,
"e": 27316,
"s": 27311,
"text": "Java"
},
{
"code": null,
"e": 27324,
"s": 27316,
"text": "Python3"
},
{
"code": null,
"e": 27327,
"s": 27324,
"text": "C#"
},
{
"code": "// C++ implementation of the approach #include <iostream> using namespace std; // This helper function is called whenever // closing bracket is encountered. // Hence count is decremented // j and i points to opening and closing // brackets to be matched respectively // If brackets at i and j is a match // replace them with \"#\" character and decrement j // to point next opening bracket to * be matched // Similarly, increment i to point to next closing // bracket to be matched // If j is out of bound or brackets did not match return 0 bool helperFunc(int& count, string& s, int& i, int& j, char tocom) { count--; if (j > -1 && s[j] == tocom) { s[i] = '#'; s[j] = '#'; while (j >= 0 && s[j] == '#') j--; i++; return 1; } else return 0; } // Function that returns true if s is a // valid balanced bracket string bool isValid(string s) { // Empty string is considered balanced if (s.length() == 0) return true; else { int i = 0; // Increments for opening bracket and // decrements for closing bracket int count = 0; int j = -1; bool result; while (i < s.length()) { switch (s[i]) { case '}': result = helperFunc(count, s, i, j, '{'); if (result == 0) { return false; } break; case ')': result = helperFunc(count, s, i, j, '('); if (result == 0) { return false; } break; case ']': result = helperFunc(count, s, i, j, '['); if (result == 0) { return false; } break; default: j = i; i++; count++; } } // count != 0 indicates unbalanced parentheses // this check is required to handle cases where // count of opening brackets > closing brackets if (count != 0) return false; return true; } } // Driver code int main() { string str = \"[[]][]()\"; if (isValid(str)) cout << \"Yes\"; else cout << \"No\"; return 0; } ",
"e": 29678,
"s": 27327,
"text": null
},
{
"code": "// Java implementation of the approach import java.util.*; class GFG { static String s = \"[[]][]()\"; static int count = 0; static int i = 0; static int j = -1; // This helper function is called whenever // closing bracket is encountered. // Hence count is decremented // j and i points to opening and closing // brackets to be matched respectively // If brackets at i and j is a match // replace them with \"#\" character and decrement j // to point next opening bracket to * be matched // Similarly, increment i to point to next closing // bracket to be matched // If j is out of bound or brackets did not match return 0 static int helperFunc(char tocom) { count--; char temp = s.charAt(j); if (j > -1 && temp == tocom) { s = s.replace(s.charAt(i),'#'); s = s.replace(s.charAt(j),'#'); temp = s.charAt(j); while (j >= 0 && temp == '#') j--; i++; return 1; } else return 0; } // Function that returns true if s is a // valid balanced bracket string static boolean isValid() { // Empty string is considered balanced if (s.length() == 0) return true; else { int result; while (i < s.length()) { char temp = s.charAt(i); if(temp=='}') { result = helperFunc('{'); if (result == 0) { return false; } } else if(temp == ')') { result = helperFunc('('); if (result == 0) { return false; } } else if(temp == ']') { result = helperFunc('['); if (result == 0) { return false; } } else { j = i; i++; count++; } } // count != 0 indicates unbalanced parentheses // this check is required to handle cases where // count of opening brackets > closing brackets if (count != 0) return false; return true; } } // Driver code public static void main(String args[]) { if (isValid()) System.out.println(\"No\"); else System.out.println(\"Yes\"); } } // This code is contributed by Surendra_Gangwar ",
"e": 32176,
"s": 29678,
"text": null
},
{
"code": "# Python3 implementation of the approach # These are defined as global because they # are passed by reference count = 0i = 0j = -1 # This helper function is called whenever # closing bracket is encountered. # Hence count is decremented # j and i points to opening and closing # brackets to be matched respectively # If brackets at i and j is a match # replace them with \"#\" character and decrement j # to point next opening bracket to * be matched # Similarly, increment i to point to next closing # bracket to be matched # If j is out of bound or brackets # did not match return 0 def helperFunc(s, tocom): global i, j, count count -= 1 if j > -1 and s[j] == tocom: s[i] = '#' s[j] = '#' while j >= 0 and s[j] == '#': j -= 1 i += 1 return 1 else: return 0 # Function that returns true if s is a # valid balanced bracket string def isValid(s): global i, j, count # Empty string is considered balanced if len(s) == 0: return True else: # Increments for opening bracket and # decrements for closing bracket result = False while i < len(s): if s[i] == '}': result = helperFunc(s, '{') if result == 0: return False elif s[i] == ')': result = helperFunc(s, '(') if result == 0: return False elif s[i] == ']': result = helperFunc(s, '[') if result == 0: return False else: j = i i += 1 count += 1 # count != 0 indicates unbalanced parentheses # this check is required to handle cases where # count of opening brackets > closing brackets if count != 0: return False return True # Driver Code if __name__ == \"__main__\": string = \"[[]][]()\" string = list(string) print(\"Yes\") if isValid(string) else print(\"No\") # This code is contributed by # sanjeev2552 ",
"e": 34272,
"s": 32176,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static string s = \"[[]][]()\";static int count = 0;static int i = 0;static int j = -1; // This helper function is called whenever// closing bracket is encountered. Hence // count is decremented j and i points to// opening and closing brackets to be matched // respectively. If brackets at i and j is a match// replace them with \"#\" character and decrement j// to point next opening bracket to * be matched// Similarly, increment i to point to next closing// bracket to be matched. If j is out of bound or// brackets did not match return 0static int helperFunc(char tocom){ count--; char temp = s[j]; if (j > -1 && temp == tocom) { s = s.Replace(s[i],'#'); s = s.Replace(s[j],'#'); temp = s[j]; while (j >= 0 && temp == '#') j--; i++; return 1; } else return 0;} // Function that returns true if s is a// valid balanced bracket stringstatic bool isValid(){ // Empty string is considered balanced if (s.Length == 0) return true; else { int result; while (i < s.Length) { char temp = s[i]; if(temp == '}') { result = helperFunc('{'); if (result == 0) { return false; } } else if(temp == ')') { result = helperFunc('('); if (result == 0) { return false; } } else if(temp == ']') { result = helperFunc('['); if (result == 0) { return false; } } else { j = i; i++; count++; } } // count != 0 indicates unbalanced // parentheses this check is required // to handle cases where count of opening // brackets > closing brackets if (count != 0) return false; return true; }} // Driver codepublic static void Main(string []args){ if (isValid()) { Console.Write(\"No\"); } else { Console.Write(\"Yes\"); }}} // This code is contributed by rutvik_56",
"e": 36732,
"s": 34272,
"text": null
},
{
"code": null,
"e": 36737,
"s": 36732,
"text": "Yes\n"
},
{
"code": null,
"e": 36749,
"s": 36737,
"text": "sanjeev2552"
},
{
"code": null,
"e": 36766,
"s": 36749,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 36776,
"s": 36766,
"text": "rutvik_56"
},
{
"code": null,
"e": 36800,
"s": 36776,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 36813,
"s": 36800,
"text": "Mathematical"
},
{
"code": null,
"e": 36821,
"s": 36813,
"text": "Strings"
},
{
"code": null,
"e": 36829,
"s": 36821,
"text": "Strings"
},
{
"code": null,
"e": 36842,
"s": 36829,
"text": "Mathematical"
},
{
"code": null,
"e": 36940,
"s": 36842,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36984,
"s": 36940,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 37026,
"s": 36984,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 37057,
"s": 37026,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 37128,
"s": 37057,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 37153,
"s": 37128,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 37199,
"s": 37153,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 37224,
"s": 37199,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 37258,
"s": 37224,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 37333,
"s": 37258,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
numpy.amin() in Python - GeeksforGeeks
|
28 Apr, 2022
The numpy.amin() function returns minimum of an array or minimum along axis(if mentioned). Syntax : numpy.amin(arr, axis = None, out = None, keepdims = <class numpy._globals._NoValue>) Parameters :
arr : [array_like]input data
axis : [int or tuples of int]axis along which we want the min value. Otherwise, it will consider arr to be flattened.
out : [ndarray, optional]Alternative output array in which to place the result
keepdims : [boolean, optional]If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the all method of sub-classes of ndarray, however any non-default value will be. If the sub-classes sum method does not implement keepdims any exceptions will be raised.
Return : Minimum of array – arr[ndarray or scalar], scalar if axis is None; the result is an array of dimension a.ndim – 1, if axis is mentioned. Code –
Python
# Python Program illustrating# numpy.amin() method import numpy as geek # 1D arrayarr = geek.arange(8)print("arr : ", arr)print("Min of arr : ", geek.amin(arr)) # 2D arrayarr = geek.arange(10).reshape(2, 5)print("\narr : ", arr) # Minimum of the flattened arrayprint("\nMin of arr, axis = None : ", geek.amin(arr)) # Minimum along the first axis# axis 0 means verticalprint("Min of arr, axis = 0 : ", geek.amin(arr, axis = 0)) # Minimum along the second axis# axis 1 means horizontalprint("Min of arr, axis = 1 : ", geek.amin(arr, axis = 1))
Output –
arr : [0 1 2 3 4 5 6 7]
Min of arr : 0
arr : [[0 1 2 3 4]
[5 6 7 8 9]]
Min of arr, axis = None : 0
Min of arr, axis = 0 : [0 1 2 3 4]
Min of arr, axis = 1 : [0 5]
References – https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.amin.html#numpy.amin
Note – These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vinayedula
surinderdawra388
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
|
[
{
"code": null,
"e": 25673,
"s": 25645,
"text": "\n28 Apr, 2022"
},
{
"code": null,
"e": 25872,
"s": 25673,
"text": "The numpy.amin() function returns minimum of an array or minimum along axis(if mentioned). Syntax : numpy.amin(arr, axis = None, out = None, keepdims = <class numpy._globals._NoValue>) Parameters : "
},
{
"code": null,
"e": 25901,
"s": 25872,
"text": "arr : [array_like]input data"
},
{
"code": null,
"e": 26019,
"s": 25901,
"text": "axis : [int or tuples of int]axis along which we want the min value. Otherwise, it will consider arr to be flattened."
},
{
"code": null,
"e": 26098,
"s": 26019,
"text": "out : [ndarray, optional]Alternative output array in which to place the result"
},
{
"code": null,
"e": 26556,
"s": 26098,
"text": "keepdims : [boolean, optional]If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the all method of sub-classes of ndarray, however any non-default value will be. If the sub-classes sum method does not implement keepdims any exceptions will be raised."
},
{
"code": null,
"e": 26710,
"s": 26556,
"text": "Return : Minimum of array – arr[ndarray or scalar], scalar if axis is None; the result is an array of dimension a.ndim – 1, if axis is mentioned. Code – "
},
{
"code": null,
"e": 26717,
"s": 26710,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.amin() method import numpy as geek # 1D arrayarr = geek.arange(8)print(\"arr : \", arr)print(\"Min of arr : \", geek.amin(arr)) # 2D arrayarr = geek.arange(10).reshape(2, 5)print(\"\\narr : \", arr) # Minimum of the flattened arrayprint(\"\\nMin of arr, axis = None : \", geek.amin(arr)) # Minimum along the first axis# axis 0 means verticalprint(\"Min of arr, axis = 0 : \", geek.amin(arr, axis = 0)) # Minimum along the second axis# axis 1 means horizontalprint(\"Min of arr, axis = 1 : \", geek.amin(arr, axis = 1)) ",
"e": 27261,
"s": 26717,
"text": null
},
{
"code": null,
"e": 27271,
"s": 27261,
"text": "Output – "
},
{
"code": null,
"e": 27443,
"s": 27271,
"text": "arr : [0 1 2 3 4 5 6 7]\nMin of arr : 0\n\narr : [[0 1 2 3 4]\n [5 6 7 8 9]]\n\nMin of arr, axis = None : 0\nMin of arr, axis = 0 : [0 1 2 3 4]\nMin of arr, axis = 1 : [0 5]"
},
{
"code": null,
"e": 27544,
"s": 27443,
"text": "References – https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.amin.html#numpy.amin "
},
{
"code": null,
"e": 27650,
"s": 27544,
"text": "Note – These codes won’t run on online IDE’s. So please, run them on your systems to explore the working."
},
{
"code": null,
"e": 28075,
"s": 27650,
"text": "This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28086,
"s": 28075,
"text": "vinayedula"
},
{
"code": null,
"e": 28103,
"s": 28086,
"text": "surinderdawra388"
},
{
"code": null,
"e": 28110,
"s": 28103,
"text": "Python"
},
{
"code": null,
"e": 28208,
"s": 28110,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28226,
"s": 28208,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28258,
"s": 28226,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28300,
"s": 28258,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28326,
"s": 28300,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28355,
"s": 28326,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28399,
"s": 28355,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28436,
"s": 28399,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28472,
"s": 28436,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 28514,
"s": 28472,
"text": "Check if element exists in list in Python"
}
] |
Python OpenCV - cv2.rotate() method - GeeksforGeeks
|
08 Jun, 2020
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.rotate() method is used to rotate a 2D array in multiples of 90 degrees. The function cv::rotate rotates the array in three different ways.
Syntax: cv2.cv.rotate( src, rotateCode[, dst] )
Parameters:src: It is the image whose color space is to be changed.rotateCode: It is an enum to specify how to rotate the array.dst: It is the output image of the same size and depth as src image. It is an optional parameter.
Return Value: It returns an image.
Image used for all the below examples:
Example #1: Rotate by 90 degrees clockwise
# Python program to explain cv2.rotate() method # importing cv2import cv2 # pathpath = r'C:\Users\user\Desktop\geeks14.png' # Reading an image in default modesrc = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.rotate() method# Using cv2.ROTATE_90_CLOCKWISE rotate# by 90 degrees clockwiseimage = cv2.rotate(src, cv2.cv2.ROTATE_90_CLOCKWISE) # Displaying the imagecv2.imshow(window_name, image)cv2.waitKey(0)
Output:
Example #2: Rotate by 180 degrees clockwise
# Python program to explain cv2.rotate() method # importing cv2import cv2 # pathpath = r'C:\Users\user\Desktop\geeks14.png' # Reading an image in default modesrc = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.rotate() method# Using cv2.ROTATE_180 rotate by # 180 degrees clockwiseimage = cv2.rotate(src, cv2.ROTATE_180) # Displaying the imagecv2.imshow(window_name, image)cv2.waitKey(0)
Output:
Example #3: Rotate by 270 degrees clockwise
# Python program to explain cv2.rotate() method # importing cv2import cv2 # pathpath = r'C:\Users\user\Desktop\geeks14.png' # Reading an image in default modesrc = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.rotate() method# Using cv2.ROTATE_90_COUNTERCLOCKWISE # rotate by 270 degrees clockwiseimage = cv2.rotate(src, cv2.ROTATE_90_COUNTERCLOCKWISE) # Displaying the imagecv2.imshow(window_name, image)cv2.waitKey(0)
Output:
Image-Processing
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25723,
"s": 25695,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 25957,
"s": 25723,
"text": "OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.rotate() method is used to rotate a 2D array in multiples of 90 degrees. The function cv::rotate rotates the array in three different ways."
},
{
"code": null,
"e": 26005,
"s": 25957,
"text": "Syntax: cv2.cv.rotate( src, rotateCode[, dst] )"
},
{
"code": null,
"e": 26231,
"s": 26005,
"text": "Parameters:src: It is the image whose color space is to be changed.rotateCode: It is an enum to specify how to rotate the array.dst: It is the output image of the same size and depth as src image. It is an optional parameter."
},
{
"code": null,
"e": 26266,
"s": 26231,
"text": "Return Value: It returns an image."
},
{
"code": null,
"e": 26305,
"s": 26266,
"text": "Image used for all the below examples:"
},
{
"code": null,
"e": 26348,
"s": 26305,
"text": "Example #1: Rotate by 90 degrees clockwise"
},
{
"code": "# Python program to explain cv2.rotate() method # importing cv2import cv2 # pathpath = r'C:\\Users\\user\\Desktop\\geeks14.png' # Reading an image in default modesrc = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.rotate() method# Using cv2.ROTATE_90_CLOCKWISE rotate# by 90 degrees clockwiseimage = cv2.rotate(src, cv2.cv2.ROTATE_90_CLOCKWISE) # Displaying the imagecv2.imshow(window_name, image)cv2.waitKey(0)",
"e": 26808,
"s": 26348,
"text": null
},
{
"code": null,
"e": 26816,
"s": 26808,
"text": "Output:"
},
{
"code": null,
"e": 26860,
"s": 26816,
"text": "Example #2: Rotate by 180 degrees clockwise"
},
{
"code": "# Python program to explain cv2.rotate() method # importing cv2import cv2 # pathpath = r'C:\\Users\\user\\Desktop\\geeks14.png' # Reading an image in default modesrc = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.rotate() method# Using cv2.ROTATE_180 rotate by # 180 degrees clockwiseimage = cv2.rotate(src, cv2.ROTATE_180) # Displaying the imagecv2.imshow(window_name, image)cv2.waitKey(0)",
"e": 27300,
"s": 26860,
"text": null
},
{
"code": null,
"e": 27308,
"s": 27300,
"text": "Output:"
},
{
"code": null,
"e": 27352,
"s": 27308,
"text": "Example #3: Rotate by 270 degrees clockwise"
},
{
"code": "# Python program to explain cv2.rotate() method # importing cv2import cv2 # pathpath = r'C:\\Users\\user\\Desktop\\geeks14.png' # Reading an image in default modesrc = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.rotate() method# Using cv2.ROTATE_90_COUNTERCLOCKWISE # rotate by 270 degrees clockwiseimage = cv2.rotate(src, cv2.ROTATE_90_COUNTERCLOCKWISE) # Displaying the imagecv2.imshow(window_name, image)cv2.waitKey(0)",
"e": 27824,
"s": 27352,
"text": null
},
{
"code": null,
"e": 27832,
"s": 27824,
"text": "Output:"
},
{
"code": null,
"e": 27849,
"s": 27832,
"text": "Image-Processing"
},
{
"code": null,
"e": 27863,
"s": 27849,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 27870,
"s": 27863,
"text": "Python"
},
{
"code": null,
"e": 27968,
"s": 27870,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27986,
"s": 27968,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28018,
"s": 27986,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28040,
"s": 28018,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28082,
"s": 28040,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28108,
"s": 28082,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28137,
"s": 28108,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28181,
"s": 28137,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28218,
"s": 28181,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28254,
"s": 28218,
"text": "Convert integer to string in Python"
}
] |
Bitcoin Miners and Bitcoin Mining - GeeksforGeeks
|
11 May, 2022
Bitcoin is different from other types of traditional currency such as dollars or euros which you can also use to buy things and exchange value electronically, there are no physical coins for bitcoin or paper bills.
When we send bitcoin to someone, or use bitcoin to buy anything we don’t need to use a bank, a credit card or any other third party type of clearinghouse. Instead, we simply send bitcoin directly to another party over the internet and it will arrive securely and almost instantly.
There are four components of bitcoin:
1. Software
2. Cryptography
3. Hardware
4. Gaming theory
Bitcoin is basically a software that defines how a bitcoin gets transferred. It identifies what are the rules of a valid bitcoin. That software at its core uses cryptography and bitcoin is a cryptocurrency. As a cryptocurrency it uses cryptography to regulate the transfer of bitcoin between parties as well as creation of new units of bitcoin. So, if it wasn’t for cryptography, bitcoin would simply not be possible. All this needs to run on hardware. This hardware is composed of thousands of miners around the world running their computers.
The final component that ties it all together is gaming theory. Because bitcoin in essence is truly a game that is run by these miners around the world.
Bitcoin miners:Within the bitcoin network there are a group of people which are called miners and their role is to process and confirm transactions. Anybody can apply to be a miner, and you could run the client yourself.
Role of bitcoin miners:The role of the miners is to process and confirm transactions to chain together the blocks of transactions. Typically these miners use very powerful computers that are specifically designed to mine bitcoin transactions, and the way they do that is by actually solving math problems and resolving cryptography issues, because every one of these transactions need to be cryptographically encoded and secured. These mathematical problems are what actually ensures that the data is secure and nobody is tampering with that data.
How is bitcoin created:Bitcoin miners process transactions and secure the network using specialized hardware, therefore the miners are rewarded in bitcoin which is a key component of bitcoin. Because money in bitcoin is not created like you create normal fiat currency(like euros, dollars, rupees, etc) the way bitcoin is created is by rewarding these miners for their work in solving these math and cryptography problems. That reward is currently 12.5 bitcoins. That is how new bitcoins are created.
Bitcoin mining:The software for bitcoin issues a cryptography challenge every 10 minutes. This cryptography challenge involves trying to find a nonce which will make the hash of a specific block be valid. As this challenge gets issued the miners start running their hardware. They basically have thousands of mining computers around the world that are running the bitcoin software. When the challenge is issued all these miners compete against each other, trying to find the solution to that one nonce that will satisfy the hash for that block.
At some specific point one of those miners in the global community will solve the cryptography challenge and that will be the winner. Now the rest of the community has a very important role and that is to verify the validity of that new block. And this is what makes the bitcoin so strong because in one stage of this cycle the miners are competing against each other and in the next stage of the cycle the rest of the community rallies together to ensure that the solution is correct. So it’s a competition and a cooperation, as they’re helping each other to verify that every single transaction is valid. If the transactions are valid then the block is added to the bitcoin blockchain. This is how new blocks are added to the bitcoin blockchain and each block will include all the transactions that the specific miner has identified to be added into that block. For that task the miner will earn a reward.
Factors influencing the price of bitcoin:
The supply of bitcoin and market demand for it.The cost of producing a bitcoin through the mining process.The rewards issued to bitcoin miners for verifying transactions to the blockchain.The number of competing cryptocurrencies.The exchanges it trades on.Regulations governing its sale.Its internal governance.
The supply of bitcoin and market demand for it.
The cost of producing a bitcoin through the mining process.
The rewards issued to bitcoin miners for verifying transactions to the blockchain.
The number of competing cryptocurrencies.
The exchanges it trades on.
Regulations governing its sale.
Its internal governance.
cryptography
Blockchain
Write From Home
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Solidity - Mappings
Solidity - Enums and Structs
How to Become a Blockchain Developer?
How to connect ReactJS with MetaMask ?
Solidity - Constructors
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
|
[
{
"code": null,
"e": 25679,
"s": 25651,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 25894,
"s": 25679,
"text": "Bitcoin is different from other types of traditional currency such as dollars or euros which you can also use to buy things and exchange value electronically, there are no physical coins for bitcoin or paper bills."
},
{
"code": null,
"e": 26175,
"s": 25894,
"text": "When we send bitcoin to someone, or use bitcoin to buy anything we don’t need to use a bank, a credit card or any other third party type of clearinghouse. Instead, we simply send bitcoin directly to another party over the internet and it will arrive securely and almost instantly."
},
{
"code": null,
"e": 26213,
"s": 26175,
"text": "There are four components of bitcoin:"
},
{
"code": null,
"e": 26271,
"s": 26213,
"text": "1. Software\n2. Cryptography\n3. Hardware\n4. Gaming theory "
},
{
"code": null,
"e": 26815,
"s": 26271,
"text": "Bitcoin is basically a software that defines how a bitcoin gets transferred. It identifies what are the rules of a valid bitcoin. That software at its core uses cryptography and bitcoin is a cryptocurrency. As a cryptocurrency it uses cryptography to regulate the transfer of bitcoin between parties as well as creation of new units of bitcoin. So, if it wasn’t for cryptography, bitcoin would simply not be possible. All this needs to run on hardware. This hardware is composed of thousands of miners around the world running their computers."
},
{
"code": null,
"e": 26968,
"s": 26815,
"text": "The final component that ties it all together is gaming theory. Because bitcoin in essence is truly a game that is run by these miners around the world."
},
{
"code": null,
"e": 27189,
"s": 26968,
"text": "Bitcoin miners:Within the bitcoin network there are a group of people which are called miners and their role is to process and confirm transactions. Anybody can apply to be a miner, and you could run the client yourself."
},
{
"code": null,
"e": 27737,
"s": 27189,
"text": "Role of bitcoin miners:The role of the miners is to process and confirm transactions to chain together the blocks of transactions. Typically these miners use very powerful computers that are specifically designed to mine bitcoin transactions, and the way they do that is by actually solving math problems and resolving cryptography issues, because every one of these transactions need to be cryptographically encoded and secured. These mathematical problems are what actually ensures that the data is secure and nobody is tampering with that data."
},
{
"code": null,
"e": 28238,
"s": 27737,
"text": "How is bitcoin created:Bitcoin miners process transactions and secure the network using specialized hardware, therefore the miners are rewarded in bitcoin which is a key component of bitcoin. Because money in bitcoin is not created like you create normal fiat currency(like euros, dollars, rupees, etc) the way bitcoin is created is by rewarding these miners for their work in solving these math and cryptography problems. That reward is currently 12.5 bitcoins. That is how new bitcoins are created."
},
{
"code": null,
"e": 28783,
"s": 28238,
"text": "Bitcoin mining:The software for bitcoin issues a cryptography challenge every 10 minutes. This cryptography challenge involves trying to find a nonce which will make the hash of a specific block be valid. As this challenge gets issued the miners start running their hardware. They basically have thousands of mining computers around the world that are running the bitcoin software. When the challenge is issued all these miners compete against each other, trying to find the solution to that one nonce that will satisfy the hash for that block."
},
{
"code": null,
"e": 29691,
"s": 28783,
"text": "At some specific point one of those miners in the global community will solve the cryptography challenge and that will be the winner. Now the rest of the community has a very important role and that is to verify the validity of that new block. And this is what makes the bitcoin so strong because in one stage of this cycle the miners are competing against each other and in the next stage of the cycle the rest of the community rallies together to ensure that the solution is correct. So it’s a competition and a cooperation, as they’re helping each other to verify that every single transaction is valid. If the transactions are valid then the block is added to the bitcoin blockchain. This is how new blocks are added to the bitcoin blockchain and each block will include all the transactions that the specific miner has identified to be added into that block. For that task the miner will earn a reward."
},
{
"code": null,
"e": 29733,
"s": 29691,
"text": "Factors influencing the price of bitcoin:"
},
{
"code": null,
"e": 30045,
"s": 29733,
"text": "The supply of bitcoin and market demand for it.The cost of producing a bitcoin through the mining process.The rewards issued to bitcoin miners for verifying transactions to the blockchain.The number of competing cryptocurrencies.The exchanges it trades on.Regulations governing its sale.Its internal governance."
},
{
"code": null,
"e": 30093,
"s": 30045,
"text": "The supply of bitcoin and market demand for it."
},
{
"code": null,
"e": 30153,
"s": 30093,
"text": "The cost of producing a bitcoin through the mining process."
},
{
"code": null,
"e": 30236,
"s": 30153,
"text": "The rewards issued to bitcoin miners for verifying transactions to the blockchain."
},
{
"code": null,
"e": 30278,
"s": 30236,
"text": "The number of competing cryptocurrencies."
},
{
"code": null,
"e": 30306,
"s": 30278,
"text": "The exchanges it trades on."
},
{
"code": null,
"e": 30338,
"s": 30306,
"text": "Regulations governing its sale."
},
{
"code": null,
"e": 30363,
"s": 30338,
"text": "Its internal governance."
},
{
"code": null,
"e": 30376,
"s": 30363,
"text": "cryptography"
},
{
"code": null,
"e": 30387,
"s": 30376,
"text": "Blockchain"
},
{
"code": null,
"e": 30403,
"s": 30387,
"text": "Write From Home"
},
{
"code": null,
"e": 30416,
"s": 30403,
"text": "cryptography"
},
{
"code": null,
"e": 30514,
"s": 30416,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30534,
"s": 30514,
"text": "Solidity - Mappings"
},
{
"code": null,
"e": 30563,
"s": 30534,
"text": "Solidity - Enums and Structs"
},
{
"code": null,
"e": 30601,
"s": 30563,
"text": "How to Become a Blockchain Developer?"
},
{
"code": null,
"e": 30640,
"s": 30601,
"text": "How to connect ReactJS with MetaMask ?"
},
{
"code": null,
"e": 30664,
"s": 30640,
"text": "Solidity - Constructors"
},
{
"code": null,
"e": 30700,
"s": 30664,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 30736,
"s": 30700,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 30797,
"s": 30736,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30813,
"s": 30797,
"text": "Python infinity"
}
] |
array data() in C++ STL with Examples - GeeksforGeeks
|
23 Jul, 2018
The array::data() is a built-in function in C++ STL which returns an pointer pointing to the first element in the array object.
Syntax:
array_name.data()
Parameters: The function does not accept any parameters.
Return Value: The function returns an pointer.
Below programs illustrate the above function:
Program 1:
// CPP program to demonstrate the// array::data() function#include <bits/stdc++.h>using namespace std;int main(){ array<int, 5> arr = { 1, 2, 3, 4, 5 }; // prints the array elements cout << "The array elements are: "; for (auto it = arr.begin(); it != arr.end(); it++) cout << *it << " "; // Points to the first element auto it = arr.data(); cout << "\nThe first element is:" << *it; return 0;}
The array elements are: 1 2 3 4 5
The first element is:1
Program 2:
// CPP program to demonstrate the// array::data() function#include <bits/stdc++.h>using namespace std;int main(){ array<int, 5> arr = { 1, 2, 3, 4, 5 }; // prints the array elements cout << "The array elements are: "; for (auto it = arr.begin(); it != arr.end(); it++) cout << *it << " "; // Points to the first element auto it = arr.data(); // increment it++; cout << "\nThe second element is: " << *it; // increment it++; cout << "\nThe third element is: " << *it; return 0;}
The array elements are: 1 2 3 4 5
The second element is: 2
The third element is: 3
cpp-array
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++
std::string class in C++
Inline Functions in C++
Pair in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Queue in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 25367,
"s": 25339,
"text": "\n23 Jul, 2018"
},
{
"code": null,
"e": 25495,
"s": 25367,
"text": "The array::data() is a built-in function in C++ STL which returns an pointer pointing to the first element in the array object."
},
{
"code": null,
"e": 25503,
"s": 25495,
"text": "Syntax:"
},
{
"code": null,
"e": 25521,
"s": 25503,
"text": "array_name.data()"
},
{
"code": null,
"e": 25578,
"s": 25521,
"text": "Parameters: The function does not accept any parameters."
},
{
"code": null,
"e": 25625,
"s": 25578,
"text": "Return Value: The function returns an pointer."
},
{
"code": null,
"e": 25671,
"s": 25625,
"text": "Below programs illustrate the above function:"
},
{
"code": null,
"e": 25682,
"s": 25671,
"text": "Program 1:"
},
{
"code": "// CPP program to demonstrate the// array::data() function#include <bits/stdc++.h>using namespace std;int main(){ array<int, 5> arr = { 1, 2, 3, 4, 5 }; // prints the array elements cout << \"The array elements are: \"; for (auto it = arr.begin(); it != arr.end(); it++) cout << *it << \" \"; // Points to the first element auto it = arr.data(); cout << \"\\nThe first element is:\" << *it; return 0;}",
"e": 26116,
"s": 25682,
"text": null
},
{
"code": null,
"e": 26175,
"s": 26116,
"text": "The array elements are: 1 2 3 4 5 \nThe first element is:1\n"
},
{
"code": null,
"e": 26186,
"s": 26175,
"text": "Program 2:"
},
{
"code": "// CPP program to demonstrate the// array::data() function#include <bits/stdc++.h>using namespace std;int main(){ array<int, 5> arr = { 1, 2, 3, 4, 5 }; // prints the array elements cout << \"The array elements are: \"; for (auto it = arr.begin(); it != arr.end(); it++) cout << *it << \" \"; // Points to the first element auto it = arr.data(); // increment it++; cout << \"\\nThe second element is: \" << *it; // increment it++; cout << \"\\nThe third element is: \" << *it; return 0;}",
"e": 26720,
"s": 26186,
"text": null
},
{
"code": null,
"e": 26805,
"s": 26720,
"text": "The array elements are: 1 2 3 4 5 \nThe second element is: 2\nThe third element is: 3\n"
},
{
"code": null,
"e": 26815,
"s": 26805,
"text": "cpp-array"
},
{
"code": null,
"e": 26819,
"s": 26815,
"text": "STL"
},
{
"code": null,
"e": 26823,
"s": 26819,
"text": "C++"
},
{
"code": null,
"e": 26827,
"s": 26823,
"text": "STL"
},
{
"code": null,
"e": 26831,
"s": 26827,
"text": "CPP"
},
{
"code": null,
"e": 26929,
"s": 26831,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26957,
"s": 26929,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26977,
"s": 26957,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27010,
"s": 26977,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27034,
"s": 27010,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27059,
"s": 27034,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27083,
"s": 27059,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 27127,
"s": 27083,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27180,
"s": 27127,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 27216,
"s": 27180,
"text": "Convert string to char array in C++"
}
] |
How to Restore SQL Server Database From Backup? - GeeksforGeeks
|
15 Oct, 2021
A Database is defined as a structured form of data that is stored database a computer or data in an organized manner and can be accessed in various ways. It is also the collection of schemas, tables, queries, views, etc. Databases help us with easily storing, accessing, and manipulating data held on a computer. The Database Management System allows a user to interact with the database. In this article, we will see how can we restore SQL Server Database from Backup.
For the demonstration purpose, we will create one database named ‘geeks’.
Step 1: Create Database
Use the below SQL statement to create database called geeks;
QUERY:
CREATE DATABASE geeks;
you can see database with name ‘geeks’ is created.
Step 2: Use database
Query:
USE geeks;
Step 3: Table definition
We have the following demo_table in the database.
Query:
CREATE TABLE demo_table
(FIRSTNAME varchar(20),
LASTNAME varchar(20),
GENDER varchar(10), AGE int);
Step 4: Insert values
Following command is used to insert values into the table.
Query:
INSERT INTO demo_table VALUES
('ROMY','KUMARI','FEMALE', 22),
('PUSHKAR', 'JHA', 'MALE', 23),
('SOUMYA', 'SHRIYA', 'FEMALE', 22),
('NIKHIL', 'KALRA', 'MALE', 23),
('ROHIT', 'KUMAR', 'MALE', 23),
Step 5: View data of the table
Query:
SELECT * FROM demo_table;
Output:
Restoring of database can be done through Object explorer in SQL Server.
Steps to restore database:
Select View from menu bar.
Select Object explorer option. Object explorer will be appeared on left side of the screen.
Right click on Database folder and select ‘Restore Database’ option.
The dialog box will open, select device option and browse the backup media.
After selecting the Backup media, click OK
Database will be restored successfully.
Now, for demonstration of restoring the database. Delete the geeks database.
Step 6: Delete the Database
Syntax:
DROP DATABASE database_name;
We can not drop the database while in use.
Query:
DROP DATABASE geeks;
Output:
geeks database is deleted. You can not find geeks database in the object explorer.
Step 7: Restore database
Right click on database and select ‘Restore database’ option
Select ‘device’ option and add backup media
Click Ok button
Prompt will appear showing the message as “Database restored successfully”. Click OK.
Check Object explorer.
‘geeks’ database is restored successfully.
Picked
SQL-Server
TrueGeek-2021
SQL
TrueGeek
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
How to redirect to another page in ReactJS ?
How to remove duplicate elements from JavaScript Array ?
Basics of API Testing Using Postman
SQL Statement to Remove Part of a String
Types of Internet Protocols
|
[
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n15 Oct, 2021"
},
{
"code": null,
"e": 25983,
"s": 25513,
"text": "A Database is defined as a structured form of data that is stored database a computer or data in an organized manner and can be accessed in various ways. It is also the collection of schemas, tables, queries, views, etc. Databases help us with easily storing, accessing, and manipulating data held on a computer. The Database Management System allows a user to interact with the database. In this article, we will see how can we restore SQL Server Database from Backup."
},
{
"code": null,
"e": 26057,
"s": 25983,
"text": "For the demonstration purpose, we will create one database named ‘geeks’."
},
{
"code": null,
"e": 26081,
"s": 26057,
"text": "Step 1: Create Database"
},
{
"code": null,
"e": 26142,
"s": 26081,
"text": "Use the below SQL statement to create database called geeks;"
},
{
"code": null,
"e": 26149,
"s": 26142,
"text": "QUERY:"
},
{
"code": null,
"e": 26172,
"s": 26149,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 26223,
"s": 26172,
"text": "you can see database with name ‘geeks’ is created."
},
{
"code": null,
"e": 26244,
"s": 26223,
"text": "Step 2: Use database"
},
{
"code": null,
"e": 26251,
"s": 26244,
"text": "Query:"
},
{
"code": null,
"e": 26262,
"s": 26251,
"text": "USE geeks;"
},
{
"code": null,
"e": 26287,
"s": 26262,
"text": "Step 3: Table definition"
},
{
"code": null,
"e": 26338,
"s": 26287,
"text": "We have the following demo_table in the database."
},
{
"code": null,
"e": 26345,
"s": 26338,
"text": "Query:"
},
{
"code": null,
"e": 26445,
"s": 26345,
"text": "CREATE TABLE demo_table\n(FIRSTNAME varchar(20),\nLASTNAME varchar(20),\nGENDER varchar(10), AGE int);"
},
{
"code": null,
"e": 26467,
"s": 26445,
"text": "Step 4: Insert values"
},
{
"code": null,
"e": 26526,
"s": 26467,
"text": "Following command is used to insert values into the table."
},
{
"code": null,
"e": 26533,
"s": 26526,
"text": "Query:"
},
{
"code": null,
"e": 26728,
"s": 26533,
"text": "INSERT INTO demo_table VALUES\n('ROMY','KUMARI','FEMALE', 22),\n('PUSHKAR', 'JHA', 'MALE', 23),\n('SOUMYA', 'SHRIYA', 'FEMALE', 22),\n('NIKHIL', 'KALRA', 'MALE', 23),\n('ROHIT', 'KUMAR', 'MALE', 23),"
},
{
"code": null,
"e": 26759,
"s": 26728,
"text": "Step 5: View data of the table"
},
{
"code": null,
"e": 26766,
"s": 26759,
"text": "Query:"
},
{
"code": null,
"e": 26792,
"s": 26766,
"text": "SELECT * FROM demo_table;"
},
{
"code": null,
"e": 26800,
"s": 26792,
"text": "Output:"
},
{
"code": null,
"e": 26873,
"s": 26800,
"text": "Restoring of database can be done through Object explorer in SQL Server."
},
{
"code": null,
"e": 26900,
"s": 26873,
"text": "Steps to restore database:"
},
{
"code": null,
"e": 26927,
"s": 26900,
"text": "Select View from menu bar."
},
{
"code": null,
"e": 27019,
"s": 26927,
"text": "Select Object explorer option. Object explorer will be appeared on left side of the screen."
},
{
"code": null,
"e": 27088,
"s": 27019,
"text": "Right click on Database folder and select ‘Restore Database’ option."
},
{
"code": null,
"e": 27164,
"s": 27088,
"text": "The dialog box will open, select device option and browse the backup media."
},
{
"code": null,
"e": 27207,
"s": 27164,
"text": "After selecting the Backup media, click OK"
},
{
"code": null,
"e": 27247,
"s": 27207,
"text": "Database will be restored successfully."
},
{
"code": null,
"e": 27324,
"s": 27247,
"text": "Now, for demonstration of restoring the database. Delete the geeks database."
},
{
"code": null,
"e": 27352,
"s": 27324,
"text": "Step 6: Delete the Database"
},
{
"code": null,
"e": 27360,
"s": 27352,
"text": "Syntax:"
},
{
"code": null,
"e": 27389,
"s": 27360,
"text": "DROP DATABASE database_name;"
},
{
"code": null,
"e": 27432,
"s": 27389,
"text": "We can not drop the database while in use."
},
{
"code": null,
"e": 27439,
"s": 27432,
"text": "Query:"
},
{
"code": null,
"e": 27460,
"s": 27439,
"text": "DROP DATABASE geeks;"
},
{
"code": null,
"e": 27468,
"s": 27460,
"text": "Output:"
},
{
"code": null,
"e": 27551,
"s": 27468,
"text": "geeks database is deleted. You can not find geeks database in the object explorer."
},
{
"code": null,
"e": 27576,
"s": 27551,
"text": "Step 7: Restore database"
},
{
"code": null,
"e": 27637,
"s": 27576,
"text": "Right click on database and select ‘Restore database’ option"
},
{
"code": null,
"e": 27681,
"s": 27637,
"text": "Select ‘device’ option and add backup media"
},
{
"code": null,
"e": 27697,
"s": 27681,
"text": "Click Ok button"
},
{
"code": null,
"e": 27783,
"s": 27697,
"text": "Prompt will appear showing the message as “Database restored successfully”. Click OK."
},
{
"code": null,
"e": 27806,
"s": 27783,
"text": "Check Object explorer."
},
{
"code": null,
"e": 27849,
"s": 27806,
"text": "‘geeks’ database is restored successfully."
},
{
"code": null,
"e": 27856,
"s": 27849,
"text": "Picked"
},
{
"code": null,
"e": 27867,
"s": 27856,
"text": "SQL-Server"
},
{
"code": null,
"e": 27881,
"s": 27867,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 27885,
"s": 27881,
"text": "SQL"
},
{
"code": null,
"e": 27894,
"s": 27885,
"text": "TrueGeek"
},
{
"code": null,
"e": 27898,
"s": 27894,
"text": "SQL"
},
{
"code": null,
"e": 27996,
"s": 27898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28062,
"s": 27996,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 28077,
"s": 28062,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 28134,
"s": 28077,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 28166,
"s": 28134,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 28244,
"s": 28166,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 28289,
"s": 28244,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 28346,
"s": 28289,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 28382,
"s": 28346,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 28423,
"s": 28382,
"text": "SQL Statement to Remove Part of a String"
}
] |
Python | Pandas DataFrame.transpose - GeeksforGeeks
|
21 Feb, 2019
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas.
Pandas DataFrame.transpose() function transpose index and columns of the dataframe. It reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa.
Syntax: DataFrame.transpose(*args, **kwargs)
Parameter :copy : If True, the underlying data is copied. Otherwise (default), no copy is made if possible.*args, **kwargs : Additional keywords have no effect but might be accepted for compatibility with numpy.
Returns : The transposed DataFrame
Example #1: Use DataFrame.transpose() function to find the transpose of the given dataframe.
# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Create the indexindex_ = pd.date_range('2010-10-09 08:45', periods = 5, freq ='H') # Set the indexdf.index = index_ # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.transpose() function to find the transpose of the given dataframe.
# return the transposeresult = df.transpose() # Print the resultprint(result)
Output :
As we can see in the output, the DataFrame.transpose() function has successfully returned the transpose of the given dataframe. Example #2: Use DataFrame.transpose() function to find the transpose of the given dataframe.
# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.transpose() function to find the transpose of the given dataframe.
# return the transposeresult = df.transpose() # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.transpose() function has successfully returned the transpose of the given dataframe.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26181,
"s": 26153,
"text": "\n21 Feb, 2019"
},
{
"code": null,
"e": 26495,
"s": 26181,
"text": "Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas."
},
{
"code": null,
"e": 26670,
"s": 26495,
"text": "Pandas DataFrame.transpose() function transpose index and columns of the dataframe. It reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa."
},
{
"code": null,
"e": 26715,
"s": 26670,
"text": "Syntax: DataFrame.transpose(*args, **kwargs)"
},
{
"code": null,
"e": 26927,
"s": 26715,
"text": "Parameter :copy : If True, the underlying data is copied. Otherwise (default), no copy is made if possible.*args, **kwargs : Additional keywords have no effect but might be accepted for compatibility with numpy."
},
{
"code": null,
"e": 26962,
"s": 26927,
"text": "Returns : The transposed DataFrame"
},
{
"code": null,
"e": 27055,
"s": 26962,
"text": "Example #1: Use DataFrame.transpose() function to find the transpose of the given dataframe."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Create the indexindex_ = pd.date_range('2010-10-09 08:45', periods = 5, freq ='H') # Set the indexdf.index = index_ # Print the DataFrameprint(df)",
"e": 27440,
"s": 27055,
"text": null
},
{
"code": null,
"e": 27449,
"s": 27440,
"text": "Output :"
},
{
"code": null,
"e": 27542,
"s": 27449,
"text": "Now we will use DataFrame.transpose() function to find the transpose of the given dataframe."
},
{
"code": "# return the transposeresult = df.transpose() # Print the resultprint(result)",
"e": 27621,
"s": 27542,
"text": null
},
{
"code": null,
"e": 27630,
"s": 27621,
"text": "Output :"
},
{
"code": null,
"e": 27851,
"s": 27630,
"text": "As we can see in the output, the DataFrame.transpose() function has successfully returned the transpose of the given dataframe. Example #2: Use DataFrame.transpose() function to find the transpose of the given dataframe."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)",
"e": 28237,
"s": 27851,
"text": null
},
{
"code": null,
"e": 28246,
"s": 28237,
"text": "Output :"
},
{
"code": null,
"e": 28339,
"s": 28246,
"text": "Now we will use DataFrame.transpose() function to find the transpose of the given dataframe."
},
{
"code": "# return the transposeresult = df.transpose() # Print the resultprint(result)",
"e": 28418,
"s": 28339,
"text": null
},
{
"code": null,
"e": 28554,
"s": 28418,
"text": "Output :As we can see in the output, the DataFrame.transpose() function has successfully returned the transpose of the given dataframe."
},
{
"code": null,
"e": 28578,
"s": 28554,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 28610,
"s": 28578,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 28624,
"s": 28610,
"text": "Python-pandas"
},
{
"code": null,
"e": 28631,
"s": 28624,
"text": "Python"
},
{
"code": null,
"e": 28729,
"s": 28631,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28747,
"s": 28729,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28782,
"s": 28747,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28814,
"s": 28782,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28836,
"s": 28814,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28878,
"s": 28836,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28908,
"s": 28878,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28934,
"s": 28908,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28963,
"s": 28934,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29007,
"s": 28963,
"text": "Reading and Writing to text files in Python"
}
] |
Imshow with two colorbars under Matplotlib - GeeksforGeeks
|
24 Jan, 2021
In this article, we will learn how to use Imshow with two colorbars under Matplotlib. Let’s discuss some concepts :
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
One of the greatest benefits of visualization is that it allows us visual access to huge amounts of data in easily digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram etc.
The imshow() function in pyplot module of matplotlib library is used to display data as an image; i.e. on a 2D regular raster.
The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale.
A simple Imshow() with one colorbar
Python3
# import librariesimport matplotlib.pyplot as pltimport numpy as np # create image = 10x10 arrayimg = np.random.randint(-100, 100, (10, 10)) # make plotfig, ax = plt.subplots() # show imageshw = ax.imshow(img) # make barbar = plt.colorbar(shw) # show plot with labelsplt.xlabel('X Label')plt.ylabel('Y Label')bar.set_label('ColorBar')plt.show()
Output :
In the above output, we can see that there is one colorbar with values ranges from -100 to 100. This is not looking effective and not clear the difference of small positive values to larger positive values similarly not clear the difference of small negative values to larger negative values. Here, we divide colorbar in two parts :
one with positive values
one with negative values
With different colors, which help us to understand the plot clearly and effectively. Below all steps are mentioned for such work.
Steps Needed:
Import libraries (matplotlib)Create / load image dataMasked array to positive and negative valuesMake plot using subplot() methodShow image using imshow() methodMake bars using matplotlib.pyplot.colorbar() methodShow plot with labels
Import libraries (matplotlib)
Create / load image data
Masked array to positive and negative values
Make plot using subplot() method
Show image using imshow() method
Make bars using matplotlib.pyplot.colorbar() method
Show plot with labels
Example:
Python3
# import librariesimport matplotlib.pyplot as pltimport numpy as npfrom numpy.ma import masked_array # create image = 10x10 arrayimg = np.random.randint(-100, 100, (10, 10)) # masked array to positive and negative valuesneg_img = masked_array(img, img >= 0)pos_img = masked_array(img, img < 0) # make plotfig, ax = plt.subplots() # show imageshw1 = ax.imshow(neg_img, cmap=plt.cm.Reds)shw2 = ax.imshow(pos_img, cmap=plt.cm.winter) # make barsbar1 = plt.colorbar(shw1)bar2 = plt.colorbar(shw2) # show plot with labelsplt.xlabel('X Label')plt.ylabel('Y Label')bar1.set_label('ColorBar 1')bar2.set_label('ColorBar 2')plt.show()
Output :
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 25653,
"s": 25537,
"text": "In this article, we will learn how to use Imshow with two colorbars under Matplotlib. Let’s discuss some concepts :"
},
{
"code": null,
"e": 25916,
"s": 25653,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002."
},
{
"code": null,
"e": 26128,
"s": 25916,
"text": "One of the greatest benefits of visualization is that it allows us visual access to huge amounts of data in easily digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram etc."
},
{
"code": null,
"e": 26255,
"s": 26128,
"text": "The imshow() function in pyplot module of matplotlib library is used to display data as an image; i.e. on a 2D regular raster."
},
{
"code": null,
"e": 26364,
"s": 26255,
"text": "The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale."
},
{
"code": null,
"e": 26400,
"s": 26364,
"text": "A simple Imshow() with one colorbar"
},
{
"code": null,
"e": 26408,
"s": 26400,
"text": "Python3"
},
{
"code": "# import librariesimport matplotlib.pyplot as pltimport numpy as np # create image = 10x10 arrayimg = np.random.randint(-100, 100, (10, 10)) # make plotfig, ax = plt.subplots() # show imageshw = ax.imshow(img) # make barbar = plt.colorbar(shw) # show plot with labelsplt.xlabel('X Label')plt.ylabel('Y Label')bar.set_label('ColorBar')plt.show()",
"e": 26758,
"s": 26408,
"text": null
},
{
"code": null,
"e": 26767,
"s": 26758,
"text": "Output :"
},
{
"code": null,
"e": 27100,
"s": 26767,
"text": "In the above output, we can see that there is one colorbar with values ranges from -100 to 100. This is not looking effective and not clear the difference of small positive values to larger positive values similarly not clear the difference of small negative values to larger negative values. Here, we divide colorbar in two parts :"
},
{
"code": null,
"e": 27125,
"s": 27100,
"text": "one with positive values"
},
{
"code": null,
"e": 27150,
"s": 27125,
"text": "one with negative values"
},
{
"code": null,
"e": 27280,
"s": 27150,
"text": "With different colors, which help us to understand the plot clearly and effectively. Below all steps are mentioned for such work."
},
{
"code": null,
"e": 27294,
"s": 27280,
"text": "Steps Needed:"
},
{
"code": null,
"e": 27528,
"s": 27294,
"text": "Import libraries (matplotlib)Create / load image dataMasked array to positive and negative valuesMake plot using subplot() methodShow image using imshow() methodMake bars using matplotlib.pyplot.colorbar() methodShow plot with labels"
},
{
"code": null,
"e": 27558,
"s": 27528,
"text": "Import libraries (matplotlib)"
},
{
"code": null,
"e": 27583,
"s": 27558,
"text": "Create / load image data"
},
{
"code": null,
"e": 27628,
"s": 27583,
"text": "Masked array to positive and negative values"
},
{
"code": null,
"e": 27661,
"s": 27628,
"text": "Make plot using subplot() method"
},
{
"code": null,
"e": 27694,
"s": 27661,
"text": "Show image using imshow() method"
},
{
"code": null,
"e": 27746,
"s": 27694,
"text": "Make bars using matplotlib.pyplot.colorbar() method"
},
{
"code": null,
"e": 27768,
"s": 27746,
"text": "Show plot with labels"
},
{
"code": null,
"e": 27777,
"s": 27768,
"text": "Example:"
},
{
"code": null,
"e": 27785,
"s": 27777,
"text": "Python3"
},
{
"code": "# import librariesimport matplotlib.pyplot as pltimport numpy as npfrom numpy.ma import masked_array # create image = 10x10 arrayimg = np.random.randint(-100, 100, (10, 10)) # masked array to positive and negative valuesneg_img = masked_array(img, img >= 0)pos_img = masked_array(img, img < 0) # make plotfig, ax = plt.subplots() # show imageshw1 = ax.imshow(neg_img, cmap=plt.cm.Reds)shw2 = ax.imshow(pos_img, cmap=plt.cm.winter) # make barsbar1 = plt.colorbar(shw1)bar2 = plt.colorbar(shw2) # show plot with labelsplt.xlabel('X Label')plt.ylabel('Y Label')bar1.set_label('ColorBar 1')bar2.set_label('ColorBar 2')plt.show()",
"e": 28416,
"s": 27785,
"text": null
},
{
"code": null,
"e": 28425,
"s": 28416,
"text": "Output :"
},
{
"code": null,
"e": 28432,
"s": 28425,
"text": "Picked"
},
{
"code": null,
"e": 28450,
"s": 28432,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28457,
"s": 28450,
"text": "Python"
},
{
"code": null,
"e": 28555,
"s": 28457,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28587,
"s": 28555,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28629,
"s": 28587,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28671,
"s": 28629,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28698,
"s": 28671,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28754,
"s": 28698,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28776,
"s": 28754,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28815,
"s": 28776,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28846,
"s": 28815,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28875,
"s": 28846,
"text": "Create a directory in Python"
}
] |
Java Program to Check if JVM is 32 or 64 bit - GeeksforGeeks
|
10 Mar, 2021
JVM Stands for Java Virtual Machine. It is an abstract computing machine that allows a computer to run a Java program. It is a platform-independent environment, responsible for compiling Java programs by performing conversion of Java code into machine language i.e. byte code. The memory needed by JVM to run a Java program is called heap memory.
In Java, the getProperty() method is used to get information about various properties related to the system. Similarly, there two different approaches to check the bit of JVM by using System property “sun.arch.data.model” or “os. arch”. It will return either 32 bit or 64 bit based on your Java installation.
Method required : get.Property()
Syntax:
String System.getProperty( String key )
Parameter:
Key is the property of the operating system
Return Type
1) Returns a string containing the value of the property
2) Returns Null if the property does not exist
There are basically 3 methods to check whether the JVM is 32 bit or 64 bit:-
Using sun.arch.data.model
Java
// Java Program to check bitness of JVM by// using System property "sun.arch.data.model"public class checkBit { // get bitness of JVM private static final String a = System.getProperty("sun.arch.data.model"); public static void main(String[] args) { // printing the JVM version System.out.println("JVM is " + a + " bit"); }}
Output:
Case 1: When JVM is 64 bit
Case 2: When JVM is 32 bit
Using os.arch.model
Java
// Java Program to check bitness of JVM by// using System property "os.arch.model"public class bit { // get bitness of JVM private static final String s = System.getProperty("os.arch"); public static void main(String[] args) { // printing the of what bit JVM is System.out.println("JVM is " + s + " bit"); }}
Output:
Case 1: When JVM is 64 bit
Case 2: When JVM is 32 bit
Note: There is another approach to check the bits of JVM without Java program is by executing instruction ‘java -version’ in command prompt.
Case 1: When JVM is 64 bit
Case 2: When JVM is 32 bit
java-JVM
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?
Iterate through List in Java
|
[
{
"code": null,
"e": 25237,
"s": 25209,
"text": "\n10 Mar, 2021"
},
{
"code": null,
"e": 25585,
"s": 25237,
"text": "JVM Stands for Java Virtual Machine. It is an abstract computing machine that allows a computer to run a Java program. It is a platform-independent environment, responsible for compiling Java programs by performing conversion of Java code into machine language i.e. byte code. The memory needed by JVM to run a Java program is called heap memory."
},
{
"code": null,
"e": 25896,
"s": 25585,
"text": "In Java, the getProperty() method is used to get information about various properties related to the system. Similarly, there two different approaches to check the bit of JVM by using System property “sun.arch.data.model” or “os. arch”. It will return either 32 bit or 64 bit based on your Java installation. "
},
{
"code": null,
"e": 25929,
"s": 25896,
"text": "Method required : get.Property()"
},
{
"code": null,
"e": 25937,
"s": 25929,
"text": "Syntax:"
},
{
"code": null,
"e": 25977,
"s": 25937,
"text": "String System.getProperty( String key )"
},
{
"code": null,
"e": 25988,
"s": 25977,
"text": "Parameter:"
},
{
"code": null,
"e": 26032,
"s": 25988,
"text": "Key is the property of the operating system"
},
{
"code": null,
"e": 26044,
"s": 26032,
"text": "Return Type"
},
{
"code": null,
"e": 26101,
"s": 26044,
"text": "1) Returns a string containing the value of the property"
},
{
"code": null,
"e": 26148,
"s": 26101,
"text": "2) Returns Null if the property does not exist"
},
{
"code": null,
"e": 26225,
"s": 26148,
"text": "There are basically 3 methods to check whether the JVM is 32 bit or 64 bit:-"
},
{
"code": null,
"e": 26251,
"s": 26225,
"text": "Using sun.arch.data.model"
},
{
"code": null,
"e": 26256,
"s": 26251,
"text": "Java"
},
{
"code": "// Java Program to check bitness of JVM by// using System property \"sun.arch.data.model\"public class checkBit { // get bitness of JVM private static final String a = System.getProperty(\"sun.arch.data.model\"); public static void main(String[] args) { // printing the JVM version System.out.println(\"JVM is \" + a + \" bit\"); }}",
"e": 26619,
"s": 26256,
"text": null
},
{
"code": null,
"e": 26627,
"s": 26619,
"text": "Output:"
},
{
"code": null,
"e": 26654,
"s": 26627,
"text": "Case 1: When JVM is 64 bit"
},
{
"code": null,
"e": 26681,
"s": 26654,
"text": "Case 2: When JVM is 32 bit"
},
{
"code": null,
"e": 26701,
"s": 26681,
"text": "Using os.arch.model"
},
{
"code": null,
"e": 26706,
"s": 26701,
"text": "Java"
},
{
"code": "// Java Program to check bitness of JVM by// using System property \"os.arch.model\"public class bit { // get bitness of JVM private static final String s = System.getProperty(\"os.arch\"); public static void main(String[] args) { // printing the of what bit JVM is System.out.println(\"JVM is \" + s + \" bit\"); }}",
"e": 27053,
"s": 26706,
"text": null
},
{
"code": null,
"e": 27061,
"s": 27053,
"text": "Output:"
},
{
"code": null,
"e": 27088,
"s": 27061,
"text": "Case 1: When JVM is 64 bit"
},
{
"code": null,
"e": 27115,
"s": 27088,
"text": "Case 2: When JVM is 32 bit"
},
{
"code": null,
"e": 27256,
"s": 27115,
"text": "Note: There is another approach to check the bits of JVM without Java program is by executing instruction ‘java -version’ in command prompt."
},
{
"code": null,
"e": 27283,
"s": 27256,
"text": "Case 1: When JVM is 64 bit"
},
{
"code": null,
"e": 27310,
"s": 27283,
"text": "Case 2: When JVM is 32 bit"
},
{
"code": null,
"e": 27319,
"s": 27310,
"text": "java-JVM"
},
{
"code": null,
"e": 27326,
"s": 27319,
"text": "Picked"
},
{
"code": null,
"e": 27331,
"s": 27326,
"text": "Java"
},
{
"code": null,
"e": 27345,
"s": 27331,
"text": "Java Programs"
},
{
"code": null,
"e": 27350,
"s": 27345,
"text": "Java"
},
{
"code": null,
"e": 27448,
"s": 27350,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27463,
"s": 27448,
"text": "Stream In Java"
},
{
"code": null,
"e": 27484,
"s": 27463,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27503,
"s": 27484,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27533,
"s": 27503,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27579,
"s": 27533,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27605,
"s": 27579,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27639,
"s": 27605,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 27686,
"s": 27639,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 27718,
"s": 27686,
"text": "How to Iterate HashMap in Java?"
}
] |
User Stories in Agile Software Development - GeeksforGeeks
|
25 Feb, 2021
In Agile software development and product management User Story refers to a short, informal, and simple description of software features that are required by the end-users in the software system. Its main purpose is to provide software features that will add value to the customer requirements. User stories are considered an important tool in Incremental software development. Mainly a user story defines the type of user, their need, and why they need that. So in simple, a user story is a simple description of requirements that needs to be implemented in the software system.
Pattern of User Story :User stories are completely from the end-user perspective which follows the Role-Feature-Benefit pattern.
As a [ type of user ], I want [ an action ], so that [ some reason ]
For example :As the project manager of a construction team, I want our team-messaging app to include file sharing and information update so that my team can collaborate and communicate with each other in real-time as a result the construction project development and completion will be fast.
Writing User Stories :User stories are from a user perspective. So when user stories are written, users are given more importance during the process. Some points outlined which are taken into consideration during writing user stories like
RequirementsTasks and their subtasksActual userImportance to user words/feedbackBreaking user stories for larger requirements
Requirements
Tasks and their subtasks
Actual user
Importance to user words/feedback
Breaking user stories for larger requirements
With this also some other principles which are given importance during creating user stories are discussed below.
INVEST Principle of User story :A good user story should be based on INVEST principle which expresses the quality of the user story because in base a good software product is completely dependent upon a good user story. In 2003 INVEST checklist was introduced by Bill Wake in an article.
Independent –Not dependent on other.Negotiable –Includes the important avoid contract.Valuable –Provide value to customer.Estimable –It should be estimated.Small –It should be simple and small not complex.Testable –It should be evaluated by pre-written acceptance criteria.
Independent –Not dependent on other.
Negotiable –Includes the important avoid contract.
Valuable –Provide value to customer.
Estimable –It should be estimated.
Small –It should be simple and small not complex.
Testable –It should be evaluated by pre-written acceptance criteria.
3 C’s in User Stories :
Card –Write stories on cards, prioritize, estimate and schedule it accordingly.Conversation –Conduct conversations, Specify the requirements and bring clarity.Confirmation –Meet the acceptance criteria of the software.
Card –Write stories on cards, prioritize, estimate and schedule it accordingly.
Conversation –Conduct conversations, Specify the requirements and bring clarity.
Confirmation –Meet the acceptance criteria of the software.
Working with User Stories :Below points represents working with user stories
Once the user story is fully written then it undergoes review and verification.In project workflow meetings it is reviewed and verified then added to the actual workflow.Actual requirements and functionality are decided based on the stories.User stories are scored based on their complexity and the team starts work based on user stories.
Once the user story is fully written then it undergoes review and verification.
In project workflow meetings it is reviewed and verified then added to the actual workflow.
Actual requirements and functionality are decided based on the stories.
User stories are scored based on their complexity and the team starts work based on user stories.
Importance of creating User stories :
Stories clear idea about requirementsMakes it easy to understand the featuresDelivers higher customer satisfactionFasten development processCreates an effective work environmentEnables collaboration between teamsDelivery of valuable software
Stories clear idea about requirements
Makes it easy to understand the features
Delivers higher customer satisfaction
Fasten development process
Creates an effective work environment
Enables collaboration between teams
Delivery of valuable software
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Software Engineering | Integration Testing
System Testing
Software Engineering | Black box testing
Software Engineering | Software Quality Assurance
What is DFD(Data Flow Diagram)?
Difference between Unit Testing and Integration Testing
Difference between IAAS, PAAS and SAAS
Use Case Diagram for Library Management System
Object Oriented Analysis and Design
Software Development Life Cycle (SDLC)
|
[
{
"code": null,
"e": 26235,
"s": 26207,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 26815,
"s": 26235,
"text": "In Agile software development and product management User Story refers to a short, informal, and simple description of software features that are required by the end-users in the software system. Its main purpose is to provide software features that will add value to the customer requirements. User stories are considered an important tool in Incremental software development. Mainly a user story defines the type of user, their need, and why they need that. So in simple, a user story is a simple description of requirements that needs to be implemented in the software system."
},
{
"code": null,
"e": 26944,
"s": 26815,
"text": "Pattern of User Story :User stories are completely from the end-user perspective which follows the Role-Feature-Benefit pattern."
},
{
"code": null,
"e": 27013,
"s": 26944,
"text": "As a [ type of user ], I want [ an action ], so that [ some reason ]"
},
{
"code": null,
"e": 27305,
"s": 27013,
"text": "For example :As the project manager of a construction team, I want our team-messaging app to include file sharing and information update so that my team can collaborate and communicate with each other in real-time as a result the construction project development and completion will be fast."
},
{
"code": null,
"e": 27544,
"s": 27305,
"text": "Writing User Stories :User stories are from a user perspective. So when user stories are written, users are given more importance during the process. Some points outlined which are taken into consideration during writing user stories like"
},
{
"code": null,
"e": 27670,
"s": 27544,
"text": "RequirementsTasks and their subtasksActual userImportance to user words/feedbackBreaking user stories for larger requirements"
},
{
"code": null,
"e": 27683,
"s": 27670,
"text": "Requirements"
},
{
"code": null,
"e": 27708,
"s": 27683,
"text": "Tasks and their subtasks"
},
{
"code": null,
"e": 27720,
"s": 27708,
"text": "Actual user"
},
{
"code": null,
"e": 27754,
"s": 27720,
"text": "Importance to user words/feedback"
},
{
"code": null,
"e": 27800,
"s": 27754,
"text": "Breaking user stories for larger requirements"
},
{
"code": null,
"e": 27914,
"s": 27800,
"text": "With this also some other principles which are given importance during creating user stories are discussed below."
},
{
"code": null,
"e": 28202,
"s": 27914,
"text": "INVEST Principle of User story :A good user story should be based on INVEST principle which expresses the quality of the user story because in base a good software product is completely dependent upon a good user story. In 2003 INVEST checklist was introduced by Bill Wake in an article."
},
{
"code": null,
"e": 28476,
"s": 28202,
"text": "Independent –Not dependent on other.Negotiable –Includes the important avoid contract.Valuable –Provide value to customer.Estimable –It should be estimated.Small –It should be simple and small not complex.Testable –It should be evaluated by pre-written acceptance criteria."
},
{
"code": null,
"e": 28513,
"s": 28476,
"text": "Independent –Not dependent on other."
},
{
"code": null,
"e": 28564,
"s": 28513,
"text": "Negotiable –Includes the important avoid contract."
},
{
"code": null,
"e": 28601,
"s": 28564,
"text": "Valuable –Provide value to customer."
},
{
"code": null,
"e": 28636,
"s": 28601,
"text": "Estimable –It should be estimated."
},
{
"code": null,
"e": 28686,
"s": 28636,
"text": "Small –It should be simple and small not complex."
},
{
"code": null,
"e": 28755,
"s": 28686,
"text": "Testable –It should be evaluated by pre-written acceptance criteria."
},
{
"code": null,
"e": 28779,
"s": 28755,
"text": "3 C’s in User Stories :"
},
{
"code": null,
"e": 28998,
"s": 28779,
"text": "Card –Write stories on cards, prioritize, estimate and schedule it accordingly.Conversation –Conduct conversations, Specify the requirements and bring clarity.Confirmation –Meet the acceptance criteria of the software."
},
{
"code": null,
"e": 29078,
"s": 28998,
"text": "Card –Write stories on cards, prioritize, estimate and schedule it accordingly."
},
{
"code": null,
"e": 29159,
"s": 29078,
"text": "Conversation –Conduct conversations, Specify the requirements and bring clarity."
},
{
"code": null,
"e": 29219,
"s": 29159,
"text": "Confirmation –Meet the acceptance criteria of the software."
},
{
"code": null,
"e": 29296,
"s": 29219,
"text": "Working with User Stories :Below points represents working with user stories"
},
{
"code": null,
"e": 29635,
"s": 29296,
"text": "Once the user story is fully written then it undergoes review and verification.In project workflow meetings it is reviewed and verified then added to the actual workflow.Actual requirements and functionality are decided based on the stories.User stories are scored based on their complexity and the team starts work based on user stories."
},
{
"code": null,
"e": 29715,
"s": 29635,
"text": "Once the user story is fully written then it undergoes review and verification."
},
{
"code": null,
"e": 29807,
"s": 29715,
"text": "In project workflow meetings it is reviewed and verified then added to the actual workflow."
},
{
"code": null,
"e": 29879,
"s": 29807,
"text": "Actual requirements and functionality are decided based on the stories."
},
{
"code": null,
"e": 29977,
"s": 29879,
"text": "User stories are scored based on their complexity and the team starts work based on user stories."
},
{
"code": null,
"e": 30015,
"s": 29977,
"text": "Importance of creating User stories :"
},
{
"code": null,
"e": 30257,
"s": 30015,
"text": "Stories clear idea about requirementsMakes it easy to understand the featuresDelivers higher customer satisfactionFasten development processCreates an effective work environmentEnables collaboration between teamsDelivery of valuable software"
},
{
"code": null,
"e": 30295,
"s": 30257,
"text": "Stories clear idea about requirements"
},
{
"code": null,
"e": 30336,
"s": 30295,
"text": "Makes it easy to understand the features"
},
{
"code": null,
"e": 30374,
"s": 30336,
"text": "Delivers higher customer satisfaction"
},
{
"code": null,
"e": 30401,
"s": 30374,
"text": "Fasten development process"
},
{
"code": null,
"e": 30439,
"s": 30401,
"text": "Creates an effective work environment"
},
{
"code": null,
"e": 30475,
"s": 30439,
"text": "Enables collaboration between teams"
},
{
"code": null,
"e": 30505,
"s": 30475,
"text": "Delivery of valuable software"
},
{
"code": null,
"e": 30526,
"s": 30505,
"text": "Software Engineering"
},
{
"code": null,
"e": 30624,
"s": 30526,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30667,
"s": 30624,
"text": "Software Engineering | Integration Testing"
},
{
"code": null,
"e": 30682,
"s": 30667,
"text": "System Testing"
},
{
"code": null,
"e": 30723,
"s": 30682,
"text": "Software Engineering | Black box testing"
},
{
"code": null,
"e": 30773,
"s": 30723,
"text": "Software Engineering | Software Quality Assurance"
},
{
"code": null,
"e": 30805,
"s": 30773,
"text": "What is DFD(Data Flow Diagram)?"
},
{
"code": null,
"e": 30861,
"s": 30805,
"text": "Difference between Unit Testing and Integration Testing"
},
{
"code": null,
"e": 30900,
"s": 30861,
"text": "Difference between IAAS, PAAS and SAAS"
},
{
"code": null,
"e": 30947,
"s": 30900,
"text": "Use Case Diagram for Library Management System"
},
{
"code": null,
"e": 30983,
"s": 30947,
"text": "Object Oriented Analysis and Design"
}
] |
MySQL | COALESCE( ) Function - GeeksforGeeks
|
21 Nov, 2019
The MySQL COALESCE() function is used for returning the first non-null value in a list of expressions. If all the values in the list evaluate to NULL, then the COALESCE() function returns NULL.
The COALESCE() function accepts one parameter which is the list which can contain various values. The value returned by the MySQL COALESCE() function is the first non-null value in a list of expressions or NULL if all the values in a list are NULL.
Syntax:
COALESCE(value_1, value_2, ...., value_n)
Parameters Used:
value_1 – It is used to specify the first value in the list.
Return Value:The MySQL COALESCE() function returns the first non-null value in a list of expressions or NULL if all the values in a list are NULL.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
MySQL 4.0
MySQL 3.23
Example-1: Implementing COALESCE() function on a list.
SELECT COALESCE(NULL, 'A', 'B', NULL);
Output:
A
Example-2: Implementing COALESCE() function on a list.
SELECT COALESCE('A', NULL, 'B', NULL);
Output:
A
Example-3: Implementing COALESCE() function on a list.
SELECT COALESCE(NULL, 1, 2, 3, NULL, 'B', NULL);
Output:
1
Example-4: Implementing COALESCE() function on a list.
SELECT COALESCE(NULL, NULL, 'geeksforgeeks', NULL);
Output:
geeksforgeeks
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
Difference between DDL and DML in DBMS
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL | Subquery
|
[
{
"code": null,
"e": 25317,
"s": 25289,
"text": "\n21 Nov, 2019"
},
{
"code": null,
"e": 25511,
"s": 25317,
"text": "The MySQL COALESCE() function is used for returning the first non-null value in a list of expressions. If all the values in the list evaluate to NULL, then the COALESCE() function returns NULL."
},
{
"code": null,
"e": 25760,
"s": 25511,
"text": "The COALESCE() function accepts one parameter which is the list which can contain various values. The value returned by the MySQL COALESCE() function is the first non-null value in a list of expressions or NULL if all the values in a list are NULL."
},
{
"code": null,
"e": 25768,
"s": 25760,
"text": "Syntax:"
},
{
"code": null,
"e": 25810,
"s": 25768,
"text": "COALESCE(value_1, value_2, ...., value_n)"
},
{
"code": null,
"e": 25827,
"s": 25810,
"text": "Parameters Used:"
},
{
"code": null,
"e": 25888,
"s": 25827,
"text": "value_1 – It is used to specify the first value in the list."
},
{
"code": null,
"e": 26035,
"s": 25888,
"text": "Return Value:The MySQL COALESCE() function returns the first non-null value in a list of expressions or NULL if all the values in a list are NULL."
},
{
"code": null,
"e": 26064,
"s": 26035,
"text": "Supported Versions of MySQL:"
},
{
"code": null,
"e": 26074,
"s": 26064,
"text": "MySQL 5.7"
},
{
"code": null,
"e": 26084,
"s": 26074,
"text": "MySQL 5.6"
},
{
"code": null,
"e": 26094,
"s": 26084,
"text": "MySQL 5.5"
},
{
"code": null,
"e": 26104,
"s": 26094,
"text": "MySQL 5.1"
},
{
"code": null,
"e": 26114,
"s": 26104,
"text": "MySQL 5.0"
},
{
"code": null,
"e": 26124,
"s": 26114,
"text": "MySQL 4.1"
},
{
"code": null,
"e": 26134,
"s": 26124,
"text": "MySQL 4.0"
},
{
"code": null,
"e": 26145,
"s": 26134,
"text": "MySQL 3.23"
},
{
"code": null,
"e": 26200,
"s": 26145,
"text": "Example-1: Implementing COALESCE() function on a list."
},
{
"code": null,
"e": 26240,
"s": 26200,
"text": "SELECT COALESCE(NULL, 'A', 'B', NULL); "
},
{
"code": null,
"e": 26248,
"s": 26240,
"text": "Output:"
},
{
"code": null,
"e": 26251,
"s": 26248,
"text": "A "
},
{
"code": null,
"e": 26306,
"s": 26251,
"text": "Example-2: Implementing COALESCE() function on a list."
},
{
"code": null,
"e": 26346,
"s": 26306,
"text": "SELECT COALESCE('A', NULL, 'B', NULL); "
},
{
"code": null,
"e": 26354,
"s": 26346,
"text": "Output:"
},
{
"code": null,
"e": 26357,
"s": 26354,
"text": "A "
},
{
"code": null,
"e": 26412,
"s": 26357,
"text": "Example-3: Implementing COALESCE() function on a list."
},
{
"code": null,
"e": 26462,
"s": 26412,
"text": "SELECT COALESCE(NULL, 1, 2, 3, NULL, 'B', NULL); "
},
{
"code": null,
"e": 26470,
"s": 26462,
"text": "Output:"
},
{
"code": null,
"e": 26473,
"s": 26470,
"text": "1 "
},
{
"code": null,
"e": 26528,
"s": 26473,
"text": "Example-4: Implementing COALESCE() function on a list."
},
{
"code": null,
"e": 26581,
"s": 26528,
"text": "SELECT COALESCE(NULL, NULL, 'geeksforgeeks', NULL); "
},
{
"code": null,
"e": 26589,
"s": 26581,
"text": "Output:"
},
{
"code": null,
"e": 26604,
"s": 26589,
"text": "geeksforgeeks "
},
{
"code": null,
"e": 26610,
"s": 26604,
"text": "mysql"
},
{
"code": null,
"e": 26619,
"s": 26610,
"text": "SQLmysql"
},
{
"code": null,
"e": 26623,
"s": 26619,
"text": "SQL"
},
{
"code": null,
"e": 26627,
"s": 26623,
"text": "SQL"
},
{
"code": null,
"e": 26725,
"s": 26627,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26749,
"s": 26725,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 26760,
"s": 26749,
"text": "CTE in SQL"
},
{
"code": null,
"e": 26826,
"s": 26760,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26859,
"s": 26826,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 26898,
"s": 26859,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 26910,
"s": 26898,
"text": "SQL | Views"
},
{
"code": null,
"e": 26955,
"s": 26910,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 26987,
"s": 26955,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 27026,
"s": 26987,
"text": "Difference between DELETE and TRUNCATE"
}
] |
Count number of vector values in range with R - GeeksforGeeks
|
28 Sep, 2021
In this article, we will see how to count the number of vector values present in the given range in R. To achieve this functionality we can follow the following approach.
Approach
Create vector
Set range
Iterate through the vector
Check for elements that are within the range
Add them
Display sum
Implementation using this approach is given below.
Example 1:
R
# declaring a integer point vectorvec <- c(1,12,3,14,-1,-3) # specifying the range to check the element inmin_range = -2max_range = 8 # computing the size of the vectorsize = length(vec) # declaring sum =0 as the count of elements in rangesum = 0 # looping over the vector elementsfor(i in 1:size) { # check if elements lies in the range provided if(vec[i]>=min_range && vec[i]<=max_range) # incrementing count of sum if condition satisfied sum =sum+1 } print ("Sum of elements in range : ")print (sum)
Output
[1] “Sum of elements in range : “
[1] 3
Example 2:
R
# declaring a integer point vectorvec <- c(1,12,3,14,-1,-3,0.1) # specifying the range to check the element inmin_range = -2max_range = 8print ("Sum of elements in specified range : ") # and operator check if the element is less than# max range and greater than min rangesum(vec>min_range & vec<max_range)
Output
[1] “Sum of elements in specified range : “
[1] 4
However, if any of the elements of the vector is NA, then sum() method returns NA as the output. It can be ignored by specifying na.rm=TRUE.
Example 3:
R
# declaring a integer point vectorvec <- c(1,12,3,14,NA,-3,0.1) # specifying the range to check the element inmin_range = -2max_range = 8print ("Sum of elements in specified range without ignoring NA: ") # and operator check if the element is less than# max range and greater than min rangesum(vec>min_range & vec<max_range) print ("Sum of elements in specified range ignoring NA: ")sum(vec>min_range & vec<max_range,na.rm=TRUE)
Output
[1] “Sum of elements in specified range without ignoring NA: “
[1] NA
[1] “Sum of elements in specified range ignoring NA: “
[1] 3
simmytarika5
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame
|
[
{
"code": null,
"e": 26169,
"s": 26141,
"text": "\n28 Sep, 2021"
},
{
"code": null,
"e": 26340,
"s": 26169,
"text": "In this article, we will see how to count the number of vector values present in the given range in R. To achieve this functionality we can follow the following approach."
},
{
"code": null,
"e": 26349,
"s": 26340,
"text": "Approach"
},
{
"code": null,
"e": 26363,
"s": 26349,
"text": "Create vector"
},
{
"code": null,
"e": 26373,
"s": 26363,
"text": "Set range"
},
{
"code": null,
"e": 26400,
"s": 26373,
"text": "Iterate through the vector"
},
{
"code": null,
"e": 26445,
"s": 26400,
"text": "Check for elements that are within the range"
},
{
"code": null,
"e": 26454,
"s": 26445,
"text": "Add them"
},
{
"code": null,
"e": 26466,
"s": 26454,
"text": "Display sum"
},
{
"code": null,
"e": 26517,
"s": 26466,
"text": "Implementation using this approach is given below."
},
{
"code": null,
"e": 26528,
"s": 26517,
"text": "Example 1:"
},
{
"code": null,
"e": 26530,
"s": 26528,
"text": "R"
},
{
"code": "# declaring a integer point vectorvec <- c(1,12,3,14,-1,-3) # specifying the range to check the element inmin_range = -2max_range = 8 # computing the size of the vectorsize = length(vec) # declaring sum =0 as the count of elements in rangesum = 0 # looping over the vector elementsfor(i in 1:size) { # check if elements lies in the range provided if(vec[i]>=min_range && vec[i]<=max_range) # incrementing count of sum if condition satisfied sum =sum+1 } print (\"Sum of elements in range : \")print (sum)",
"e": 27048,
"s": 26530,
"text": null
},
{
"code": null,
"e": 27055,
"s": 27048,
"text": "Output"
},
{
"code": null,
"e": 27089,
"s": 27055,
"text": "[1] “Sum of elements in range : “"
},
{
"code": null,
"e": 27095,
"s": 27089,
"text": "[1] 3"
},
{
"code": null,
"e": 27106,
"s": 27095,
"text": "Example 2:"
},
{
"code": null,
"e": 27108,
"s": 27106,
"text": "R"
},
{
"code": "# declaring a integer point vectorvec <- c(1,12,3,14,-1,-3,0.1) # specifying the range to check the element inmin_range = -2max_range = 8print (\"Sum of elements in specified range : \") # and operator check if the element is less than# max range and greater than min rangesum(vec>min_range & vec<max_range)",
"e": 27414,
"s": 27108,
"text": null
},
{
"code": null,
"e": 27422,
"s": 27414,
"text": "Output "
},
{
"code": null,
"e": 27466,
"s": 27422,
"text": "[1] “Sum of elements in specified range : “"
},
{
"code": null,
"e": 27472,
"s": 27466,
"text": "[1] 4"
},
{
"code": null,
"e": 27613,
"s": 27472,
"text": "However, if any of the elements of the vector is NA, then sum() method returns NA as the output. It can be ignored by specifying na.rm=TRUE."
},
{
"code": null,
"e": 27624,
"s": 27613,
"text": "Example 3:"
},
{
"code": null,
"e": 27626,
"s": 27624,
"text": "R"
},
{
"code": "# declaring a integer point vectorvec <- c(1,12,3,14,NA,-3,0.1) # specifying the range to check the element inmin_range = -2max_range = 8print (\"Sum of elements in specified range without ignoring NA: \") # and operator check if the element is less than# max range and greater than min rangesum(vec>min_range & vec<max_range) print (\"Sum of elements in specified range ignoring NA: \")sum(vec>min_range & vec<max_range,na.rm=TRUE)",
"e": 28055,
"s": 27626,
"text": null
},
{
"code": null,
"e": 28062,
"s": 28055,
"text": "Output"
},
{
"code": null,
"e": 28125,
"s": 28062,
"text": "[1] “Sum of elements in specified range without ignoring NA: “"
},
{
"code": null,
"e": 28132,
"s": 28125,
"text": "[1] NA"
},
{
"code": null,
"e": 28187,
"s": 28132,
"text": "[1] “Sum of elements in specified range ignoring NA: “"
},
{
"code": null,
"e": 28193,
"s": 28187,
"text": "[1] 3"
},
{
"code": null,
"e": 28206,
"s": 28193,
"text": "simmytarika5"
},
{
"code": null,
"e": 28213,
"s": 28206,
"text": "Picked"
},
{
"code": null,
"e": 28231,
"s": 28213,
"text": "R Vector-Programs"
},
{
"code": null,
"e": 28241,
"s": 28231,
"text": "R-Vectors"
},
{
"code": null,
"e": 28252,
"s": 28241,
"text": "R Language"
},
{
"code": null,
"e": 28263,
"s": 28252,
"text": "R Programs"
},
{
"code": null,
"e": 28361,
"s": 28263,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28419,
"s": 28361,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 28471,
"s": 28419,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 28503,
"s": 28471,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 28547,
"s": 28503,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 28599,
"s": 28547,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28657,
"s": 28599,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 28701,
"s": 28657,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 28759,
"s": 28701,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28802,
"s": 28759,
"text": "Replace Specific Characters in String in R"
}
] |
Ruby | Enumerable max() function - GeeksforGeeks
|
05 Dec, 2019
The max() of enumerable is an inbuilt method in Ruby returns the maximum elements or an array containing the maximum N elements in the enumerable. When no block is given, it assumes all elements to be self comparable, but when the block is given then it is compared using .
Syntax: enu.max(n) { |a, b| block }
Parameters: The function takes two optional parameters n and block. N signifies the number of maximum elements and block determines the comparison property.
Return Value: It returns a max element or an array containing N max elements.
Example #1:
# Ruby program for max method in Enumerable # Initialize enu1 = (2..6) # Printsputs enu1.max p enu1.max(2)
Output:
6
[6, 5]
Example #2:
# Ruby program for max method in Enumerable # Initialize enu1 = [10, 17, 9, 10, 100, 34] # Printsputs enu1.max { |a, b| a<=>b} p enu1.max(2){ |a, b| a<=>b}
Output:
100
[100, 34]
Ruby Enumerable-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array count() operation
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
Ruby | Numeric round() function
|
[
{
"code": null,
"e": 24911,
"s": 24883,
"text": "\n05 Dec, 2019"
},
{
"code": null,
"e": 25185,
"s": 24911,
"text": "The max() of enumerable is an inbuilt method in Ruby returns the maximum elements or an array containing the maximum N elements in the enumerable. When no block is given, it assumes all elements to be self comparable, but when the block is given then it is compared using ."
},
{
"code": null,
"e": 25221,
"s": 25185,
"text": "Syntax: enu.max(n) { |a, b| block }"
},
{
"code": null,
"e": 25378,
"s": 25221,
"text": "Parameters: The function takes two optional parameters n and block. N signifies the number of maximum elements and block determines the comparison property."
},
{
"code": null,
"e": 25456,
"s": 25378,
"text": "Return Value: It returns a max element or an array containing N max elements."
},
{
"code": null,
"e": 25468,
"s": 25456,
"text": "Example #1:"
},
{
"code": "# Ruby program for max method in Enumerable # Initialize enu1 = (2..6) # Printsputs enu1.max p enu1.max(2)",
"e": 25581,
"s": 25468,
"text": null
},
{
"code": null,
"e": 25589,
"s": 25581,
"text": "Output:"
},
{
"code": null,
"e": 25599,
"s": 25589,
"text": "6\n[6, 5]\n"
},
{
"code": null,
"e": 25611,
"s": 25599,
"text": "Example #2:"
},
{
"code": "# Ruby program for max method in Enumerable # Initialize enu1 = [10, 17, 9, 10, 100, 34] # Printsputs enu1.max { |a, b| a<=>b} p enu1.max(2){ |a, b| a<=>b} ",
"e": 25774,
"s": 25611,
"text": null
},
{
"code": null,
"e": 25782,
"s": 25774,
"text": "Output:"
},
{
"code": null,
"e": 25797,
"s": 25782,
"text": "100\n[100, 34]\n"
},
{
"code": null,
"e": 25819,
"s": 25797,
"text": "Ruby Enumerable-class"
},
{
"code": null,
"e": 25832,
"s": 25819,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 25837,
"s": 25832,
"text": "Ruby"
},
{
"code": null,
"e": 25935,
"s": 25837,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25966,
"s": 25935,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 25993,
"s": 25966,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 26017,
"s": 25993,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 26047,
"s": 26017,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 26073,
"s": 26047,
"text": "Ruby | Types of Variables"
},
{
"code": null,
"e": 26116,
"s": 26073,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 26138,
"s": 26116,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 26169,
"s": 26138,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 26187,
"s": 26169,
"text": "Ruby | Data Types"
}
] |
All palindrome numbers in a list?
|
Here we will see one simple problem. We have to find all numbers that are palindrome in nature in a given list. The approach is simple, take each number from list and check it is palindrome or not, and print the number.
Begin
for each element e in arr, do
if e is palindrome, then
print e
end if
done
End
#include <iostream>
#include <cmath>
using namespace std;
bool isPalindrome(int n){
int reverse = 0, t;
t = n;
while (t != 0){
reverse = reverse * 10;
reverse = reverse + t%10;
t = t/10;
}
return (n == reverse);
}
int getAllPalindrome(int arr[], int n) {
for(int i = 0; i<n; i++){
if(isPalindrome(arr[i])){
cout << arr[i] << " ";
}
}
}
int main() {
int arr[] = {25, 145, 85, 121, 632, 111, 858, 45};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "All palindromes: ";
getAllPalindrome(arr, n);
}
All palindromes: 121 111 858
|
[
{
"code": null,
"e": 1282,
"s": 1062,
"text": "Here we will see one simple problem. We have to find all numbers that are palindrome in nature in a given list. The approach is simple, take each number from list and check it is palindrome or not, and print the number."
},
{
"code": null,
"e": 1394,
"s": 1282,
"text": "Begin\n for each element e in arr, do\n if e is palindrome, then\n print e\n end if\n done\nEnd"
},
{
"code": null,
"e": 1961,
"s": 1394,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nbool isPalindrome(int n){\n int reverse = 0, t;\n t = n;\n while (t != 0){\n reverse = reverse * 10;\n reverse = reverse + t%10;\n t = t/10;\n }\n return (n == reverse);\n}\nint getAllPalindrome(int arr[], int n) {\n for(int i = 0; i<n; i++){\n if(isPalindrome(arr[i])){\n cout << arr[i] << \" \";\n }\n }\n}\nint main() {\n int arr[] = {25, 145, 85, 121, 632, 111, 858, 45};\n int n = sizeof(arr) / sizeof(arr[0]);\n cout << \"All palindromes: \";\n getAllPalindrome(arr, n);\n}"
},
{
"code": null,
"e": 1990,
"s": 1961,
"text": "All palindromes: 121 111 858"
}
] |
VB.Net - XML Processing
|
The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard.
The System.Xml namespace in the .Net Framework contains classes for processing XML documents. Following are some of the commonly used classes in the System.Xml namespace.
XmlAttribute
Represents an attribute. Valid and default values for the attribute are defined in a document type definition (DTD) or schema.
XmlCDataSection
Represents a CDATA section.
XmlCharacterData
Provides text manipulation methods that are used by several classes.
XmlComment
Represents the content of an XML comment.
XmlConvert
Encodes and decodes XML names and provides methods for converting between common language runtime types and XML Schema definition language (XSD) types. When converting data types, the values returned are locale independent.
XmlDeclaration
Represents the XML declaration node <?xml version='1.0'...?>.
XmlDictionary
Implements a dictionary used to optimize Windows Communication Foundation (WCF)'s XML reader/writer implementations.
XmlDictionaryReader
An abstract class that the Windows Communication Foundation (WCF) derives from XmlReader to do serialization and deserialization.
XmlDictionaryWriter
Represents an abstract class that Windows Communication Foundation (WCF) derives from XmlWriter to do serialization and deserialization.
XmlDocument
Represents an XML document.
XmlDocumentFragment
Represents a lightweight object that is useful for tree insert operations.
XmlDocumentType
Represents the document type declaration.
XmlElement
Represents an element.
XmlEntity
Represents an entity declaration, such as <!ENTITY... >.
XmlEntityReference
Represents an entity reference node.
XmlException
Returns detailed information about the last exception.
XmlImplementation
Defines the context for a set of XmlDocument objects.
XmlLinkedNode
Gets the node immediately preceding or following this node.
XmlNode
Represents a single node in the XML document.
XmlNodeList
Represents an ordered collection of nodes.
XmlNodeReader
Represents a reader that provides fast, non-cached forward only access to XML data in an XmlNode.
XmlNotation
Represents a notation declaration, such as <!NOTATION... >.
XmlParserContext
Provides all the context information required by the XmlReader to parse an XML fragment.
XmlProcessingInstruction
Represents a processing instruction, which XML defines to keep processor-specific information in the text of the document.
XmlQualifiedName
Represents an XML qualified name.
XmlReader
Represents a reader that provides fast, noncached, forward-only access to XML data.
XmlReaderSettings
Specifies a set of features to support on the XmlReader object created by the Create method.
XmlResolver
Resolves external XML resources named by a Uniform Resource Identifier (URI).
XmlSecureResolver
Helps to secure another implementation of XmlResolver by wrapping the XmlResolver object and restricting the resources that the underlying XmlResolver has access to.
XmlSignificantWhitespace
Represents white space between markup in a mixed content node or white space within an xml:space= 'preserve' scope. This is also referred to as significant white space.
XmlText
Represents the text content of an element or attribute.
XmlTextReader
Represents a reader that provides fast, non-cached, forward-only access to XML data.
XmlTextWriter
Represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations.
XmlUrlResolver
Resolves external XML resources named by a Uniform Resource Identifier (URI).
XmlWhitespace
Represents white space in element content.
XmlWriter
Represents a writer that provides a fast, non-cached, forward-only means of generating streams or files containing XML data.
XmlWriterSettings
Specifies a set of features to support on the XmlWriter object created by the XmlWriter.Create method.
The two most basic and broadly used APIs to XML data are the SAX and DOM interfaces.
Simple API for XML (SAX) − Here, you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk, and the entire file is never stored in memory.
Simple API for XML (SAX) − Here, you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk, and the entire file is never stored in memory.
Document Object Model (DOM) API − This is World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document.
Document Object Model (DOM) API − This is World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document.
SAX obviously can't process information as fast as DOM can when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on a lot of small files.
SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other there is no reason why you can't use them both for large projects.
For all our XML code examples, let's use a simple XML file movies.xml as an input −
<?xml version = "1.0"?>
<collection shelf = "New Arrivals">
<movie title = "Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movie>
<movie title = "Transformers">
<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>8</stars>
<description>A schientific fiction</description>
</movie>
<movie title = "Trigun">
<type>Anime, Action</type>
<format>DVD</format>
<episodes>4</episodes>
<rating>PG</rating>
<stars>10</stars>
<description>Vash the Stampede!</description>
</movie>
<movie title = "Ishtar">
<type>Comedy</type>
<format>VHS</format>
<rating>PG</rating>
<stars>2</stars>
<description>Viewable boredom</description>
</movie>
</collection>
In SAX model, you use the XmlReader and XmlWriter classes to work with the XML data.
The XmlReader class is used to read XML data in a fast, forward-only and non-cached manner. It reads an XML document or a stream.
This example demonstrates reading XML data from the file movies.xml.
Take the following steps −
Add the movies.xml file in the bin\Debug folder of your application.
Add the movies.xml file in the bin\Debug folder of your application.
Import the System.Xml namespace in Form1.vb file.
Import the System.Xml namespace in Form1.vb file.
Add a label in the form and change its text to 'Movies Galore'.
Add a label in the form and change its text to 'Movies Galore'.
Add three list boxes and three buttons to show the title, type and description of a movie from the xml file.
Add three list boxes and three buttons to show the title, type and description of a movie from the xml file.
Add the following code using the code editor window.
Add the following code using the code editor window.
Imports System.Xml
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1().Items.Clear()
Dim xr As XmlReader = XmlReader.Create("movies.xml")
Do While xr.Read()
If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "movie" Then
ListBox1.Items.Add(xr.GetAttribute(0))
End If
Loop
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
ListBox2().Items.Clear()
Dim xr As XmlReader = XmlReader.Create("movies.xml")
Do While xr.Read()
If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "type" Then
ListBox2.Items.Add(xr.ReadElementString)
Else
xr.Read()
End If
Loop
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
ListBox3().Items.Clear()
Dim xr As XmlReader = XmlReader.Create("movies.xml")
Do While xr.Read()
If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "description" Then
ListBox3.Items.Add(xr.ReadElementString)
Else
xr.Read()
End If
Loop
End Sub
End Class
Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the buttons would display, title, type and description of the movies from the file.
The XmlWriter class is used to write XML data into a stream, a file or a TextWriter object. It also works in a forward-only, non-cached manner.
Let us create an XML file by adding some data at runtime. Take the following steps −
Add a WebBrowser control and a button control in the form.
Add a WebBrowser control and a button control in the form.
Change the Text property of the button to Show Authors File.
Change the Text property of the button to Show Authors File.
Add the following code in the code editor.
Add the following code in the code editor.
Imports System.Xml
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim xws As XmlWriterSettings = New XmlWriterSettings()
xws.Indent = True
xws.NewLineOnAttributes = True
Dim xw As XmlWriter = XmlWriter.Create("authors.xml", xws)
xw.WriteStartDocument()
xw.WriteStartElement("Authors")
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "1")
xw.WriteElementString("fname", "Zara")
xw.WriteElementString("lname", "Ali")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "2")
xw.WriteElementString("fname", "Priya")
xw.WriteElementString("lname", "Sharma")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "3")
xw.WriteElementString("fname", "Anshuman")
xw.WriteElementString("lname", "Mohan")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "4")
xw.WriteElementString("fname", "Bibhuti")
xw.WriteElementString("lname", "Banerjee")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "5")
xw.WriteElementString("fname", "Riyan")
xw.WriteElementString("lname", "Sengupta")
xw.WriteEndElement()
xw.WriteEndElement()
xw.WriteEndDocument()
xw.Flush()
xw.Close()
WebBrowser1.Url = New Uri(AppDomain.CurrentDomain.BaseDirectory + "authors.xml")
End Sub
End Class
Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the Show Author File would display the newly created authors.xml file on the web browser.
Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the Show Author File would display the newly created authors.xml file on the web browser.
According to the Document Object Model (DOM), an XML document consists of nodes and attributes of the nodes. The XmlDocument class is used to implement the XML DOM parser of the .Net Framework. It also allows you to modify an existing XML document by inserting, deleting or updating data in the document.
Following are some of the commonly used methods of the XmlDocument class −
AppendChild
Adds the specified node to the end of the list of child nodes, of this node.
CreateAttribute(String)
Creates an XmlAttribute with the specified Name.
CreateComment
Creates an XmlComment containing the specified data.
CreateDefaultAttribute
Creates a default attribute with the specified prefix, local name and namespace URI.
CreateElement(String)
Creates an element with the specified name.
CreateNode(String, String, String)
Creates an XmlNode with the specified node type, Name, and NamespaceURI.
CreateNode(XmlNodeType, String, String)
Creates an XmlNode with the specified XmlNodeType, Name, and NamespaceURI.
CreateNode(XmlNodeType, String, String, String)
Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI.
CreateProcessingInstruction
Creates an XmlProcessingInstruction with the specified name and data.
CreateSignificantWhitespace
Creates an XmlSignificantWhitespace node.
CreateTextNode
Creates an XmlText with the specified text.
CreateWhitespace
Creates an XmlWhitespace node.
CreateXmlDeclaration
Creates an XmlDeclaration node with the specified values.
GetElementById
Gets the XmlElement with the specified ID.
GetElementsByTagName(String)
Returns an XmlNodeList containing a list of all descendant elements that match the specified Name.
GetElementsByTagName(String, String)
Returns an XmlNodeList containing a list of all descendant elements that match the specified LocalName and NamespaceURI.
InsertAfter
Inserts the specified node immediately after the specified reference node.
InsertBefore
Inserts the specified node immediately before the specified reference node.
Load(Stream)
Loads the XML document from the specified stream.
Load(String)
Loads the XML document from the specified URL.
Load(TextReader)
Loads the XML document from the specified TextReader.
Load(XmlReader)
Loads the XML document from the specified XmlReader.
LoadXml
Loads the XML document from the specified string.
PrependChild
Adds the specified node to the beginning of the list of child nodes for this node.
ReadNode
Creates an XmlNode object based on the information in the XmlReader. The reader must be positioned on a node or attribute.
RemoveAll
Removes all the child nodes and/or attributes of the current node.
RemoveChild
Removes specified child node.
ReplaceChild
Replaces the child node oldChild with newChild node.
Save(Stream)
Saves the XML document to the specified stream.
Save(String)
Saves the XML document to the specified file.
Save(TextWriter)
Saves the XML document to the specified TextWriter.
Save(XmlWriter)
Saves the XML document to the specified XmlWriter.
In this example, let us insert some new nodes in the xml document authors.xml and then show all the authors' first names in a list box.
Take the following steps −
Add the authors.xml file in the bin/Debug folder of your application( it should be there if you have tried the last example)
Add the authors.xml file in the bin/Debug folder of your application( it should be there if you have tried the last example)
Import the System.Xml namespace
Import the System.Xml namespace
Add a list box and a button control in the form and set the text property of the button control to Show Authors.
Add a list box and a button control in the form and set the text property of the button control to Show Authors.
Add the following code using the code editor.
Add the following code using the code editor.
Imports System.Xml
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
Dim xd As XmlDocument = New XmlDocument()
xd.Load("authors.xml")
Dim newAuthor As XmlElement = xd.CreateElement("author")
newAuthor.SetAttribute("code", "6")
Dim fn As XmlElement = xd.CreateElement("fname")
fn.InnerText = "Bikram"
newAuthor.AppendChild(fn)
Dim ln As XmlElement = xd.CreateElement("lname")
ln.InnerText = "Seth"
newAuthor.AppendChild(ln)
xd.DocumentElement.AppendChild(newAuthor)
Dim tr As XmlTextWriter = New XmlTextWriter("movies.xml", Nothing)
tr.Formatting = Formatting.Indented
xd.WriteContentTo(tr)
tr.Close()
Dim nl As XmlNodeList = xd.GetElementsByTagName("fname")
For Each node As XmlNode In nl
ListBox1.Items.Add(node.InnerText)
Next node
End Sub
End Class
Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the Show Author button would display the first names of all the authors including the one we have added at runtime.
Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the Show Author button would display the first names of all the authors including the one we have added at runtime.
63 Lectures
4 hours
Frahaan Hussain
103 Lectures
12 hours
Arnold Higuit
60 Lectures
9.5 hours
Arnold Higuit
97 Lectures
9 hours
Arnold Higuit
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2470,
"s": 2300,
"text": "The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard."
},
{
"code": null,
"e": 2641,
"s": 2470,
"text": "The System.Xml namespace in the .Net Framework contains classes for processing XML documents. Following are some of the commonly used classes in the System.Xml namespace."
},
{
"code": null,
"e": 2654,
"s": 2641,
"text": "XmlAttribute"
},
{
"code": null,
"e": 2781,
"s": 2654,
"text": "Represents an attribute. Valid and default values for the attribute are defined in a document type definition (DTD) or schema."
},
{
"code": null,
"e": 2797,
"s": 2781,
"text": "XmlCDataSection"
},
{
"code": null,
"e": 2825,
"s": 2797,
"text": "Represents a CDATA section."
},
{
"code": null,
"e": 2842,
"s": 2825,
"text": "XmlCharacterData"
},
{
"code": null,
"e": 2911,
"s": 2842,
"text": "Provides text manipulation methods that are used by several classes."
},
{
"code": null,
"e": 2922,
"s": 2911,
"text": "XmlComment"
},
{
"code": null,
"e": 2964,
"s": 2922,
"text": "Represents the content of an XML comment."
},
{
"code": null,
"e": 2975,
"s": 2964,
"text": "XmlConvert"
},
{
"code": null,
"e": 3199,
"s": 2975,
"text": "Encodes and decodes XML names and provides methods for converting between common language runtime types and XML Schema definition language (XSD) types. When converting data types, the values returned are locale independent."
},
{
"code": null,
"e": 3214,
"s": 3199,
"text": "XmlDeclaration"
},
{
"code": null,
"e": 3276,
"s": 3214,
"text": "Represents the XML declaration node <?xml version='1.0'...?>."
},
{
"code": null,
"e": 3290,
"s": 3276,
"text": "XmlDictionary"
},
{
"code": null,
"e": 3407,
"s": 3290,
"text": "Implements a dictionary used to optimize Windows Communication Foundation (WCF)'s XML reader/writer implementations."
},
{
"code": null,
"e": 3427,
"s": 3407,
"text": "XmlDictionaryReader"
},
{
"code": null,
"e": 3557,
"s": 3427,
"text": "An abstract class that the Windows Communication Foundation (WCF) derives from XmlReader to do serialization and deserialization."
},
{
"code": null,
"e": 3577,
"s": 3557,
"text": "XmlDictionaryWriter"
},
{
"code": null,
"e": 3714,
"s": 3577,
"text": "Represents an abstract class that Windows Communication Foundation (WCF) derives from XmlWriter to do serialization and deserialization."
},
{
"code": null,
"e": 3726,
"s": 3714,
"text": "XmlDocument"
},
{
"code": null,
"e": 3754,
"s": 3726,
"text": "Represents an XML document."
},
{
"code": null,
"e": 3774,
"s": 3754,
"text": "XmlDocumentFragment"
},
{
"code": null,
"e": 3849,
"s": 3774,
"text": "Represents a lightweight object that is useful for tree insert operations."
},
{
"code": null,
"e": 3865,
"s": 3849,
"text": "XmlDocumentType"
},
{
"code": null,
"e": 3907,
"s": 3865,
"text": "Represents the document type declaration."
},
{
"code": null,
"e": 3918,
"s": 3907,
"text": "XmlElement"
},
{
"code": null,
"e": 3941,
"s": 3918,
"text": "Represents an element."
},
{
"code": null,
"e": 3951,
"s": 3941,
"text": "XmlEntity"
},
{
"code": null,
"e": 4008,
"s": 3951,
"text": "Represents an entity declaration, such as <!ENTITY... >."
},
{
"code": null,
"e": 4027,
"s": 4008,
"text": "XmlEntityReference"
},
{
"code": null,
"e": 4064,
"s": 4027,
"text": "Represents an entity reference node."
},
{
"code": null,
"e": 4077,
"s": 4064,
"text": "XmlException"
},
{
"code": null,
"e": 4132,
"s": 4077,
"text": "Returns detailed information about the last exception."
},
{
"code": null,
"e": 4150,
"s": 4132,
"text": "XmlImplementation"
},
{
"code": null,
"e": 4204,
"s": 4150,
"text": "Defines the context for a set of XmlDocument objects."
},
{
"code": null,
"e": 4218,
"s": 4204,
"text": "XmlLinkedNode"
},
{
"code": null,
"e": 4278,
"s": 4218,
"text": "Gets the node immediately preceding or following this node."
},
{
"code": null,
"e": 4286,
"s": 4278,
"text": "XmlNode"
},
{
"code": null,
"e": 4332,
"s": 4286,
"text": "Represents a single node in the XML document."
},
{
"code": null,
"e": 4344,
"s": 4332,
"text": "XmlNodeList"
},
{
"code": null,
"e": 4387,
"s": 4344,
"text": "Represents an ordered collection of nodes."
},
{
"code": null,
"e": 4401,
"s": 4387,
"text": "XmlNodeReader"
},
{
"code": null,
"e": 4499,
"s": 4401,
"text": "Represents a reader that provides fast, non-cached forward only access to XML data in an XmlNode."
},
{
"code": null,
"e": 4511,
"s": 4499,
"text": "XmlNotation"
},
{
"code": null,
"e": 4571,
"s": 4511,
"text": "Represents a notation declaration, such as <!NOTATION... >."
},
{
"code": null,
"e": 4588,
"s": 4571,
"text": "XmlParserContext"
},
{
"code": null,
"e": 4677,
"s": 4588,
"text": "Provides all the context information required by the XmlReader to parse an XML fragment."
},
{
"code": null,
"e": 4702,
"s": 4677,
"text": "XmlProcessingInstruction"
},
{
"code": null,
"e": 4825,
"s": 4702,
"text": "Represents a processing instruction, which XML defines to keep processor-specific information in the text of the document."
},
{
"code": null,
"e": 4842,
"s": 4825,
"text": "XmlQualifiedName"
},
{
"code": null,
"e": 4876,
"s": 4842,
"text": "Represents an XML qualified name."
},
{
"code": null,
"e": 4886,
"s": 4876,
"text": "XmlReader"
},
{
"code": null,
"e": 4970,
"s": 4886,
"text": "Represents a reader that provides fast, noncached, forward-only access to XML data."
},
{
"code": null,
"e": 4988,
"s": 4970,
"text": "XmlReaderSettings"
},
{
"code": null,
"e": 5081,
"s": 4988,
"text": "Specifies a set of features to support on the XmlReader object created by the Create method."
},
{
"code": null,
"e": 5093,
"s": 5081,
"text": "XmlResolver"
},
{
"code": null,
"e": 5171,
"s": 5093,
"text": "Resolves external XML resources named by a Uniform Resource Identifier (URI)."
},
{
"code": null,
"e": 5189,
"s": 5171,
"text": "XmlSecureResolver"
},
{
"code": null,
"e": 5355,
"s": 5189,
"text": "Helps to secure another implementation of XmlResolver by wrapping the XmlResolver object and restricting the resources that the underlying XmlResolver has access to."
},
{
"code": null,
"e": 5380,
"s": 5355,
"text": "XmlSignificantWhitespace"
},
{
"code": null,
"e": 5549,
"s": 5380,
"text": "Represents white space between markup in a mixed content node or white space within an xml:space= 'preserve' scope. This is also referred to as significant white space."
},
{
"code": null,
"e": 5557,
"s": 5549,
"text": "XmlText"
},
{
"code": null,
"e": 5613,
"s": 5557,
"text": "Represents the text content of an element or attribute."
},
{
"code": null,
"e": 5627,
"s": 5613,
"text": "XmlTextReader"
},
{
"code": null,
"e": 5712,
"s": 5627,
"text": "Represents a reader that provides fast, non-cached, forward-only access to XML data."
},
{
"code": null,
"e": 5726,
"s": 5712,
"text": "XmlTextWriter"
},
{
"code": null,
"e": 5953,
"s": 5726,
"text": "Represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations."
},
{
"code": null,
"e": 5968,
"s": 5953,
"text": "XmlUrlResolver"
},
{
"code": null,
"e": 6046,
"s": 5968,
"text": "Resolves external XML resources named by a Uniform Resource Identifier (URI)."
},
{
"code": null,
"e": 6060,
"s": 6046,
"text": "XmlWhitespace"
},
{
"code": null,
"e": 6103,
"s": 6060,
"text": "Represents white space in element content."
},
{
"code": null,
"e": 6113,
"s": 6103,
"text": "XmlWriter"
},
{
"code": null,
"e": 6238,
"s": 6113,
"text": "Represents a writer that provides a fast, non-cached, forward-only means of generating streams or files containing XML data."
},
{
"code": null,
"e": 6256,
"s": 6238,
"text": "XmlWriterSettings"
},
{
"code": null,
"e": 6359,
"s": 6256,
"text": "Specifies a set of features to support on the XmlWriter object created by the XmlWriter.Create method."
},
{
"code": null,
"e": 6444,
"s": 6359,
"text": "The two most basic and broadly used APIs to XML data are the SAX and DOM interfaces."
},
{
"code": null,
"e": 6746,
"s": 6444,
"text": "Simple API for XML (SAX) − Here, you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk, and the entire file is never stored in memory."
},
{
"code": null,
"e": 7048,
"s": 6746,
"text": "Simple API for XML (SAX) − Here, you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk, and the entire file is never stored in memory."
},
{
"code": null,
"e": 7272,
"s": 7048,
"text": "Document Object Model (DOM) API − This is World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document."
},
{
"code": null,
"e": 7496,
"s": 7272,
"text": "Document Object Model (DOM) API − This is World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document."
},
{
"code": null,
"e": 7703,
"s": 7496,
"text": "SAX obviously can't process information as fast as DOM can when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on a lot of small files."
},
{
"code": null,
"e": 7893,
"s": 7703,
"text": "SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other there is no reason why you can't use them both for large projects."
},
{
"code": null,
"e": 7977,
"s": 7893,
"text": "For all our XML code examples, let's use a simple XML file movies.xml as an input −"
},
{
"code": null,
"e": 8959,
"s": 7977,
"text": "<?xml version = \"1.0\"?>\n\n<collection shelf = \"New Arrivals\">\n <movie title = \"Enemy Behind\">\n <type>War, Thriller</type>\n <format>DVD</format>\n <year>2003</year>\n <rating>PG</rating>\n <stars>10</stars>\n <description>Talk about a US-Japan war</description>\n </movie>\n\n <movie title = \"Transformers\">\n <type>Anime, Science Fiction</type>\n <format>DVD</format>\n <year>1989</year>\n <rating>R</rating>\n <stars>8</stars>\n <description>A schientific fiction</description>\n </movie>\n\n <movie title = \"Trigun\">\n <type>Anime, Action</type>\n <format>DVD</format>\n <episodes>4</episodes>\n <rating>PG</rating>\n <stars>10</stars>\n <description>Vash the Stampede!</description>\n </movie>\n\n <movie title = \"Ishtar\">\n <type>Comedy</type>\n <format>VHS</format>\n <rating>PG</rating>\n <stars>2</stars>\n <description>Viewable boredom</description>\n </movie>\n</collection>"
},
{
"code": null,
"e": 9044,
"s": 8959,
"text": "In SAX model, you use the XmlReader and XmlWriter classes to work with the XML data."
},
{
"code": null,
"e": 9174,
"s": 9044,
"text": "The XmlReader class is used to read XML data in a fast, forward-only and non-cached manner. It reads an XML document or a stream."
},
{
"code": null,
"e": 9243,
"s": 9174,
"text": "This example demonstrates reading XML data from the file movies.xml."
},
{
"code": null,
"e": 9270,
"s": 9243,
"text": "Take the following steps −"
},
{
"code": null,
"e": 9339,
"s": 9270,
"text": "Add the movies.xml file in the bin\\Debug folder of your application."
},
{
"code": null,
"e": 9408,
"s": 9339,
"text": "Add the movies.xml file in the bin\\Debug folder of your application."
},
{
"code": null,
"e": 9458,
"s": 9408,
"text": "Import the System.Xml namespace in Form1.vb file."
},
{
"code": null,
"e": 9508,
"s": 9458,
"text": "Import the System.Xml namespace in Form1.vb file."
},
{
"code": null,
"e": 9572,
"s": 9508,
"text": "Add a label in the form and change its text to 'Movies Galore'."
},
{
"code": null,
"e": 9636,
"s": 9572,
"text": "Add a label in the form and change its text to 'Movies Galore'."
},
{
"code": null,
"e": 9745,
"s": 9636,
"text": "Add three list boxes and three buttons to show the title, type and description of a movie from the xml file."
},
{
"code": null,
"e": 9854,
"s": 9745,
"text": "Add three list boxes and three buttons to show the title, type and description of a movie from the xml file."
},
{
"code": null,
"e": 9907,
"s": 9854,
"text": "Add the following code using the code editor window."
},
{
"code": null,
"e": 9960,
"s": 9907,
"text": "Add the following code using the code editor window."
},
{
"code": null,
"e": 11376,
"s": 9960,
"text": "Imports System.Xml\nPublic Class Form1\n Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n ' Set the caption bar text of the form. \n Me.Text = \"tutorialspoint.com\"\n End Sub\n \n Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click\n ListBox1().Items.Clear()\n Dim xr As XmlReader = XmlReader.Create(\"movies.xml\")\n Do While xr.Read()\n If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = \"movie\" Then\n ListBox1.Items.Add(xr.GetAttribute(0))\n End If\n Loop\n End Sub\n \n Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click\n ListBox2().Items.Clear()\n Dim xr As XmlReader = XmlReader.Create(\"movies.xml\")\n Do While xr.Read()\n If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = \"type\" Then\n ListBox2.Items.Add(xr.ReadElementString)\n Else\n xr.Read()\n End If\n Loop\n End Sub\n \n Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click\n ListBox3().Items.Clear()\n Dim xr As XmlReader = XmlReader.Create(\"movies.xml\")\n Do While xr.Read()\n If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = \"description\" Then\n ListBox3.Items.Add(xr.ReadElementString)\n Else\n xr.Read()\n End If\n Loop\n End Sub\nEnd Class"
},
{
"code": null,
"e": 11573,
"s": 11376,
"text": "Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the buttons would display, title, type and description of the movies from the file."
},
{
"code": null,
"e": 11717,
"s": 11573,
"text": "The XmlWriter class is used to write XML data into a stream, a file or a TextWriter object. It also works in a forward-only, non-cached manner."
},
{
"code": null,
"e": 11802,
"s": 11717,
"text": "Let us create an XML file by adding some data at runtime. Take the following steps −"
},
{
"code": null,
"e": 11861,
"s": 11802,
"text": "Add a WebBrowser control and a button control in the form."
},
{
"code": null,
"e": 11920,
"s": 11861,
"text": "Add a WebBrowser control and a button control in the form."
},
{
"code": null,
"e": 11981,
"s": 11920,
"text": "Change the Text property of the button to Show Authors File."
},
{
"code": null,
"e": 12042,
"s": 11981,
"text": "Change the Text property of the button to Show Authors File."
},
{
"code": null,
"e": 12085,
"s": 12042,
"text": "Add the following code in the code editor."
},
{
"code": null,
"e": 12128,
"s": 12085,
"text": "Add the following code in the code editor."
},
{
"code": null,
"e": 13884,
"s": 12128,
"text": "Imports System.Xml\nPublic Class Form1\n Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n ' Set the caption bar text of the form. \n Me.Text = \"tutorialspoint.com\"\n End Sub\n Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click\n Dim xws As XmlWriterSettings = New XmlWriterSettings()\n xws.Indent = True\n xws.NewLineOnAttributes = True\n Dim xw As XmlWriter = XmlWriter.Create(\"authors.xml\", xws)\n xw.WriteStartDocument()\n xw.WriteStartElement(\"Authors\")\n xw.WriteStartElement(\"author\")\n xw.WriteAttributeString(\"code\", \"1\")\n xw.WriteElementString(\"fname\", \"Zara\")\n xw.WriteElementString(\"lname\", \"Ali\")\n xw.WriteEndElement()\n xw.WriteStartElement(\"author\")\n xw.WriteAttributeString(\"code\", \"2\")\n xw.WriteElementString(\"fname\", \"Priya\")\n xw.WriteElementString(\"lname\", \"Sharma\")\n xw.WriteEndElement()\n xw.WriteStartElement(\"author\")\n xw.WriteAttributeString(\"code\", \"3\")\n xw.WriteElementString(\"fname\", \"Anshuman\")\n xw.WriteElementString(\"lname\", \"Mohan\")\n xw.WriteEndElement()\n xw.WriteStartElement(\"author\")\n xw.WriteAttributeString(\"code\", \"4\")\n xw.WriteElementString(\"fname\", \"Bibhuti\")\n xw.WriteElementString(\"lname\", \"Banerjee\")\n xw.WriteEndElement()\n xw.WriteStartElement(\"author\")\n xw.WriteAttributeString(\"code\", \"5\")\n xw.WriteElementString(\"fname\", \"Riyan\")\n xw.WriteElementString(\"lname\", \"Sengupta\")\n xw.WriteEndElement()\n xw.WriteEndElement()\n xw.WriteEndDocument()\n xw.Flush()\n xw.Close()\n WebBrowser1.Url = New Uri(AppDomain.CurrentDomain.BaseDirectory + \"authors.xml\")\n End Sub\nEnd Class"
},
{
"code": null,
"e": 14087,
"s": 13884,
"text": "Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the Show Author File would display the newly created authors.xml file on the web browser."
},
{
"code": null,
"e": 14290,
"s": 14087,
"text": "Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the Show Author File would display the newly created authors.xml file on the web browser."
},
{
"code": null,
"e": 14595,
"s": 14290,
"text": "According to the Document Object Model (DOM), an XML document consists of nodes and attributes of the nodes. The XmlDocument class is used to implement the XML DOM parser of the .Net Framework. It also allows you to modify an existing XML document by inserting, deleting or updating data in the document."
},
{
"code": null,
"e": 14670,
"s": 14595,
"text": "Following are some of the commonly used methods of the XmlDocument class −"
},
{
"code": null,
"e": 14682,
"s": 14670,
"text": "AppendChild"
},
{
"code": null,
"e": 14759,
"s": 14682,
"text": "Adds the specified node to the end of the list of child nodes, of this node."
},
{
"code": null,
"e": 14783,
"s": 14759,
"text": "CreateAttribute(String)"
},
{
"code": null,
"e": 14832,
"s": 14783,
"text": "Creates an XmlAttribute with the specified Name."
},
{
"code": null,
"e": 14846,
"s": 14832,
"text": "CreateComment"
},
{
"code": null,
"e": 14899,
"s": 14846,
"text": "Creates an XmlComment containing the specified data."
},
{
"code": null,
"e": 14922,
"s": 14899,
"text": "CreateDefaultAttribute"
},
{
"code": null,
"e": 15007,
"s": 14922,
"text": "Creates a default attribute with the specified prefix, local name and namespace URI."
},
{
"code": null,
"e": 15029,
"s": 15007,
"text": "CreateElement(String)"
},
{
"code": null,
"e": 15073,
"s": 15029,
"text": "Creates an element with the specified name."
},
{
"code": null,
"e": 15108,
"s": 15073,
"text": "CreateNode(String, String, String)"
},
{
"code": null,
"e": 15181,
"s": 15108,
"text": "Creates an XmlNode with the specified node type, Name, and NamespaceURI."
},
{
"code": null,
"e": 15221,
"s": 15181,
"text": "CreateNode(XmlNodeType, String, String)"
},
{
"code": null,
"e": 15296,
"s": 15221,
"text": "Creates an XmlNode with the specified XmlNodeType, Name, and NamespaceURI."
},
{
"code": null,
"e": 15344,
"s": 15296,
"text": "CreateNode(XmlNodeType, String, String, String)"
},
{
"code": null,
"e": 15426,
"s": 15344,
"text": "Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI."
},
{
"code": null,
"e": 15454,
"s": 15426,
"text": "CreateProcessingInstruction"
},
{
"code": null,
"e": 15524,
"s": 15454,
"text": "Creates an XmlProcessingInstruction with the specified name and data."
},
{
"code": null,
"e": 15552,
"s": 15524,
"text": "CreateSignificantWhitespace"
},
{
"code": null,
"e": 15594,
"s": 15552,
"text": "Creates an XmlSignificantWhitespace node."
},
{
"code": null,
"e": 15609,
"s": 15594,
"text": "CreateTextNode"
},
{
"code": null,
"e": 15653,
"s": 15609,
"text": "Creates an XmlText with the specified text."
},
{
"code": null,
"e": 15670,
"s": 15653,
"text": "CreateWhitespace"
},
{
"code": null,
"e": 15701,
"s": 15670,
"text": "Creates an XmlWhitespace node."
},
{
"code": null,
"e": 15722,
"s": 15701,
"text": "CreateXmlDeclaration"
},
{
"code": null,
"e": 15780,
"s": 15722,
"text": "Creates an XmlDeclaration node with the specified values."
},
{
"code": null,
"e": 15795,
"s": 15780,
"text": "GetElementById"
},
{
"code": null,
"e": 15838,
"s": 15795,
"text": "Gets the XmlElement with the specified ID."
},
{
"code": null,
"e": 15867,
"s": 15838,
"text": "GetElementsByTagName(String)"
},
{
"code": null,
"e": 15966,
"s": 15867,
"text": "Returns an XmlNodeList containing a list of all descendant elements that match the specified Name."
},
{
"code": null,
"e": 16003,
"s": 15966,
"text": "GetElementsByTagName(String, String)"
},
{
"code": null,
"e": 16124,
"s": 16003,
"text": "Returns an XmlNodeList containing a list of all descendant elements that match the specified LocalName and NamespaceURI."
},
{
"code": null,
"e": 16136,
"s": 16124,
"text": "InsertAfter"
},
{
"code": null,
"e": 16211,
"s": 16136,
"text": "Inserts the specified node immediately after the specified reference node."
},
{
"code": null,
"e": 16224,
"s": 16211,
"text": "InsertBefore"
},
{
"code": null,
"e": 16300,
"s": 16224,
"text": "Inserts the specified node immediately before the specified reference node."
},
{
"code": null,
"e": 16313,
"s": 16300,
"text": "Load(Stream)"
},
{
"code": null,
"e": 16363,
"s": 16313,
"text": "Loads the XML document from the specified stream."
},
{
"code": null,
"e": 16376,
"s": 16363,
"text": "Load(String)"
},
{
"code": null,
"e": 16423,
"s": 16376,
"text": "Loads the XML document from the specified URL."
},
{
"code": null,
"e": 16440,
"s": 16423,
"text": "Load(TextReader)"
},
{
"code": null,
"e": 16494,
"s": 16440,
"text": "Loads the XML document from the specified TextReader."
},
{
"code": null,
"e": 16510,
"s": 16494,
"text": "Load(XmlReader)"
},
{
"code": null,
"e": 16563,
"s": 16510,
"text": "Loads the XML document from the specified XmlReader."
},
{
"code": null,
"e": 16571,
"s": 16563,
"text": "LoadXml"
},
{
"code": null,
"e": 16621,
"s": 16571,
"text": "Loads the XML document from the specified string."
},
{
"code": null,
"e": 16634,
"s": 16621,
"text": "PrependChild"
},
{
"code": null,
"e": 16717,
"s": 16634,
"text": "Adds the specified node to the beginning of the list of child nodes for this node."
},
{
"code": null,
"e": 16726,
"s": 16717,
"text": "ReadNode"
},
{
"code": null,
"e": 16849,
"s": 16726,
"text": "Creates an XmlNode object based on the information in the XmlReader. The reader must be positioned on a node or attribute."
},
{
"code": null,
"e": 16859,
"s": 16849,
"text": "RemoveAll"
},
{
"code": null,
"e": 16926,
"s": 16859,
"text": "Removes all the child nodes and/or attributes of the current node."
},
{
"code": null,
"e": 16938,
"s": 16926,
"text": "RemoveChild"
},
{
"code": null,
"e": 16968,
"s": 16938,
"text": "Removes specified child node."
},
{
"code": null,
"e": 16981,
"s": 16968,
"text": "ReplaceChild"
},
{
"code": null,
"e": 17034,
"s": 16981,
"text": "Replaces the child node oldChild with newChild node."
},
{
"code": null,
"e": 17047,
"s": 17034,
"text": "Save(Stream)"
},
{
"code": null,
"e": 17095,
"s": 17047,
"text": "Saves the XML document to the specified stream."
},
{
"code": null,
"e": 17108,
"s": 17095,
"text": "Save(String)"
},
{
"code": null,
"e": 17154,
"s": 17108,
"text": "Saves the XML document to the specified file."
},
{
"code": null,
"e": 17171,
"s": 17154,
"text": "Save(TextWriter)"
},
{
"code": null,
"e": 17223,
"s": 17171,
"text": "Saves the XML document to the specified TextWriter."
},
{
"code": null,
"e": 17239,
"s": 17223,
"text": "Save(XmlWriter)"
},
{
"code": null,
"e": 17290,
"s": 17239,
"text": "Saves the XML document to the specified XmlWriter."
},
{
"code": null,
"e": 17426,
"s": 17290,
"text": "In this example, let us insert some new nodes in the xml document authors.xml and then show all the authors' first names in a list box."
},
{
"code": null,
"e": 17453,
"s": 17426,
"text": "Take the following steps −"
},
{
"code": null,
"e": 17578,
"s": 17453,
"text": "Add the authors.xml file in the bin/Debug folder of your application( it should be there if you have tried the last example)"
},
{
"code": null,
"e": 17703,
"s": 17578,
"text": "Add the authors.xml file in the bin/Debug folder of your application( it should be there if you have tried the last example)"
},
{
"code": null,
"e": 17735,
"s": 17703,
"text": "Import the System.Xml namespace"
},
{
"code": null,
"e": 17767,
"s": 17735,
"text": "Import the System.Xml namespace"
},
{
"code": null,
"e": 17880,
"s": 17767,
"text": "Add a list box and a button control in the form and set the text property of the button control to Show Authors."
},
{
"code": null,
"e": 17993,
"s": 17880,
"text": "Add a list box and a button control in the form and set the text property of the button control to Show Authors."
},
{
"code": null,
"e": 18039,
"s": 17993,
"text": "Add the following code using the code editor."
},
{
"code": null,
"e": 18085,
"s": 18039,
"text": "Add the following code using the code editor."
},
{
"code": null,
"e": 19270,
"s": 18085,
"text": "Imports System.Xml\nPublic Class Form1\n Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n ' Set the caption bar text of the form. \n Me.Text = \"tutorialspoint.com\"\n End Sub\n \n Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click\n ListBox1.Items.Clear()\n \n Dim xd As XmlDocument = New XmlDocument()\n xd.Load(\"authors.xml\")\n \n Dim newAuthor As XmlElement = xd.CreateElement(\"author\")\n newAuthor.SetAttribute(\"code\", \"6\")\n \n Dim fn As XmlElement = xd.CreateElement(\"fname\")\n fn.InnerText = \"Bikram\"\n newAuthor.AppendChild(fn)\n \n Dim ln As XmlElement = xd.CreateElement(\"lname\")\n ln.InnerText = \"Seth\"\n newAuthor.AppendChild(ln)\n xd.DocumentElement.AppendChild(newAuthor)\n \n Dim tr As XmlTextWriter = New XmlTextWriter(\"movies.xml\", Nothing)\n tr.Formatting = Formatting.Indented\n xd.WriteContentTo(tr)\n tr.Close()\n \n Dim nl As XmlNodeList = xd.GetElementsByTagName(\"fname\")\n \n For Each node As XmlNode In nl\n ListBox1.Items.Add(node.InnerText)\n Next node\n End Sub\nEnd Class"
},
{
"code": null,
"e": 19499,
"s": 19270,
"text": "Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the Show Author button would display the first names of all the authors including the one we have added at runtime."
},
{
"code": null,
"e": 19728,
"s": 19499,
"text": "Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the Show Author button would display the first names of all the authors including the one we have added at runtime."
},
{
"code": null,
"e": 19761,
"s": 19728,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 19778,
"s": 19761,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 19813,
"s": 19778,
"text": "\n 103 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 19828,
"s": 19813,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 19863,
"s": 19828,
"text": "\n 60 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 19878,
"s": 19863,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 19911,
"s": 19878,
"text": "\n 97 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 19926,
"s": 19911,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 19933,
"s": 19926,
"text": " Print"
},
{
"code": null,
"e": 19944,
"s": 19933,
"text": " Add Notes"
}
] |
TypeScript - Numbers
|
TypeScript like JavaScript supports numeric values as Number objects. A number object converts numeric literal to an instance of the number class. The Number class acts as a wrapper and enables manipulation of numeric literals as they were objects.
var var_name = new Number(value)
In case a non-numeric argument is passed as an argument to the Number’s constructor, it returns NaN (Not–a–Number)
The following table lists a set of properties of the Number object −
MAX_VALUE
The largest possible value a number in JavaScript can have 1.7976931348623157E+308.
MIN_VALUE
The smallest possible value a number in JavaScript can have 5E-324.
NaN
Equal to a value that is not a number.
NEGATIVE_INFINITY
A value that is less than MIN_VALUE.
POSITIVE_INFINITY
A value that is greater than MAX_VALUE.
prototype
A static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document.
constructor
Returns the function that created this object's instance. By default, this is the Number object.
console.log("TypeScript Number Properties: ");
console.log("Maximum value that a number variable can hold: " + Number.MAX_VALUE);
console.log("The least value that a number variable can hold: " + Number.MIN_VALUE);
console.log("Value of Negative Infinity: " + Number.NEGATIVE_INFINITY);
console.log("Value of Negative Infinity:" + Number.POSITIVE_INFINITY);
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
TypeScript Number Properties:
Maximum value that a number variable can hold: 1.7976931348623157e+308
The least value that a number variable can hold: 5e-324
Value of Negative Infinity: -Infinity
Value of Negative Infinity:Infinity
var month = 0
if( month<=0 || month >12) {
month = Number.NaN
console.log("Month is "+ month)
} else {
console.log("Value Accepted..")
}
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
Month is NaN
function employee(id:number,name:string) {
this.id = id
this.name = name
}
var emp = new employee(123,"Smith")
employee.prototype.email = "smith@abc.com"
console.log("Employee 's Id: "+emp.id)
console.log("Employee's name: "+emp.name)
console.log("Employee's Email ID: "+emp.email)
On compiling, it will generate the following JavaScript code −
//Generated by typescript 1.8.10
function employee(id, name) {
this.id = id;
this.name = name;
}
var emp = new employee(123, "Smith");
employee.prototype.email = "smith@abc.com";
console.log("Employee 's Id: " + emp.id);
console.log("Employee's name: " + emp.name);
console.log("Employee's Email ID: " + emp.email);
Its output is as follows −
Employee’s Id: 123
Emaployee’s name: Smith
Employee’s Email ID: smith@abc.com
The Number object contains only the default methods that are a part of every object's definition. Some of the commonly used methods are listed below −
Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation.
Formats a number with a specific number of digits to the right of the decimal.
Returns a string value version of the current number in a format that may vary according to a browser's local settings.
Defines how many total digits (including digits to the left and right of the decimal) to display of a number. A negative precision will throw an error.
Returns the string representation of the number's value. The function is passed the radix, an integer between 2 and 36 specifying the base to use for representing numeric values.
Returns the number's primitive value.
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2297,
"s": 2048,
"text": "TypeScript like JavaScript supports numeric values as Number objects. A number object converts numeric literal to an instance of the number class. The Number class acts as a wrapper and enables manipulation of numeric literals as they were objects."
},
{
"code": null,
"e": 2331,
"s": 2297,
"text": "var var_name = new Number(value)\n"
},
{
"code": null,
"e": 2446,
"s": 2331,
"text": "In case a non-numeric argument is passed as an argument to the Number’s constructor, it returns NaN (Not–a–Number)"
},
{
"code": null,
"e": 2515,
"s": 2446,
"text": "The following table lists a set of properties of the Number object −"
},
{
"code": null,
"e": 2525,
"s": 2515,
"text": "MAX_VALUE"
},
{
"code": null,
"e": 2609,
"s": 2525,
"text": "The largest possible value a number in JavaScript can have 1.7976931348623157E+308."
},
{
"code": null,
"e": 2619,
"s": 2609,
"text": "MIN_VALUE"
},
{
"code": null,
"e": 2687,
"s": 2619,
"text": "The smallest possible value a number in JavaScript can have 5E-324."
},
{
"code": null,
"e": 2691,
"s": 2687,
"text": "NaN"
},
{
"code": null,
"e": 2730,
"s": 2691,
"text": "Equal to a value that is not a number."
},
{
"code": null,
"e": 2748,
"s": 2730,
"text": "NEGATIVE_INFINITY"
},
{
"code": null,
"e": 2785,
"s": 2748,
"text": "A value that is less than MIN_VALUE."
},
{
"code": null,
"e": 2803,
"s": 2785,
"text": "POSITIVE_INFINITY"
},
{
"code": null,
"e": 2843,
"s": 2803,
"text": "A value that is greater than MAX_VALUE."
},
{
"code": null,
"e": 2853,
"s": 2843,
"text": "prototype"
},
{
"code": null,
"e": 3003,
"s": 2853,
"text": "A static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document."
},
{
"code": null,
"e": 3015,
"s": 3003,
"text": "constructor"
},
{
"code": null,
"e": 3112,
"s": 3015,
"text": "Returns the function that created this object's instance. By default, this is the Number object."
},
{
"code": null,
"e": 3475,
"s": 3112,
"text": "console.log(\"TypeScript Number Properties: \"); \nconsole.log(\"Maximum value that a number variable can hold: \" + Number.MAX_VALUE); \nconsole.log(\"The least value that a number variable can hold: \" + Number.MIN_VALUE); \nconsole.log(\"Value of Negative Infinity: \" + Number.NEGATIVE_INFINITY); \nconsole.log(\"Value of Negative Infinity:\" + Number.POSITIVE_INFINITY);\n"
},
{
"code": null,
"e": 3535,
"s": 3475,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 3562,
"s": 3535,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3799,
"s": 3562,
"text": "TypeScript Number Properties: \nMaximum value that a number variable can hold: 1.7976931348623157e+308 \nThe least value that a number variable can hold: 5e-324 \nValue of Negative Infinity: -Infinity \nValue of Negative Infinity:Infinity\n"
},
{
"code": null,
"e": 3952,
"s": 3799,
"text": "var month = 0 \nif( month<=0 || month >12) { \n month = Number.NaN \n console.log(\"Month is \"+ month) \n} else { \n console.log(\"Value Accepted..\") \n}\n"
},
{
"code": null,
"e": 4012,
"s": 3952,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 4039,
"s": 4012,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4053,
"s": 4039,
"text": "Month is NaN\n"
},
{
"code": null,
"e": 4352,
"s": 4053,
"text": "function employee(id:number,name:string) { \n this.id = id \n this.name = name \n} \n\nvar emp = new employee(123,\"Smith\") \nemployee.prototype.email = \"smith@abc.com\" \n\nconsole.log(\"Employee 's Id: \"+emp.id) \nconsole.log(\"Employee's name: \"+emp.name) \nconsole.log(\"Employee's Email ID: \"+emp.email)\n"
},
{
"code": null,
"e": 4415,
"s": 4352,
"text": "On compiling, it will generate the following JavaScript code −"
},
{
"code": null,
"e": 4740,
"s": 4415,
"text": "//Generated by typescript 1.8.10\nfunction employee(id, name) {\n this.id = id;\n this.name = name;\n}\n\nvar emp = new employee(123, \"Smith\");\nemployee.prototype.email = \"smith@abc.com\";\n\nconsole.log(\"Employee 's Id: \" + emp.id);\nconsole.log(\"Employee's name: \" + emp.name);\nconsole.log(\"Employee's Email ID: \" + emp.email);\n"
},
{
"code": null,
"e": 4767,
"s": 4740,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4848,
"s": 4767,
"text": "Employee’s Id: 123 \nEmaployee’s name: Smith \nEmployee’s Email ID: smith@abc.com\n"
},
{
"code": null,
"e": 4999,
"s": 4848,
"text": "The Number object contains only the default methods that are a part of every object's definition. Some of the commonly used methods are listed below −"
},
{
"code": null,
"e": 5139,
"s": 4999,
"text": "Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation."
},
{
"code": null,
"e": 5218,
"s": 5139,
"text": "Formats a number with a specific number of digits to the right of the decimal."
},
{
"code": null,
"e": 5338,
"s": 5218,
"text": "Returns a string value version of the current number in a format that may vary according to a browser's local settings."
},
{
"code": null,
"e": 5490,
"s": 5338,
"text": "Defines how many total digits (including digits to the left and right of the decimal) to display of a number. A negative precision will throw an error."
},
{
"code": null,
"e": 5669,
"s": 5490,
"text": "Returns the string representation of the number's value. The function is passed the radix, an integer between 2 and 36 specifying the base to use for representing numeric values."
},
{
"code": null,
"e": 5707,
"s": 5669,
"text": "Returns the number's primitive value."
},
{
"code": null,
"e": 5740,
"s": 5707,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5754,
"s": 5740,
"text": " Antonio Papa"
},
{
"code": null,
"e": 5787,
"s": 5754,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5801,
"s": 5787,
"text": " Haider Malik"
},
{
"code": null,
"e": 5836,
"s": 5801,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5856,
"s": 5836,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5889,
"s": 5856,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5903,
"s": 5889,
"text": " Sean Bradley"
},
{
"code": null,
"e": 5938,
"s": 5903,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5954,
"s": 5938,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 5987,
"s": 5954,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6007,
"s": 5987,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 6014,
"s": 6007,
"text": " Print"
},
{
"code": null,
"e": 6025,
"s": 6014,
"text": " Add Notes"
}
] |
How to Create TreeMap in Java? - GeeksforGeeks
|
07 Jan, 2021
The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
To create TreeMap we can use Map class or TreeMap class reference.
Example 1:
Java
// Java program demonstrate how to create a TreeMap import java.util.*; class GFG { public static void main(String[] args) { // Declaring a treemap TreeMap<Integer, String> map; // Creating an empty TreeMap map = new TreeMap<Integer, String>(); System.out.println("TreeMap successfully" + " created"); }}
TreeMap successfully created
Example 2:
Java
// Java program demonstrate how to create and add elements// to TreeMap import java.util.*; class GFG { public static void main(String[] args) { // Creating an empty TreeMap using Map interface Map<Integer, String> map = new TreeMap<>(); System.out.println("TreeMap successfully" + " created"); // Adding elements map.put(1, "Geeks"); map.put(2, "for"); map.put(3, "Geeks"); // Printing TreeMap System.out.println("TreeMap: " + map); }}
TreeMap successfully created
TreeMap: {1=Geeks, 2=for, 3=Geeks}
Java-Collections
java-TreeMap
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Generics in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n07 Jan, 2021"
},
{
"code": null,
"e": 24206,
"s": 23948,
"text": "The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used."
},
{
"code": null,
"e": 24273,
"s": 24206,
"text": "To create TreeMap we can use Map class or TreeMap class reference."
},
{
"code": null,
"e": 24284,
"s": 24273,
"text": "Example 1:"
},
{
"code": null,
"e": 24289,
"s": 24284,
"text": "Java"
},
{
"code": "// Java program demonstrate how to create a TreeMap import java.util.*; class GFG { public static void main(String[] args) { // Declaring a treemap TreeMap<Integer, String> map; // Creating an empty TreeMap map = new TreeMap<Integer, String>(); System.out.println(\"TreeMap successfully\" + \" created\"); }}",
"e": 24672,
"s": 24289,
"text": null
},
{
"code": null,
"e": 24701,
"s": 24672,
"text": "TreeMap successfully created"
},
{
"code": null,
"e": 24712,
"s": 24701,
"text": "Example 2:"
},
{
"code": null,
"e": 24717,
"s": 24712,
"text": "Java"
},
{
"code": "// Java program demonstrate how to create and add elements// to TreeMap import java.util.*; class GFG { public static void main(String[] args) { // Creating an empty TreeMap using Map interface Map<Integer, String> map = new TreeMap<>(); System.out.println(\"TreeMap successfully\" + \" created\"); // Adding elements map.put(1, \"Geeks\"); map.put(2, \"for\"); map.put(3, \"Geeks\"); // Printing TreeMap System.out.println(\"TreeMap: \" + map); }}",
"e": 25266,
"s": 24717,
"text": null
},
{
"code": null,
"e": 25330,
"s": 25266,
"text": "TreeMap successfully created\nTreeMap: {1=Geeks, 2=for, 3=Geeks}"
},
{
"code": null,
"e": 25347,
"s": 25330,
"text": "Java-Collections"
},
{
"code": null,
"e": 25360,
"s": 25347,
"text": "java-TreeMap"
},
{
"code": null,
"e": 25367,
"s": 25360,
"text": "Picked"
},
{
"code": null,
"e": 25372,
"s": 25367,
"text": "Java"
},
{
"code": null,
"e": 25386,
"s": 25372,
"text": "Java Programs"
},
{
"code": null,
"e": 25391,
"s": 25386,
"text": "Java"
},
{
"code": null,
"e": 25408,
"s": 25391,
"text": "Java-Collections"
},
{
"code": null,
"e": 25506,
"s": 25408,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25521,
"s": 25506,
"text": "Stream In Java"
},
{
"code": null,
"e": 25567,
"s": 25521,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25588,
"s": 25567,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25607,
"s": 25588,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 25624,
"s": 25607,
"text": "Generics in Java"
},
{
"code": null,
"e": 25668,
"s": 25624,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 25694,
"s": 25668,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 25728,
"s": 25694,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 25775,
"s": 25728,
"text": "Implementing a Linked List in Java using Class"
}
] |
Convert Python Nested Lists to Multidimensional NumPy Arrays - GeeksforGeeks
|
09 Jul, 2021
Prerequisite: Python List, Numpy ndarray
Both lists and NumPy arrays are inter-convertible. Since NumPy is a fast (High-performance) Python library for performing mathematical operations so it is preferred to work on NumPy arrays rather than nested lists.
Method 1: Using numpy.array().
Approach :
Import numpy package.
Initialize the nested list and then use numpy.array() function to convert the list to an array and store it in a different object.
Display both list and NumPy array and observe the difference.
Below is the implementation.
Python3
# importing numpy libraryimport numpy # initializing listls = [[1, 7, 0], [ 6, 2, 5]] # converting list to arrayar = numpy.array(ls) # displaying listprint ( ls) # displaying arrayprint ( ar)
Output :
[[1, 7, 0], [6, 2, 5]]
[[1 7 0]
[6 2 5]]
Method 2: Using numpy.asarray().
Approach :
Import numpy package.
Initialize the nested 4-dimensional list and then use numpy.asarray() function to convert the list to the array and store it in a different object.
Display both list and NumPy array and observe the difference.
Below is the implementation.
Python3
# importing numpy libraryimport numpy # initializing listls = [[1, 7, 0],[ 6, 2, 5],[ 7, 8, 9],[ 41, 10, 20]] # converting list to arrayar = numpy.asarray(ls) # displaying listprint ( ls) # displaying arrayprint ( ar)
Output :
[[1, 7, 0], [6, 2, 5], [7, 8, 9], [41, 10, 20]]
[[ 1 7 0]
[ 6 2 5]
[ 7 8 9]
[41 10 20]]
abhishek0719kadiyan
Python numpy-ndarray
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
Print lists in Python (4 Different Ways)
|
[
{
"code": null,
"e": 24184,
"s": 24156,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 24225,
"s": 24184,
"text": "Prerequisite: Python List, Numpy ndarray"
},
{
"code": null,
"e": 24440,
"s": 24225,
"text": "Both lists and NumPy arrays are inter-convertible. Since NumPy is a fast (High-performance) Python library for performing mathematical operations so it is preferred to work on NumPy arrays rather than nested lists."
},
{
"code": null,
"e": 24471,
"s": 24440,
"text": "Method 1: Using numpy.array()."
},
{
"code": null,
"e": 24482,
"s": 24471,
"text": "Approach :"
},
{
"code": null,
"e": 24504,
"s": 24482,
"text": "Import numpy package."
},
{
"code": null,
"e": 24635,
"s": 24504,
"text": "Initialize the nested list and then use numpy.array() function to convert the list to an array and store it in a different object."
},
{
"code": null,
"e": 24697,
"s": 24635,
"text": "Display both list and NumPy array and observe the difference."
},
{
"code": null,
"e": 24726,
"s": 24697,
"text": "Below is the implementation."
},
{
"code": null,
"e": 24734,
"s": 24726,
"text": "Python3"
},
{
"code": "# importing numpy libraryimport numpy # initializing listls = [[1, 7, 0], [ 6, 2, 5]] # converting list to arrayar = numpy.array(ls) # displaying listprint ( ls) # displaying arrayprint ( ar)",
"e": 24932,
"s": 24734,
"text": null
},
{
"code": null,
"e": 24941,
"s": 24932,
"text": "Output :"
},
{
"code": null,
"e": 24983,
"s": 24941,
"text": "[[1, 7, 0], [6, 2, 5]]\n[[1 7 0]\n [6 2 5]]"
},
{
"code": null,
"e": 25016,
"s": 24983,
"text": "Method 2: Using numpy.asarray()."
},
{
"code": null,
"e": 25027,
"s": 25016,
"text": "Approach :"
},
{
"code": null,
"e": 25049,
"s": 25027,
"text": "Import numpy package."
},
{
"code": null,
"e": 25197,
"s": 25049,
"text": "Initialize the nested 4-dimensional list and then use numpy.asarray() function to convert the list to the array and store it in a different object."
},
{
"code": null,
"e": 25259,
"s": 25197,
"text": "Display both list and NumPy array and observe the difference."
},
{
"code": null,
"e": 25288,
"s": 25259,
"text": "Below is the implementation."
},
{
"code": null,
"e": 25296,
"s": 25288,
"text": "Python3"
},
{
"code": "# importing numpy libraryimport numpy # initializing listls = [[1, 7, 0],[ 6, 2, 5],[ 7, 8, 9],[ 41, 10, 20]] # converting list to arrayar = numpy.asarray(ls) # displaying listprint ( ls) # displaying arrayprint ( ar)",
"e": 25514,
"s": 25296,
"text": null
},
{
"code": null,
"e": 25523,
"s": 25514,
"text": "Output :"
},
{
"code": null,
"e": 25620,
"s": 25523,
"text": "[[1, 7, 0], [6, 2, 5], [7, 8, 9], [41, 10, 20]]\n[[ 1 7 0]\n [ 6 2 5]\n [ 7 8 9]\n [41 10 20]]"
},
{
"code": null,
"e": 25640,
"s": 25620,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 25661,
"s": 25640,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 25673,
"s": 25661,
"text": "python-list"
},
{
"code": null,
"e": 25680,
"s": 25673,
"text": "Python"
},
{
"code": null,
"e": 25692,
"s": 25680,
"text": "python-list"
},
{
"code": null,
"e": 25790,
"s": 25692,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25812,
"s": 25790,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25844,
"s": 25812,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25886,
"s": 25844,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25912,
"s": 25886,
"text": "Python String | replace()"
},
{
"code": null,
"e": 25949,
"s": 25912,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 25978,
"s": 25949,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 26020,
"s": 25978,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26076,
"s": 26020,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26101,
"s": 26076,
"text": "sum() function in Python"
}
] |
The New “Unified Star Schema” Paradigm in Analytics Data Modeling Review | by Andriy Zabavskyy | Towards Data Science
|
Recently I accidentally came across the new book of Bill Inmon and Francesco Puppini called “Unified Star Schema” (will refer to it USS downstream). Having a new book in 2020 from the father of data warehousing definitely grabbed my attention, I bought it and read it in the following 3 days with lots of enthusiasm. It turned out the author of the concept is Francesco Puppini and Bill Inmon is a supporter and promoter of it, but it doesn’t really diminish the value of a new approach for modeling and organizing the data.
In the beginning, I was really skeptical. Replacement of a traditional dimensional model, proved by decades didn’t make me feel well about it. But the book opened to me a new perspective of data model view. Now I believe it could be treated as not a replacement of traditional dimensional modeling (despite the fact the author claims it to be), but a good enrichment of it. So let’s review it briefly.
On the high level, the author proposes the ingeniously simple approach for managing connections (relationships) between entities in the analytics database: instead of having the net of interrelationships, introduce the super switchboard and manage all the connections via it:
If we translate this statement into the data warehouse data model, it would mean replacement of the galaxy schema (set of star schemas joint via conformed dimensions) by one super star where all the tables (both fact and dimensions) are joined via one big auxiliary table called Bridge (named by author) or Puppini Bridge(named by Inmon; I like it more, so will use it :) like on the picture below:
The Puppini Bridge is used strictly to join the tables between each other, it doesn’t have a business value, and is suggested to be hidden from the end customers.
How the magic table is being built? It’s not a trivial thing so let’s take a look.
There is a prerequisite: each table in the data warehouse should have a primary key built on a single column. It is recommended to follow the naming convention: use the_KEY_ prefix followed by the table name.
The Puppini Bridge table is a matrix-like table where
Columns — list of primary keys of each data warehouse table (fact or dimension) plus one extra column called Stage . So the number of columns equal to the number of tables in the data warehouse (dimensions and facts) plus one.
Rows — a result of union all operation of all data warehouse tables carrying only the key columns. So the number of rows in a Bridge table is a sum of all records in the data warehouse (fact and dimensions).
To fill the Bridge table we would need to split the process into stages, where each stage — loading data from one of the data warehouse tables. For each table, we need to set the Stage column value equal to the data warehouse table name and load:
The primary key of the data warehouse table
All foreign keys to other data warehouse table; direct foreign keys, and derived ones
For the example above the initial relationships between fact and dimension tables would lead to the following Puppini Bridge fulfillment (dark red cells contain derived foreign keys):
Having such an intermediate bridge table we could join any two Data warehouse tables using the proper key columns. For example, to group Sales Orders and Sales Forecast Amounts by Product Category and combine the results we would need to do a left join with Puppini Bridge table like that:
select pc.CategoryName, sum(so.SalesAmount), sum(sf.ForecastedAmount) from _PuppiniBridge pb left join SalesOrders so on pb._KEY_SalesOrders = so._KEY_SalesOrders left join SalesForecast sf on pb._KEY_SalesForecast = sf._KEY_SalesForecast left join ProductCategory pc on pc._KEY_ProductCategory = pc._KEY_ProductCategory group by pc.CategoryName
The whole “Unified Star Schema” book is around the benefits of USS in Self Service BI. By self-service BI it is meant the possibility of exploring and discovering the data in any modern BI platform, such as Tableau, Qlik View/Qlik Sense, Tibco SpotFire, MS PowerBI, by data analysts and business representatives.
The galaxy schema always contains the loop connections (unless it is not a trivial one) which leads to ambiguity. That is why the BI platform limits the possibilities for table connections between each other to avoid loops, which leads to the limitations of the data exploration possibilities or the necessity of workarounds on the data model side.
Converting the galaxy schema into the USS, which is a simple star schema eliminates the set of constraints put by BI platforms.
The USS schema helps to resolve the following challenges:
Loops
The Fan Trap
the Chasm Trap
Non-conformed granularity joins
The detailed explanation of these challenges along with detailed descriptions and examples you could find in the book.
Besides the Self Service BI there are also other aspects of Data Warehouse data consumption scenarios, so let’s try to look at the USS from another point of view.
My main concern related to the USS is the efficiency of Join operations and the scalability of the approach in general.
Since the Puppini Bridge table is a superset of all data warehouse tables including the fact tables, it is going to be a large table. So in case of querying at least one fact table, we would have always a join between two large tables (bridge with a fact table) which is always a challenge for the relational database. We could think of merge join for optimizing that, but most probably it won’t be possible since the ordering for one fact table won’t work for another fact table, etc.
A similar challenge is related to the data distribution for cluster deployments. If we distribute a large fact table according to a certain rule, we won’t be able to apply the same rule for the Puppini Bridge table. Even though we could do that for one fact table, we won’t be able to do that for another fact table. So this leads to the same concern of joining efficiency between _Puppini_Bridge and other large fact table on the database clusters.
The schema extension is always a pretty challenging aspect of a Data Warehouse solution.
When we introduce a new subject area into the data warehouse or a new set of business processes, in a traditional way — we introduce a new set of tables (a new set of star schemas).
In the case of USS we would need besides that perform really heavy lifting operations on the Bridge table:
alter it by adding a list of new columns with proper key columns
backfill it with proper connection information
So, in the case of a large data warehouse, it tends to be a really heavy operation.
If to step out of Self Service BI and think of predefined reports or data scientist’s data exploration activities, it is more natural, logical, and easier to join the fact table directly to the related dimension tables using the inner join avoiding the left(or right) joins to the Bridge table.
Even if it is needed to join 2 fact tables between each other, an experienced data engineer will do that more efficiently than doing that via Bridge table. In such a case it will be 2 big tables join instead of 3 big tables join.
In my opinion, the USS is really a brilliant solution for the Self Service BI. Once the Puppini Bridge table is built, the data analysts and business users could do their work on the BI platform concentrating on insights and not on data connectivity challenges avoiding many possible pitfalls there.
In other areas of data consuming it seems not to be that beneficial and increases the maintenance efforts.
The USS approach with its Puppini Bridge in my opinion could be used in addition to the traditional dimensional data model as a big bonus for the Self Service BI.
As long as all the fact and dimension table have a one-column based primary key, which is actually one of the best practices in dimensional modeling, it is possible to implement the Puppini Bridge Table and use it for the SelfService BI.
I did my best to review briefly the approach. USS is a really new, interesting, and not yet proved by the industry way of building Analytics. The whole idea is very interesting and really worth evaluating. In case you build a Self Service BI solution it definitely deserves to be tried out.
It is blessed by Bill Inmon, so it should survive :)
The links to the book and the podcast could be found below:
|
[
{
"code": null,
"e": 696,
"s": 171,
"text": "Recently I accidentally came across the new book of Bill Inmon and Francesco Puppini called “Unified Star Schema” (will refer to it USS downstream). Having a new book in 2020 from the father of data warehousing definitely grabbed my attention, I bought it and read it in the following 3 days with lots of enthusiasm. It turned out the author of the concept is Francesco Puppini and Bill Inmon is a supporter and promoter of it, but it doesn’t really diminish the value of a new approach for modeling and organizing the data."
},
{
"code": null,
"e": 1098,
"s": 696,
"text": "In the beginning, I was really skeptical. Replacement of a traditional dimensional model, proved by decades didn’t make me feel well about it. But the book opened to me a new perspective of data model view. Now I believe it could be treated as not a replacement of traditional dimensional modeling (despite the fact the author claims it to be), but a good enrichment of it. So let’s review it briefly."
},
{
"code": null,
"e": 1374,
"s": 1098,
"text": "On the high level, the author proposes the ingeniously simple approach for managing connections (relationships) between entities in the analytics database: instead of having the net of interrelationships, introduce the super switchboard and manage all the connections via it:"
},
{
"code": null,
"e": 1773,
"s": 1374,
"text": "If we translate this statement into the data warehouse data model, it would mean replacement of the galaxy schema (set of star schemas joint via conformed dimensions) by one super star where all the tables (both fact and dimensions) are joined via one big auxiliary table called Bridge (named by author) or Puppini Bridge(named by Inmon; I like it more, so will use it :) like on the picture below:"
},
{
"code": null,
"e": 1936,
"s": 1773,
"text": "The Puppini Bridge is used strictly to join the tables between each other, it doesn’t have a business value, and is suggested to be hidden from the end customers."
},
{
"code": null,
"e": 2019,
"s": 1936,
"text": "How the magic table is being built? It’s not a trivial thing so let’s take a look."
},
{
"code": null,
"e": 2228,
"s": 2019,
"text": "There is a prerequisite: each table in the data warehouse should have a primary key built on a single column. It is recommended to follow the naming convention: use the_KEY_ prefix followed by the table name."
},
{
"code": null,
"e": 2282,
"s": 2228,
"text": "The Puppini Bridge table is a matrix-like table where"
},
{
"code": null,
"e": 2509,
"s": 2282,
"text": "Columns — list of primary keys of each data warehouse table (fact or dimension) plus one extra column called Stage . So the number of columns equal to the number of tables in the data warehouse (dimensions and facts) plus one."
},
{
"code": null,
"e": 2717,
"s": 2509,
"text": "Rows — a result of union all operation of all data warehouse tables carrying only the key columns. So the number of rows in a Bridge table is a sum of all records in the data warehouse (fact and dimensions)."
},
{
"code": null,
"e": 2964,
"s": 2717,
"text": "To fill the Bridge table we would need to split the process into stages, where each stage — loading data from one of the data warehouse tables. For each table, we need to set the Stage column value equal to the data warehouse table name and load:"
},
{
"code": null,
"e": 3008,
"s": 2964,
"text": "The primary key of the data warehouse table"
},
{
"code": null,
"e": 3094,
"s": 3008,
"text": "All foreign keys to other data warehouse table; direct foreign keys, and derived ones"
},
{
"code": null,
"e": 3278,
"s": 3094,
"text": "For the example above the initial relationships between fact and dimension tables would lead to the following Puppini Bridge fulfillment (dark red cells contain derived foreign keys):"
},
{
"code": null,
"e": 3568,
"s": 3278,
"text": "Having such an intermediate bridge table we could join any two Data warehouse tables using the proper key columns. For example, to group Sales Orders and Sales Forecast Amounts by Product Category and combine the results we would need to do a left join with Puppini Bridge table like that:"
},
{
"code": null,
"e": 3983,
"s": 3568,
"text": "select pc.CategoryName, sum(so.SalesAmount), sum(sf.ForecastedAmount) from _PuppiniBridge pb left join SalesOrders so on pb._KEY_SalesOrders = so._KEY_SalesOrders left join SalesForecast sf on pb._KEY_SalesForecast = sf._KEY_SalesForecast left join ProductCategory pc on pc._KEY_ProductCategory = pc._KEY_ProductCategory group by pc.CategoryName"
},
{
"code": null,
"e": 4296,
"s": 3983,
"text": "The whole “Unified Star Schema” book is around the benefits of USS in Self Service BI. By self-service BI it is meant the possibility of exploring and discovering the data in any modern BI platform, such as Tableau, Qlik View/Qlik Sense, Tibco SpotFire, MS PowerBI, by data analysts and business representatives."
},
{
"code": null,
"e": 4645,
"s": 4296,
"text": "The galaxy schema always contains the loop connections (unless it is not a trivial one) which leads to ambiguity. That is why the BI platform limits the possibilities for table connections between each other to avoid loops, which leads to the limitations of the data exploration possibilities or the necessity of workarounds on the data model side."
},
{
"code": null,
"e": 4773,
"s": 4645,
"text": "Converting the galaxy schema into the USS, which is a simple star schema eliminates the set of constraints put by BI platforms."
},
{
"code": null,
"e": 4831,
"s": 4773,
"text": "The USS schema helps to resolve the following challenges:"
},
{
"code": null,
"e": 4837,
"s": 4831,
"text": "Loops"
},
{
"code": null,
"e": 4850,
"s": 4837,
"text": "The Fan Trap"
},
{
"code": null,
"e": 4865,
"s": 4850,
"text": "the Chasm Trap"
},
{
"code": null,
"e": 4897,
"s": 4865,
"text": "Non-conformed granularity joins"
},
{
"code": null,
"e": 5016,
"s": 4897,
"text": "The detailed explanation of these challenges along with detailed descriptions and examples you could find in the book."
},
{
"code": null,
"e": 5179,
"s": 5016,
"text": "Besides the Self Service BI there are also other aspects of Data Warehouse data consumption scenarios, so let’s try to look at the USS from another point of view."
},
{
"code": null,
"e": 5299,
"s": 5179,
"text": "My main concern related to the USS is the efficiency of Join operations and the scalability of the approach in general."
},
{
"code": null,
"e": 5785,
"s": 5299,
"text": "Since the Puppini Bridge table is a superset of all data warehouse tables including the fact tables, it is going to be a large table. So in case of querying at least one fact table, we would have always a join between two large tables (bridge with a fact table) which is always a challenge for the relational database. We could think of merge join for optimizing that, but most probably it won’t be possible since the ordering for one fact table won’t work for another fact table, etc."
},
{
"code": null,
"e": 6235,
"s": 5785,
"text": "A similar challenge is related to the data distribution for cluster deployments. If we distribute a large fact table according to a certain rule, we won’t be able to apply the same rule for the Puppini Bridge table. Even though we could do that for one fact table, we won’t be able to do that for another fact table. So this leads to the same concern of joining efficiency between _Puppini_Bridge and other large fact table on the database clusters."
},
{
"code": null,
"e": 6324,
"s": 6235,
"text": "The schema extension is always a pretty challenging aspect of a Data Warehouse solution."
},
{
"code": null,
"e": 6506,
"s": 6324,
"text": "When we introduce a new subject area into the data warehouse or a new set of business processes, in a traditional way — we introduce a new set of tables (a new set of star schemas)."
},
{
"code": null,
"e": 6613,
"s": 6506,
"text": "In the case of USS we would need besides that perform really heavy lifting operations on the Bridge table:"
},
{
"code": null,
"e": 6678,
"s": 6613,
"text": "alter it by adding a list of new columns with proper key columns"
},
{
"code": null,
"e": 6725,
"s": 6678,
"text": "backfill it with proper connection information"
},
{
"code": null,
"e": 6809,
"s": 6725,
"text": "So, in the case of a large data warehouse, it tends to be a really heavy operation."
},
{
"code": null,
"e": 7104,
"s": 6809,
"text": "If to step out of Self Service BI and think of predefined reports or data scientist’s data exploration activities, it is more natural, logical, and easier to join the fact table directly to the related dimension tables using the inner join avoiding the left(or right) joins to the Bridge table."
},
{
"code": null,
"e": 7334,
"s": 7104,
"text": "Even if it is needed to join 2 fact tables between each other, an experienced data engineer will do that more efficiently than doing that via Bridge table. In such a case it will be 2 big tables join instead of 3 big tables join."
},
{
"code": null,
"e": 7634,
"s": 7334,
"text": "In my opinion, the USS is really a brilliant solution for the Self Service BI. Once the Puppini Bridge table is built, the data analysts and business users could do their work on the BI platform concentrating on insights and not on data connectivity challenges avoiding many possible pitfalls there."
},
{
"code": null,
"e": 7741,
"s": 7634,
"text": "In other areas of data consuming it seems not to be that beneficial and increases the maintenance efforts."
},
{
"code": null,
"e": 7904,
"s": 7741,
"text": "The USS approach with its Puppini Bridge in my opinion could be used in addition to the traditional dimensional data model as a big bonus for the Self Service BI."
},
{
"code": null,
"e": 8142,
"s": 7904,
"text": "As long as all the fact and dimension table have a one-column based primary key, which is actually one of the best practices in dimensional modeling, it is possible to implement the Puppini Bridge Table and use it for the SelfService BI."
},
{
"code": null,
"e": 8433,
"s": 8142,
"text": "I did my best to review briefly the approach. USS is a really new, interesting, and not yet proved by the industry way of building Analytics. The whole idea is very interesting and really worth evaluating. In case you build a Self Service BI solution it definitely deserves to be tried out."
},
{
"code": null,
"e": 8486,
"s": 8433,
"text": "It is blessed by Bill Inmon, so it should survive :)"
}
] |
How to automate 3D point cloud segmentation with Python | Towards Data Science
|
If you have worked with point clouds in the past (or, for this matter, with data), you know how important it is to find patterns between your observations 📈. Indeed, we often need to extract some higher-level knowledge that heavily relies on determining “objects” formed by data points that share a pattern.
This is a task that is accomplished quite comfortably by our visual cognitive system. However, mimicking this human capability by computational methods is a highly challenging problem 🤯. Basically, we want to leverage the predisposition of the human visual system to group sets of elements.
Excellent question! Actually, the cardinal motivations for point cloud segmentation are threefold:
Firstly, it provides end-users with the flexibility to efficiently access and manipulates individual content through higher-level generalisations: segments.
Secondly, it creates a compact representation of the data wherein all subsequent processing can be done at a regional level instead of the individual point level, resulting in potentially significant computational gains.
Finally, it gives the ability to extract relationships between neighbourhoods, graphs and topology, which is non-existent in raw point-based data sets.
For these reasons, segmentation is predominantly employed as a pre-processing step to annotate, enhance, analyse, classify, categorise, extract and abstract information from point cloud data. But the real question now. How do we do it?
Aaand... let’s open the box 👐!
In this tutorial, I already made a selection for you of two of the best and more robust approaches that you will master at the end. We will rely on two central and efficient approaches: RANSAC and Euclidean Clustering through DBSCAN. But before using them, it is, I guess 😀, Important to understand the main idea, simply put.
So RANSAC stands for RANdom SAmple Consensus, and it is a quite simple but highly effective algorithm that you can use if your data is affected by outliers, which is our case 😊. Indeed, whenever you work with real-world sensors, your data will never be perfect. And quite often, your sensor data is affected by outliers. And RANSAC is a kind of a trial-and-error approach that will group your data points into two segments: an inlier set and an outlier set. Then, you can forget about the outliers and work with your inliers.
So let me use a tiny but simple example to illustrate how RANSAC works. Let us say that we want to fit a plane through the point cloud below. How can we do that?
First, we create a plane from the data, and for this, we randomly select 3 points from the point cloud necessary to establish a plane. And then, we simply check how many of the remaining points kind of fall on the plane (to a certain threshold), which will give a score to the proposal.
Then, we repeat the process with 3 new random points and see how we are doing. Is it better? Is it worse? And again, we repeat this process over and over again, let’s say 10 times, 100 times, 1000 times, and then we select the plane model which has the highest score (i.e. which has the best “support” of the remaining data points). And that will be our solution: the supporting points plus the three points that we have sampled constitute our inlier point set, and the rest is our outlier point set. Easy enough, hun 😁?
Haha, but for the sceptics, don’t you have a rising question? How do we actually determine how many times we should repeat the process? How often should we try that? Well, that is actually something that we can compute, but let put it aside for now to focus on the matter at hand: point cloud segmentation 😉.
With point cloud datasets, we often need to group sets of points spatially contiguous, as illustrated below. But how can we do this efficiently?
The DBSCAN (Density-Based Spatial Clustering of Applications with Noise) algorithm was introduced in 1996 for this purpose. This algorithm is widely used, which is why it was awarded a scientific contribution award in 2014 that has stood the test of time.
DBSCAN iterates over the points in the dataset. For each point that it analyzes, it constructs the set of points reachable by density from this point: it computes the neighbourhood of this point, and if this neighbourhood contains more than a certain amount of points, it is included in the region. Each neighbouring points go through the same process until it can no longer expand the cluster. If the point considered is not an interior point, i.e. it does not have enough neighbours, it will be labelled as noise. This allows DBSCAN to be robust to outliers since this mechanism isolates them. How cool is that 😆?
Ah, I almost forgot. The choice of parameters (ε for the neighbourhood and n_min for the minimal number of points) can also be tricky: One must take great care when setting parameters to create enough interior points (which will not happen if n_min is too large or ε too small). In particular, this means that DBSCAN will have trouble finding clusters of different densities. BUT, DBSCAN has the great advantage of being computationally efficient without requiring to predefine the number of clusters, unlike Kmeans, for example. Finally, it allows finding clusters of arbitrary shape.
And now, let us put all of this mumbo jumbo into a super useful “software” through a 5-Step process 💻!
In previous tutorials, I illustrated point cloud processing and meshing over a 3D dataset obtained by using photogrammetry and aerial LiDAR from Open Topography. This time, we will use a dataset that I gathered using a Terrestrial Laser Scanner!
I will skip the details on I/O operations and file formats but know that they are covered in the articles below if you want to clarify or build fully-fledged expertise 🧐. Today, we will jump right to using the well known .ply file format.
towardsdatascience.com
towardsdatascience.com
🤓 Note: For this how-to guide, you can use the point cloud in this repository, that I already filtered and translated so that you are in the optimal conditions. If you want to visualize and play with it beforehand without installing anything, you can check out the webGL version.
In the previous article below, we saw how to set up an environment with Anaconda easily and how to use the IDE Spyder to manage your code. I recommend continuing in this fashion if you set yourself up to becoming a fully-fledged python app developer 😆.
towardsdatascience.com
But hey, if you prefer to do everything from scratch in the next 5 minutes, I also give you access to a Google Colab notebook that you will find at the end of the article. There is nothing to install; you can just save it to your google drive and start working with it, also using the free datasets from Step 1☝️.
🤓 Note: I highly recommend using a desktop IDE such as Spyder and avoiding Google Colab or Jupyter IF you need to visualise 3D point clouds using the libraries provided, as they will be unstable at best or not working at worse (unfortunately...).
Well, for quickly getting results, I will take a “parti-pris”. Indeed, we will accomplish a nice segmentation by following a minimalistic approach to coding 💻. That means being very picky about the underlying libraries! We will use three very robust ones, namely numpy, matplotlib, and open3d.
Okay, to install the library package above in your environment, I suggest you run the following command from the terminal (also, notice the open3d-admin channel):
conda install numpyconda install matplotlibconda install -c open3d-admin open3d
🤓 Disclaimer Note: We choose Python, not C++ or Julia, so performances are what they are 😄. Hopefully, it will be enough for your application 😉, for what we call “offline” processes (not real-time).
And it is the long-awaited time now to get to see the first results!
Let us first import the data in the pcd variable, with the following line:
pcd = o3d.io.read_point_cloud("your_path/kitchen.ply")
Do you want to do wonders quickly? Well, I have excellent news, open3d comes equipped with a RANSAC implementation for planar shape detection in point clouds. The only line to write is the following:
plane_model, inliers = pcd.segment_plane(distance_threshold=0.01, ransac_n=3, num_iterations=1000)
🤓 Note: As you can see, the segment_plane() method holds 3 parameters. These are the distance threshold (distance_threshold) from the plane to consider a point inlier or outlier, the number of sampled points drawn (3 here, as we want a plane) to estimate each plane candidate (ransac_n) and the number of iterations (num_iterations). These are standard values, but beware that depending on the dataset at hand, the distance_threshold should be double-checked.
The result of the line above is the best plane candidate parameters a,b,c and d captured in plane_model, and the index of the points that are considered as inliers, captured in inliers.
Let us now visualize the results, shall we? For this, we actually have to select the points based on the indexes captured in inliers, and optionally select all the others as outliers. How do we do this? Well, like this:
inlier_cloud = pcd.select_by_index(inliers)outlier_cloud = pcd.select_by_index(inliers, invert=True)
🤓 Note: The argument invert=True permits to select the opposite of the first argument, which means all indexes not present in inliers.
Okay, now your variables hold the points, but before visualizing the results, I propose that we paint the inliers in red and the rest grey. For this, you can just pass a list of R, G, B values as floats like this:
inlier_cloud.paint_uniform_color([1, 0, 0])outlier_cloud.paint_uniform_color([0.6, 0.6, 0.6])
And now, let us visualise the results with the following line:
o3d.visualization.draw_geometries([inlier_cloud, outlier_cloud])
🤓 Note: If you want to grasp better the geometry washed up by the colour, you can compute normals using the following command beforehand: pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.1, max_nn=16), fast_normal_computation=True). This will make sure you get a much nicer rendering, as below😉.
Great! You know how to segment your point cloud in an inlier point set and an outlier point set 🥳! Now, let us study how to find some clusters close to one another. So let us imagine that once we detected the big planar portions, we have some “floating” objects that we want to delineate. How to do this? (yes, it is a false question, I have the answer for you 😀)
First, we select a sample, where we assume we got rid of all the planar regions (this sample can be found here: Access data sample), as shown below.
Okay, so now, let us write some DBSCAN clustering. Again, to simplify everything, we will use the DBSCAN method part of open3d package, but know that if you need more flexibility, the implementation in scikit-learn may be a more long-term choice. Time-wise, it is pretty much the same. The method cluster_dbscan acts on the pcd point cloud entity directly and returns a list of labels following the initial indexing of the point cloud.
labels = np.array(pcd.cluster_dbscan(eps=0.05, min_points=10))
🤓 Note: The labels vary between -1 and n, where -1 indicate it is a “noise” point and values 0 to n are then the cluster labels given to the corresponding point. Note that we want to get the labels as a NumPy array and that we use a radius of 5 cm for “growing” clusters, and considering one only if after this step we have at least 10 points. Feel free to experiment 😀.
Nice, now that we have groups of points defined with a label per point, let us colour the results. This is optional, but it is handy for iterative processes to search for the right parameter’s values. To this end, I propose to use the Matplotlib library to get specific colour ranges, such as the tab20:
max_label = labels.max()colors = plt.get_cmap("tab20")(labels / (max_label if max_label > 0 else 1))colors[labels < 0] = 0pcd.colors = o3d.utility.Vector3dVector(colors[:, :3])o3d.visualization.draw_geometries([pcd])
🤓 Note: The max_label should be intuitive: it stores the maximal value in the labels list. This permits to use it as a denominator for the colouring scheme while treating with an “if” statement the special case where the clustering is skewed and delivers only noise + one cluster. After, we make sure to set these noisy points with the label -1 to black (0). Then, we give to the attribute colors of the point cloud pcd the 2D NumPy array of 3 “columns”, representing R, G, B.
Et voilà! Below the result of our clustering.
Great, it is working nicely, and now, how can we actually put all of this to scale and in an automated fashion?
Our philosophy will be very simple. We will first run RANSAC multiple times (let say n times) to extract the different planar regions constituting the scene. Then we will deal with the “floating elements” through Euclidean Clustering (DBSCAN). It means that we have to make sure we have a way to store the results during iterations. Ready?
Okay, let us instantiate an empty dictionary that will hold the results of the iterations (the plane parameters in segment_models, and the planar regions from the point cloud in segments):
segment_models={}segments={}
Then, we want to make sure that we can influence later on the number of times we want to iterate for detecting the planes. To this end, let us create a variable max_plane_idx that holds the number of iterations:
max_plane_idx=20
🤓 Note: Here, we say that we want to iterate 20 times to find 20 planes, but there are smarter ways to define such a parameter. It actually extends the scope of the article, but if you want to learn more, you can check out the 3D Geodata Academy.
Now let us go into a working loopy-loopy 😁, that I will first quickly illustrate. In the first pass (loop i=0), we separate the inliers from the outliers. We store the inliers in segments, and then we want to pursue with only the remaining points stored in rest, that becomes the subject of interest for the loop n+1 (loop i=1). That means that we want to consider the outliers from the previous step as the base point cloud until reaching the above threshold of iterations (not to be confused with RANSAC iterations). This translates into the following:
rest=pcdfor i in range(max_plane_idx): colors = plt.get_cmap("tab20")(i) segment_models[i], inliers = rest.segment_plane( distance_threshold=0.01,ransac_n=3,num_iterations=1000) segments[i]=rest.select_by_index(inliers) segments[i].paint_uniform_color(list(colors[:3])) rest = rest.select_by_index(inliers, invert=True) print("pass",i,"/",max_plane_idx,"done.")
And that is pretty much it! Now, for visualising the ensemble, as we paint each segment detected with a colour from tab20 through the first line in the loop (colors = plt.get_cmap(“tab20”)(i)), you just need to write:
o3d.visualization.draw_geometries([segments[i] for i in range(max_plane_idx)]+[rest])
🤓 Note: The list [segments[i] for i in range(max_plane_idx)] that we pass to the function o3d.visualization.draw_geometries() is actually a “list comprehension” 🤔. It is equivalent to writing a for loop that appends the first element segments[i] to a list. Conveniently, we can then add the [rest] to this list and the draw.geometries() method will understand we want to consider one point cloud to draw. How cool is that?
Ha! We think we are done... But are we? Do you notice something strange here? If you closely look, there are some strange artefacts, like “lines” that actually cut some planar elements. Why? 🧐
In fact, because we fit all the points to RANSAC plane candidates (which have no limit extent in the euclidean space) independently of the points density continuity, then we have these “lines” artefacts depending on the order in which the planes are detected. So the next step is to prevent such behaviour! For this, I propose to include in the iterative process a condition based on Euclidean clustering to refine inlier point sets in contiguous clusters. Ready?
To this end, we will rely on the DBSCAN algorithm. Let me detail the logical process, but not so straightforward (Activate the beast mode👹). Within the for loop defined before, we will run DBSCAN just after the assignment of the inliers (segments[i]=rest.select_by_index(inliers)), by adding the following line right after:
labels = np.array(segments[i].cluster_dbscan(eps=d_threshold*10, min_points=10))
🤓 Note: I actually set the epsilon in function of the initial threshold of the RANSAC plane search, with a magnitude 10 times higher. This is not deep science, this is a purely empirical choice, but it works well usually and makes thing easier with parameters 😀.
Then, within the loop, we will count how many points each cluster that we found holds, using a weird notation that makes use of a list comprehension. The result is then stored in the variable candidates:
candidates=[len(np.where(labels==j)[0]) for j in np.unique(labels)]
And now? We have to find the “best candidate”, which is normally the cluster that holds the more points! And for this, here is the line:
best_candidate=int(np.unique(labels)[np.where(candidates== np.max(candidates))[0]])
Okay, many tricks are happening under the hood here, but essentially, we use Numpy proficiency to search and return the index of the points that belong to the biggest cluster. From here, it is downhill skiing, and we just need to make sure to add the eventual remaining clusters per iteration in considerations for the follow-up RANSAC iterations (🔥 sentence to read 5 times to digest):
rest = rest.select_by_index(inliers, invert=True) + segments[i].select_by_index(list(np.where(labels!=best_candidate)[0]))segments[i]=segments[i].select_by_index(list(np.where(labels== best_candidate)[0]))
🤓 Note: the rest variable now makes sure to hold both the remaining points from RANSAC and DBSCAN. And of course, the inliers are now filtered to the biggest cluster present in the raw RANSAC inlier set.
When the loop is over, you get a clean set of segments holding spatially contiguous point sets that follow planar shapes, as shown below.
But is this the end? Noooo, never 😄! One last final step!
Finally, we go outside the loop, and we work on the remaining elements stored in rest that are not yet attributed to any segment. For this, a simple pass of Euclidean clustering (DBSCAN) should do the trick:
labels = np.array(rest.cluster_dbscan(eps=0.05, min_points=5))max_label = labels.max()print(f"point cloud has {max_label + 1} clusters")colors = plt.get_cmap("tab10")(labels / (max_label if max_label > 0 else 1))colors[labels < 0] = 0rest.colors = o3d.utility.Vector3dVector(colors[:, :3])
I employ the same methodology as before, no sorcery! I just make sure to use coherent parameters to have a refined clustering to get the beautiful rainbow kitchen you always dreamed of 🥳!
If you want to get it working directly, I also create a Google Colab script that you can access here: To the Python Google Colab script.
Massive congratulations 🎉! You just learned how to import and develop an automatic segmentation and visualisation program for 3D point clouds composed of millions of points, with different strategies! Sincerely, well done! But the path certainly does not end here, because you just unlocked a tremendous potential for intelligent processes that reason at a segment level!
Future posts will dive deeper into point cloud spatial analysis, file formats, data structures, object detection, segmentation, classification, visualization, animation and meshing. We will especially look into how to manage big point cloud data as defined in the article below:
towardsdatascience.com
My contributions aim to condense actionable information so you can start from scratch to build 3D automation systems for your projects. You can get started today by taking a formation at the Geodata Academy.
learngeodata.eu
Other advanced segmentation methods for point cloud exist. It is actually a research field in which I am deeply involved, and you can already find some well-designed methodologies in the articles [1–6]. For the more advanced 3D deep learning architectures, some comprehensive tutorials are coming very soon!
Poux, F., & Billen, R. (2019). Voxel-based 3D point cloud semantic segmentation: unsupervised geometric and relationship featuring vs deep learning methods. ISPRS International Journal of Geo-Information. 8(5), 213; https://doi.org/10.3390/ijgi8050213 — Jack Dangermond Award (Link to press coverage)Poux, F., Neuville, R., Nys, G.-A., & Billen, R. (2018). 3D Point Cloud Semantic Modelling: Integrated Framework for Indoor Spaces and Furniture. Remote Sensing, 10(9), 1412. https://doi.org/10.3390/rs10091412Poux, F., Neuville, R., Van Wersch, L., Nys, G.-A., & Billen, R. (2017). 3D Point Clouds in Archaeology: Advances in Acquisition, Processing and Knowledge Integration Applied to Quasi-Planar Objects. Geosciences, 7(4), 96. https://doi.org/10.3390/GEOSCIENCES7040096Poux, F., Mattes, C., Kobbelt, L., 2020. Unsupervised segmentation of indoor 3D point cloud: application to object-based classification, ISPRS — International Archives of the Photogrammetry, Remote Sensing and Spatial Information Sciences. pp. 111–118. https://doi:10.5194/isprs-archives-XLIV-4-W1-2020-111-2020Poux, F., Ponciano, J.J., 2020. Self-learning ontology for instance segmentation of 3d indoor point cloud, ISPRS — International Archives of Photogrammetry, Remote Sensing and Spatial Information Sciences. pp. 309–316. https://doi:10.5194/isprs-archives-XLIII-B2-2020-309-2020Bassier, M., Vergauwen, M., Poux, F., (2020). Point Cloud vs. Mesh Features for Building Interior Classification. Remote Sensing. 12, 2224. https://doi:10.3390/rs12142224
Poux, F., & Billen, R. (2019). Voxel-based 3D point cloud semantic segmentation: unsupervised geometric and relationship featuring vs deep learning methods. ISPRS International Journal of Geo-Information. 8(5), 213; https://doi.org/10.3390/ijgi8050213 — Jack Dangermond Award (Link to press coverage)
Poux, F., Neuville, R., Nys, G.-A., & Billen, R. (2018). 3D Point Cloud Semantic Modelling: Integrated Framework for Indoor Spaces and Furniture. Remote Sensing, 10(9), 1412. https://doi.org/10.3390/rs10091412
Poux, F., Neuville, R., Van Wersch, L., Nys, G.-A., & Billen, R. (2017). 3D Point Clouds in Archaeology: Advances in Acquisition, Processing and Knowledge Integration Applied to Quasi-Planar Objects. Geosciences, 7(4), 96. https://doi.org/10.3390/GEOSCIENCES7040096
Poux, F., Mattes, C., Kobbelt, L., 2020. Unsupervised segmentation of indoor 3D point cloud: application to object-based classification, ISPRS — International Archives of the Photogrammetry, Remote Sensing and Spatial Information Sciences. pp. 111–118. https://doi:10.5194/isprs-archives-XLIV-4-W1-2020-111-2020
Poux, F., Ponciano, J.J., 2020. Self-learning ontology for instance segmentation of 3d indoor point cloud, ISPRS — International Archives of Photogrammetry, Remote Sensing and Spatial Information Sciences. pp. 309–316. https://doi:10.5194/isprs-archives-XLIII-B2-2020-309-2020
Bassier, M., Vergauwen, M., Poux, F., (2020). Point Cloud vs. Mesh Features for Building Interior Classification. Remote Sensing. 12, 2224. https://doi:10.3390/rs12142224
|
[
{
"code": null,
"e": 355,
"s": 47,
"text": "If you have worked with point clouds in the past (or, for this matter, with data), you know how important it is to find patterns between your observations 📈. Indeed, we often need to extract some higher-level knowledge that heavily relies on determining “objects” formed by data points that share a pattern."
},
{
"code": null,
"e": 646,
"s": 355,
"text": "This is a task that is accomplished quite comfortably by our visual cognitive system. However, mimicking this human capability by computational methods is a highly challenging problem 🤯. Basically, we want to leverage the predisposition of the human visual system to group sets of elements."
},
{
"code": null,
"e": 745,
"s": 646,
"text": "Excellent question! Actually, the cardinal motivations for point cloud segmentation are threefold:"
},
{
"code": null,
"e": 902,
"s": 745,
"text": "Firstly, it provides end-users with the flexibility to efficiently access and manipulates individual content through higher-level generalisations: segments."
},
{
"code": null,
"e": 1123,
"s": 902,
"text": "Secondly, it creates a compact representation of the data wherein all subsequent processing can be done at a regional level instead of the individual point level, resulting in potentially significant computational gains."
},
{
"code": null,
"e": 1275,
"s": 1123,
"text": "Finally, it gives the ability to extract relationships between neighbourhoods, graphs and topology, which is non-existent in raw point-based data sets."
},
{
"code": null,
"e": 1511,
"s": 1275,
"text": "For these reasons, segmentation is predominantly employed as a pre-processing step to annotate, enhance, analyse, classify, categorise, extract and abstract information from point cloud data. But the real question now. How do we do it?"
},
{
"code": null,
"e": 1542,
"s": 1511,
"text": "Aaand... let’s open the box 👐!"
},
{
"code": null,
"e": 1868,
"s": 1542,
"text": "In this tutorial, I already made a selection for you of two of the best and more robust approaches that you will master at the end. We will rely on two central and efficient approaches: RANSAC and Euclidean Clustering through DBSCAN. But before using them, it is, I guess 😀, Important to understand the main idea, simply put."
},
{
"code": null,
"e": 2394,
"s": 1868,
"text": "So RANSAC stands for RANdom SAmple Consensus, and it is a quite simple but highly effective algorithm that you can use if your data is affected by outliers, which is our case 😊. Indeed, whenever you work with real-world sensors, your data will never be perfect. And quite often, your sensor data is affected by outliers. And RANSAC is a kind of a trial-and-error approach that will group your data points into two segments: an inlier set and an outlier set. Then, you can forget about the outliers and work with your inliers."
},
{
"code": null,
"e": 2556,
"s": 2394,
"text": "So let me use a tiny but simple example to illustrate how RANSAC works. Let us say that we want to fit a plane through the point cloud below. How can we do that?"
},
{
"code": null,
"e": 2843,
"s": 2556,
"text": "First, we create a plane from the data, and for this, we randomly select 3 points from the point cloud necessary to establish a plane. And then, we simply check how many of the remaining points kind of fall on the plane (to a certain threshold), which will give a score to the proposal."
},
{
"code": null,
"e": 3364,
"s": 2843,
"text": "Then, we repeat the process with 3 new random points and see how we are doing. Is it better? Is it worse? And again, we repeat this process over and over again, let’s say 10 times, 100 times, 1000 times, and then we select the plane model which has the highest score (i.e. which has the best “support” of the remaining data points). And that will be our solution: the supporting points plus the three points that we have sampled constitute our inlier point set, and the rest is our outlier point set. Easy enough, hun 😁?"
},
{
"code": null,
"e": 3673,
"s": 3364,
"text": "Haha, but for the sceptics, don’t you have a rising question? How do we actually determine how many times we should repeat the process? How often should we try that? Well, that is actually something that we can compute, but let put it aside for now to focus on the matter at hand: point cloud segmentation 😉."
},
{
"code": null,
"e": 3818,
"s": 3673,
"text": "With point cloud datasets, we often need to group sets of points spatially contiguous, as illustrated below. But how can we do this efficiently?"
},
{
"code": null,
"e": 4074,
"s": 3818,
"text": "The DBSCAN (Density-Based Spatial Clustering of Applications with Noise) algorithm was introduced in 1996 for this purpose. This algorithm is widely used, which is why it was awarded a scientific contribution award in 2014 that has stood the test of time."
},
{
"code": null,
"e": 4690,
"s": 4074,
"text": "DBSCAN iterates over the points in the dataset. For each point that it analyzes, it constructs the set of points reachable by density from this point: it computes the neighbourhood of this point, and if this neighbourhood contains more than a certain amount of points, it is included in the region. Each neighbouring points go through the same process until it can no longer expand the cluster. If the point considered is not an interior point, i.e. it does not have enough neighbours, it will be labelled as noise. This allows DBSCAN to be robust to outliers since this mechanism isolates them. How cool is that 😆?"
},
{
"code": null,
"e": 5276,
"s": 4690,
"text": "Ah, I almost forgot. The choice of parameters (ε for the neighbourhood and n_min for the minimal number of points) can also be tricky: One must take great care when setting parameters to create enough interior points (which will not happen if n_min is too large or ε too small). In particular, this means that DBSCAN will have trouble finding clusters of different densities. BUT, DBSCAN has the great advantage of being computationally efficient without requiring to predefine the number of clusters, unlike Kmeans, for example. Finally, it allows finding clusters of arbitrary shape."
},
{
"code": null,
"e": 5379,
"s": 5276,
"text": "And now, let us put all of this mumbo jumbo into a super useful “software” through a 5-Step process 💻!"
},
{
"code": null,
"e": 5625,
"s": 5379,
"text": "In previous tutorials, I illustrated point cloud processing and meshing over a 3D dataset obtained by using photogrammetry and aerial LiDAR from Open Topography. This time, we will use a dataset that I gathered using a Terrestrial Laser Scanner!"
},
{
"code": null,
"e": 5864,
"s": 5625,
"text": "I will skip the details on I/O operations and file formats but know that they are covered in the articles below if you want to clarify or build fully-fledged expertise 🧐. Today, we will jump right to using the well known .ply file format."
},
{
"code": null,
"e": 5887,
"s": 5864,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5910,
"s": 5887,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6190,
"s": 5910,
"text": "🤓 Note: For this how-to guide, you can use the point cloud in this repository, that I already filtered and translated so that you are in the optimal conditions. If you want to visualize and play with it beforehand without installing anything, you can check out the webGL version."
},
{
"code": null,
"e": 6443,
"s": 6190,
"text": "In the previous article below, we saw how to set up an environment with Anaconda easily and how to use the IDE Spyder to manage your code. I recommend continuing in this fashion if you set yourself up to becoming a fully-fledged python app developer 😆."
},
{
"code": null,
"e": 6466,
"s": 6443,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6780,
"s": 6466,
"text": "But hey, if you prefer to do everything from scratch in the next 5 minutes, I also give you access to a Google Colab notebook that you will find at the end of the article. There is nothing to install; you can just save it to your google drive and start working with it, also using the free datasets from Step 1☝️."
},
{
"code": null,
"e": 7027,
"s": 6780,
"text": "🤓 Note: I highly recommend using a desktop IDE such as Spyder and avoiding Google Colab or Jupyter IF you need to visualise 3D point clouds using the libraries provided, as they will be unstable at best or not working at worse (unfortunately...)."
},
{
"code": null,
"e": 7321,
"s": 7027,
"text": "Well, for quickly getting results, I will take a “parti-pris”. Indeed, we will accomplish a nice segmentation by following a minimalistic approach to coding 💻. That means being very picky about the underlying libraries! We will use three very robust ones, namely numpy, matplotlib, and open3d."
},
{
"code": null,
"e": 7484,
"s": 7321,
"text": "Okay, to install the library package above in your environment, I suggest you run the following command from the terminal (also, notice the open3d-admin channel):"
},
{
"code": null,
"e": 7564,
"s": 7484,
"text": "conda install numpyconda install matplotlibconda install -c open3d-admin open3d"
},
{
"code": null,
"e": 7763,
"s": 7564,
"text": "🤓 Disclaimer Note: We choose Python, not C++ or Julia, so performances are what they are 😄. Hopefully, it will be enough for your application 😉, for what we call “offline” processes (not real-time)."
},
{
"code": null,
"e": 7832,
"s": 7763,
"text": "And it is the long-awaited time now to get to see the first results!"
},
{
"code": null,
"e": 7907,
"s": 7832,
"text": "Let us first import the data in the pcd variable, with the following line:"
},
{
"code": null,
"e": 7962,
"s": 7907,
"text": "pcd = o3d.io.read_point_cloud(\"your_path/kitchen.ply\")"
},
{
"code": null,
"e": 8162,
"s": 7962,
"text": "Do you want to do wonders quickly? Well, I have excellent news, open3d comes equipped with a RANSAC implementation for planar shape detection in point clouds. The only line to write is the following:"
},
{
"code": null,
"e": 8261,
"s": 8162,
"text": "plane_model, inliers = pcd.segment_plane(distance_threshold=0.01, ransac_n=3, num_iterations=1000)"
},
{
"code": null,
"e": 8721,
"s": 8261,
"text": "🤓 Note: As you can see, the segment_plane() method holds 3 parameters. These are the distance threshold (distance_threshold) from the plane to consider a point inlier or outlier, the number of sampled points drawn (3 here, as we want a plane) to estimate each plane candidate (ransac_n) and the number of iterations (num_iterations). These are standard values, but beware that depending on the dataset at hand, the distance_threshold should be double-checked."
},
{
"code": null,
"e": 8907,
"s": 8721,
"text": "The result of the line above is the best plane candidate parameters a,b,c and d captured in plane_model, and the index of the points that are considered as inliers, captured in inliers."
},
{
"code": null,
"e": 9127,
"s": 8907,
"text": "Let us now visualize the results, shall we? For this, we actually have to select the points based on the indexes captured in inliers, and optionally select all the others as outliers. How do we do this? Well, like this:"
},
{
"code": null,
"e": 9228,
"s": 9127,
"text": "inlier_cloud = pcd.select_by_index(inliers)outlier_cloud = pcd.select_by_index(inliers, invert=True)"
},
{
"code": null,
"e": 9363,
"s": 9228,
"text": "🤓 Note: The argument invert=True permits to select the opposite of the first argument, which means all indexes not present in inliers."
},
{
"code": null,
"e": 9577,
"s": 9363,
"text": "Okay, now your variables hold the points, but before visualizing the results, I propose that we paint the inliers in red and the rest grey. For this, you can just pass a list of R, G, B values as floats like this:"
},
{
"code": null,
"e": 9671,
"s": 9577,
"text": "inlier_cloud.paint_uniform_color([1, 0, 0])outlier_cloud.paint_uniform_color([0.6, 0.6, 0.6])"
},
{
"code": null,
"e": 9734,
"s": 9671,
"text": "And now, let us visualise the results with the following line:"
},
{
"code": null,
"e": 9799,
"s": 9734,
"text": "o3d.visualization.draw_geometries([inlier_cloud, outlier_cloud])"
},
{
"code": null,
"e": 10126,
"s": 9799,
"text": "🤓 Note: If you want to grasp better the geometry washed up by the colour, you can compute normals using the following command beforehand: pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.1, max_nn=16), fast_normal_computation=True). This will make sure you get a much nicer rendering, as below😉."
},
{
"code": null,
"e": 10490,
"s": 10126,
"text": "Great! You know how to segment your point cloud in an inlier point set and an outlier point set 🥳! Now, let us study how to find some clusters close to one another. So let us imagine that once we detected the big planar portions, we have some “floating” objects that we want to delineate. How to do this? (yes, it is a false question, I have the answer for you 😀)"
},
{
"code": null,
"e": 10639,
"s": 10490,
"text": "First, we select a sample, where we assume we got rid of all the planar regions (this sample can be found here: Access data sample), as shown below."
},
{
"code": null,
"e": 11075,
"s": 10639,
"text": "Okay, so now, let us write some DBSCAN clustering. Again, to simplify everything, we will use the DBSCAN method part of open3d package, but know that if you need more flexibility, the implementation in scikit-learn may be a more long-term choice. Time-wise, it is pretty much the same. The method cluster_dbscan acts on the pcd point cloud entity directly and returns a list of labels following the initial indexing of the point cloud."
},
{
"code": null,
"e": 11138,
"s": 11075,
"text": "labels = np.array(pcd.cluster_dbscan(eps=0.05, min_points=10))"
},
{
"code": null,
"e": 11509,
"s": 11138,
"text": "🤓 Note: The labels vary between -1 and n, where -1 indicate it is a “noise” point and values 0 to n are then the cluster labels given to the corresponding point. Note that we want to get the labels as a NumPy array and that we use a radius of 5 cm for “growing” clusters, and considering one only if after this step we have at least 10 points. Feel free to experiment 😀."
},
{
"code": null,
"e": 11813,
"s": 11509,
"text": "Nice, now that we have groups of points defined with a label per point, let us colour the results. This is optional, but it is handy for iterative processes to search for the right parameter’s values. To this end, I propose to use the Matplotlib library to get specific colour ranges, such as the tab20:"
},
{
"code": null,
"e": 12030,
"s": 11813,
"text": "max_label = labels.max()colors = plt.get_cmap(\"tab20\")(labels / (max_label if max_label > 0 else 1))colors[labels < 0] = 0pcd.colors = o3d.utility.Vector3dVector(colors[:, :3])o3d.visualization.draw_geometries([pcd])"
},
{
"code": null,
"e": 12507,
"s": 12030,
"text": "🤓 Note: The max_label should be intuitive: it stores the maximal value in the labels list. This permits to use it as a denominator for the colouring scheme while treating with an “if” statement the special case where the clustering is skewed and delivers only noise + one cluster. After, we make sure to set these noisy points with the label -1 to black (0). Then, we give to the attribute colors of the point cloud pcd the 2D NumPy array of 3 “columns”, representing R, G, B."
},
{
"code": null,
"e": 12554,
"s": 12507,
"text": "Et voilà! Below the result of our clustering."
},
{
"code": null,
"e": 12666,
"s": 12554,
"text": "Great, it is working nicely, and now, how can we actually put all of this to scale and in an automated fashion?"
},
{
"code": null,
"e": 13006,
"s": 12666,
"text": "Our philosophy will be very simple. We will first run RANSAC multiple times (let say n times) to extract the different planar regions constituting the scene. Then we will deal with the “floating elements” through Euclidean Clustering (DBSCAN). It means that we have to make sure we have a way to store the results during iterations. Ready?"
},
{
"code": null,
"e": 13195,
"s": 13006,
"text": "Okay, let us instantiate an empty dictionary that will hold the results of the iterations (the plane parameters in segment_models, and the planar regions from the point cloud in segments):"
},
{
"code": null,
"e": 13224,
"s": 13195,
"text": "segment_models={}segments={}"
},
{
"code": null,
"e": 13436,
"s": 13224,
"text": "Then, we want to make sure that we can influence later on the number of times we want to iterate for detecting the planes. To this end, let us create a variable max_plane_idx that holds the number of iterations:"
},
{
"code": null,
"e": 13453,
"s": 13436,
"text": "max_plane_idx=20"
},
{
"code": null,
"e": 13700,
"s": 13453,
"text": "🤓 Note: Here, we say that we want to iterate 20 times to find 20 planes, but there are smarter ways to define such a parameter. It actually extends the scope of the article, but if you want to learn more, you can check out the 3D Geodata Academy."
},
{
"code": null,
"e": 14255,
"s": 13700,
"text": "Now let us go into a working loopy-loopy 😁, that I will first quickly illustrate. In the first pass (loop i=0), we separate the inliers from the outliers. We store the inliers in segments, and then we want to pursue with only the remaining points stored in rest, that becomes the subject of interest for the loop n+1 (loop i=1). That means that we want to consider the outliers from the previous step as the base point cloud until reaching the above threshold of iterations (not to be confused with RANSAC iterations). This translates into the following:"
},
{
"code": null,
"e": 14638,
"s": 14255,
"text": "rest=pcdfor i in range(max_plane_idx): colors = plt.get_cmap(\"tab20\")(i) segment_models[i], inliers = rest.segment_plane( distance_threshold=0.01,ransac_n=3,num_iterations=1000) segments[i]=rest.select_by_index(inliers) segments[i].paint_uniform_color(list(colors[:3])) rest = rest.select_by_index(inliers, invert=True) print(\"pass\",i,\"/\",max_plane_idx,\"done.\")"
},
{
"code": null,
"e": 14856,
"s": 14638,
"text": "And that is pretty much it! Now, for visualising the ensemble, as we paint each segment detected with a colour from tab20 through the first line in the loop (colors = plt.get_cmap(“tab20”)(i)), you just need to write:"
},
{
"code": null,
"e": 14942,
"s": 14856,
"text": "o3d.visualization.draw_geometries([segments[i] for i in range(max_plane_idx)]+[rest])"
},
{
"code": null,
"e": 15365,
"s": 14942,
"text": "🤓 Note: The list [segments[i] for i in range(max_plane_idx)] that we pass to the function o3d.visualization.draw_geometries() is actually a “list comprehension” 🤔. It is equivalent to writing a for loop that appends the first element segments[i] to a list. Conveniently, we can then add the [rest] to this list and the draw.geometries() method will understand we want to consider one point cloud to draw. How cool is that?"
},
{
"code": null,
"e": 15558,
"s": 15365,
"text": "Ha! We think we are done... But are we? Do you notice something strange here? If you closely look, there are some strange artefacts, like “lines” that actually cut some planar elements. Why? 🧐"
},
{
"code": null,
"e": 16022,
"s": 15558,
"text": "In fact, because we fit all the points to RANSAC plane candidates (which have no limit extent in the euclidean space) independently of the points density continuity, then we have these “lines” artefacts depending on the order in which the planes are detected. So the next step is to prevent such behaviour! For this, I propose to include in the iterative process a condition based on Euclidean clustering to refine inlier point sets in contiguous clusters. Ready?"
},
{
"code": null,
"e": 16346,
"s": 16022,
"text": "To this end, we will rely on the DBSCAN algorithm. Let me detail the logical process, but not so straightforward (Activate the beast mode👹). Within the for loop defined before, we will run DBSCAN just after the assignment of the inliers (segments[i]=rest.select_by_index(inliers)), by adding the following line right after:"
},
{
"code": null,
"e": 16427,
"s": 16346,
"text": "labels = np.array(segments[i].cluster_dbscan(eps=d_threshold*10, min_points=10))"
},
{
"code": null,
"e": 16690,
"s": 16427,
"text": "🤓 Note: I actually set the epsilon in function of the initial threshold of the RANSAC plane search, with a magnitude 10 times higher. This is not deep science, this is a purely empirical choice, but it works well usually and makes thing easier with parameters 😀."
},
{
"code": null,
"e": 16894,
"s": 16690,
"text": "Then, within the loop, we will count how many points each cluster that we found holds, using a weird notation that makes use of a list comprehension. The result is then stored in the variable candidates:"
},
{
"code": null,
"e": 16962,
"s": 16894,
"text": "candidates=[len(np.where(labels==j)[0]) for j in np.unique(labels)]"
},
{
"code": null,
"e": 17099,
"s": 16962,
"text": "And now? We have to find the “best candidate”, which is normally the cluster that holds the more points! And for this, here is the line:"
},
{
"code": null,
"e": 17183,
"s": 17099,
"text": "best_candidate=int(np.unique(labels)[np.where(candidates== np.max(candidates))[0]])"
},
{
"code": null,
"e": 17570,
"s": 17183,
"text": "Okay, many tricks are happening under the hood here, but essentially, we use Numpy proficiency to search and return the index of the points that belong to the biggest cluster. From here, it is downhill skiing, and we just need to make sure to add the eventual remaining clusters per iteration in considerations for the follow-up RANSAC iterations (🔥 sentence to read 5 times to digest):"
},
{
"code": null,
"e": 17776,
"s": 17570,
"text": "rest = rest.select_by_index(inliers, invert=True) + segments[i].select_by_index(list(np.where(labels!=best_candidate)[0]))segments[i]=segments[i].select_by_index(list(np.where(labels== best_candidate)[0]))"
},
{
"code": null,
"e": 17980,
"s": 17776,
"text": "🤓 Note: the rest variable now makes sure to hold both the remaining points from RANSAC and DBSCAN. And of course, the inliers are now filtered to the biggest cluster present in the raw RANSAC inlier set."
},
{
"code": null,
"e": 18118,
"s": 17980,
"text": "When the loop is over, you get a clean set of segments holding spatially contiguous point sets that follow planar shapes, as shown below."
},
{
"code": null,
"e": 18176,
"s": 18118,
"text": "But is this the end? Noooo, never 😄! One last final step!"
},
{
"code": null,
"e": 18384,
"s": 18176,
"text": "Finally, we go outside the loop, and we work on the remaining elements stored in rest that are not yet attributed to any segment. For this, a simple pass of Euclidean clustering (DBSCAN) should do the trick:"
},
{
"code": null,
"e": 18674,
"s": 18384,
"text": "labels = np.array(rest.cluster_dbscan(eps=0.05, min_points=5))max_label = labels.max()print(f\"point cloud has {max_label + 1} clusters\")colors = plt.get_cmap(\"tab10\")(labels / (max_label if max_label > 0 else 1))colors[labels < 0] = 0rest.colors = o3d.utility.Vector3dVector(colors[:, :3])"
},
{
"code": null,
"e": 18862,
"s": 18674,
"text": "I employ the same methodology as before, no sorcery! I just make sure to use coherent parameters to have a refined clustering to get the beautiful rainbow kitchen you always dreamed of 🥳!"
},
{
"code": null,
"e": 18999,
"s": 18862,
"text": "If you want to get it working directly, I also create a Google Colab script that you can access here: To the Python Google Colab script."
},
{
"code": null,
"e": 19371,
"s": 18999,
"text": "Massive congratulations 🎉! You just learned how to import and develop an automatic segmentation and visualisation program for 3D point clouds composed of millions of points, with different strategies! Sincerely, well done! But the path certainly does not end here, because you just unlocked a tremendous potential for intelligent processes that reason at a segment level!"
},
{
"code": null,
"e": 19650,
"s": 19371,
"text": "Future posts will dive deeper into point cloud spatial analysis, file formats, data structures, object detection, segmentation, classification, visualization, animation and meshing. We will especially look into how to manage big point cloud data as defined in the article below:"
},
{
"code": null,
"e": 19673,
"s": 19650,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 19881,
"s": 19673,
"text": "My contributions aim to condense actionable information so you can start from scratch to build 3D automation systems for your projects. You can get started today by taking a formation at the Geodata Academy."
},
{
"code": null,
"e": 19897,
"s": 19881,
"text": "learngeodata.eu"
},
{
"code": null,
"e": 20205,
"s": 19897,
"text": "Other advanced segmentation methods for point cloud exist. It is actually a research field in which I am deeply involved, and you can already find some well-designed methodologies in the articles [1–6]. For the more advanced 3D deep learning architectures, some comprehensive tutorials are coming very soon!"
},
{
"code": null,
"e": 21737,
"s": 20205,
"text": "Poux, F., & Billen, R. (2019). Voxel-based 3D point cloud semantic segmentation: unsupervised geometric and relationship featuring vs deep learning methods. ISPRS International Journal of Geo-Information. 8(5), 213; https://doi.org/10.3390/ijgi8050213 — Jack Dangermond Award (Link to press coverage)Poux, F., Neuville, R., Nys, G.-A., & Billen, R. (2018). 3D Point Cloud Semantic Modelling: Integrated Framework for Indoor Spaces and Furniture. Remote Sensing, 10(9), 1412. https://doi.org/10.3390/rs10091412Poux, F., Neuville, R., Van Wersch, L., Nys, G.-A., & Billen, R. (2017). 3D Point Clouds in Archaeology: Advances in Acquisition, Processing and Knowledge Integration Applied to Quasi-Planar Objects. Geosciences, 7(4), 96. https://doi.org/10.3390/GEOSCIENCES7040096Poux, F., Mattes, C., Kobbelt, L., 2020. Unsupervised segmentation of indoor 3D point cloud: application to object-based classification, ISPRS — International Archives of the Photogrammetry, Remote Sensing and Spatial Information Sciences. pp. 111–118. https://doi:10.5194/isprs-archives-XLIV-4-W1-2020-111-2020Poux, F., Ponciano, J.J., 2020. Self-learning ontology for instance segmentation of 3d indoor point cloud, ISPRS — International Archives of Photogrammetry, Remote Sensing and Spatial Information Sciences. pp. 309–316. https://doi:10.5194/isprs-archives-XLIII-B2-2020-309-2020Bassier, M., Vergauwen, M., Poux, F., (2020). Point Cloud vs. Mesh Features for Building Interior Classification. Remote Sensing. 12, 2224. https://doi:10.3390/rs12142224"
},
{
"code": null,
"e": 22038,
"s": 21737,
"text": "Poux, F., & Billen, R. (2019). Voxel-based 3D point cloud semantic segmentation: unsupervised geometric and relationship featuring vs deep learning methods. ISPRS International Journal of Geo-Information. 8(5), 213; https://doi.org/10.3390/ijgi8050213 — Jack Dangermond Award (Link to press coverage)"
},
{
"code": null,
"e": 22248,
"s": 22038,
"text": "Poux, F., Neuville, R., Nys, G.-A., & Billen, R. (2018). 3D Point Cloud Semantic Modelling: Integrated Framework for Indoor Spaces and Furniture. Remote Sensing, 10(9), 1412. https://doi.org/10.3390/rs10091412"
},
{
"code": null,
"e": 22514,
"s": 22248,
"text": "Poux, F., Neuville, R., Van Wersch, L., Nys, G.-A., & Billen, R. (2017). 3D Point Clouds in Archaeology: Advances in Acquisition, Processing and Knowledge Integration Applied to Quasi-Planar Objects. Geosciences, 7(4), 96. https://doi.org/10.3390/GEOSCIENCES7040096"
},
{
"code": null,
"e": 22826,
"s": 22514,
"text": "Poux, F., Mattes, C., Kobbelt, L., 2020. Unsupervised segmentation of indoor 3D point cloud: application to object-based classification, ISPRS — International Archives of the Photogrammetry, Remote Sensing and Spatial Information Sciences. pp. 111–118. https://doi:10.5194/isprs-archives-XLIV-4-W1-2020-111-2020"
},
{
"code": null,
"e": 23103,
"s": 22826,
"text": "Poux, F., Ponciano, J.J., 2020. Self-learning ontology for instance segmentation of 3d indoor point cloud, ISPRS — International Archives of Photogrammetry, Remote Sensing and Spatial Information Sciences. pp. 309–316. https://doi:10.5194/isprs-archives-XLIII-B2-2020-309-2020"
}
] |
How to find the number of columns of an R data frame that satisfies a condition based on row values?
|
Sometimes we want to extract the count from the data frame and that count could be the number of columns that have same characteristics based on row values. For example, if we have a data frame containing three columns with fifty rows and the values are integers between 1 and 100 then we might want to find the number of columns that have value greater than 20 for each of the rows. This can be done by using rowSums function.
Consider the below data frame −
Live Demo
> x1<-sample(1:10,20,replace=TRUE)
> x2<-sample(1:100,20)
> x3<-rpois(20,5)
> df<-data.frame(x1,x2,x3)
> df
x1 x2 x3
1 9 72 9
2 5 20 6
3 3 82 4
4 5 47 4
5 1 45 10
6 6 14 6
7 10 54 7
8 10 13 6
9 4 98 5
10 4 76 5
11 5 53 5
12 9 87 2
13 3 79 6
14 2 73 5
15 10 75 3
16 1 7 2
17 5 92 7
18 5 34 5
19 9 52 5
20 5 43 4
Adding a new column to df with number columns having values greater than 5 −
> df$Number_of_columns_LargerThan5<-rowSums(df>5)
> df
x1 x2 x3 Number_of_columns_LargerThan5
1 9 72 9 3
2 5 20 6 2
3 3 82 4 1
4 5 47 4 1
5 1 45 10 2
6 6 14 6 3
7 10 54 7 3
8 10 13 6 3
9 4 98 5 1
10 4 76 5 1
11 5 53 5 1
12 9 87 2 2
13 3 79 6 2
14 2 73 5 1
15 10 75 3 2
16 1 7 2 1
17 5 92 7 2
18 5 34 5 1
19 9 52 5 2
20 5 43 4 1
Adding a new column to df with number columns having values less than 5 −
> df$Number_of_columns_LessThan5<-rowSums(df<5)
> df
x1 x2 x3 Number_of_columns_LargerThan5 Number_of_columns_LessThan5
1 9 72 9 3 1
2 5 20 6 2 1
3 3 82 4 1 3
4 5 47 4 1 2
5 1 45 10 2 2
6 6 14 6 3 1
7 10 54 7 3 1
8 10 13 6 3 1
9 4 98 5 1 2
10 4 76 5 1 2
11 5 53 5 1 1
12 9 87 2 2 2
13 3 79 6 2 2
14 2 73 5 1 2
15 10 75 3 2 2
16 1 7 2 1 3
17 5 92 7 2 1
18 5 34 5 1 1
19 9 52 5 2 1
20 5 43 4 1 2
Let’s have a look at another example −
Live Demo
> y1<-sample(1:100,20)
> y2<-sample(1:1000,20)
> df_y<-data.frame(y1,y2)
> df_y
y1 y2
1 33 663
2 20 523
3 24 791
4 100 330
5 48 264
6 32 579
7 56 51
8 94 57
9 76 711
10 58 411
11 49 849
12 63 805
13 67 696
14 1 237
15 11 147
16 12 448
17 75 465
18 65 220
19 99 958
20 34 909
> df_y$Number_of_columns_less_than_equalto_50<-rowSums(df_y<=50)
> df_y
y1 y2 Number_of_columns_less_than_equalto_50
1 33 663 1
2 20 523 1
3 24 791 1
4 100 330 0
5 48 264 1
6 32 579 1
7 56 51 0
8 94 57 0
9 76 711 0
10 58 411 0
11 49 849 1
12 63 805 0
13 67 696 0
14 1 237 1
15 11 147 1
16 12 448 1
17 75 465 0
18 65 220 0
19 99 958 0
20 34 909 1
|
[
{
"code": null,
"e": 1490,
"s": 1062,
"text": "Sometimes we want to extract the count from the data frame and that count could be the number of columns that have same characteristics based on row values. For example, if we have a data frame containing three columns with fifty rows and the values are integers between 1 and 100 then we might want to find the number of columns that have value greater than 20 for each of the rows. This can be done by using rowSums function."
},
{
"code": null,
"e": 1522,
"s": 1490,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1533,
"s": 1522,
"text": " Live Demo"
},
{
"code": null,
"e": 1641,
"s": 1533,
"text": "> x1<-sample(1:10,20,replace=TRUE)\n> x2<-sample(1:100,20)\n> x3<-rpois(20,5)\n> df<-data.frame(x1,x2,x3)\n> df"
},
{
"code": null,
"e": 1845,
"s": 1641,
"text": " x1 x2 x3\n1 9 72 9\n2 5 20 6\n3 3 82 4\n4 5 47 4\n5 1 45 10\n6 6 14 6\n7 10 54 7\n8 10 13 6\n9 4 98 5\n10 4 76 5\n11 5 53 5\n12 9 87 2\n13 3 79 6\n14 2 73 5\n15 10 75 3\n16 1 7 2\n17 5 92 7\n18 5 34 5\n19 9 52 5\n20 5 43 4"
},
{
"code": null,
"e": 1922,
"s": 1845,
"text": "Adding a new column to df with number columns having values greater than 5 −"
},
{
"code": null,
"e": 1977,
"s": 1922,
"text": "> df$Number_of_columns_LargerThan5<-rowSums(df>5)\n> df"
},
{
"code": null,
"e": 2297,
"s": 1977,
"text": " x1 x2 x3 Number_of_columns_LargerThan5\n1 9 72 9 3\n2 5 20 6 2\n3 3 82 4 1\n4 5 47 4 1\n5 1 45 10 2\n6 6 14 6 3\n7 10 54 7 3\n8 10 13 6 3\n9 4 98 5 1\n10 4 76 5 1\n11 5 53 5 1\n12 9 87 2 2\n13 3 79 6 2\n14 2 73 5 1\n15 10 75 3 2\n16 1 7 2 1\n17 5 92 7 2\n18 5 34 5 1\n19 9 52 5 2\n20 5 43 4 1"
},
{
"code": null,
"e": 2371,
"s": 2297,
"text": "Adding a new column to df with number columns having values less than 5 −"
},
{
"code": null,
"e": 2424,
"s": 2371,
"text": "> df$Number_of_columns_LessThan5<-rowSums(df<5)\n> df"
},
{
"code": null,
"e": 3411,
"s": 2424,
"text": "x1 x2 x3 Number_of_columns_LargerThan5 Number_of_columns_LessThan5\n1 9 72 9 3 1\n2 5 20 6 2 1\n3 3 82 4 1 3\n4 5 47 4 1 2\n5 1 45 10 2 2\n6 6 14 6 3 1\n7 10 54 7 3 1\n8 10 13 6 3 1\n9 4 98 5 1 2\n10 4 76 5 1 2\n11 5 53 5 1 1\n12 9 87 2 2 2\n13 3 79 6 2 2\n14 2 73 5 1 2\n15 10 75 3 2 2\n16 1 7 2 1 3\n17 5 92 7 2 1\n18 5 34 5 1 1\n19 9 52 5 2 1\n20 5 43 4 1 2"
},
{
"code": null,
"e": 3450,
"s": 3411,
"text": "Let’s have a look at another example −"
},
{
"code": null,
"e": 3461,
"s": 3450,
"text": " Live Demo"
},
{
"code": null,
"e": 3541,
"s": 3461,
"text": "> y1<-sample(1:100,20)\n> y2<-sample(1:1000,20)\n> df_y<-data.frame(y1,y2)\n> df_y"
},
{
"code": null,
"e": 3739,
"s": 3541,
"text": " y1 y2\n1 33 663\n2 20 523\n3 24 791\n4 100 330\n5 48 264\n6 32 579\n7 56 51\n8 94 57\n9 76 711\n10 58 411\n11 49 849\n12 63 805\n13 67 696\n14 1 237\n15 11 147\n16 12 448\n17 75 465\n18 65 220\n19 99 958\n20 34 909"
},
{
"code": null,
"e": 3811,
"s": 3739,
"text": "> df_y$Number_of_columns_less_than_equalto_50<-rowSums(df_y<=50)\n> df_y"
},
{
"code": null,
"e": 4138,
"s": 3811,
"text": " y1 y2 Number_of_columns_less_than_equalto_50\n1 33 663 1\n2 20 523 1\n3 24 791 1\n4 100 330 0\n5 48 264 1\n6 32 579 1\n7 56 51 0\n8 94 57 0\n9 76 711 0\n10 58 411 0\n11 49 849 1\n12 63 805 0\n13 67 696 0\n14 1 237 1\n15 11 147 1\n16 12 448 1\n17 75 465 0\n18 65 220 0\n19 99 958 0\n20 34 909 1"
}
] |
nginx ssl certificate installation in linux
|
This article will help you to generate self-signed SSL certificate in Linux which allows you to configure SSL certificates for Nginx which is used to wrap the normal traffic into protected traffic, encrypted traffic. Using this server can send the data to the client without the concerned that data can be intercepted by outside persons.
Before we do anything, we have to install certain packages
Login to the server via terminal and install
# yum install mod_ssl
opensslResolving Dependencies
--> Running transaction check
---> Package mod_ssl.x86_64 1:2.2.15-47.el6.centos.1 will be updated
---> Package mod_ssl.x86_64 1:2.2.15-47.el6.centos.3 will be an update
--> Processing Dependency: httpd = 2.2.15-47.el6.centos.3 for package: 1:mod_ssl-2.2.15-47.el6.centos.3.x86_64
---> Package openssl.x86_64 0:1.0.1e-42.el6_7.1 will be updated
--> Processing Dependency: openssl = 1.0.1e-42.el6_7.1 for package: openssl-devel-1.0.1e-42.el6_7.1.x86_64
---> Package openssl.x86_64 0:1.0.1e-42.el6_7.4 will be an update
--> Running transaction check
---> Package httpd.x86_64 0:2.2.15-47.el6.centos.1 will be updated
---> Package httpd.x86_64 0:2.2.15-47.el6.centos.3 will be an update
--> Processing Dependency: httpd-tools = 2.2.15-47.el6.centos.3 for package: httpd-2.2.15-47.el6.centos.3.x86_64
---> Package openssl-devel.x86_64 0:1.0.1e-42.el6_7.1 will be updated
---> Package openssl-devel.x86_64 0:1.0.1e-42.el6_7.4 will be an update
--> Running transaction check
---> Package httpd-tools.x86_64 0:2.2.15-47.el6.centos.1 will be updated
---> Package httpd-tools.x86_64 0:2.2.15-47.el6.centos.3 will be an update
--> Finished Dependency Resolution
Dependencies Resolved
==========================================================================================================================================
Package Arch Version Repository Size
==========================================================================================================================================
Updating:
mod_ssl x86_64 1:2.2.15-47.el6.centos.3 updates 95 k
openssl x86_64 1.0.1e-42.el6_7.4 updates 1.5 M
Updating for dependencies:
httpd x86_64 2.2.15-47.el6.centos.3 updates 831 k
httpd-tools x86_64 2.2.15-47.el6.centos.3 updates 77 k
openssl-devel x86_64 1.0.1e-42.el6_7.4 updates 1.2 M
Transaction Summary
==========================================================================================================================================
Upgrade 5 Package(s)
Total download size: 3.7 M
Is this ok [y/N]: y
Downloading Packages:
(1/5): httpd-2.2.15-47.el6.centos.3.x86_64.rpm | 831 kB 00:00
(2/5): httpd-tools-2.2.15-47.el6.centos.3.x86_64.rpm | 77 kB 00:00
(3/5): mod_ssl-2.2.15-47.el6.centos.3.x86_64.rpm | 95 kB 00:00
(4/5): openssl-1.0.1e-42.el6_7.4.x86_64.rpm | 1.5 MB 00:00
(5/5): openssl-devel-1.0.1e-42.el6_7.4.x86_64.rpm | 1.2 MB 00:00
------------------------------------------------------------------------------------------------------------------------------------------
Total 529 kB/s | 3.7 MB 00:07
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Updating : openssl-1.0.1e-42.el6_7.4.x86_64 1/5
Updating : httpd-tools-2.2.15-47.el6.centos.3.x86_64 2/5
Updating : httpd-2.2.15-47.el6.centos.3.x86_64 3/5
Updating : 1:mod_ssl-2.2.15-47.el6.centos.3.x86_64 4/5
Updating :openssl-devel-1.0.1e-42.el6_7.4.x86_64 5/5
Updated:
mod_ssl.x86_64 1:2.2.15-47.el6.centos.3 openssl.x86_64 0:1.0.1e-42.el6_7.4
Dependency Updated:
httpd.x86_64 0:2.2.15-47.el6.centos.3 httpd-tools.x86_64 0:2.2.15-47.el6.centos.3 openssl-devel.x86_64 0:1.0.1e-42.el6_7.4
Complete!
To generate the SSL certificate files, we need to run this command
This will begin the process of generating two files: the Private-Key file for the decryption of your SSL Certificate, and a certificate signing request (CSR) file used to apply for your SSL Certificate.
When you are prompted for the Common Name (domain name), enter the fully qualified domain name for the site you are securing. If you are generating an Nginx CSR for a Wildcard SSL Certificate make sure your common name starts with an asterisk (e.g. *.example.com).
After that, you will be prompted for your organizational information, beginning with geographic information. There may be default information which might be set already.
# openssl req -new -newkey rsa:2048 -nodes -keyout your_domain_name.key -out your_domain_name.csr
Generating a 2048 bit RSA private key
..................+++
........................+++
writing new private key to 'your_domain_name.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:IN
State or Province Name (full name) []:TELENGANA
Locality Name (eg, city) [Default City]:HYDERABAD
Organization Name (eg, company) [Default Company Ltd]:domain_name.com
Organizational Unit Name (eg, section) []:HYDERABAD
Common Name (eg, your name or your server's hostname) []:domain_name.com
Email Address []:server@ domain_name.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:test
An optional company name []:test
Your .csr file will be created.
Save (backup) the generated .key file as it will be required later when installing your SSL certificate in Nginx.
Copy the generated certificate files for your_domain_name.key and your_domain_name.csr files to /etc/ssl/domainname
# mkdir -p /etc/ssl/domain_name
# cp your_domain_name.* /etc/ssl/domain_name
Now open your Nginx virtual host file for the website you are securing. If you need your site to be accessible through both secure (https) and non-secure (http) connections, you will need a server module for each type of connection. Make a copy of the existing non-secure server module and paste it below the original. Then add the lines in bold below −
# vi /etc/nginx/conf.d/virtual.conf
server {
listen 443;
ssl on;
ssl_certificate /etc/ssl/your_domain_name.pem; (or bundle.crt)
ssl_certificate_key /etc/ssl/your_domain_name.key;
server_name your.domain.com;
access_log /var/log/nginx/nginx.vhost.access.log;
error_log /var/log/nginx/nginx.vhost.error.log;
location / {
root /home/www/public_html/your.domain.com/public/;
index index.html;
}
}
ssl_certificate should be your primary certificate combined with the intermediate certificate that you made in the previous step (e.g. your_domain_name.crt).
ssl_certificate_key should be the key file generated when you create the CSR.
Run the below command to restart Nginx to apply the changes in the configuration file.
# sudo /etc/init.d/nginx restart
Once we restart the Nginx services, we can now access the site and check if it is SSL certified.
Also, we can observe that, https is visible in green as shown below screenshot.
If we want to see the details of the certificate, then Click on the https which is in Green and click on the details.
Now we can see the Certificate information, and the Issues by as LetsEncrypt Authority.
In the above article, we have now learned about – “How to get the SSL Certificate from Let’s Encrypt” which is a digitally signed SSL certificate (provided for free) and is used as a certificate to secure a site on the Nginx Web Server.
|
[
{
"code": null,
"e": 1400,
"s": 1062,
"text": "This article will help you to generate self-signed SSL certificate in Linux which allows you to configure SSL certificates for Nginx which is used to wrap the normal traffic into protected traffic, encrypted traffic. Using this server can send the data to the client without the concerned that data can be intercepted by outside persons."
},
{
"code": null,
"e": 1459,
"s": 1400,
"text": "Before we do anything, we have to install certain packages"
},
{
"code": null,
"e": 1504,
"s": 1459,
"text": "Login to the server via terminal and install"
},
{
"code": null,
"e": 4671,
"s": 1504,
"text": "# yum install mod_ssl\nopensslResolving Dependencies\n--> Running transaction check\n---> Package mod_ssl.x86_64 1:2.2.15-47.el6.centos.1 will be updated\n---> Package mod_ssl.x86_64 1:2.2.15-47.el6.centos.3 will be an update\n--> Processing Dependency: httpd = 2.2.15-47.el6.centos.3 for package: 1:mod_ssl-2.2.15-47.el6.centos.3.x86_64\n---> Package openssl.x86_64 0:1.0.1e-42.el6_7.1 will be updated\n--> Processing Dependency: openssl = 1.0.1e-42.el6_7.1 for package: openssl-devel-1.0.1e-42.el6_7.1.x86_64\n---> Package openssl.x86_64 0:1.0.1e-42.el6_7.4 will be an update\n--> Running transaction check\n---> Package httpd.x86_64 0:2.2.15-47.el6.centos.1 will be updated\n---> Package httpd.x86_64 0:2.2.15-47.el6.centos.3 will be an update\n--> Processing Dependency: httpd-tools = 2.2.15-47.el6.centos.3 for package: httpd-2.2.15-47.el6.centos.3.x86_64\n---> Package openssl-devel.x86_64 0:1.0.1e-42.el6_7.1 will be updated\n---> Package openssl-devel.x86_64 0:1.0.1e-42.el6_7.4 will be an update\n--> Running transaction check\n---> Package httpd-tools.x86_64 0:2.2.15-47.el6.centos.1 will be updated\n---> Package httpd-tools.x86_64 0:2.2.15-47.el6.centos.3 will be an update\n--> Finished Dependency Resolution\nDependencies Resolved\n==========================================================================================================================================\nPackage Arch Version Repository Size\n==========================================================================================================================================\nUpdating:\nmod_ssl x86_64 1:2.2.15-47.el6.centos.3 updates 95 k\nopenssl x86_64 1.0.1e-42.el6_7.4 updates 1.5 M\nUpdating for dependencies:\nhttpd x86_64 2.2.15-47.el6.centos.3 updates 831 k\nhttpd-tools x86_64 2.2.15-47.el6.centos.3 updates 77 k\nopenssl-devel x86_64 1.0.1e-42.el6_7.4 updates 1.2 M\nTransaction Summary\n==========================================================================================================================================\nUpgrade 5 Package(s)\nTotal download size: 3.7 M\nIs this ok [y/N]: y\nDownloading Packages:\n(1/5): httpd-2.2.15-47.el6.centos.3.x86_64.rpm | 831 kB 00:00\n(2/5): httpd-tools-2.2.15-47.el6.centos.3.x86_64.rpm | 77 kB 00:00\n(3/5): mod_ssl-2.2.15-47.el6.centos.3.x86_64.rpm | 95 kB 00:00\n(4/5): openssl-1.0.1e-42.el6_7.4.x86_64.rpm | 1.5 MB 00:00\n(5/5): openssl-devel-1.0.1e-42.el6_7.4.x86_64.rpm | 1.2 MB 00:00\n------------------------------------------------------------------------------------------------------------------------------------------\nTotal 529 kB/s | 3.7 MB 00:07\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\nUpdating : openssl-1.0.1e-42.el6_7.4.x86_64 1/5\nUpdating : httpd-tools-2.2.15-47.el6.centos.3.x86_64 2/5\nUpdating : httpd-2.2.15-47.el6.centos.3.x86_64 3/5\nUpdating : 1:mod_ssl-2.2.15-47.el6.centos.3.x86_64 4/5\nUpdating :openssl-devel-1.0.1e-42.el6_7.4.x86_64 5/5\nUpdated:\nmod_ssl.x86_64 1:2.2.15-47.el6.centos.3 openssl.x86_64 0:1.0.1e-42.el6_7.4\nDependency Updated:\nhttpd.x86_64 0:2.2.15-47.el6.centos.3 httpd-tools.x86_64 0:2.2.15-47.el6.centos.3 openssl-devel.x86_64 0:1.0.1e-42.el6_7.4\nComplete!"
},
{
"code": null,
"e": 4738,
"s": 4671,
"text": "To generate the SSL certificate files, we need to run this command"
},
{
"code": null,
"e": 4941,
"s": 4738,
"text": "This will begin the process of generating two files: the Private-Key file for the decryption of your SSL Certificate, and a certificate signing request (CSR) file used to apply for your SSL Certificate."
},
{
"code": null,
"e": 5206,
"s": 4941,
"text": "When you are prompted for the Common Name (domain name), enter the fully qualified domain name for the site you are securing. If you are generating an Nginx CSR for a Wildcard SSL Certificate make sure your common name starts with an asterisk (e.g. *.example.com)."
},
{
"code": null,
"e": 5376,
"s": 5206,
"text": "After that, you will be prompted for your organizational information, beginning with geographic information. There may be default information which might be set already."
},
{
"code": null,
"e": 5474,
"s": 5376,
"text": "# openssl req -new -newkey rsa:2048 -nodes -keyout your_domain_name.key -out your_domain_name.csr"
},
{
"code": null,
"e": 6509,
"s": 5474,
"text": "Generating a 2048 bit RSA private key\n..................+++\n........................+++\nwriting new private key to 'your_domain_name.key'\n-----\nYou are about to be asked to enter information that will be incorporated\ninto your certificate request.\nWhat you are about to enter is what is called a Distinguished Name or a DN.\nThere are quite a few fields but you can leave some blank\nFor some fields there will be a default value,\nIf you enter '.', the field will be left blank.\n-----\nCountry Name (2 letter code) [XX]:IN\nState or Province Name (full name) []:TELENGANA\nLocality Name (eg, city) [Default City]:HYDERABAD\nOrganization Name (eg, company) [Default Company Ltd]:domain_name.com\nOrganizational Unit Name (eg, section) []:HYDERABAD\nCommon Name (eg, your name or your server's hostname) []:domain_name.com\nEmail Address []:server@ domain_name.com\nPlease enter the following 'extra' attributes\nto be sent with your certificate request\nA challenge password []:test\nAn optional company name []:test\nYour .csr file will be created."
},
{
"code": null,
"e": 6623,
"s": 6509,
"text": "Save (backup) the generated .key file as it will be required later when installing your SSL certificate in Nginx."
},
{
"code": null,
"e": 6739,
"s": 6623,
"text": "Copy the generated certificate files for your_domain_name.key and your_domain_name.csr files to /etc/ssl/domainname"
},
{
"code": null,
"e": 6816,
"s": 6739,
"text": "# mkdir -p /etc/ssl/domain_name\n# cp your_domain_name.* /etc/ssl/domain_name"
},
{
"code": null,
"e": 7170,
"s": 6816,
"text": "Now open your Nginx virtual host file for the website you are securing. If you need your site to be accessible through both secure (https) and non-secure (http) connections, you will need a server module for each type of connection. Make a copy of the existing non-secure server module and paste it below the original. Then add the lines in bold below −"
},
{
"code": null,
"e": 7206,
"s": 7170,
"text": "# vi /etc/nginx/conf.d/virtual.conf"
},
{
"code": null,
"e": 7603,
"s": 7206,
"text": "server {\n listen 443;\n ssl on;\n ssl_certificate /etc/ssl/your_domain_name.pem; (or bundle.crt)\n ssl_certificate_key /etc/ssl/your_domain_name.key;\n server_name your.domain.com;\n access_log /var/log/nginx/nginx.vhost.access.log;\n error_log /var/log/nginx/nginx.vhost.error.log;\n location / {\n root /home/www/public_html/your.domain.com/public/;\n index index.html;\n } \n}"
},
{
"code": null,
"e": 7761,
"s": 7603,
"text": "ssl_certificate should be your primary certificate combined with the intermediate certificate that you made in the previous step (e.g. your_domain_name.crt)."
},
{
"code": null,
"e": 7839,
"s": 7761,
"text": "ssl_certificate_key should be the key file generated when you create the CSR."
},
{
"code": null,
"e": 7926,
"s": 7839,
"text": "Run the below command to restart Nginx to apply the changes in the configuration file."
},
{
"code": null,
"e": 7959,
"s": 7926,
"text": "# sudo /etc/init.d/nginx restart"
},
{
"code": null,
"e": 8056,
"s": 7959,
"text": "Once we restart the Nginx services, we can now access the site and check if it is SSL certified."
},
{
"code": null,
"e": 8136,
"s": 8056,
"text": "Also, we can observe that, https is visible in green as shown below screenshot."
},
{
"code": null,
"e": 8254,
"s": 8136,
"text": "If we want to see the details of the certificate, then Click on the https which is in Green and click on the details."
},
{
"code": null,
"e": 8342,
"s": 8254,
"text": "Now we can see the Certificate information, and the Issues by as LetsEncrypt Authority."
},
{
"code": null,
"e": 8579,
"s": 8342,
"text": "In the above article, we have now learned about – “How to get the SSL Certificate from Let’s Encrypt” which is a digitally signed SSL certificate (provided for free) and is used as a certificate to secure a site on the Nginx Web Server."
}
] |
Lists in Python. Iteration and Filtering | by Sadrach Pierre, Ph.D. | Towards Data Science
|
In python, a list is delimited by the characters ‘[]’. The characters ‘[]’, alone, designate an empty list. An example of a list is [‘Guido van Rossum’, ‘Bjarne Stroustrup’, ‘James Gosling’], which is a list containing three string instances. Further, the elements of a list can be arbitrary objects (including None). For example, you can have the following list: [8200000, ‘Python’, None]. Lists are one of the most used containers in python and are central to data structures and algorithms in computer science.
In this post, we will discuss how to iterate through and filter lists using three different looping constructs in python. We will discuss how to use ‘while loops’, ‘for loops’, and ‘index-based for loops’ for list iteration. We will also give an example of list comprehension in python for list filtering.
While loops allow us to repeat an action based on repeated testing of a condition. In other words, any time you need a program to keep doing something until a condition is met, ‘while loops’ are useful.
For our example, we will consider the problem of filtering a list of songs based on the song writer. Suppose we have a list of tuples of songs and writers from the first side of the album Abbey Road, by The Beatles:
abbey_road = [('Come Together', 'Lennon'), ('Something', 'Harrison'), ('Maxwell's Silver Hammer', 'McCartney'), ('Oh! Darling!','McCartney'), ('Octopus's Garden', 'Starr'), ('I Want You', 'Lennon')]
We can iterate over the list of tuples using a ‘while loop’:
j = 0 #initialize the index while j < len(abbey_road): print(abbey_road[j]) j+=1 #advanced the index
Here, the ‘while loop’ condition is that the index we advance after each iteration must be less than the length of the list.
To filter the list of tuples based on the song writer, we can apply an additional condition. Suppose we want to remove songs by Paul McCartney. We can do the following:
j = 0while j < len(abbey_road): if abbey_road[j][1] != "McCartney": print(abbey_road[j]) j+=1
We can do the same for the other song writers as well. I encourage you to give it a shot! Now let’s move on to ‘for loops’.
We will be using ‘for loops’ to solve the same problem of list filtering. To start, let’s iterate over the ‘abbey_road’ list and print each element:
for song, artist in abbey_road: print((song, artist))
As you can see, this is a bit easier to read. This construct allows us to define names for the elements we are iterating over, which helps with code readability. Let’s filter out songs by Lennon:
for song, artist in abbey_road: if artist != "Lennon": print((song, artist))
Try modifying the condition to filter by song or a different string value for the artist. Let’s move on the ‘index-based for loops’.
For this example, we will iterate through the ‘abbey_road’ list using ‘index-based for loops’.
for i in range(len(abbey_road)): print((abbey_road[i][0], abbey_road[i][1]))
Which gives us the expected result. Let’s apply the filter for songs written by Harrison:
for i in range(len(abbey_road)): if abbey_road[i][1] != "Harrison": print((abbey_road[i][0], abbey_road[i][1]))
As you can see, this for loop construct is not as readable as the previous construct. Now let’s move on to the last example, list comprehension.
For this last example, we will use list comprehension to filter the ‘abbey_road’ list. Let’s filter out songs by “Lennon” again:
filtered_list = [(song, artist) for song, artist in abbey_road if artist != "Lennon"]print(filtered_list)
In my opinion, this is the most readable and compact way to filter a list in python.
To summarize, in this post we discussed list objects in python. We went over three ways in which we can iterate over and filter the elements of a list in python. We also gave an example of list filtering using list comprehension. I encourage you to play around with the methods of filtering and iterating through lists. For example, you can define a new list and apply the methods above or try changing the conditions for filtering in each example. I hope you found this post interesting/useful. The code in this post is available on GitHub. Thank you for reading!
|
[
{
"code": null,
"e": 686,
"s": 172,
"text": "In python, a list is delimited by the characters ‘[]’. The characters ‘[]’, alone, designate an empty list. An example of a list is [‘Guido van Rossum’, ‘Bjarne Stroustrup’, ‘James Gosling’], which is a list containing three string instances. Further, the elements of a list can be arbitrary objects (including None). For example, you can have the following list: [8200000, ‘Python’, None]. Lists are one of the most used containers in python and are central to data structures and algorithms in computer science."
},
{
"code": null,
"e": 992,
"s": 686,
"text": "In this post, we will discuss how to iterate through and filter lists using three different looping constructs in python. We will discuss how to use ‘while loops’, ‘for loops’, and ‘index-based for loops’ for list iteration. We will also give an example of list comprehension in python for list filtering."
},
{
"code": null,
"e": 1195,
"s": 992,
"text": "While loops allow us to repeat an action based on repeated testing of a condition. In other words, any time you need a program to keep doing something until a condition is met, ‘while loops’ are useful."
},
{
"code": null,
"e": 1411,
"s": 1195,
"text": "For our example, we will consider the problem of filtering a list of songs based on the song writer. Suppose we have a list of tuples of songs and writers from the first side of the album Abbey Road, by The Beatles:"
},
{
"code": null,
"e": 1610,
"s": 1411,
"text": "abbey_road = [('Come Together', 'Lennon'), ('Something', 'Harrison'), ('Maxwell's Silver Hammer', 'McCartney'), ('Oh! Darling!','McCartney'), ('Octopus's Garden', 'Starr'), ('I Want You', 'Lennon')]"
},
{
"code": null,
"e": 1671,
"s": 1610,
"text": "We can iterate over the list of tuples using a ‘while loop’:"
},
{
"code": null,
"e": 1780,
"s": 1671,
"text": "j = 0 #initialize the index while j < len(abbey_road): print(abbey_road[j]) j+=1 #advanced the index "
},
{
"code": null,
"e": 1905,
"s": 1780,
"text": "Here, the ‘while loop’ condition is that the index we advance after each iteration must be less than the length of the list."
},
{
"code": null,
"e": 2074,
"s": 1905,
"text": "To filter the list of tuples based on the song writer, we can apply an additional condition. Suppose we want to remove songs by Paul McCartney. We can do the following:"
},
{
"code": null,
"e": 2195,
"s": 2074,
"text": "j = 0while j < len(abbey_road): if abbey_road[j][1] != \"McCartney\": print(abbey_road[j]) j+=1"
},
{
"code": null,
"e": 2319,
"s": 2195,
"text": "We can do the same for the other song writers as well. I encourage you to give it a shot! Now let’s move on to ‘for loops’."
},
{
"code": null,
"e": 2468,
"s": 2319,
"text": "We will be using ‘for loops’ to solve the same problem of list filtering. To start, let’s iterate over the ‘abbey_road’ list and print each element:"
},
{
"code": null,
"e": 2525,
"s": 2468,
"text": "for song, artist in abbey_road: print((song, artist))"
},
{
"code": null,
"e": 2721,
"s": 2525,
"text": "As you can see, this is a bit easier to read. This construct allows us to define names for the elements we are iterating over, which helps with code readability. Let’s filter out songs by Lennon:"
},
{
"code": null,
"e": 2808,
"s": 2721,
"text": "for song, artist in abbey_road: if artist != \"Lennon\": print((song, artist))"
},
{
"code": null,
"e": 2941,
"s": 2808,
"text": "Try modifying the condition to filter by song or a different string value for the artist. Let’s move on the ‘index-based for loops’."
},
{
"code": null,
"e": 3036,
"s": 2941,
"text": "For this example, we will iterate through the ‘abbey_road’ list using ‘index-based for loops’."
},
{
"code": null,
"e": 3116,
"s": 3036,
"text": "for i in range(len(abbey_road)): print((abbey_road[i][0], abbey_road[i][1]))"
},
{
"code": null,
"e": 3206,
"s": 3116,
"text": "Which gives us the expected result. Let’s apply the filter for songs written by Harrison:"
},
{
"code": null,
"e": 3328,
"s": 3206,
"text": "for i in range(len(abbey_road)): if abbey_road[i][1] != \"Harrison\": print((abbey_road[i][0], abbey_road[i][1]))"
},
{
"code": null,
"e": 3473,
"s": 3328,
"text": "As you can see, this for loop construct is not as readable as the previous construct. Now let’s move on to the last example, list comprehension."
},
{
"code": null,
"e": 3602,
"s": 3473,
"text": "For this last example, we will use list comprehension to filter the ‘abbey_road’ list. Let’s filter out songs by “Lennon” again:"
},
{
"code": null,
"e": 3708,
"s": 3602,
"text": "filtered_list = [(song, artist) for song, artist in abbey_road if artist != \"Lennon\"]print(filtered_list)"
},
{
"code": null,
"e": 3793,
"s": 3708,
"text": "In my opinion, this is the most readable and compact way to filter a list in python."
}
] |
TrimEnd() method in C#
|
The TrimEnd() method removes all trailing occurrences of a set of characters specified in an array.
For example, the following string has trailing 1s.
String str ="234561111".
We can easily remove the above trailing 1s from a string using the TrimEnd() method.
Let us see an example to remove all trailing 1s.
Live Demo
using System;
class Program {
static void Main() {
String str ="234561111".TrimEnd(new Char[] { '1' } );
Console.WriteLine(str);
}
}
23456
|
[
{
"code": null,
"e": 1162,
"s": 1062,
"text": "The TrimEnd() method removes all trailing occurrences of a set of characters specified in an array."
},
{
"code": null,
"e": 1213,
"s": 1162,
"text": "For example, the following string has trailing 1s."
},
{
"code": null,
"e": 1238,
"s": 1213,
"text": "String str =\"234561111\"."
},
{
"code": null,
"e": 1323,
"s": 1238,
"text": "We can easily remove the above trailing 1s from a string using the TrimEnd() method."
},
{
"code": null,
"e": 1372,
"s": 1323,
"text": "Let us see an example to remove all trailing 1s."
},
{
"code": null,
"e": 1383,
"s": 1372,
"text": " Live Demo"
},
{
"code": null,
"e": 1535,
"s": 1383,
"text": "using System;\nclass Program {\n static void Main() {\n\n String str =\"234561111\".TrimEnd(new Char[] { '1' } );\n Console.WriteLine(str);\n }\n}"
},
{
"code": null,
"e": 1541,
"s": 1535,
"text": "23456"
}
] |
Graph Plotting in Python
|
Python has the ability to create graphs by using the matplotlib library. It has numerous packages and functions which generate a wide variety of graphs and plots. It is also very simple to use. It along with numpy and other python built-in functions achieves the goal. In this article we will see some of the different kinds of graphs it can generate.
Here we take a mathematical function to generate the x and Y coordinates of the graph. Then we use matplotlib to plot the graph for that function. Here we can apply labels and show the title of the graph as shown below. We are plotting the graph for the trigonometric function − tan.
from matplotlib import pyplot as plt
import numpy as np
import math #needed for definition of pi
x = np.arange(0, math.pi*2, 0.05)
y = np.tan(x)
plt.plot(x,y)
plt.xlabel("angle")
plt.ylabel("Tan value")
plt.title('Tan wave')
plt.show()
Running the above code gives us the following result −
We can have two or more plots on a single canvas by creating multiple axes and using them in the program.
import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
fig=plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.55, 0.55, 0.3, 0.3]) # inset axes
axes3 = fig.add_axes([0.2, 0.3, 0.2, 0.3]) # inset axes
axes1.plot(x, np.sin(x), 'b')
axes2.plot(x,np.cos(x),'r')
axes3.plot(x,np.tan(x),'g')
axes1.set_title('sine')
axes2.set_title("cosine")
axes3.set_title("tangent")
plt.show()
Running the above code gives us the following result −
We can also create a grid containing different graphs each of which is a subplot. For this we use the function subplot2grid. Here we have to choose the axes carefully so that all the subplots can fit in to the grid. A little hit an dtrail may be needed.
import matplotlib.pyplot as plt
a1 = plt.subplot2grid((3,3),(0,0),colspan = 2)
a2 = plt.subplot2grid((3,3),(0,2), rowspan = 3)
a3 = plt.subplot2grid((3,3),(1,0),rowspan = 2, colspan = 2)
import numpy as np
x = np.arange(1,10)
a2.plot(x, x*x,'r')
a2.set_title('square')
a1.plot(x, np.exp(x),'b')
a1.set_title('exp')
a3.plot(x, np.log(x),'g')
a3.set_title('log')
plt.tight_layout()
plt.show()
Running the above code gives us the following result:
Contour plots (sometimes called Level Plots) are a way to show a three-dimensional surface on a two-dimensional plane. It graphs two predictor variables X Y on the y-axis and a response variable Z as contours.Matplotlib contains contour() and contourf() functions that draw contour lines and filled contours, respectively.
import numpy as np
import matplotlib.pyplot as plt
xlist = np.linspace(-3.0, 3.0, 100)
ylist = np.linspace(-3.0, 3.0, 100)
X, Y = np.meshgrid(xlist, ylist)
Z = np.sqrt(X**2 + Y**2)
fig,ax=plt.subplots(1,1)
cp = ax.contourf(X, Y, Z)
fig.colorbar(cp) # Add a colorbar to a plot
ax.set_title('Filled Contours Plot')
#ax.set_xlabel('x (cm)')
ax.set_ylabel('y (cm)')
plt.show()
Running the above code gives us the following result:
|
[
{
"code": null,
"e": 1414,
"s": 1062,
"text": "Python has the ability to create graphs by using the matplotlib library. It has numerous packages and functions which generate a wide variety of graphs and plots. It is also very simple to use. It along with numpy and other python built-in functions achieves the goal. In this article we will see some of the different kinds of graphs it can generate."
},
{
"code": null,
"e": 1698,
"s": 1414,
"text": "Here we take a mathematical function to generate the x and Y coordinates of the graph. Then we use matplotlib to plot the graph for that function. Here we can apply labels and show the title of the graph as shown below. We are plotting the graph for the trigonometric function − tan."
},
{
"code": null,
"e": 1934,
"s": 1698,
"text": "from matplotlib import pyplot as plt\nimport numpy as np\nimport math #needed for definition of pi\nx = np.arange(0, math.pi*2, 0.05)\ny = np.tan(x)\nplt.plot(x,y)\nplt.xlabel(\"angle\")\nplt.ylabel(\"Tan value\")\nplt.title('Tan wave')\nplt.show()"
},
{
"code": null,
"e": 1989,
"s": 1934,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2095,
"s": 1989,
"text": "We can have two or more plots on a single canvas by creating multiple axes and using them in the program."
},
{
"code": null,
"e": 2552,
"s": 2095,
"text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport math\nx = np.arange(0, math.pi*2, 0.05)\nfig=plt.figure()\naxes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes\naxes2 = fig.add_axes([0.55, 0.55, 0.3, 0.3]) # inset axes\naxes3 = fig.add_axes([0.2, 0.3, 0.2, 0.3]) # inset axes\naxes1.plot(x, np.sin(x), 'b')\naxes2.plot(x,np.cos(x),'r')\naxes3.plot(x,np.tan(x),'g')\naxes1.set_title('sine')\naxes2.set_title(\"cosine\")\naxes3.set_title(\"tangent\")\nplt.show()"
},
{
"code": null,
"e": 2607,
"s": 2552,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2861,
"s": 2607,
"text": "We can also create a grid containing different graphs each of which is a subplot. For this we use the function subplot2grid. Here we have to choose the axes carefully so that all the subplots can fit in to the grid. A little hit an dtrail may be needed."
},
{
"code": null,
"e": 3252,
"s": 2861,
"text": "import matplotlib.pyplot as plt\na1 = plt.subplot2grid((3,3),(0,0),colspan = 2)\na2 = plt.subplot2grid((3,3),(0,2), rowspan = 3)\na3 = plt.subplot2grid((3,3),(1,0),rowspan = 2, colspan = 2)\nimport numpy as np\nx = np.arange(1,10)\na2.plot(x, x*x,'r')\na2.set_title('square')\na1.plot(x, np.exp(x),'b')\na1.set_title('exp')\na3.plot(x, np.log(x),'g')\na3.set_title('log')\nplt.tight_layout()\nplt.show()"
},
{
"code": null,
"e": 3306,
"s": 3252,
"text": "Running the above code gives us the following result:"
},
{
"code": null,
"e": 3629,
"s": 3306,
"text": "Contour plots (sometimes called Level Plots) are a way to show a three-dimensional surface on a two-dimensional plane. It graphs two predictor variables X Y on the y-axis and a response variable Z as contours.Matplotlib contains contour() and contourf() functions that draw contour lines and filled contours, respectively."
},
{
"code": null,
"e": 4006,
"s": 3629,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nxlist = np.linspace(-3.0, 3.0, 100)\nylist = np.linspace(-3.0, 3.0, 100)\n\nX, Y = np.meshgrid(xlist, ylist)\nZ = np.sqrt(X**2 + Y**2)\n\nfig,ax=plt.subplots(1,1)\ncp = ax.contourf(X, Y, Z)\nfig.colorbar(cp) # Add a colorbar to a plot\nax.set_title('Filled Contours Plot')\n\n#ax.set_xlabel('x (cm)')\nax.set_ylabel('y (cm)')\nplt.show()"
},
{
"code": null,
"e": 4060,
"s": 4006,
"text": "Running the above code gives us the following result:"
}
] |
HashMap in Java
|
The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets.
Following is the list of constructors supported by the HashMap class.
Let us see another example −
import java.util.*;
public class Main {
public static void main(String args[]) {
HashMap hashMap = new HashMap();
hashMap.put("John", new Integer(10000));
hashMap.put("Tim", new Integer(25000));
hashMap.put("Adam", new Integer(15000));
hashMap.put("Katie", new Integer(30000));
hashMap.put("Jacob", new Integer(45000));
hashMap.put("Steve", new Integer(23000));
hashMap.put("Nathan", new Integer(25000));
hashMap.put("Amy", new Integer(27000));
Set set = hashMap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry map = (Map.Entry)iterator.next();
System.out.print(map.getKey() + ": ");
System.out.println(map.getValue());
}
System.out.println();
System.out.println("Size of IdentintyHashMap: "+hashMap.size());
int bonus = ((Integer)hashMap.get("Amy")).intValue();
hashMap.put("Amy", new Integer(bonus + 5000));
System.out.println("Amy's salary after bonus = " + hashMap.get("Amy"));
int deductions = ((Integer)hashMap.get("Steve")).intValue();
hashMap.put("Steve", new Integer(deductions - 3000));
System.out.println("Steve's salary after deductions = " + hashMap.get("Steve"));
}
}
Adam: 15000
Nathan: 25000
Katie: 30000
Steve: 23000
John: 10000
Tim: 25000
Amy: 27000
Jacob: 45000
Size of IdentintyHashMap: 8
Amy's salary after bonus = 32000
Steve's salary after deductions = 20000
|
[
{
"code": null,
"e": 1248,
"s": 1062,
"text": "The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets."
},
{
"code": null,
"e": 1318,
"s": 1248,
"text": "Following is the list of constructors supported by the HashMap class."
},
{
"code": null,
"e": 1347,
"s": 1318,
"text": "Let us see another example −"
},
{
"code": null,
"e": 2626,
"s": 1347,
"text": "import java.util.*;\npublic class Main {\n public static void main(String args[]) {\n HashMap hashMap = new HashMap();\n hashMap.put(\"John\", new Integer(10000));\n hashMap.put(\"Tim\", new Integer(25000));\n hashMap.put(\"Adam\", new Integer(15000));\n hashMap.put(\"Katie\", new Integer(30000));\n hashMap.put(\"Jacob\", new Integer(45000));\n hashMap.put(\"Steve\", new Integer(23000));\n hashMap.put(\"Nathan\", new Integer(25000));\n hashMap.put(\"Amy\", new Integer(27000));\n Set set = hashMap.entrySet();\n Iterator iterator = set.iterator();\n while(iterator.hasNext()) {\n Map.Entry map = (Map.Entry)iterator.next();\n System.out.print(map.getKey() + \": \");\n System.out.println(map.getValue());\n }\n System.out.println();\n System.out.println(\"Size of IdentintyHashMap: \"+hashMap.size());\n int bonus = ((Integer)hashMap.get(\"Amy\")).intValue();\n hashMap.put(\"Amy\", new Integer(bonus + 5000));\n System.out.println(\"Amy's salary after bonus = \" + hashMap.get(\"Amy\"));\n int deductions = ((Integer)hashMap.get(\"Steve\")).intValue();\n hashMap.put(\"Steve\", new Integer(deductions - 3000));\n System.out.println(\"Steve's salary after deductions = \" + hashMap.get(\"Steve\"));\n }\n}"
},
{
"code": null,
"e": 2827,
"s": 2626,
"text": "Adam: 15000\nNathan: 25000\nKatie: 30000\nSteve: 23000\nJohn: 10000\nTim: 25000\nAmy: 27000\nJacob: 45000\n\nSize of IdentintyHashMap: 8\nAmy's salary after bonus = 32000\nSteve's salary after deductions = 20000"
}
] |
Get first value in Java TreeSet
|
To get the first value in TreeSet, use the first() method.
First, get the TreeSet and add elements to it
TreeSet<String> tSet = new TreeSet<String>();
tSet.add("10");
tSet.add("20");
tSet.add("30");
tSet.add("40");
tSet.add("50");
tSet.add("60");
Now, get the first value
tSet.first()
The following is an example to get the first value in TreeSet
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]){
TreeSet<String> tSet = new TreeSet<String>();
tSet.add("10");
tSet.add("20");
tSet.add("30");
tSet.add("40");
tSet.add("50");
tSet.add("60");
System.out.println("TreeSet elements...");
Iterator i = tSet.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
System.out.println("First Value = " + tSet.first());
}
}
The output is as follows
TreeSet elements...
10
20
30
40
50
60
First Value = 10
|
[
{
"code": null,
"e": 1121,
"s": 1062,
"text": "To get the first value in TreeSet, use the first() method."
},
{
"code": null,
"e": 1167,
"s": 1121,
"text": "First, get the TreeSet and add elements to it"
},
{
"code": null,
"e": 1309,
"s": 1167,
"text": "TreeSet<String> tSet = new TreeSet<String>();\ntSet.add(\"10\");\ntSet.add(\"20\");\ntSet.add(\"30\");\ntSet.add(\"40\");\ntSet.add(\"50\");\ntSet.add(\"60\");"
},
{
"code": null,
"e": 1334,
"s": 1309,
"text": "Now, get the first value"
},
{
"code": null,
"e": 1347,
"s": 1334,
"text": "tSet.first()"
},
{
"code": null,
"e": 1409,
"s": 1347,
"text": "The following is an example to get the first value in TreeSet"
},
{
"code": null,
"e": 1420,
"s": 1409,
"text": " Live Demo"
},
{
"code": null,
"e": 1911,
"s": 1420,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]){\n TreeSet<String> tSet = new TreeSet<String>();\n tSet.add(\"10\");\n tSet.add(\"20\");\n tSet.add(\"30\");\n tSet.add(\"40\");\n tSet.add(\"50\");\n tSet.add(\"60\");\n System.out.println(\"TreeSet elements...\");\n Iterator i = tSet.iterator();\n while(i.hasNext()){\n System.out.println(i.next());\n }\n System.out.println(\"First Value = \" + tSet.first());\n }\n}"
},
{
"code": null,
"e": 1936,
"s": 1911,
"text": "The output is as follows"
},
{
"code": null,
"e": 1991,
"s": 1936,
"text": "TreeSet elements...\n10\n20\n30\n40\n50\n60\nFirst Value = 10"
}
] |
Python - String Exercises
|
Now you have learned a lot about Strings, and how to use them in Python.
Are you ready for a test?
Try to insert the missing part to make the code work as expected:
Use the len method to print the length of the string.
x = "Hello World"
print()
Go to the Exercise section and test all of our Python Strings Exercises:
Python String Exercises
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 73,
"s": 0,
"text": "Now you have learned a lot about Strings, and how to use them in Python."
},
{
"code": null,
"e": 99,
"s": 73,
"text": "Are you ready for a test?"
},
{
"code": null,
"e": 165,
"s": 99,
"text": "Try to insert the missing part to make the code work as expected:"
},
{
"code": null,
"e": 219,
"s": 165,
"text": "Use the len method to print the length of the string."
},
{
"code": null,
"e": 246,
"s": 219,
"text": "x = \"Hello World\"\nprint()\n"
},
{
"code": null,
"e": 319,
"s": 246,
"text": "Go to the Exercise section and test all of our Python Strings Exercises:"
},
{
"code": null,
"e": 345,
"s": 319,
"text": "\nPython String Exercises\n"
},
{
"code": null,
"e": 378,
"s": 345,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 420,
"s": 378,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 527,
"s": 420,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 546,
"s": 527,
"text": "help@w3schools.com"
}
] |
Python - IP Address
|
IP Address (Internet Protocol) is a fundamental networking concept that provides address assignation capability in a network.
The python module ipaddress is used extensively to validate and categorize IP address to IPV4 and IPV6 type. It can also be used to
do comparison of the IP address values as well as IP address arithmetic for manipulating the ip addresses.
The ip_address function validates the IPV4 address. If the range of values is beyond 0 to 255, then it throws an error.
print (ipaddress.ip_address(u'192.168.0.255'))
print (ipaddress.ip_address(u'192.168.0.256'))
When we run the above program, we get the following output −
192.168.0.255
ValueError: u'192.168.0.256' does not appear to be an IPv4 or IPv6 address
The ip_address function validates the IPV6 address. If the range of values is beyond 0 to ffff, then it throws an error.
print (ipaddress.ip_address(u'FFFF:9999:2:FDE:257:0:2FAE:112D'))
#invalid IPV6 address
print (ipaddress.ip_address(u'FFFF:10000:2:FDE:257:0:2FAE:112D'))
When we run the above program, we get the following output −
ffff:9999:2:fde:257:0:2fae:112d
ValueError: u'FFFF:10000:2:FDE:257:0:2FAE:112D' does not appear to be an IPv4 or IPv6 address
We can supply the IP address of various formats and the module will be able to recognize the valid formats. It will also indicate which category of IP address it is.
print type(ipaddress.ip_address(u'192.168.0.255'))
print type(ipaddress.ip_address(u'2001:db8::'))
print ipaddress.ip_address(u'192.168.0.255').reverse_pointer
print ipaddress.ip_network(u'192.168.0.0/28')
When we run the above program, we get the following output −
255.0.168.192.in-addr.arpa
192.168.0.0/28
We can make a logical comparison of the IP addresses finding out if they are equal or not. We can also compare if one IP address is greater than the other in its value.
print (ipaddress.IPv4Address(u'192.168.0.2') > ipaddress.IPv4Address(u'192.168.0.1'))
print (ipaddress.IPv4Address(u'192.168.0.2') == ipaddress.IPv4Address(u'192.168.0.1'))
print (ipaddress.IPv4Address(u'192.168.0.2') != ipaddress.IPv4Address(u'192.168.0.1'))
When we run the above program, we get the following output −
True
False
True
We can also apply arithmetic operations to manipulate IP addresses. We can add or subtract integers to an IP address. If after addition the value of the last octet goes beyond 255 then
the previous octet gets incremented to accommodate the value. If the extra value can not be absorbed by any of the previous octet then a value error is raised.
print (ipaddress.IPv4Address(u'192.168.0.2')+1)
print (ipaddress.IPv4Address(u'192.168.0.253')-3)
# Increases the previous octet by value 1.
print (ipaddress.IPv4Address(u'192.168.10.253')+3)
# Throws Value error
print (ipaddress.IPv4Address(u'255.255.255.255')+1)
When we run the above program, we get the following output −
192.168.0.3
192.168.0.250
192.168.11.0
AddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address
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": 2691,
"s": 2326,
"text": "IP Address (Internet Protocol) is a fundamental networking concept that provides address assignation capability in a network.\nThe python module ipaddress is used extensively to validate and categorize IP address to IPV4 and IPV6 type. It can also be used to\ndo comparison of the IP address values as well as IP address arithmetic for manipulating the ip addresses."
},
{
"code": null,
"e": 2811,
"s": 2691,
"text": "The ip_address function validates the IPV4 address. If the range of values is beyond 0 to 255, then it throws an error."
},
{
"code": null,
"e": 2905,
"s": 2811,
"text": "print (ipaddress.ip_address(u'192.168.0.255'))\nprint (ipaddress.ip_address(u'192.168.0.256'))"
},
{
"code": null,
"e": 2966,
"s": 2905,
"text": "When we run the above program, we get the following output −"
},
{
"code": null,
"e": 3056,
"s": 2966,
"text": "192.168.0.255\nValueError: u'192.168.0.256' does not appear to be an IPv4 or IPv6 address\n"
},
{
"code": null,
"e": 3177,
"s": 3056,
"text": "The ip_address function validates the IPV6 address. If the range of values is beyond 0 to ffff, then it throws an error."
},
{
"code": null,
"e": 3331,
"s": 3177,
"text": "print (ipaddress.ip_address(u'FFFF:9999:2:FDE:257:0:2FAE:112D'))\n\n#invalid IPV6 address\nprint (ipaddress.ip_address(u'FFFF:10000:2:FDE:257:0:2FAE:112D'))"
},
{
"code": null,
"e": 3392,
"s": 3331,
"text": "When we run the above program, we get the following output −"
},
{
"code": null,
"e": 3519,
"s": 3392,
"text": "ffff:9999:2:fde:257:0:2fae:112d\nValueError: u'FFFF:10000:2:FDE:257:0:2FAE:112D' does not appear to be an IPv4 or IPv6 address\n"
},
{
"code": null,
"e": 3685,
"s": 3519,
"text": "We can supply the IP address of various formats and the module will be able to recognize the valid formats. It will also indicate which category of IP address it is."
},
{
"code": null,
"e": 3894,
"s": 3685,
"text": "print type(ipaddress.ip_address(u'192.168.0.255'))\n\nprint type(ipaddress.ip_address(u'2001:db8::'))\n\nprint ipaddress.ip_address(u'192.168.0.255').reverse_pointer\n\nprint ipaddress.ip_network(u'192.168.0.0/28')"
},
{
"code": null,
"e": 3955,
"s": 3894,
"text": "When we run the above program, we get the following output −"
},
{
"code": null,
"e": 4000,
"s": 3955,
"text": "\n\n255.0.168.192.in-addr.arpa\n192.168.0.0/28\n"
},
{
"code": null,
"e": 4169,
"s": 4000,
"text": "We can make a logical comparison of the IP addresses finding out if they are equal or not. We can also compare if one IP address is greater than the other in its value."
},
{
"code": null,
"e": 4429,
"s": 4169,
"text": "print (ipaddress.IPv4Address(u'192.168.0.2') > ipaddress.IPv4Address(u'192.168.0.1'))\nprint (ipaddress.IPv4Address(u'192.168.0.2') == ipaddress.IPv4Address(u'192.168.0.1'))\nprint (ipaddress.IPv4Address(u'192.168.0.2') != ipaddress.IPv4Address(u'192.168.0.1'))"
},
{
"code": null,
"e": 4490,
"s": 4429,
"text": "When we run the above program, we get the following output −"
},
{
"code": null,
"e": 4507,
"s": 4490,
"text": "True\nFalse\nTrue\n"
},
{
"code": null,
"e": 4853,
"s": 4507,
"text": "We can also apply arithmetic operations to manipulate IP addresses. We can add or subtract integers to an IP address. If after addition the value of the last octet goes beyond 255 then \nthe previous octet gets incremented to accommodate the value. If the extra value can not be absorbed by any of the previous octet then a value error is raised."
},
{
"code": null,
"e": 5122,
"s": 4853,
"text": "\nprint (ipaddress.IPv4Address(u'192.168.0.2')+1)\n\nprint (ipaddress.IPv4Address(u'192.168.0.253')-3)\n\n# Increases the previous octet by value 1.\nprint (ipaddress.IPv4Address(u'192.168.10.253')+3)\n\n# Throws Value error\nprint (ipaddress.IPv4Address(u'255.255.255.255')+1)"
},
{
"code": null,
"e": 5183,
"s": 5122,
"text": "When we run the above program, we get the following output −"
},
{
"code": null,
"e": 5301,
"s": 5183,
"text": "\n192.168.0.3\n192.168.0.250\n192.168.11.0\nAddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address\n"
},
{
"code": null,
"e": 5338,
"s": 5301,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5354,
"s": 5338,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5387,
"s": 5354,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5406,
"s": 5387,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5441,
"s": 5406,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 5463,
"s": 5441,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5497,
"s": 5463,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5525,
"s": 5497,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5560,
"s": 5525,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5574,
"s": 5560,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5607,
"s": 5574,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5624,
"s": 5607,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5631,
"s": 5624,
"text": " Print"
},
{
"code": null,
"e": 5642,
"s": 5631,
"text": " Add Notes"
}
] |
AWS Lambda - Copy Object Among S3 Based on Events - GeeksforGeeks
|
24 Jan, 2021
In this article, we will make AWS Lambda function to copy files from one s3 bucket to another s3 bucket. The lambda function will get triggered upon receiving the file in the source bucket. We will make use of Amazon S3 Events. Every file when uploaded to the source bucket will be an event, this needs to trigger a Lambda function which can then process this file and copy it to the destination bucket.
Steps to configure Lambda function have been given below:
Select Author from scratch template. In this, we need to write the code from scratch.
Provide the function name.
Select Runtime. There are several runtimes provided by AWS such as Java, Python, NodeJS, Ruby, etc.
Select the execution role. Execution Roles are permissions provided to Lambda Function.
Note: Lambda must have access to the S3 source and destination buckets. Therefore, make an IAM Role that has AmazonS3FullAccess policy attached. In this case, s3tos3 has full access to s3 buckets.
Once the function is created we need to add a trigger that will invoke the lambda function. The steps to add trigger is given below.
In Select Trigger, select S3. There are numerous AWS services that can act as a trigger. Since this article is focused on moving objects from one bucket to another we choose S3.In Bucket, select source bucket. This bucket will act as a trigger. We will specify the event type associated with this bucket which will further invoke our lambda function.Select Event type as All object create events. All object create event includes put, copy, post, and multi-part upload. Any one of the actions will invoke our lambda function. In our case, when we upload a file into the source bucket, the event type is PUT.Prefix and Suffix are optional. Prefix and suffix are used to match the filenames with predefined prefixes and suffixes.
In Select Trigger, select S3. There are numerous AWS services that can act as a trigger. Since this article is focused on moving objects from one bucket to another we choose S3.
In Bucket, select source bucket. This bucket will act as a trigger. We will specify the event type associated with this bucket which will further invoke our lambda function.
Select Event type as All object create events. All object create event includes put, copy, post, and multi-part upload. Any one of the actions will invoke our lambda function. In our case, when we upload a file into the source bucket, the event type is PUT.
Prefix and Suffix are optional. Prefix and suffix are used to match the filenames with predefined prefixes and suffixes.
The most remarkable thing about setting the Lambda S3 trigger is that whenever a file is uploaded, it will trigger our function. We make use of the event object to gather all the required information.
The sample event object is shown below. This object is passed to our Lambda function.
{
"Records": [
{
"eventVersion": "2.0",
"eventSource": "aws:s3",
"awsRegion": "ap-south-1",
"eventTime": "1970-01-01T00:00:00.000Z",
"eventName": "ObjectCreated:Put",
"userIdentity": {
"principalId": "GeeksforGeeks"
},
"requestParameters": {
"sourceIPAddress": "XXX.X.X.X"
},
"responseElements": {
"x-amz-request-id": "EXAMPLE123456789",
"x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH"
},
"s3": {
"s3SchemaVersion": "1.0",
"configurationId": "testConfigRule",
"bucket": {
"name": "gfg-source-bucket",
"ownerIdentity": {
"principalId": "GeeksforGeeks"
},
"arn": "arn:aws:s3:::gfg-source-bucket"
},
"object": {
"key": "geeksforgeeks.txt",
"size": 1024,
"eTag": "0123456789abcdef0123456789abcdef",
"sequencer": "0A1B2C3D4E5F678901"
}
}
}
]
}
Your Lambda function makes use of this event dictionary to identify the location where the file is uploaded. The lambda code is given below:
import json
import boto3
s3_client=boto3.client('s3')
# lambda function to copy file from 1 s3 to another s3
def lambda_handler(event, context):
#specify source bucket
source_bucket_name=event['Records'][0]['s3']['bucket']['name']
#get object that has been uploaded
file_name=event['Records'][0]['s3']['object']['key']
#specify destination bucket
destination_bucket_name='gfg-destination-bucket'
#specify from where file needs to be copied
copy_object={'Bucket':source_bucket_name,'Key':file_name}
#write copy statement
s3_client.copy_object(CopySource=copy_object,Bucket=destination_bucket_name,Key=file_name)
return {
'statusCode': 3000,
'body': json.dumps('File has been Successfully Copied')
}
Note: After writing the code, don’t forget to click Deploy.
Now when we upload a file in source bucket ‘gfg-source-bucket’, this will trigger the ‘s3Tos3-demo’ lambda function which will copy the uploaded file into destination bucket ‘gfg-destination-bucket‘. The images have been shown below:
File uploaded in Source Bucket
File Copied to Destination Bucket
Destination Bucket
The result can also be verified by clicking on Monitoring Tab in lambda function and then clicking on View logs in Cloudwatch.
CloudWatch Logs
AWS
Cloud-Computing
Advanced Computer Subject
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Principal Component Analysis with Python
Fuzzy Logic | Introduction
How to create a REST API using Java Spring Boot
Classifying data using Support Vector Machines(SVMs) in Python
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24228,
"s": 24200,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 24632,
"s": 24228,
"text": "In this article, we will make AWS Lambda function to copy files from one s3 bucket to another s3 bucket. The lambda function will get triggered upon receiving the file in the source bucket. We will make use of Amazon S3 Events. Every file when uploaded to the source bucket will be an event, this needs to trigger a Lambda function which can then process this file and copy it to the destination bucket."
},
{
"code": null,
"e": 24690,
"s": 24632,
"text": "Steps to configure Lambda function have been given below:"
},
{
"code": null,
"e": 24776,
"s": 24690,
"text": "Select Author from scratch template. In this, we need to write the code from scratch."
},
{
"code": null,
"e": 24803,
"s": 24776,
"text": "Provide the function name."
},
{
"code": null,
"e": 24903,
"s": 24803,
"text": "Select Runtime. There are several runtimes provided by AWS such as Java, Python, NodeJS, Ruby, etc."
},
{
"code": null,
"e": 24991,
"s": 24903,
"text": "Select the execution role. Execution Roles are permissions provided to Lambda Function."
},
{
"code": null,
"e": 25188,
"s": 24991,
"text": "Note: Lambda must have access to the S3 source and destination buckets. Therefore, make an IAM Role that has AmazonS3FullAccess policy attached. In this case, s3tos3 has full access to s3 buckets."
},
{
"code": null,
"e": 25321,
"s": 25188,
"text": "Once the function is created we need to add a trigger that will invoke the lambda function. The steps to add trigger is given below."
},
{
"code": null,
"e": 26049,
"s": 25321,
"text": "In Select Trigger, select S3. There are numerous AWS services that can act as a trigger. Since this article is focused on moving objects from one bucket to another we choose S3.In Bucket, select source bucket. This bucket will act as a trigger. We will specify the event type associated with this bucket which will further invoke our lambda function.Select Event type as All object create events. All object create event includes put, copy, post, and multi-part upload. Any one of the actions will invoke our lambda function. In our case, when we upload a file into the source bucket, the event type is PUT.Prefix and Suffix are optional. Prefix and suffix are used to match the filenames with predefined prefixes and suffixes."
},
{
"code": null,
"e": 26227,
"s": 26049,
"text": "In Select Trigger, select S3. There are numerous AWS services that can act as a trigger. Since this article is focused on moving objects from one bucket to another we choose S3."
},
{
"code": null,
"e": 26401,
"s": 26227,
"text": "In Bucket, select source bucket. This bucket will act as a trigger. We will specify the event type associated with this bucket which will further invoke our lambda function."
},
{
"code": null,
"e": 26659,
"s": 26401,
"text": "Select Event type as All object create events. All object create event includes put, copy, post, and multi-part upload. Any one of the actions will invoke our lambda function. In our case, when we upload a file into the source bucket, the event type is PUT."
},
{
"code": null,
"e": 26780,
"s": 26659,
"text": "Prefix and Suffix are optional. Prefix and suffix are used to match the filenames with predefined prefixes and suffixes."
},
{
"code": null,
"e": 26981,
"s": 26780,
"text": "The most remarkable thing about setting the Lambda S3 trigger is that whenever a file is uploaded, it will trigger our function. We make use of the event object to gather all the required information."
},
{
"code": null,
"e": 27067,
"s": 26981,
"text": "The sample event object is shown below. This object is passed to our Lambda function."
},
{
"code": null,
"e": 28101,
"s": 27067,
"text": "{\n \"Records\": [\n {\n \"eventVersion\": \"2.0\",\n \"eventSource\": \"aws:s3\",\n \"awsRegion\": \"ap-south-1\",\n \"eventTime\": \"1970-01-01T00:00:00.000Z\",\n \"eventName\": \"ObjectCreated:Put\",\n \"userIdentity\": {\n \"principalId\": \"GeeksforGeeks\"\n },\n \"requestParameters\": {\n \"sourceIPAddress\": \"XXX.X.X.X\"\n },\n \"responseElements\": {\n \"x-amz-request-id\": \"EXAMPLE123456789\",\n \"x-amz-id-2\": \"EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH\"\n },\n \"s3\": {\n \"s3SchemaVersion\": \"1.0\",\n \"configurationId\": \"testConfigRule\",\n \"bucket\": {\n \"name\": \"gfg-source-bucket\",\n \"ownerIdentity\": {\n \"principalId\": \"GeeksforGeeks\"\n },\n \"arn\": \"arn:aws:s3:::gfg-source-bucket\"\n },\n \"object\": {\n \"key\": \"geeksforgeeks.txt\",\n \"size\": 1024,\n \"eTag\": \"0123456789abcdef0123456789abcdef\",\n \"sequencer\": \"0A1B2C3D4E5F678901\"\n }\n }\n }\n ]\n}"
},
{
"code": null,
"e": 28242,
"s": 28101,
"text": "Your Lambda function makes use of this event dictionary to identify the location where the file is uploaded. The lambda code is given below:"
},
{
"code": null,
"e": 29007,
"s": 28242,
"text": "import json\nimport boto3\ns3_client=boto3.client('s3')\n\n# lambda function to copy file from 1 s3 to another s3\ndef lambda_handler(event, context):\n #specify source bucket\n source_bucket_name=event['Records'][0]['s3']['bucket']['name']\n #get object that has been uploaded\n file_name=event['Records'][0]['s3']['object']['key']\n #specify destination bucket\n destination_bucket_name='gfg-destination-bucket'\n #specify from where file needs to be copied\n copy_object={'Bucket':source_bucket_name,'Key':file_name}\n #write copy statement \n s3_client.copy_object(CopySource=copy_object,Bucket=destination_bucket_name,Key=file_name)\n\n return {\n 'statusCode': 3000,\n 'body': json.dumps('File has been Successfully Copied')\n }"
},
{
"code": null,
"e": 29068,
"s": 29007,
"text": "Note: After writing the code, don’t forget to click Deploy. "
},
{
"code": null,
"e": 29302,
"s": 29068,
"text": "Now when we upload a file in source bucket ‘gfg-source-bucket’, this will trigger the ‘s3Tos3-demo’ lambda function which will copy the uploaded file into destination bucket ‘gfg-destination-bucket‘. The images have been shown below:"
},
{
"code": null,
"e": 29333,
"s": 29302,
"text": "File uploaded in Source Bucket"
},
{
"code": null,
"e": 29367,
"s": 29333,
"text": "File Copied to Destination Bucket"
},
{
"code": null,
"e": 29386,
"s": 29367,
"text": "Destination Bucket"
},
{
"code": null,
"e": 29513,
"s": 29386,
"text": "The result can also be verified by clicking on Monitoring Tab in lambda function and then clicking on View logs in Cloudwatch."
},
{
"code": null,
"e": 29529,
"s": 29513,
"text": "CloudWatch Logs"
},
{
"code": null,
"e": 29533,
"s": 29529,
"text": "AWS"
},
{
"code": null,
"e": 29549,
"s": 29533,
"text": "Cloud-Computing"
},
{
"code": null,
"e": 29575,
"s": 29549,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 29582,
"s": 29575,
"text": "Python"
},
{
"code": null,
"e": 29680,
"s": 29582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29724,
"s": 29680,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 29765,
"s": 29724,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 29792,
"s": 29765,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 29840,
"s": 29792,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 29903,
"s": 29840,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 29931,
"s": 29903,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29981,
"s": 29931,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30003,
"s": 29981,
"text": "Python map() function"
}
] |
Java Program to Check if two Arrays are Equal or not - GeeksforGeeks
|
15 Oct, 2020
Given two given arrays of equal length, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain the same set of elements and in the same order.
Note: If there are repetitions, then counts of repeated elements should be the same for two arrays to be equal.
Examples:
Input : arr1[] = {1, 2, 5, 4, 0};
arr2[] = {1, 2, 5, 4, 0};
Output : Yes
Input : arr1[] = {1, 2, 5, 4, 0, 2};
arr2[] = {2, 4, 5, 0};
Output : No
Input : arr1[] = {1, 7, 7};
arr2[] = {7, 7, 1};
Output : No
Method 1: Using the pre-defined method
First, we will initialize two arrays and will insert the elements in both the arrays.
After that, Arrays.equal() function is called to check whether the two arrays are equal or not and the result will be stored into one boolean variable namely result.
Finally, the result will be printed.
Example: Below is the implementation of the above approach.
Java
// Java Program to find the if the arrays are equal import java.util.Arrays; public class CheckArraysEqual { public static void main(String[] args) { // Initializing the first array int a[] = { 30, 25, 40 }; // Initializing the second array int b[] = { 30, 25, 40 }; // store the result // Arrays.equals(a, b) function is used to check // whether two arrays are equal or not boolean result = Arrays.equals(a, b); // condition to check whether the // result is true or false if (result == true) { // Print the result System.out.println("Two arrays are equal"); } else { // Print the result System.out.println("Two arrays are not equal"); } }}
Two arrays are equal
Example 2:
Java
// Java Program to find the if the arrays are equal import java.util.Arrays; public class CheckArraysEqual { public static void main(String[] args) { // Initializing the first array int a[] = { 30, 25, 40, 23 }; // Initializing the second array int b[] = { 30, 26, 40 }; // store the result // Arrays.equals(a, b) function is used to check // whether two arrays are equal or not boolean result = Arrays.equals(a, b); // condition to check whether the // result is true or false if (result == true) { // Print the result System.out.println("Two arrays are equal"); } else { // Print the result System.out.println("Two arrays are not equal"); } }}
Two arrays are not equal
Time Complexity : O(n)Auxiliary Space : O(1)
Method 2: Without using pre-defined function
First, we will initialize two arrays a and b and insert the elements in both the arrays. Then create a boolean variable called result to store the result after checking.
Then we will check the length of the arrays whether the length of the arrays are equal or not.
If it is equal then, loop will repeat for every element till the end of the array. If somewhere some element is not equal then we will make the result as false.
If the value of the result variable is false, it means the arrays are not equal.
If the arrays are equal then the value of the result variable will remain true.
And also if the length of the arrays is not equal it will return false.
Example 1: Below is the implementation of the above approach.
Java
// Java Program to check if the arrays are equal public class checkArraysEqual { public static void main(String[] args) { // Initializing the first array int a[] = { 10, 30, 12 }; // Initializing the second array int b[] = { 10, 30, 12 }; // store the result boolean result = true; // Check if length of the two arrays are equal or // not if (a.length == b.length) { // Loop to check elements of arrays one by one for (int i = 0; i < a.length; i = i + 1) { // To check if any element is different if (a[i] != b[i]) { // If any element is different then it // will assign false into boolean // variable result = false; } } } else { // If the length of two arrays is // different then it will assign // false into boolean variable result = false; } // After completion to check whether // result is true of false if (result == true) { // Print the result System.out.println("Arrays are equal"); } else { // Print the result System.out.println("Arrays are not equal"); } }}
Arrays are equal
Example 2:
Java
// Java Program to check if the arrays are equal public class checkArraysEqual { public static void main(String[] args) { // Initializing the first array int a[] = { 10, 30, 12 }; // Initializing the second array int b[] = { 45, 50, 55, 60, 65 }; // stores the result boolean result = true; // Check if length of the two arrays are equal or // not if (a.length == b.length) { // Loop to check elements of arrays one by one for (int i = 0; i < a.length; i = i + 1) { // To check if any element is different if (a[i] != b[i]) { // If any element is different then it // will assign false into boolean // variable result = false; } } } else { // If the length of two arrays is different then // it will assign false into boolean variable result = false; } // After completion to check whether result is true // of false if (result == true) { // Print the result System.out.println("Arrays are equal"); } else { // Print the result System.out.println("Arrays are not equal"); } }}
Arrays are not equal
Time Complexity : O(n)Auxiliary Space : O(1)
Java-Array-Programs
Java-Arrays
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 24479,
"s": 24451,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 24678,
"s": 24479,
"text": "Given two given arrays of equal length, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain the same set of elements and in the same order. "
},
{
"code": null,
"e": 24790,
"s": 24678,
"text": "Note: If there are repetitions, then counts of repeated elements should be the same for two arrays to be equal."
},
{
"code": null,
"e": 24800,
"s": 24790,
"text": "Examples:"
},
{
"code": null,
"e": 25039,
"s": 24800,
"text": "Input : arr1[] = {1, 2, 5, 4, 0};\n arr2[] = {1, 2, 5, 4, 0}; \nOutput : Yes\n\nInput : arr1[] = {1, 2, 5, 4, 0, 2};\n arr2[] = {2, 4, 5, 0}; \nOutput : No\n \nInput : arr1[] = {1, 7, 7};\n arr2[] = {7, 7, 1};\nOutput : No\n"
},
{
"code": null,
"e": 25078,
"s": 25039,
"text": "Method 1: Using the pre-defined method"
},
{
"code": null,
"e": 25164,
"s": 25078,
"text": "First, we will initialize two arrays and will insert the elements in both the arrays."
},
{
"code": null,
"e": 25330,
"s": 25164,
"text": "After that, Arrays.equal() function is called to check whether the two arrays are equal or not and the result will be stored into one boolean variable namely result."
},
{
"code": null,
"e": 25367,
"s": 25330,
"text": "Finally, the result will be printed."
},
{
"code": null,
"e": 25428,
"s": 25367,
"text": "Example: Below is the implementation of the above approach. "
},
{
"code": null,
"e": 25433,
"s": 25428,
"text": "Java"
},
{
"code": "// Java Program to find the if the arrays are equal import java.util.Arrays; public class CheckArraysEqual { public static void main(String[] args) { // Initializing the first array int a[] = { 30, 25, 40 }; // Initializing the second array int b[] = { 30, 25, 40 }; // store the result // Arrays.equals(a, b) function is used to check // whether two arrays are equal or not boolean result = Arrays.equals(a, b); // condition to check whether the // result is true or false if (result == true) { // Print the result System.out.println(\"Two arrays are equal\"); } else { // Print the result System.out.println(\"Two arrays are not equal\"); } }}",
"e": 26234,
"s": 25433,
"text": null
},
{
"code": null,
"e": 26255,
"s": 26234,
"text": "Two arrays are equal"
},
{
"code": null,
"e": 26266,
"s": 26255,
"text": "Example 2:"
},
{
"code": null,
"e": 26271,
"s": 26266,
"text": "Java"
},
{
"code": "// Java Program to find the if the arrays are equal import java.util.Arrays; public class CheckArraysEqual { public static void main(String[] args) { // Initializing the first array int a[] = { 30, 25, 40, 23 }; // Initializing the second array int b[] = { 30, 26, 40 }; // store the result // Arrays.equals(a, b) function is used to check // whether two arrays are equal or not boolean result = Arrays.equals(a, b); // condition to check whether the // result is true or false if (result == true) { // Print the result System.out.println(\"Two arrays are equal\"); } else { // Print the result System.out.println(\"Two arrays are not equal\"); } }}",
"e": 27076,
"s": 26271,
"text": null
},
{
"code": null,
"e": 27101,
"s": 27076,
"text": "Two arrays are not equal"
},
{
"code": null,
"e": 27146,
"s": 27101,
"text": "Time Complexity : O(n)Auxiliary Space : O(1)"
},
{
"code": null,
"e": 27191,
"s": 27146,
"text": "Method 2: Without using pre-defined function"
},
{
"code": null,
"e": 27361,
"s": 27191,
"text": "First, we will initialize two arrays a and b and insert the elements in both the arrays. Then create a boolean variable called result to store the result after checking."
},
{
"code": null,
"e": 27456,
"s": 27361,
"text": "Then we will check the length of the arrays whether the length of the arrays are equal or not."
},
{
"code": null,
"e": 27617,
"s": 27456,
"text": "If it is equal then, loop will repeat for every element till the end of the array. If somewhere some element is not equal then we will make the result as false."
},
{
"code": null,
"e": 27698,
"s": 27617,
"text": "If the value of the result variable is false, it means the arrays are not equal."
},
{
"code": null,
"e": 27778,
"s": 27698,
"text": "If the arrays are equal then the value of the result variable will remain true."
},
{
"code": null,
"e": 27850,
"s": 27778,
"text": "And also if the length of the arrays is not equal it will return false."
},
{
"code": null,
"e": 27912,
"s": 27850,
"text": "Example 1: Below is the implementation of the above approach."
},
{
"code": null,
"e": 27917,
"s": 27912,
"text": "Java"
},
{
"code": "// Java Program to check if the arrays are equal public class checkArraysEqual { public static void main(String[] args) { // Initializing the first array int a[] = { 10, 30, 12 }; // Initializing the second array int b[] = { 10, 30, 12 }; // store the result boolean result = true; // Check if length of the two arrays are equal or // not if (a.length == b.length) { // Loop to check elements of arrays one by one for (int i = 0; i < a.length; i = i + 1) { // To check if any element is different if (a[i] != b[i]) { // If any element is different then it // will assign false into boolean // variable result = false; } } } else { // If the length of two arrays is // different then it will assign // false into boolean variable result = false; } // After completion to check whether // result is true of false if (result == true) { // Print the result System.out.println(\"Arrays are equal\"); } else { // Print the result System.out.println(\"Arrays are not equal\"); } }}",
"e": 29362,
"s": 27917,
"text": null
},
{
"code": null,
"e": 29379,
"s": 29362,
"text": "Arrays are equal"
},
{
"code": null,
"e": 29391,
"s": 29379,
"text": "Example 2: "
},
{
"code": null,
"e": 29396,
"s": 29391,
"text": "Java"
},
{
"code": "// Java Program to check if the arrays are equal public class checkArraysEqual { public static void main(String[] args) { // Initializing the first array int a[] = { 10, 30, 12 }; // Initializing the second array int b[] = { 45, 50, 55, 60, 65 }; // stores the result boolean result = true; // Check if length of the two arrays are equal or // not if (a.length == b.length) { // Loop to check elements of arrays one by one for (int i = 0; i < a.length; i = i + 1) { // To check if any element is different if (a[i] != b[i]) { // If any element is different then it // will assign false into boolean // variable result = false; } } } else { // If the length of two arrays is different then // it will assign false into boolean variable result = false; } // After completion to check whether result is true // of false if (result == true) { // Print the result System.out.println(\"Arrays are equal\"); } else { // Print the result System.out.println(\"Arrays are not equal\"); } }}",
"e": 30828,
"s": 29396,
"text": null
},
{
"code": null,
"e": 30849,
"s": 30828,
"text": "Arrays are not equal"
},
{
"code": null,
"e": 30894,
"s": 30849,
"text": "Time Complexity : O(n)Auxiliary Space : O(1)"
},
{
"code": null,
"e": 30914,
"s": 30894,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 30926,
"s": 30914,
"text": "Java-Arrays"
},
{
"code": null,
"e": 30933,
"s": 30926,
"text": "Picked"
},
{
"code": null,
"e": 30938,
"s": 30933,
"text": "Java"
},
{
"code": null,
"e": 30952,
"s": 30938,
"text": "Java Programs"
},
{
"code": null,
"e": 30957,
"s": 30952,
"text": "Java"
},
{
"code": null,
"e": 31055,
"s": 30957,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31064,
"s": 31055,
"text": "Comments"
},
{
"code": null,
"e": 31077,
"s": 31064,
"text": "Old Comments"
},
{
"code": null,
"e": 31128,
"s": 31077,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 31158,
"s": 31128,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 31189,
"s": 31158,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 31221,
"s": 31189,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31240,
"s": 31221,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31284,
"s": 31240,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 31312,
"s": 31284,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 31338,
"s": 31312,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 31372,
"s": 31338,
"text": "Convert Double to Integer in Java"
}
] |
How to pass reference parameters PHP?
|
In PHP, use &$ in function parameter to pass reference parameters.
The PHP code is as follows
Live Demo
<!DOCTYPE html>
<html>
<body>
<?php
function referenceDemo(&$number){
$number=$number+100;
return $number;
}
$number=900;
echo "The actual value is=",$number,"<br>";
$result=referenceDemo($number);
echo "The modified value is=",$result;
?>
</body>
</html>
This will produce the following output
The actual value is=900
The modified value is=1000
|
[
{
"code": null,
"e": 1129,
"s": 1062,
"text": "In PHP, use &$ in function parameter to pass reference parameters."
},
{
"code": null,
"e": 1156,
"s": 1129,
"text": "The PHP code is as follows"
},
{
"code": null,
"e": 1167,
"s": 1156,
"text": " Live Demo"
},
{
"code": null,
"e": 1429,
"s": 1167,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<?php\nfunction referenceDemo(&$number){\n $number=$number+100;\n return $number;\n}\n$number=900;\necho \"The actual value is=\",$number,\"<br>\";\n$result=referenceDemo($number);\necho \"The modified value is=\",$result;\n?>\n</body>\n</html>"
},
{
"code": null,
"e": 1469,
"s": 1429,
"text": "This will produce the following output "
},
{
"code": null,
"e": 1520,
"s": 1469,
"text": "The actual value is=900\nThe modified value is=1000"
}
] |
Elixir - Pattern Matching
|
Pattern matching is a technique which Elixir inherits form Erlang. It is a very powerful technique that allows us to extract simpler substructures from complicated data structures like lists, tuples, maps, etc.
A match has 2 main parts, a left and a right side. The right side is a data structure of any kind. The left side attempts to match the data structure on the right side and bind any variables on the left to the respective substructure on the right. If a match is not found, the operator raises an error.
The simplest match is a lone variable on the left and any data structure on the right. This variable will match anything. For example,
x = 12
x = "Hello"
IO.puts(x)
You can place variables inside a structure so that you can capture a substructure. For example,
[var_1, _unused_var, var_2] = [{"First variable"}, 25, "Second variable" ]
IO.puts(var_1)
IO.puts(var_2)
This will store the values, {"First variable"} in var_1 and "Second variable" in var_2. There is also a special _ variable(or variables prefixed with '_') that works exactly like other variables but tells elixir, "Make sure something is here, but I don't care exactly what it is.". In the previous example, _unused_var was one such variable.
We can match more complicated patterns using this technique. For example if you want to unwrap and get a number in a tuple which is inside a list which itself is in a list, you can use the following command −
[_, [_, {a}]] = ["Random string", [:an_atom, {24}]]
IO.puts(a)
The above program generates the following result −
24
This will bind a to 24. Other values are ignored as we are using '_'.
In pattern matching, if we use a variable on the right, its value is used. If you want to use the value of a variable on the left, you'll need to use the pin operator.
For example, if you have a variable "a" having value 25 and you want to match it with another variable "b" having value 25, then you need to enter −
a = 25
b = 25
^a = b
The last line matches the current value of a, instead of assigning it, to the value of b. If we have a non-matching set of left and right hand side, the match operator raises an error. For example, if we try to match a tuple with a list or a list of size 2 with a list of size 3, an error will be displayed.
35 Lectures
3 hours
Pranjal Srivastava
54 Lectures
6 hours
Pranjal Srivastava, Harshit Srivastava
80 Lectures
9.5 hours
Pranjal Srivastava
43 Lectures
4 hours
Mohammad Nauman
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2393,
"s": 2182,
"text": "Pattern matching is a technique which Elixir inherits form Erlang. It is a very powerful technique that allows us to extract simpler substructures from complicated data structures like lists, tuples, maps, etc."
},
{
"code": null,
"e": 2696,
"s": 2393,
"text": "A match has 2 main parts, a left and a right side. The right side is a data structure of any kind. The left side attempts to match the data structure on the right side and bind any variables on the left to the respective substructure on the right. If a match is not found, the operator raises an error."
},
{
"code": null,
"e": 2831,
"s": 2696,
"text": "The simplest match is a lone variable on the left and any data structure on the right. This variable will match anything. For example,"
},
{
"code": null,
"e": 2861,
"s": 2831,
"text": "x = 12\nx = \"Hello\"\nIO.puts(x)"
},
{
"code": null,
"e": 2958,
"s": 2861,
"text": "You can place variables inside a structure so that you can capture a substructure. For example, "
},
{
"code": null,
"e": 3063,
"s": 2958,
"text": "[var_1, _unused_var, var_2] = [{\"First variable\"}, 25, \"Second variable\" ]\nIO.puts(var_1)\nIO.puts(var_2)"
},
{
"code": null,
"e": 3405,
"s": 3063,
"text": "This will store the values, {\"First variable\"} in var_1 and \"Second variable\" in var_2. There is also a special _ variable(or variables prefixed with '_') that works exactly like other variables but tells elixir, \"Make sure something is here, but I don't care exactly what it is.\". In the previous example, _unused_var was one such variable."
},
{
"code": null,
"e": 3614,
"s": 3405,
"text": "We can match more complicated patterns using this technique. For example if you want to unwrap and get a number in a tuple which is inside a list which itself is in a list, you can use the following command −"
},
{
"code": null,
"e": 3677,
"s": 3614,
"text": "[_, [_, {a}]] = [\"Random string\", [:an_atom, {24}]]\nIO.puts(a)"
},
{
"code": null,
"e": 3728,
"s": 3677,
"text": "The above program generates the following result −"
},
{
"code": null,
"e": 3732,
"s": 3728,
"text": "24\n"
},
{
"code": null,
"e": 3802,
"s": 3732,
"text": "This will bind a to 24. Other values are ignored as we are using '_'."
},
{
"code": null,
"e": 3970,
"s": 3802,
"text": "In pattern matching, if we use a variable on the right, its value is used. If you want to use the value of a variable on the left, you'll need to use the pin operator."
},
{
"code": null,
"e": 4119,
"s": 3970,
"text": "For example, if you have a variable \"a\" having value 25 and you want to match it with another variable \"b\" having value 25, then you need to enter −"
},
{
"code": null,
"e": 4140,
"s": 4119,
"text": "a = 25\nb = 25\n^a = b"
},
{
"code": null,
"e": 4448,
"s": 4140,
"text": "The last line matches the current value of a, instead of assigning it, to the value of b. If we have a non-matching set of left and right hand side, the match operator raises an error. For example, if we try to match a tuple with a list or a list of size 2 with a list of size 3, an error will be displayed."
},
{
"code": null,
"e": 4481,
"s": 4448,
"text": "\n 35 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4501,
"s": 4481,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4534,
"s": 4501,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4574,
"s": 4534,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 4609,
"s": 4574,
"text": "\n 80 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 4629,
"s": 4609,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4662,
"s": 4629,
"text": "\n 43 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4679,
"s": 4662,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 4686,
"s": 4679,
"text": " Print"
},
{
"code": null,
"e": 4697,
"s": 4686,
"text": " Add Notes"
}
] |
Tensorflow.js tf.data.Dataset class .shuffle() Method - GeeksforGeeks
|
22 Apr, 2022
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.
The tf.data.Dataset.shuffle() method randomly shuffles a tensor along its first dimension.
Syntax:
tf.data.Dataset.shuffle(
buffer_size, seed=None,
reshuffle_each_iteration=None
)
Parameters:
buffer_size: This is the number of elements from which the new dataset will be sampled.
seed[optional]: It is an optional parameter used to create a random seed for the distribution, to see the same results use same seed.
reshuffle_each_iteration: A Boolean, which is true indicates that the dataset should be pseudo randomly reshuffled each time it is iterated over. Default value is true. It is Optional parameter.
Return Value: A tensor with same shape and data type as value, but shuffled along its first dimension.
Example 1: In this example first we will create a tensor and then shuffle it, In this example reshuffle_each_iteration is True
Javascript
async function shuffle() { // Creating a Tensor const a = tf.data.array([1, 2, 3, 4, 5, 6]).shuffle(3); await a.forEachAsync(e => console.log(e)); //print 1 await a.forEachAsync(e => console.log(e)); //print 2} shuffle();
Output:
3 4 1 2 5 6
3 4 2 5 6 1
Example 2: In this example, seed is set to an Integer, whenever a specific integer is used it will generate that specific output
Javascript
async function shuffleseed() { const a = tf.data.array([1, 2, 3]).shuffle(3, seed = 42); await a.forEachAsync(e => console.log(e)); const b = tf.data.array([1, 2, 3]).shuffle(3, seed = 42); await b.forEachAsync(e => console.log(e));} shuffleseed();
Output:
2 1 3
2 1 3
Reference: https://js.tensorflow.org/api/3.6.0/#tf.data.Dataset.shuffle
rishikgoyal
Picked
Tensorflow.js
TensorFlow.js-Classes
TensorFlow.js-Data
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 filter object array based on attributes?
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25220,
"s": 25192,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 25386,
"s": 25220,
"text": "Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment."
},
{
"code": null,
"e": 25477,
"s": 25386,
"text": "The tf.data.Dataset.shuffle() method randomly shuffles a tensor along its first dimension."
},
{
"code": null,
"e": 25485,
"s": 25477,
"text": "Syntax:"
},
{
"code": null,
"e": 25575,
"s": 25485,
"text": "tf.data.Dataset.shuffle(\n buffer_size, seed=None, \n reshuffle_each_iteration=None\n)"
},
{
"code": null,
"e": 25587,
"s": 25575,
"text": "Parameters:"
},
{
"code": null,
"e": 25675,
"s": 25587,
"text": "buffer_size: This is the number of elements from which the new dataset will be sampled."
},
{
"code": null,
"e": 25809,
"s": 25675,
"text": "seed[optional]: It is an optional parameter used to create a random seed for the distribution, to see the same results use same seed."
},
{
"code": null,
"e": 26004,
"s": 25809,
"text": "reshuffle_each_iteration: A Boolean, which is true indicates that the dataset should be pseudo randomly reshuffled each time it is iterated over. Default value is true. It is Optional parameter."
},
{
"code": null,
"e": 26107,
"s": 26004,
"text": "Return Value: A tensor with same shape and data type as value, but shuffled along its first dimension."
},
{
"code": null,
"e": 26234,
"s": 26107,
"text": "Example 1: In this example first we will create a tensor and then shuffle it, In this example reshuffle_each_iteration is True"
},
{
"code": null,
"e": 26245,
"s": 26234,
"text": "Javascript"
},
{
"code": "async function shuffle() { // Creating a Tensor const a = tf.data.array([1, 2, 3, 4, 5, 6]).shuffle(3); await a.forEachAsync(e => console.log(e)); //print 1 await a.forEachAsync(e => console.log(e)); //print 2} shuffle();",
"e": 26482,
"s": 26245,
"text": null
},
{
"code": null,
"e": 26490,
"s": 26482,
"text": "Output:"
},
{
"code": null,
"e": 26514,
"s": 26490,
"text": "3 4 1 2 5 6\n3 4 2 5 6 1"
},
{
"code": null,
"e": 26643,
"s": 26514,
"text": "Example 2: In this example, seed is set to an Integer, whenever a specific integer is used it will generate that specific output"
},
{
"code": null,
"e": 26654,
"s": 26643,
"text": "Javascript"
},
{
"code": "async function shuffleseed() { const a = tf.data.array([1, 2, 3]).shuffle(3, seed = 42); await a.forEachAsync(e => console.log(e)); const b = tf.data.array([1, 2, 3]).shuffle(3, seed = 42); await b.forEachAsync(e => console.log(e));} shuffleseed();",
"e": 26918,
"s": 26654,
"text": null
},
{
"code": null,
"e": 26926,
"s": 26918,
"text": "Output:"
},
{
"code": null,
"e": 26938,
"s": 26926,
"text": "2 1 3\n2 1 3"
},
{
"code": null,
"e": 27010,
"s": 26938,
"text": "Reference: https://js.tensorflow.org/api/3.6.0/#tf.data.Dataset.shuffle"
},
{
"code": null,
"e": 27022,
"s": 27010,
"text": "rishikgoyal"
},
{
"code": null,
"e": 27029,
"s": 27022,
"text": "Picked"
},
{
"code": null,
"e": 27043,
"s": 27029,
"text": "Tensorflow.js"
},
{
"code": null,
"e": 27065,
"s": 27043,
"text": "TensorFlow.js-Classes"
},
{
"code": null,
"e": 27084,
"s": 27065,
"text": "TensorFlow.js-Data"
},
{
"code": null,
"e": 27095,
"s": 27084,
"text": "JavaScript"
},
{
"code": null,
"e": 27112,
"s": 27095,
"text": "Web Technologies"
},
{
"code": null,
"e": 27210,
"s": 27112,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27219,
"s": 27210,
"text": "Comments"
},
{
"code": null,
"e": 27232,
"s": 27219,
"text": "Old Comments"
},
{
"code": null,
"e": 27293,
"s": 27232,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27334,
"s": 27293,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27382,
"s": 27334,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27444,
"s": 27382,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27501,
"s": 27444,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 27534,
"s": 27501,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27576,
"s": 27534,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27619,
"s": 27576,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27681,
"s": 27619,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Sum of Semi-Prime Numbers less than or equal to N - GeeksforGeeks
|
02 Feb, 2022
Given an integer N, the task is to find the sum of semi-prime numbers which are less than or equal to N. A Semi prime number is a number that is a multiple of two prime numbers.
Examples:
Input: N = 6 Output: 10 4 and 6 are the semi primes ≤ 6 4 + 6 = 10Input: N = 10000000 Output: 9322298311255
Approach:
First Calculate the primes less than or equal to N using Sieve and store them in a vector in sorted order.Iterate over the vector of primes. Fix one of the primes and starting checking the value of the product of all primes with this fixed prime.As the primes are arranged in sorted order, once we find a prime for which the product exceeds N, then it would exceed for all remaining primes. Hence, break the nested loop here.Add the product value to the answer variable for all valid pairs.
First Calculate the primes less than or equal to N using Sieve and store them in a vector in sorted order.
Iterate over the vector of primes. Fix one of the primes and starting checking the value of the product of all primes with this fixed prime.
As the primes are arranged in sorted order, once we find a prime for which the product exceeds N, then it would exceed for all remaining primes. Hence, break the nested loop here.
Add the product value to the answer variable for all valid pairs.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Vector to store the primesvector<ll> pr; // Create a boolean array "prime[0..n]"bool prime[10000000 + 1];void sieve(ll n){ // Initialize all prime values to be true for (int i = 2; i <= n; i += 1) { prime[i] = 1; } for (ll p = 2; (ll)p * (ll)p <= n; p++) { // If prime[p] is not changed then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked for (ll i = (ll)p * (ll)p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (ll p = 2; p <= n; p++) if (prime[p]) pr.push_back(p);} // Function to return the semi-prime sumll SemiPrimeSum(ll N){ // Variable to store the sum of semi-primes ll ans = 0; // Iterate over the prime values for (int i = 0; i < pr.size(); i += 1) { for (int j = i; j < pr.size(); j += 1) { // Break the loop once the product exceeds N if ((ll)pr[i] * (ll)pr[j] > N) break; // Add valid products which are less than // or equal to N // each product is a semi-prime number ans += (ll)pr[i] * (ll)pr[j]; } } return ans;} // Driver codeint main(){ ll N = 6; sieve(N); cout << SemiPrimeSum(N); return 0;}
// Java implementation of the above approachimport java.util.*; class GFG{ // Vector to store the primesstatic Vector<Long> pr = new Vector<>(); // Create a boolean array "prime[0..n]"static boolean prime[] = new boolean[10000000 + 1];static void sieve(long n){ // Initialize along prime values to be true for (int i = 2; i <= n; i += 1) { prime[i] = true; } for (int p = 2; (int)p * (int)p <= n; p++) { // If prime[p] is not changed then it is a prime if (prime[p] == true) { // Update along multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked for (int i = (int)p * (int)p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) pr.add((long)p);} // Function to return the semi-prime sumstatic long SemiPrimeSum(long N){ // Variable to store the sum of semi-primes long ans = 0; // Iterate over the prime values for (int i = 0; i < pr.size(); i += 1) { for (int j = i; j < pr.size(); j += 1) { // Break the loop once the product exceeds N if ((long)pr.get(i) * (long)pr.get(j) > N) break; // Add valid products which are less than // or equal to N // each product is a semi-prime number ans += (long)pr.get(i) * (long)pr.get(j); } } return ans;} // Driver codepublic static void main(String[] args){ long N = 6; sieve(N); System.out.println(SemiPrimeSum(N));}} // This code is contributed by Princi Singh
# Python3 implementation of the approach # Vector to store the primespr=[] # Create a boolean array "prime[0..n]"prime = [1 for i in range(10000000 + 1)]def sieve(n): for p in range(2, n): if p * p > n: break # If prime[p] is not changed then it is a prime if (prime[p] == True): # Update amultiples of p greater than or # equal to the square of it # numbers which are multiple of p and are # less than p^2 are already been marked for i in range(2 * p, n + 1, p): prime[i] = False # Print all prime numbers for p in range(2, n + 1): if (prime[p]): pr.append(p) # Function to return the semi-prime sumdef SemiPrimeSum(N): # Variable to store the sum of semi-primes ans = 0 # Iterate over the prime values for i in range(len(pr)): for j in range(i,len(pr)): # Break the loop once the product exceeds N if (pr[i] * pr[j] > N): break # Add valid products which are less than # or equal to N # each product is a semi-prime number ans += pr[i] * pr[j] return ans # Driver codeN = 6 sieve(N) print(SemiPrimeSum(N)) # This code is contributed by mohit kumar 29
// C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{ // Vector to store the primesstatic List<long> pr = new List<long>(); // Create a boolean array "prime[0..n]"static bool []prime = new bool[10000000 + 1];static void sieve(long n){ // Initialize along prime values to be true for (int i = 2; i <= n; i += 1) { prime[i] = true; } for (int p = 2; (int)p * (int)p <= n; p++) { // If prime[p] is not changed then it is a prime if (prime[p] == true) { // Update along multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked for (int i = (int)p * (int)p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) pr.Add((long)p);} // Function to return the semi-prime sumstatic long SemiPrimeSum(long N){ // Variable to store the sum of semi-primes long ans = 0; // Iterate over the prime values for (int i = 0; i < pr.Count; i += 1) { for (int j = i; j < pr.Count; j += 1) { // Break the loop once the product exceeds N if ((long)pr[i] * (long)pr[j] > N) break; // Add valid products which are less than // or equal to N // each product is a semi-prime number ans += (long)pr[i] * (long)pr[j]; } } return ans;} // Driver codepublic static void Main(String[] args){ long N = 6; sieve(N); Console.WriteLine(SemiPrimeSum(N));}} // This code is contributed by Rajput-Ji
<script>// Javascript implementation of the approach // Vector to store the primeslet pr = []; // Create a boolean array "prime[0..n]"let prime = new Array(10000000 + 1);function sieve(n){ // Initialize all prime values to be true for (let i = 2; i <= n; i += 1) { prime[i] = 1; } for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked for (let i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (let p = 2; p <= n; p++) if (prime[p]) pr.push(p);} // Function to return the semi-prime sumfunction SemiPrimeSum(N){ // Variable to store the sum of semi-primes let ans = 0; // Iterate over the prime values for (let i = 0; i < pr.length; i += 1) { for (let j = i; j < pr.length; j += 1) { // Break the loop once the product exceeds N if (pr[i] * pr[j] > N) break; // Add valid products which are less than // or equal to N // each product is a semi-prime number ans += pr[i] * pr[j]; } } return ans;} // Driver code let N = 6; sieve(N); document.write(SemiPrimeSum(N)); </script>
10
mohit kumar 29
princi singh
Rajput-Ji
subham348
simmytarika5
Prime Number
sieve
Mathematical
Sorting
Mathematical
Sorting
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Program to add two binary strings
Program to multiply two matrices
|
[
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 24479,
"s": 24301,
"text": "Given an integer N, the task is to find the sum of semi-prime numbers which are less than or equal to N. A Semi prime number is a number that is a multiple of two prime numbers."
},
{
"code": null,
"e": 24490,
"s": 24479,
"text": "Examples: "
},
{
"code": null,
"e": 24599,
"s": 24490,
"text": "Input: N = 6 Output: 10 4 and 6 are the semi primes ≤ 6 4 + 6 = 10Input: N = 10000000 Output: 9322298311255 "
},
{
"code": null,
"e": 24610,
"s": 24599,
"text": "Approach: "
},
{
"code": null,
"e": 25101,
"s": 24610,
"text": "First Calculate the primes less than or equal to N using Sieve and store them in a vector in sorted order.Iterate over the vector of primes. Fix one of the primes and starting checking the value of the product of all primes with this fixed prime.As the primes are arranged in sorted order, once we find a prime for which the product exceeds N, then it would exceed for all remaining primes. Hence, break the nested loop here.Add the product value to the answer variable for all valid pairs."
},
{
"code": null,
"e": 25208,
"s": 25101,
"text": "First Calculate the primes less than or equal to N using Sieve and store them in a vector in sorted order."
},
{
"code": null,
"e": 25349,
"s": 25208,
"text": "Iterate over the vector of primes. Fix one of the primes and starting checking the value of the product of all primes with this fixed prime."
},
{
"code": null,
"e": 25529,
"s": 25349,
"text": "As the primes are arranged in sorted order, once we find a prime for which the product exceeds N, then it would exceed for all remaining primes. Hence, break the nested loop here."
},
{
"code": null,
"e": 25595,
"s": 25529,
"text": "Add the product value to the answer variable for all valid pairs."
},
{
"code": null,
"e": 25648,
"s": 25595,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25652,
"s": 25648,
"text": "C++"
},
{
"code": null,
"e": 25657,
"s": 25652,
"text": "Java"
},
{
"code": null,
"e": 25665,
"s": 25657,
"text": "Python3"
},
{
"code": null,
"e": 25668,
"s": 25665,
"text": "C#"
},
{
"code": null,
"e": 25679,
"s": 25668,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Vector to store the primesvector<ll> pr; // Create a boolean array \"prime[0..n]\"bool prime[10000000 + 1];void sieve(ll n){ // Initialize all prime values to be true for (int i = 2; i <= n; i += 1) { prime[i] = 1; } for (ll p = 2; (ll)p * (ll)p <= n; p++) { // If prime[p] is not changed then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked for (ll i = (ll)p * (ll)p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (ll p = 2; p <= n; p++) if (prime[p]) pr.push_back(p);} // Function to return the semi-prime sumll SemiPrimeSum(ll N){ // Variable to store the sum of semi-primes ll ans = 0; // Iterate over the prime values for (int i = 0; i < pr.size(); i += 1) { for (int j = i; j < pr.size(); j += 1) { // Break the loop once the product exceeds N if ((ll)pr[i] * (ll)pr[j] > N) break; // Add valid products which are less than // or equal to N // each product is a semi-prime number ans += (ll)pr[i] * (ll)pr[j]; } } return ans;} // Driver codeint main(){ ll N = 6; sieve(N); cout << SemiPrimeSum(N); return 0;}",
"e": 27248,
"s": 25679,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.util.*; class GFG{ // Vector to store the primesstatic Vector<Long> pr = new Vector<>(); // Create a boolean array \"prime[0..n]\"static boolean prime[] = new boolean[10000000 + 1];static void sieve(long n){ // Initialize along prime values to be true for (int i = 2; i <= n; i += 1) { prime[i] = true; } for (int p = 2; (int)p * (int)p <= n; p++) { // If prime[p] is not changed then it is a prime if (prime[p] == true) { // Update along multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked for (int i = (int)p * (int)p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) pr.add((long)p);} // Function to return the semi-prime sumstatic long SemiPrimeSum(long N){ // Variable to store the sum of semi-primes long ans = 0; // Iterate over the prime values for (int i = 0; i < pr.size(); i += 1) { for (int j = i; j < pr.size(); j += 1) { // Break the loop once the product exceeds N if ((long)pr.get(i) * (long)pr.get(j) > N) break; // Add valid products which are less than // or equal to N // each product is a semi-prime number ans += (long)pr.get(i) * (long)pr.get(j); } } return ans;} // Driver codepublic static void main(String[] args){ long N = 6; sieve(N); System.out.println(SemiPrimeSum(N));}} // This code is contributed by Princi Singh",
"e": 28993,
"s": 27248,
"text": null
},
{
"code": "# Python3 implementation of the approach # Vector to store the primespr=[] # Create a boolean array \"prime[0..n]\"prime = [1 for i in range(10000000 + 1)]def sieve(n): for p in range(2, n): if p * p > n: break # If prime[p] is not changed then it is a prime if (prime[p] == True): # Update amultiples of p greater than or # equal to the square of it # numbers which are multiple of p and are # less than p^2 are already been marked for i in range(2 * p, n + 1, p): prime[i] = False # Print all prime numbers for p in range(2, n + 1): if (prime[p]): pr.append(p) # Function to return the semi-prime sumdef SemiPrimeSum(N): # Variable to store the sum of semi-primes ans = 0 # Iterate over the prime values for i in range(len(pr)): for j in range(i,len(pr)): # Break the loop once the product exceeds N if (pr[i] * pr[j] > N): break # Add valid products which are less than # or equal to N # each product is a semi-prime number ans += pr[i] * pr[j] return ans # Driver codeN = 6 sieve(N) print(SemiPrimeSum(N)) # This code is contributed by mohit kumar 29",
"e": 30300,
"s": 28993,
"text": null
},
{
"code": "// C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{ // Vector to store the primesstatic List<long> pr = new List<long>(); // Create a boolean array \"prime[0..n]\"static bool []prime = new bool[10000000 + 1];static void sieve(long n){ // Initialize along prime values to be true for (int i = 2; i <= n; i += 1) { prime[i] = true; } for (int p = 2; (int)p * (int)p <= n; p++) { // If prime[p] is not changed then it is a prime if (prime[p] == true) { // Update along multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked for (int i = (int)p * (int)p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) pr.Add((long)p);} // Function to return the semi-prime sumstatic long SemiPrimeSum(long N){ // Variable to store the sum of semi-primes long ans = 0; // Iterate over the prime values for (int i = 0; i < pr.Count; i += 1) { for (int j = i; j < pr.Count; j += 1) { // Break the loop once the product exceeds N if ((long)pr[i] * (long)pr[j] > N) break; // Add valid products which are less than // or equal to N // each product is a semi-prime number ans += (long)pr[i] * (long)pr[j]; } } return ans;} // Driver codepublic static void Main(String[] args){ long N = 6; sieve(N); Console.WriteLine(SemiPrimeSum(N));}} // This code is contributed by Rajput-Ji",
"e": 32042,
"s": 30300,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach // Vector to store the primeslet pr = []; // Create a boolean array \"prime[0..n]\"let prime = new Array(10000000 + 1);function sieve(n){ // Initialize all prime values to be true for (let i = 2; i <= n; i += 1) { prime[i] = 1; } for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked for (let i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (let p = 2; p <= n; p++) if (prime[p]) pr.push(p);} // Function to return the semi-prime sumfunction SemiPrimeSum(N){ // Variable to store the sum of semi-primes let ans = 0; // Iterate over the prime values for (let i = 0; i < pr.length; i += 1) { for (let j = i; j < pr.length; j += 1) { // Break the loop once the product exceeds N if (pr[i] * pr[j] > N) break; // Add valid products which are less than // or equal to N // each product is a semi-prime number ans += pr[i] * pr[j]; } } return ans;} // Driver code let N = 6; sieve(N); document.write(SemiPrimeSum(N)); </script>",
"e": 33531,
"s": 32042,
"text": null
},
{
"code": null,
"e": 33534,
"s": 33531,
"text": "10"
},
{
"code": null,
"e": 33551,
"s": 33536,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33564,
"s": 33551,
"text": "princi singh"
},
{
"code": null,
"e": 33574,
"s": 33564,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 33584,
"s": 33574,
"text": "subham348"
},
{
"code": null,
"e": 33597,
"s": 33584,
"text": "simmytarika5"
},
{
"code": null,
"e": 33610,
"s": 33597,
"text": "Prime Number"
},
{
"code": null,
"e": 33616,
"s": 33610,
"text": "sieve"
},
{
"code": null,
"e": 33629,
"s": 33616,
"text": "Mathematical"
},
{
"code": null,
"e": 33637,
"s": 33629,
"text": "Sorting"
},
{
"code": null,
"e": 33650,
"s": 33637,
"text": "Mathematical"
},
{
"code": null,
"e": 33658,
"s": 33650,
"text": "Sorting"
},
{
"code": null,
"e": 33671,
"s": 33658,
"text": "Prime Number"
},
{
"code": null,
"e": 33677,
"s": 33671,
"text": "sieve"
},
{
"code": null,
"e": 33775,
"s": 33677,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33784,
"s": 33775,
"text": "Comments"
},
{
"code": null,
"e": 33797,
"s": 33784,
"text": "Old Comments"
},
{
"code": null,
"e": 33842,
"s": 33797,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 33874,
"s": 33842,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 33918,
"s": 33874,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 33952,
"s": 33918,
"text": "Program to add two binary strings"
}
] |
How to get Euler's constant value in JavaScript?
|
To get Euler’s constant value in JavaScript, use the Math E property. This is a Euler's constant and the base of natural logarithms, approximately 2.718.
You can try to run the following code to get Euler’s constant value in JavaScript −
Live Demo
<html>
<head>
<title>JavaScript Math E Property</title>
</head>
<body>
<script>
var property_value = Math.E
document.write("Property Value is :" + property_value);
</script>
</body>
</html>
Property Value is :2.718281828459045
|
[
{
"code": null,
"e": 1216,
"s": 1062,
"text": "To get Euler’s constant value in JavaScript, use the Math E property. This is a Euler's constant and the base of natural logarithms, approximately 2.718."
},
{
"code": null,
"e": 1300,
"s": 1216,
"text": "You can try to run the following code to get Euler’s constant value in JavaScript −"
},
{
"code": null,
"e": 1310,
"s": 1300,
"text": "Live Demo"
},
{
"code": null,
"e": 1548,
"s": 1310,
"text": "<html>\n <head>\n <title>JavaScript Math E Property</title>\n </head>\n <body>\n <script>\n var property_value = Math.E\n document.write(\"Property Value is :\" + property_value);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 1585,
"s": 1548,
"text": "Property Value is :2.718281828459045"
}
] |
The Best Disney Movies to Learn English According to Data Science | Towards Data Science
|
The first time I used Disney Plus, I was thrilled — and it wasn’t because of the Pixar and Marvel movies available in the catalog, but because of their content available in multiple languages.
English, Spanish, Portuguese, Italian, you name it! At that moment, I thought, “this is a good opportunity for learning foreign languages.” On top of that, we’re already familiar with some Disney movies, which is an advantage because it increases our chances of understanding the dialogue in any language.
But Disney+ has around 662 movies in its catalog. This is too much content to choose from, so I made a data analysis to find the best Disney movies that will help us learn a foreign language easily as I previously did for Netflix shows and 3000 top-rated movies.
The movies analyzed are from the Disney+catalog, so content from Pixar, Marvel, Star Wars and National Geographic were also included.
Table of Contents1. How Am I Choosing The Best Movies?2. The Best Disney Movies to Learn a Foreign Language - Ranking of The 300 Disney Movies - The Best Movies for Beginner, Intermediate and Advanced Level - The Movie Genres With Simple and Hard Vocabulary3. Methodology - Data Collection - Tokenization - Lemmatization - Data Cleaning4. Final Note
To choose the best Disney movies to learn a foreign language, I used the transcripts that contain the dialogue in each movie.
Thanks to a wordlist created for corpus analysis in the linguistic field, I could find the difficulty of the vocabulary used in each movie. Then with some Python code, I created a ranking of the best movies that is based on the histogram below.
Don’t let the picture scare you! The important thing to know is that the simpler the movie's vocabulary, the easier to understand it. For example, the top 20 movies are the best because you only need to know the top 1000 most common words in a language to recognize at least 93% of the words.
The vocabulary in a language follows the Pareto rule. The top 1,000 most frequent words in a language make up over 80% of everyday conversation. Learning common words is a good opportunity for learning a foreign language!
Now that you know my definition of “best movies,” let’s find out which are the best Disney movies to learn a foreign language.
More details about the analysis are in the following sections.
The following are the 10 best Disney movies, in which you only need 1000 words to recognize at least 93% of the dialogues. There are 19 movies in the first bar previously shown, but I’m listing the 10 most popular to find a trade-off between movies with easy vocabulary and popularity:
The Last Song (2010)Pete’s Dragon (2016)The Parent Trap (1961 and 1998)Camp Rock 2: The Final Jam (2010)High School Musical 3 (2008)Confessions of a Teenage Drama Queen (2004)Brother Bear (2003)A Wrinkle In Time (2018)The Straight Story (1999)Frozen 2 (2019)
The Last Song (2010)
Pete’s Dragon (2016)
The Parent Trap (1961 and 1998)
Camp Rock 2: The Final Jam (2010)
High School Musical 3 (2008)
Confessions of a Teenage Drama Queen (2004)
Brother Bear (2003)
A Wrinkle In Time (2018)
The Straight Story (1999)
Frozen 2 (2019)
But that’s not all! The analysis goes beyond the top 10 movies. You don’t become fluent in a foreign language by only watching 10 movies, right?
If you want to find the top 20, 50, 100 or challenge yourself and watch the movie that ranks #300 (the one with the most difficult vocabulary), you just need to search them in the table below.
For example, I enjoyed watching the movie Finding Nemo when I was a kid, so to know whether that’s a good choice to watch in Spanish or Portuguese, I just type Finding Nemo in the box and find its ranking.
So, I found that Finding Nemo is in #123 in the ranking. Not bad; however, Finding Dory ranks #70, so I think I’ll watch that one first to improve my language skills.
If you want more customization, then you can find the perfect movie for your language level in the plot below. Unlike the previous analysis, where we only focus on the most common 1000 words (beginner level), in this case, we also analyze the percentage of dialogues that the most common 2000 and 3000 words cover in each movie.
If 300 movies aren’t enough for you, check my other articles to find the best Netflix movies and shows and the best 3000 most popular movies for learning a foreign language.
In case you’d like to know more about how to learn languages by watching TV shows and movies, I wrote a complete guide explaining how I learned 3 languages so far by watching TV.
medium.com
After obtaining the results for this analysis, I couldn’t help noticing that many documentaries rank in the last 10, so I spent some of my time watching some of them to obtain a better understanding.
After watching The African Lion, Dolfin Reef and The Living Desert on Disney Plus, I realized that the vocabulary might be challenging for most language learners. Unless you’re into flora and fauna, I wouldn’t recommend watching that kind of content if your goal is to become fluent in a foreign language.
On the other hand, the top 10 contain movies from different genres, so I can’t come up with a conclusion about the best movie genre to learn a foreign language. I’ll try to make a different analysis in this regard.
I did all this analysis in Python. The details are on my Github. These were the steps I followed:
For this analysis, I used 2 datasets — the Disney Plus catalog and movie transcripts. I googled movie transcripts to find as many Disney movie transcripts as I could get. In the end, I only found around 400, but after the cleaning process, only 300 transcripts remained for the analysis.
Then I downloaded the Disney Plus catalog dataset available on Kaggle. It consists of titles available on Disney Plus as of 2020. I used the catalog to match the transcripts with the titles available on Disney Plus.
To analyze the vocabulary in the transcripts, I tokenized all words spoken by characters. There are many tools for tokenization in Python, but I used CountVectorizer because it converts the transcripts collected to a dataframe of token counts, which simplifies the analysis. I explained a bit more about how the CountVectorizer works in the article where I analyzed 3000 movies.
from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction import text import scipy.sparsecv = CountVectorizer()cv_matrix = cv.fit_transform(df_analysis['transcripts'])df_dtm = pd.DataFrame.sparse.from_spmatrix(cv_matrix, index=df_analysis.index,columns=cv.get_feature_names())df_dtm = df_dtm.T
After tokenizing, I had to find the base form of each token. You can do this by using lemmatization techniques, which you can find in the NLTK library. However, I used word-family lists that do a similar job and also give you the level of difficulty of each word based on its frequency. As of 2020, there are 29-word-family lists and you can find some of them here. These lists were evaluated on research papers in linguistics and English learning as a second language.
I removed words that couldn’t be heard in the movies, such as scenes’ descriptions and speakers’ names. The cleaning method I used is far from perfect, but it helps me standardized the dialogues within transcripts. The clean_transcripts file I used is available on my Github.
I also excluded transcripts whose dialogue had more than 4.5% of words that didn’t match the word-family lists (they could be outliers or corrupted data). I usually used 3.5%, but in this case, I watched some of the movies that had between 3.5% and 4.5% and I didn’t find anything weird in the transcripts.
from cleaning import clean_transcriptsround1 = lambda x: clean_transcripts(x)df_analysis['transcripts'] = df_analysis['transcripts'].apply(round1)...df_statistics = df_statistics[df_statistics[100]<4.5]
In this analysis, we found the best Disney movies to learn a language. It’s a great idea to start with easy movies, so we have less trouble understanding dialogues and more fun watching the scenes. However, also consider watching movies you like, so pick movies you like that rank high.
The transcripts used for the analysis are in English. I tested the results for some languages like Spanish and Portuguese and they work fine. I would say that this works well for romance languages, but I can’t guarantee the same results for other languages.
Please let me know if the movies still have an easy vocabulary by watching them in the language you’re learning.
|
[
{
"code": null,
"e": 365,
"s": 172,
"text": "The first time I used Disney Plus, I was thrilled — and it wasn’t because of the Pixar and Marvel movies available in the catalog, but because of their content available in multiple languages."
},
{
"code": null,
"e": 671,
"s": 365,
"text": "English, Spanish, Portuguese, Italian, you name it! At that moment, I thought, “this is a good opportunity for learning foreign languages.” On top of that, we’re already familiar with some Disney movies, which is an advantage because it increases our chances of understanding the dialogue in any language."
},
{
"code": null,
"e": 934,
"s": 671,
"text": "But Disney+ has around 662 movies in its catalog. This is too much content to choose from, so I made a data analysis to find the best Disney movies that will help us learn a foreign language easily as I previously did for Netflix shows and 3000 top-rated movies."
},
{
"code": null,
"e": 1068,
"s": 934,
"text": "The movies analyzed are from the Disney+catalog, so content from Pixar, Marvel, Star Wars and National Geographic were also included."
},
{
"code": null,
"e": 1418,
"s": 1068,
"text": "Table of Contents1. How Am I Choosing The Best Movies?2. The Best Disney Movies to Learn a Foreign Language - Ranking of The 300 Disney Movies - The Best Movies for Beginner, Intermediate and Advanced Level - The Movie Genres With Simple and Hard Vocabulary3. Methodology - Data Collection - Tokenization - Lemmatization - Data Cleaning4. Final Note"
},
{
"code": null,
"e": 1544,
"s": 1418,
"text": "To choose the best Disney movies to learn a foreign language, I used the transcripts that contain the dialogue in each movie."
},
{
"code": null,
"e": 1789,
"s": 1544,
"text": "Thanks to a wordlist created for corpus analysis in the linguistic field, I could find the difficulty of the vocabulary used in each movie. Then with some Python code, I created a ranking of the best movies that is based on the histogram below."
},
{
"code": null,
"e": 2082,
"s": 1789,
"text": "Don’t let the picture scare you! The important thing to know is that the simpler the movie's vocabulary, the easier to understand it. For example, the top 20 movies are the best because you only need to know the top 1000 most common words in a language to recognize at least 93% of the words."
},
{
"code": null,
"e": 2304,
"s": 2082,
"text": "The vocabulary in a language follows the Pareto rule. The top 1,000 most frequent words in a language make up over 80% of everyday conversation. Learning common words is a good opportunity for learning a foreign language!"
},
{
"code": null,
"e": 2431,
"s": 2304,
"text": "Now that you know my definition of “best movies,” let’s find out which are the best Disney movies to learn a foreign language."
},
{
"code": null,
"e": 2494,
"s": 2431,
"text": "More details about the analysis are in the following sections."
},
{
"code": null,
"e": 2780,
"s": 2494,
"text": "The following are the 10 best Disney movies, in which you only need 1000 words to recognize at least 93% of the dialogues. There are 19 movies in the first bar previously shown, but I’m listing the 10 most popular to find a trade-off between movies with easy vocabulary and popularity:"
},
{
"code": null,
"e": 3039,
"s": 2780,
"text": "The Last Song (2010)Pete’s Dragon (2016)The Parent Trap (1961 and 1998)Camp Rock 2: The Final Jam (2010)High School Musical 3 (2008)Confessions of a Teenage Drama Queen (2004)Brother Bear (2003)A Wrinkle In Time (2018)The Straight Story (1999)Frozen 2 (2019)"
},
{
"code": null,
"e": 3060,
"s": 3039,
"text": "The Last Song (2010)"
},
{
"code": null,
"e": 3081,
"s": 3060,
"text": "Pete’s Dragon (2016)"
},
{
"code": null,
"e": 3113,
"s": 3081,
"text": "The Parent Trap (1961 and 1998)"
},
{
"code": null,
"e": 3147,
"s": 3113,
"text": "Camp Rock 2: The Final Jam (2010)"
},
{
"code": null,
"e": 3176,
"s": 3147,
"text": "High School Musical 3 (2008)"
},
{
"code": null,
"e": 3220,
"s": 3176,
"text": "Confessions of a Teenage Drama Queen (2004)"
},
{
"code": null,
"e": 3240,
"s": 3220,
"text": "Brother Bear (2003)"
},
{
"code": null,
"e": 3265,
"s": 3240,
"text": "A Wrinkle In Time (2018)"
},
{
"code": null,
"e": 3291,
"s": 3265,
"text": "The Straight Story (1999)"
},
{
"code": null,
"e": 3307,
"s": 3291,
"text": "Frozen 2 (2019)"
},
{
"code": null,
"e": 3452,
"s": 3307,
"text": "But that’s not all! The analysis goes beyond the top 10 movies. You don’t become fluent in a foreign language by only watching 10 movies, right?"
},
{
"code": null,
"e": 3645,
"s": 3452,
"text": "If you want to find the top 20, 50, 100 or challenge yourself and watch the movie that ranks #300 (the one with the most difficult vocabulary), you just need to search them in the table below."
},
{
"code": null,
"e": 3851,
"s": 3645,
"text": "For example, I enjoyed watching the movie Finding Nemo when I was a kid, so to know whether that’s a good choice to watch in Spanish or Portuguese, I just type Finding Nemo in the box and find its ranking."
},
{
"code": null,
"e": 4018,
"s": 3851,
"text": "So, I found that Finding Nemo is in #123 in the ranking. Not bad; however, Finding Dory ranks #70, so I think I’ll watch that one first to improve my language skills."
},
{
"code": null,
"e": 4347,
"s": 4018,
"text": "If you want more customization, then you can find the perfect movie for your language level in the plot below. Unlike the previous analysis, where we only focus on the most common 1000 words (beginner level), in this case, we also analyze the percentage of dialogues that the most common 2000 and 3000 words cover in each movie."
},
{
"code": null,
"e": 4521,
"s": 4347,
"text": "If 300 movies aren’t enough for you, check my other articles to find the best Netflix movies and shows and the best 3000 most popular movies for learning a foreign language."
},
{
"code": null,
"e": 4700,
"s": 4521,
"text": "In case you’d like to know more about how to learn languages by watching TV shows and movies, I wrote a complete guide explaining how I learned 3 languages so far by watching TV."
},
{
"code": null,
"e": 4711,
"s": 4700,
"text": "medium.com"
},
{
"code": null,
"e": 4911,
"s": 4711,
"text": "After obtaining the results for this analysis, I couldn’t help noticing that many documentaries rank in the last 10, so I spent some of my time watching some of them to obtain a better understanding."
},
{
"code": null,
"e": 5217,
"s": 4911,
"text": "After watching The African Lion, Dolfin Reef and The Living Desert on Disney Plus, I realized that the vocabulary might be challenging for most language learners. Unless you’re into flora and fauna, I wouldn’t recommend watching that kind of content if your goal is to become fluent in a foreign language."
},
{
"code": null,
"e": 5432,
"s": 5217,
"text": "On the other hand, the top 10 contain movies from different genres, so I can’t come up with a conclusion about the best movie genre to learn a foreign language. I’ll try to make a different analysis in this regard."
},
{
"code": null,
"e": 5530,
"s": 5432,
"text": "I did all this analysis in Python. The details are on my Github. These were the steps I followed:"
},
{
"code": null,
"e": 5818,
"s": 5530,
"text": "For this analysis, I used 2 datasets — the Disney Plus catalog and movie transcripts. I googled movie transcripts to find as many Disney movie transcripts as I could get. In the end, I only found around 400, but after the cleaning process, only 300 transcripts remained for the analysis."
},
{
"code": null,
"e": 6034,
"s": 5818,
"text": "Then I downloaded the Disney Plus catalog dataset available on Kaggle. It consists of titles available on Disney Plus as of 2020. I used the catalog to match the transcripts with the titles available on Disney Plus."
},
{
"code": null,
"e": 6413,
"s": 6034,
"text": "To analyze the vocabulary in the transcripts, I tokenized all words spoken by characters. There are many tools for tokenization in Python, but I used CountVectorizer because it converts the transcripts collected to a dataframe of token counts, which simplifies the analysis. I explained a bit more about how the CountVectorizer works in the article where I analyzed 3000 movies."
},
{
"code": null,
"e": 6740,
"s": 6413,
"text": "from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction import text import scipy.sparsecv = CountVectorizer()cv_matrix = cv.fit_transform(df_analysis['transcripts'])df_dtm = pd.DataFrame.sparse.from_spmatrix(cv_matrix, index=df_analysis.index,columns=cv.get_feature_names())df_dtm = df_dtm.T"
},
{
"code": null,
"e": 7210,
"s": 6740,
"text": "After tokenizing, I had to find the base form of each token. You can do this by using lemmatization techniques, which you can find in the NLTK library. However, I used word-family lists that do a similar job and also give you the level of difficulty of each word based on its frequency. As of 2020, there are 29-word-family lists and you can find some of them here. These lists were evaluated on research papers in linguistics and English learning as a second language."
},
{
"code": null,
"e": 7486,
"s": 7210,
"text": "I removed words that couldn’t be heard in the movies, such as scenes’ descriptions and speakers’ names. The cleaning method I used is far from perfect, but it helps me standardized the dialogues within transcripts. The clean_transcripts file I used is available on my Github."
},
{
"code": null,
"e": 7793,
"s": 7486,
"text": "I also excluded transcripts whose dialogue had more than 4.5% of words that didn’t match the word-family lists (they could be outliers or corrupted data). I usually used 3.5%, but in this case, I watched some of the movies that had between 3.5% and 4.5% and I didn’t find anything weird in the transcripts."
},
{
"code": null,
"e": 7996,
"s": 7793,
"text": "from cleaning import clean_transcriptsround1 = lambda x: clean_transcripts(x)df_analysis['transcripts'] = df_analysis['transcripts'].apply(round1)...df_statistics = df_statistics[df_statistics[100]<4.5]"
},
{
"code": null,
"e": 8283,
"s": 7996,
"text": "In this analysis, we found the best Disney movies to learn a language. It’s a great idea to start with easy movies, so we have less trouble understanding dialogues and more fun watching the scenes. However, also consider watching movies you like, so pick movies you like that rank high."
},
{
"code": null,
"e": 8541,
"s": 8283,
"text": "The transcripts used for the analysis are in English. I tested the results for some languages like Spanish and Portuguese and they work fine. I would say that this works well for romance languages, but I can’t guarantee the same results for other languages."
}
] |
Tryit Editor v3.7
|
Tryit: HSL Lightness
|
[] |
How to create editable div using JavaScript ? - GeeksforGeeks
|
13 Oct, 2020
In this article, we will be explaining to you how to create an editable div using HTML, CSS, and JavaScript. An editable div is one on which is you will click then it will generate an editable text area to edit or to write any text on your browser itself. After editing, when you click on somewhere else on your browser then that text will be displayed as a constant text (without editable).
Prerequisites: You should be familiar with the basics of HTML, CSS, and JavaScript.
Creating structure: Create two files for HTML, and JavaScript. To create these files run the following command
Syntax: $ touch index.html app.js
$ touch index.html app.js
Step 1: Edit index.html. This file contains the following Code.HTMLHTML<!DOCTYPE html><html lang="en"> <body> <h1 style="color: green; text-align: center;"> Creating Editable Div GeeksforGeeks </h1> <div style="text-align: center; margin-left: 35%;" class="container"> <div id="first"></div> </div> </body> <script src="app.js"></script></html>
HTML
<!DOCTYPE html><html lang="en"> <body> <h1 style="color: green; text-align: center;"> Creating Editable Div GeeksforGeeks </h1> <div style="text-align: center; margin-left: 35%;" class="container"> <div id="first"></div> </div> </body> <script src="app.js"></script></html>
Step 2: Edit the app.js file. This file contains the following Code.JavascriptJavascript// Creating a new element let editableDiv = document.createElement('div'); // Adding text to that created element let value = localStorage.getItem('text'); let text; if (value == null){ text = document.createTextNode ('Click on it to edit this Editable Div');}else{ text = document.createTextNode(value);} editableDiv.appendChild(text);editableDiv.setAttribute('id', 'elem');editableDiv.setAttribute('class', 'elem');editableDiv.setAttribute('style','font-size:3rem;border:3px solid; width:350px;height:200px;'); // Access the main container let container = document.querySelector('.container'); // Inserting the element with id = first container.insertBefore(editableDiv, first); // Adding event listener to the divElem editableDiv.addEventListener('click',function (){ let lengthOfTextAreas = document.getElementsByClassName('textarea').length; if(lengthOfTextAreas == 0){ let html = elem.innerHTML; editableDiv.innerHTML = `<textarea class="textarea form-control" id="textarea" rows="3"> ${html}</textarea>`;} // Listening the blur event on textarea let textarea = document.getElementById('textarea'); textarea.addEventListener('blur',function() { elem.innerHTML = textarea.value; localStorage.setItem( 'text', textarea.value); })});Final Solution: This is the combination of the above two steps.HTMLHTML<!DOCTYPE html><html lang="en"> <body> <h1 style="color: green; text-align: center;"> Creating Editable Div GeeksforGeeks </h1> <div style="text-align: center; margin-left: 35%;" class="container"> <div id="first"></div> </div> </body> <script> // Creating a new element let editableDiv = document.createElement('div'); // Adding text to that created element let value = localStorage.getItem('text'); let text; if (value == null){ text = document.createTextNode ('Click on it to edit this Editable Div'); } else{ text = document.createTextNode(value); } editableDiv.appendChild(text); editableDiv.setAttribute('id', 'elem'); editableDiv.setAttribute('class', 'elem'); editableDiv.setAttribute('style', 'font-size:3rem;border:3px solid; width:350px;height:200px;'); // Access the main container let container = document.querySelector('.container'); // Inserting the element with id = first container.insertBefore(editableDiv, first); // Adding event listener to the divElem editableDiv.addEventListener('click',function (){ let lengthOfTextAreas = document.getElementsByClassName('textarea').length; if(lengthOfTextAreas == 0){ let html = elem.innerHTML; editableDiv.innerHTML = `<textarea class="textarea form-control" id="textarea" rows="3"> ${html}</textarea>`; } // Listening the blur event on textarea let textarea = document.getElementById('textarea'); textarea.addEventListener('blur',function() { elem.innerHTML = textarea.value; localStorage.setItem( 'text', textarea.value); }) }); </script> </html>Output: When you will open it on any browser then the following output would be generated.My Personal Notes
arrow_drop_upSave
Javascript
// Creating a new element let editableDiv = document.createElement('div'); // Adding text to that created element let value = localStorage.getItem('text'); let text; if (value == null){ text = document.createTextNode ('Click on it to edit this Editable Div');}else{ text = document.createTextNode(value);} editableDiv.appendChild(text);editableDiv.setAttribute('id', 'elem');editableDiv.setAttribute('class', 'elem');editableDiv.setAttribute('style','font-size:3rem;border:3px solid; width:350px;height:200px;'); // Access the main container let container = document.querySelector('.container'); // Inserting the element with id = first container.insertBefore(editableDiv, first); // Adding event listener to the divElem editableDiv.addEventListener('click',function (){ let lengthOfTextAreas = document.getElementsByClassName('textarea').length; if(lengthOfTextAreas == 0){ let html = elem.innerHTML; editableDiv.innerHTML = `<textarea class="textarea form-control" id="textarea" rows="3"> ${html}</textarea>`;} // Listening the blur event on textarea let textarea = document.getElementById('textarea'); textarea.addEventListener('blur',function() { elem.innerHTML = textarea.value; localStorage.setItem( 'text', textarea.value); })});
Final Solution: This is the combination of the above two steps.
HTML
<!DOCTYPE html><html lang="en"> <body> <h1 style="color: green; text-align: center;"> Creating Editable Div GeeksforGeeks </h1> <div style="text-align: center; margin-left: 35%;" class="container"> <div id="first"></div> </div> </body> <script> // Creating a new element let editableDiv = document.createElement('div'); // Adding text to that created element let value = localStorage.getItem('text'); let text; if (value == null){ text = document.createTextNode ('Click on it to edit this Editable Div'); } else{ text = document.createTextNode(value); } editableDiv.appendChild(text); editableDiv.setAttribute('id', 'elem'); editableDiv.setAttribute('class', 'elem'); editableDiv.setAttribute('style', 'font-size:3rem;border:3px solid; width:350px;height:200px;'); // Access the main container let container = document.querySelector('.container'); // Inserting the element with id = first container.insertBefore(editableDiv, first); // Adding event listener to the divElem editableDiv.addEventListener('click',function (){ let lengthOfTextAreas = document.getElementsByClassName('textarea').length; if(lengthOfTextAreas == 0){ let html = elem.innerHTML; editableDiv.innerHTML = `<textarea class="textarea form-control" id="textarea" rows="3"> ${html}</textarea>`; } // Listening the blur event on textarea let textarea = document.getElementById('textarea'); textarea.addEventListener('blur',function() { elem.innerHTML = textarea.value; localStorage.setItem( 'text', textarea.value); }) }); </script> </html>
Output: When you will open it on any browser then the following output would be generated.
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
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
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25324,
"s": 25296,
"text": "\n13 Oct, 2020"
},
{
"code": null,
"e": 25716,
"s": 25324,
"text": "In this article, we will be explaining to you how to create an editable div using HTML, CSS, and JavaScript. An editable div is one on which is you will click then it will generate an editable text area to edit or to write any text on your browser itself. After editing, when you click on somewhere else on your browser then that text will be displayed as a constant text (without editable)."
},
{
"code": null,
"e": 25800,
"s": 25716,
"text": "Prerequisites: You should be familiar with the basics of HTML, CSS, and JavaScript."
},
{
"code": null,
"e": 25911,
"s": 25800,
"text": "Creating structure: Create two files for HTML, and JavaScript. To create these files run the following command"
},
{
"code": null,
"e": 25945,
"s": 25911,
"text": "Syntax: $ touch index.html app.js"
},
{
"code": null,
"e": 25971,
"s": 25945,
"text": "$ touch index.html app.js"
},
{
"code": null,
"e": 26442,
"s": 25971,
"text": "Step 1: Edit index.html. This file contains the following Code.HTMLHTML<!DOCTYPE html><html lang=\"en\"> <body> <h1 style=\"color: green; text-align: center;\"> Creating Editable Div GeeksforGeeks </h1> <div style=\"text-align: center; margin-left: 35%;\" class=\"container\"> <div id=\"first\"></div> </div> </body> <script src=\"app.js\"></script></html>"
},
{
"code": null,
"e": 26447,
"s": 26442,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <body> <h1 style=\"color: green; text-align: center;\"> Creating Editable Div GeeksforGeeks </h1> <div style=\"text-align: center; margin-left: 35%;\" class=\"container\"> <div id=\"first\"></div> </div> </body> <script src=\"app.js\"></script></html>",
"e": 26847,
"s": 26447,
"text": null
},
{
"code": null,
"e": 30886,
"s": 26847,
"text": "Step 2: Edit the app.js file. This file contains the following Code.JavascriptJavascript// Creating a new element let editableDiv = document.createElement('div'); // Adding text to that created element let value = localStorage.getItem('text'); let text; if (value == null){ text = document.createTextNode ('Click on it to edit this Editable Div');}else{ text = document.createTextNode(value);} editableDiv.appendChild(text);editableDiv.setAttribute('id', 'elem');editableDiv.setAttribute('class', 'elem');editableDiv.setAttribute('style','font-size:3rem;border:3px solid; width:350px;height:200px;'); // Access the main container let container = document.querySelector('.container'); // Inserting the element with id = first container.insertBefore(editableDiv, first); // Adding event listener to the divElem editableDiv.addEventListener('click',function (){ let lengthOfTextAreas = document.getElementsByClassName('textarea').length; if(lengthOfTextAreas == 0){ let html = elem.innerHTML; editableDiv.innerHTML = `<textarea class=\"textarea form-control\" id=\"textarea\" rows=\"3\"> ${html}</textarea>`;} // Listening the blur event on textarea let textarea = document.getElementById('textarea'); textarea.addEventListener('blur',function() { elem.innerHTML = textarea.value; localStorage.setItem( 'text', textarea.value); })});Final Solution: This is the combination of the above two steps.HTMLHTML<!DOCTYPE html><html lang=\"en\"> <body> <h1 style=\"color: green; text-align: center;\"> Creating Editable Div GeeksforGeeks </h1> <div style=\"text-align: center; margin-left: 35%;\" class=\"container\"> <div id=\"first\"></div> </div> </body> <script> // Creating a new element let editableDiv = document.createElement('div'); // Adding text to that created element let value = localStorage.getItem('text'); let text; if (value == null){ text = document.createTextNode ('Click on it to edit this Editable Div'); } else{ text = document.createTextNode(value); } editableDiv.appendChild(text); editableDiv.setAttribute('id', 'elem'); editableDiv.setAttribute('class', 'elem'); editableDiv.setAttribute('style', 'font-size:3rem;border:3px solid; width:350px;height:200px;'); // Access the main container let container = document.querySelector('.container'); // Inserting the element with id = first container.insertBefore(editableDiv, first); // Adding event listener to the divElem editableDiv.addEventListener('click',function (){ let lengthOfTextAreas = document.getElementsByClassName('textarea').length; if(lengthOfTextAreas == 0){ let html = elem.innerHTML; editableDiv.innerHTML = `<textarea class=\"textarea form-control\" id=\"textarea\" rows=\"3\"> ${html}</textarea>`; } // Listening the blur event on textarea let textarea = document.getElementById('textarea'); textarea.addEventListener('blur',function() { elem.innerHTML = textarea.value; localStorage.setItem( 'text', textarea.value); }) }); </script> </html>Output: When you will open it on any browser then the following output would be generated.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 30897,
"s": 30886,
"text": "Javascript"
},
{
"code": "// Creating a new element let editableDiv = document.createElement('div'); // Adding text to that created element let value = localStorage.getItem('text'); let text; if (value == null){ text = document.createTextNode ('Click on it to edit this Editable Div');}else{ text = document.createTextNode(value);} editableDiv.appendChild(text);editableDiv.setAttribute('id', 'elem');editableDiv.setAttribute('class', 'elem');editableDiv.setAttribute('style','font-size:3rem;border:3px solid; width:350px;height:200px;'); // Access the main container let container = document.querySelector('.container'); // Inserting the element with id = first container.insertBefore(editableDiv, first); // Adding event listener to the divElem editableDiv.addEventListener('click',function (){ let lengthOfTextAreas = document.getElementsByClassName('textarea').length; if(lengthOfTextAreas == 0){ let html = elem.innerHTML; editableDiv.innerHTML = `<textarea class=\"textarea form-control\" id=\"textarea\" rows=\"3\"> ${html}</textarea>`;} // Listening the blur event on textarea let textarea = document.getElementById('textarea'); textarea.addEventListener('blur',function() { elem.innerHTML = textarea.value; localStorage.setItem( 'text', textarea.value); })});",
"e": 32227,
"s": 30897,
"text": null
},
{
"code": null,
"e": 32291,
"s": 32227,
"text": "Final Solution: This is the combination of the above two steps."
},
{
"code": null,
"e": 32296,
"s": 32291,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <body> <h1 style=\"color: green; text-align: center;\"> Creating Editable Div GeeksforGeeks </h1> <div style=\"text-align: center; margin-left: 35%;\" class=\"container\"> <div id=\"first\"></div> </div> </body> <script> // Creating a new element let editableDiv = document.createElement('div'); // Adding text to that created element let value = localStorage.getItem('text'); let text; if (value == null){ text = document.createTextNode ('Click on it to edit this Editable Div'); } else{ text = document.createTextNode(value); } editableDiv.appendChild(text); editableDiv.setAttribute('id', 'elem'); editableDiv.setAttribute('class', 'elem'); editableDiv.setAttribute('style', 'font-size:3rem;border:3px solid; width:350px;height:200px;'); // Access the main container let container = document.querySelector('.container'); // Inserting the element with id = first container.insertBefore(editableDiv, first); // Adding event listener to the divElem editableDiv.addEventListener('click',function (){ let lengthOfTextAreas = document.getElementsByClassName('textarea').length; if(lengthOfTextAreas == 0){ let html = elem.innerHTML; editableDiv.innerHTML = `<textarea class=\"textarea form-control\" id=\"textarea\" rows=\"3\"> ${html}</textarea>`; } // Listening the blur event on textarea let textarea = document.getElementById('textarea'); textarea.addEventListener('blur',function() { elem.innerHTML = textarea.value; localStorage.setItem( 'text', textarea.value); }) }); </script> </html>",
"e": 34721,
"s": 32296,
"text": null
},
{
"code": null,
"e": 34812,
"s": 34721,
"text": "Output: When you will open it on any browser then the following output would be generated."
},
{
"code": null,
"e": 34828,
"s": 34812,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 34839,
"s": 34828,
"text": "JavaScript"
},
{
"code": null,
"e": 34856,
"s": 34839,
"text": "Web Technologies"
},
{
"code": null,
"e": 34883,
"s": 34856,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 34981,
"s": 34883,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35042,
"s": 34981,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 35083,
"s": 35042,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 35123,
"s": 35083,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 35177,
"s": 35123,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 35225,
"s": 35177,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 35267,
"s": 35225,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 35300,
"s": 35267,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 35343,
"s": 35300,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 35405,
"s": 35343,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Count number of ways to partition a set into k subsets - GeeksforGeeks
|
13 Apr, 2021
Given two numbers n and k where n represents a number of elements in a set, find a number of ways to partition the set into k subsets.Example:
Input: n = 3, k = 2
Output: 3
Explanation: Let the set be {1, 2, 3}, we can partition
it into 2 subsets in following ways
{{1,2}, {3}}, {{1}, {2,3}}, {{1,3}, {2}}
Input: n = 3, k = 1
Output: 1
Explanation: There is only one way {{1, 2, 3}}
Recursive Solution
Approach: Firstly, let’s define a recursive solution to find the solution for nth element. There are two cases. The previous n – 1 elements are divided into k partitions, i.e S(n-1, k) ways. Put this nth element into one of the previous k partitions. So, count = k * S(n-1, k)The previous n – 1 elements are divided into k – 1 partitions, i.e S(n-1, k-1) ways. Put the nth element into a new partition ( single element partition).So, count = S(n-1, k-1)Total count = k * S(n-1, k) + S(n-1, k-1).
The previous n – 1 elements are divided into k partitions, i.e S(n-1, k) ways. Put this nth element into one of the previous k partitions. So, count = k * S(n-1, k)The previous n – 1 elements are divided into k – 1 partitions, i.e S(n-1, k-1) ways. Put the nth element into a new partition ( single element partition).So, count = S(n-1, k-1)Total count = k * S(n-1, k) + S(n-1, k-1).
The previous n – 1 elements are divided into k partitions, i.e S(n-1, k) ways. Put this nth element into one of the previous k partitions. So, count = k * S(n-1, k)
The previous n – 1 elements are divided into k – 1 partitions, i.e S(n-1, k-1) ways. Put the nth element into a new partition ( single element partition).So, count = S(n-1, k-1)
Total count = k * S(n-1, k) + S(n-1, k-1).
Algorithm: Create a recursive function which accepts two parameters, n and k. The function returns total number of partitions of n elements into k sets.Handle the base cases. If n = 0 or k = 0 or k > n return 0 as there cannot be any subset. If n is equal to k or k is equal to 1 return 1.Else calculate the value as follows: S(n, k) = k*S(n-1, k) + S(n-1, k-1), i.e call recursive function with the recuried parameter and calculate the value of S(n, k).Return the sum.
Create a recursive function which accepts two parameters, n and k. The function returns total number of partitions of n elements into k sets.Handle the base cases. If n = 0 or k = 0 or k > n return 0 as there cannot be any subset. If n is equal to k or k is equal to 1 return 1.Else calculate the value as follows: S(n, k) = k*S(n-1, k) + S(n-1, k-1), i.e call recursive function with the recuried parameter and calculate the value of S(n, k).Return the sum.
Create a recursive function which accepts two parameters, n and k. The function returns total number of partitions of n elements into k sets.
Handle the base cases. If n = 0 or k = 0 or k > n return 0 as there cannot be any subset. If n is equal to k or k is equal to 1 return 1.
Else calculate the value as follows: S(n, k) = k*S(n-1, k) + S(n-1, k-1), i.e call recursive function with the recuried parameter and calculate the value of S(n, k).
Return the sum.
Implementation:
C++
Java
Python 3
C#
PHP
Javascript
// A C++ program to count number of partitions// of a set with n elements into k subsets#include<iostream>using namespace std; // Returns count of different partitions of n// elements in k subsetsint countP(int n, int k){ // Base cases if (n == 0 || k == 0 || k > n) return 0; if (k == 1 || k == n) return 1; // S(n+1, k) = k*S(n, k) + S(n, k-1) return k*countP(n-1, k) + countP(n-1, k-1);} // Driver programint main(){ cout << countP(3, 2); return 0;}
// Java program to count number// of partitions of a set with// n elements into k subsetsimport java.io.*; class GFG{ // Returns count of different // partitions of n elements in // k subsets public static int countP(int n, int k) { // Base cases if (n == 0 || k == 0 || k > n) return 0; if (k == 1 || k == n) return 1; // S(n+1, k) = k*S(n, k) + S(n, k-1) return (k * countP(n - 1, k) + countP(n - 1, k - 1)); } // Driver program public static void main(String args[]) { System.out.println(countP(3, 2)); }} //This code is contributed by Anshika Goyal.
# A Python3 program to count number# of partitions of a set with n# elements into k subsets # Returns count of different partitions# of n elements in k subsetsdef countP(n, k): # Base cases if (n == 0 or k == 0 or k > n): return 0 if (k == 1 or k == n): return 1 # S(n+1, k) = k*S(n, k) + S(n, k-1) return (k * countP(n - 1, k) + countP(n - 1, k - 1)) # Driver Codeif __name__ == "__main__": print(countP(3, 2)) # This code is contributed# by Akanksha Rai(Abby_akku)
// C# program to count number// of partitions of a set with// n elements into k subsetsusing System; class GFG { // Returns count of different // partitions of n elements in // k subsets public static int countP(int n, int k) { // Base cases if (n == 0 || k == 0 || k > n) return 0; if (k == 1 || k == n) return 1; // S(n+1, k) = k*S(n, k) + S(n, k-1) return (k * countP(n - 1, k) + countP(n - 1, k - 1)); } // Driver program public static void Main() { Console.WriteLine(countP(3, 2)); }} // This code is contributed by anuj_67.
<?php// A PHP program to count// number of partitions of// a set with n elements// into k subsets // Returns count of different// partitions of n elements// in k subsetsfunction countP($n, $k){ // Base cases if ($n == 0 || $k == 0 || $k > $n) return 0; if ($k == 1 || $k == $n) return 1; // S(n+1, k) = k*S(n, k) // + S(n, k-1) return $k * countP($n - 1, $k) + countP($n - 1, $k - 1);} // Driver Code echo countP(3, 2); // This code is contributed by aj_36?>
<script>// Javascript program to count number// of partitions of a set with// n elements into k subsets // Returns count of different // partitions of n elements in // k subsets function countP(n, k) { // Base cases if (n == 0 || k == 0 || k > n) return 0; if (k == 1 || k == n) return 1; // S(n + 1, k) = k*S(n, k) + S(n, k - 1) return (k * countP(n - 1, k) + countP(n - 1, k - 1)); } // Driver program document.write(countP(3, 2)); // This code is contributed by avanitrachhadiya2155 </script>
Output:
3
Complexity Analysis: Time complexity: O(2^n). For every value of n, two recursive function is called. More specifically the Time complexity is exponential.Space complexity: O(n)(Due to call stack).
Time complexity: O(2^n). For every value of n, two recursive function is called. More specifically the Time complexity is exponential.
Space complexity: O(n)(Due to call stack).
Efficient Solution
Approach: The time complexity of above recursive solution is exponential. The solution can be optimized by reducing the overlapping subproblems. Below is recursion tree of countP(10,7). The subproblem countP(8,6) or CP(8,6) is called multiple times.
So this problem has both properties (see Type 1 and Type 2) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array dp[][] in bottom up manner using the shown recursive formula.Next comes the reduction of the sub-problems to optimize the complexity of the problem. This can be done in two ways: bottom-up manner: This keeps the recursive structure intact and stores the values in a hashmap or a 2D array. Then compute the value only once and when the function is called next return the value.top-down manner: This keeps a 2D array of size n*k, where dp[i][j] represents a total number of partitions of i elements into j sets. Fill in the base cases for dp[i][0] and dp[0][i]. For a value (i,j), the values of dp[i-1][j] and dp[i-1][j-1] is needed. So fill the DP from row 0 to n and column 0 to k.
bottom-up manner: This keeps the recursive structure intact and stores the values in a hashmap or a 2D array. Then compute the value only once and when the function is called next return the value.top-down manner: This keeps a 2D array of size n*k, where dp[i][j] represents a total number of partitions of i elements into j sets. Fill in the base cases for dp[i][0] and dp[0][i]. For a value (i,j), the values of dp[i-1][j] and dp[i-1][j-1] is needed. So fill the DP from row 0 to n and column 0 to k.
bottom-up manner: This keeps the recursive structure intact and stores the values in a hashmap or a 2D array. Then compute the value only once and when the function is called next return the value.
top-down manner: This keeps a 2D array of size n*k, where dp[i][j] represents a total number of partitions of i elements into j sets. Fill in the base cases for dp[i][0] and dp[0][i]. For a value (i,j), the values of dp[i-1][j] and dp[i-1][j-1] is needed. So fill the DP from row 0 to n and column 0 to k.
Algorithm: Create a Dp array dp[n+1][k+1] of size ( n + 1 )* ( k + 1 ) .Fill the values of basic cases. For all values of i from 0 to n fill dp[i][0] = 0 and for all values of i from 0 to k fill dp[0][k] = 0Run a nested loop, the outer loop from 1 to n, and inner loop from 1 to k.For index i and j (outer loop and inner loop respectively), calculate dp[i][j] = j * dp[i – 1][j] + dp[i – 1][j – 1] and if j == 1 or i == j, calculate dp[i][j] = 1.Print values dp[n][k]
Create a Dp array dp[n+1][k+1] of size ( n + 1 )* ( k + 1 ) .Fill the values of basic cases. For all values of i from 0 to n fill dp[i][0] = 0 and for all values of i from 0 to k fill dp[0][k] = 0Run a nested loop, the outer loop from 1 to n, and inner loop from 1 to k.For index i and j (outer loop and inner loop respectively), calculate dp[i][j] = j * dp[i – 1][j] + dp[i – 1][j – 1] and if j == 1 or i == j, calculate dp[i][j] = 1.Print values dp[n][k]
Create a Dp array dp[n+1][k+1] of size ( n + 1 )* ( k + 1 ) .
Fill the values of basic cases. For all values of i from 0 to n fill dp[i][0] = 0 and for all values of i from 0 to k fill dp[0][k] = 0
Run a nested loop, the outer loop from 1 to n, and inner loop from 1 to k.
For index i and j (outer loop and inner loop respectively), calculate dp[i][j] = j * dp[i – 1][j] + dp[i – 1][j – 1] and if j == 1 or i == j, calculate dp[i][j] = 1.
Print values dp[n][k]
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// A Dynamic Programming based C++ program to count// number of partitions of a set with n elements// into k subsets#include<iostream>using namespace std; // Returns count of different partitions of n// elements in k subsetsint countP(int n, int k){ // Table to store results of subproblems int dp[n+1][k+1]; // Base cases for (int i = 0; i <= n; i++) dp[i][0] = 0; for (int i = 0; i <= k; i++) dp[0][k] = 0; // Fill rest of the entries in dp[][] // in bottom up manner for (int i = 1; i <= n; i++) for (int j = 1; j <= i; j++) if (j == 1 || i == j) dp[i][j] = 1; else dp[i][j] = j * dp[i - 1][j] + dp[i - 1][j - 1]; return dp[n][k];} // Driver programint main(){ cout << countP(5, 2); return 0;}
// A Dynamic Programming based Java program to count// number of partitions of a set with n elements// into k subsetsclass GFG{ // Returns count of different partitions of n// elements in k subsetsstatic int countP(int n, int k){ // Table to store results of subproblems int[][] dp = new int[n+1][k+1]; // Base cases for (int i = 0; i <= n; i++) dp[i][0] = 0; for (int i = 0; i <= k; i++) dp[0][k] = 0; // Fill rest of the entries in dp[][] // in bottom up manner for (int i = 1; i <= n; i++) for (int j = 1; j <= k; j++) if (j == 1 || i == j) dp[i][j] = 1; else dp[i][j] = j * dp[i - 1][j] + dp[i - 1][j - 1]; return dp[n][k]; } // Driver programpublic static void main(String[] args ){ System.out.println(countP(5, 2));}} // This code is contributed by Rajput-Ji
# A Dynamic Programming based Python3 program# to count number of partitions of a set with# n elements into k subsets # Returns count of different partitions# of n elements in k subsetsdef countP(n, k): # Table to store results of subproblems dp = [[0 for i in range(k + 1)] for j in range(n + 1)] # Base cases for i in range(n + 1): dp[i][0] = 0 for i in range(k + 1): dp[0][k] = 0 # Fill rest of the entries in # dp[][] in bottom up manner for i in range(1, n + 1): for j in range(1, k + 1): if (j == 1 or i == j): dp[i][j] = 1 else: dp[i][j] = (j * dp[i - 1][j] + dp[i - 1][j - 1]) return dp[n][k] # Driver Codeif __name__ == '__main__': print(countP(5, 2)) # This code is contributed by# Surendra_Gangwar
// A Dynamic Programming based C# program // to count number of partitions of a // set with n elements into k subsetsusing System; class GFG{ // Returns count of different partitions of n// elements in k subsetsstatic int countP(int n, int k){ // Table to store results of subproblems int[,] dp = new int[n + 1, k + 1]; // Base cases for (int i = 0; i <= n; i++) dp[i, 0] = 0; for (int i = 0; i <= k; i++) dp[0, k] = 0; // Fill rest of the entries in dp[][] // in bottom up manner for (int i = 1; i <= n; i++) for (int j = 1; j <= k; j++) if (j == 1 || i == j) dp[i, j] = 1; else dp[i, j] = j * dp[i - 1, j] + dp[i - 1, j - 1]; return dp[n, k]; } // Driver codepublic static void Main( ){ Console.Write(countP(5, 2));}} // This code is contributed by Ita_c.
<?php// A Dynamic Programming based PHP// program to count number of// partitions of a set with n // elements into k subsets // Returns count of different// partitions of n elements in// k subsetsfunction countP($n, $k){ // Table to store results// of subproblems$dp[$n + 1][$k + 1] = array(array()); // Base casesfor ($i = 0; $i <= $n; $i++) $dp[$i][0] = 0;for ($i = 0; $i <= $k; $i++) $dp[0][$k] = 0; // Fill rest of the entries in// dp[][] in bottom up mannerfor ($i = 1; $i <= $n; $i++) for ($j = 1; $j <= $i; $j++) if ($j == 1 || $i == $j) $dp[$i][$j] = 1; else $dp[$i][$j] = $j * $dp[$i - 1][$j] + $dp[$i - 1][$j - 1]; return $dp[$n][$k];} // Driver Codeecho countP(5, 2); // This code is contributed by jit_t?>
<script>// A Dynamic Programming based Javascript program to count// number of partitions of a set with n elements// into k subsets // Returns count of different partitions of n // elements in k subsets function countP(n,k) { // Table to store results of subproblems let dp = new Array(n+1); for(let i = 0; i < n + 1; i++) { dp[i] = new Array(k+1); for(let j = 0; j < k + 1; j++) { dp[i][j] = -1; } } // Base cases for (let i = 0; i <= n; i++) dp[i][0] = 0; for (let i = 0; i <= k; i++) dp[0][k] = 0; // Fill rest of the entries in dp[][] // in bottom up manner for (let i = 1; i <= n; i++) for (let j = 1; j <= k; j++) if (j == 1 || i == j) dp[i][j] = 1; else dp[i][j] = j * dp[i - 1][j] + dp[i - 1][j - 1]; return dp[n][k]; } // Driver program document.write(countP(5, 2)) // This code is contributed by rag2127</script>
Output:
15
Complexity Analysis: Time complexity:O(n*k). The 2D dp array of size n*k is filled, so the time Complexity is O(n*k).Space complexity:O(n*k). An extra 2D DP array is required.
Time complexity:O(n*k). The 2D dp array of size n*k is filled, so the time Complexity is O(n*k).
Space complexity:O(n*k). An extra 2D DP array is required.
Similar Article: Bell Numbers This article is contributed by Rajeev Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
vt_m
Akanksha_Rai
Rajput-Ji
ukasp
SURENDRA_GANGWAR
andrew1234
almasashruffkhan
satyampd5340
avanitrachhadiya2155
rag2127
Modular Arithmetic
Dynamic Programming
Recursion
Dynamic Programming
Recursion
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Sieve of Eratosthenes
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Program for Tower of Hanoi
Recursion
Program for Sum of the digits of a given number
|
[
{
"code": null,
"e": 24702,
"s": 24674,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 24846,
"s": 24702,
"text": "Given two numbers n and k where n represents a number of elements in a set, find a number of ways to partition the set into k subsets.Example: "
},
{
"code": null,
"e": 25117,
"s": 24846,
"text": "Input: n = 3, k = 2\nOutput: 3\nExplanation: Let the set be {1, 2, 3}, we can partition\n it into 2 subsets in following ways\n {{1,2}, {3}}, {{1}, {2,3}}, {{1,3}, {2}} \n\nInput: n = 3, k = 1\nOutput: 1\nExplanation: There is only one way {{1, 2, 3}}"
},
{
"code": null,
"e": 25136,
"s": 25117,
"text": "Recursive Solution"
},
{
"code": null,
"e": 25632,
"s": 25136,
"text": "Approach: Firstly, let’s define a recursive solution to find the solution for nth element. There are two cases. The previous n – 1 elements are divided into k partitions, i.e S(n-1, k) ways. Put this nth element into one of the previous k partitions. So, count = k * S(n-1, k)The previous n – 1 elements are divided into k – 1 partitions, i.e S(n-1, k-1) ways. Put the nth element into a new partition ( single element partition).So, count = S(n-1, k-1)Total count = k * S(n-1, k) + S(n-1, k-1)."
},
{
"code": null,
"e": 26016,
"s": 25632,
"text": "The previous n – 1 elements are divided into k partitions, i.e S(n-1, k) ways. Put this nth element into one of the previous k partitions. So, count = k * S(n-1, k)The previous n – 1 elements are divided into k – 1 partitions, i.e S(n-1, k-1) ways. Put the nth element into a new partition ( single element partition).So, count = S(n-1, k-1)Total count = k * S(n-1, k) + S(n-1, k-1)."
},
{
"code": null,
"e": 26181,
"s": 26016,
"text": "The previous n – 1 elements are divided into k partitions, i.e S(n-1, k) ways. Put this nth element into one of the previous k partitions. So, count = k * S(n-1, k)"
},
{
"code": null,
"e": 26359,
"s": 26181,
"text": "The previous n – 1 elements are divided into k – 1 partitions, i.e S(n-1, k-1) ways. Put the nth element into a new partition ( single element partition).So, count = S(n-1, k-1)"
},
{
"code": null,
"e": 26402,
"s": 26359,
"text": "Total count = k * S(n-1, k) + S(n-1, k-1)."
},
{
"code": null,
"e": 26872,
"s": 26402,
"text": "Algorithm: Create a recursive function which accepts two parameters, n and k. The function returns total number of partitions of n elements into k sets.Handle the base cases. If n = 0 or k = 0 or k > n return 0 as there cannot be any subset. If n is equal to k or k is equal to 1 return 1.Else calculate the value as follows: S(n, k) = k*S(n-1, k) + S(n-1, k-1), i.e call recursive function with the recuried parameter and calculate the value of S(n, k).Return the sum."
},
{
"code": null,
"e": 27331,
"s": 26872,
"text": "Create a recursive function which accepts two parameters, n and k. The function returns total number of partitions of n elements into k sets.Handle the base cases. If n = 0 or k = 0 or k > n return 0 as there cannot be any subset. If n is equal to k or k is equal to 1 return 1.Else calculate the value as follows: S(n, k) = k*S(n-1, k) + S(n-1, k-1), i.e call recursive function with the recuried parameter and calculate the value of S(n, k).Return the sum."
},
{
"code": null,
"e": 27473,
"s": 27331,
"text": "Create a recursive function which accepts two parameters, n and k. The function returns total number of partitions of n elements into k sets."
},
{
"code": null,
"e": 27611,
"s": 27473,
"text": "Handle the base cases. If n = 0 or k = 0 or k > n return 0 as there cannot be any subset. If n is equal to k or k is equal to 1 return 1."
},
{
"code": null,
"e": 27777,
"s": 27611,
"text": "Else calculate the value as follows: S(n, k) = k*S(n-1, k) + S(n-1, k-1), i.e call recursive function with the recuried parameter and calculate the value of S(n, k)."
},
{
"code": null,
"e": 27793,
"s": 27777,
"text": "Return the sum."
},
{
"code": null,
"e": 27809,
"s": 27793,
"text": "Implementation:"
},
{
"code": null,
"e": 27813,
"s": 27809,
"text": "C++"
},
{
"code": null,
"e": 27818,
"s": 27813,
"text": "Java"
},
{
"code": null,
"e": 27827,
"s": 27818,
"text": "Python 3"
},
{
"code": null,
"e": 27830,
"s": 27827,
"text": "C#"
},
{
"code": null,
"e": 27834,
"s": 27830,
"text": "PHP"
},
{
"code": null,
"e": 27845,
"s": 27834,
"text": "Javascript"
},
{
"code": "// A C++ program to count number of partitions// of a set with n elements into k subsets#include<iostream>using namespace std; // Returns count of different partitions of n// elements in k subsetsint countP(int n, int k){ // Base cases if (n == 0 || k == 0 || k > n) return 0; if (k == 1 || k == n) return 1; // S(n+1, k) = k*S(n, k) + S(n, k-1) return k*countP(n-1, k) + countP(n-1, k-1);} // Driver programint main(){ cout << countP(3, 2); return 0;}",
"e": 28319,
"s": 27845,
"text": null
},
{
"code": "// Java program to count number// of partitions of a set with// n elements into k subsetsimport java.io.*; class GFG{ // Returns count of different // partitions of n elements in // k subsets public static int countP(int n, int k) { // Base cases if (n == 0 || k == 0 || k > n) return 0; if (k == 1 || k == n) return 1; // S(n+1, k) = k*S(n, k) + S(n, k-1) return (k * countP(n - 1, k) + countP(n - 1, k - 1)); } // Driver program public static void main(String args[]) { System.out.println(countP(3, 2)); }} //This code is contributed by Anshika Goyal.",
"e": 28974,
"s": 28319,
"text": null
},
{
"code": "# A Python3 program to count number# of partitions of a set with n# elements into k subsets # Returns count of different partitions# of n elements in k subsetsdef countP(n, k): # Base cases if (n == 0 or k == 0 or k > n): return 0 if (k == 1 or k == n): return 1 # S(n+1, k) = k*S(n, k) + S(n, k-1) return (k * countP(n - 1, k) + countP(n - 1, k - 1)) # Driver Codeif __name__ == \"__main__\": print(countP(3, 2)) # This code is contributed# by Akanksha Rai(Abby_akku)",
"e": 29498,
"s": 28974,
"text": null
},
{
"code": "// C# program to count number// of partitions of a set with// n elements into k subsetsusing System; class GFG { // Returns count of different // partitions of n elements in // k subsets public static int countP(int n, int k) { // Base cases if (n == 0 || k == 0 || k > n) return 0; if (k == 1 || k == n) return 1; // S(n+1, k) = k*S(n, k) + S(n, k-1) return (k * countP(n - 1, k) + countP(n - 1, k - 1)); } // Driver program public static void Main() { Console.WriteLine(countP(3, 2)); }} // This code is contributed by anuj_67.",
"e": 30157,
"s": 29498,
"text": null
},
{
"code": "<?php// A PHP program to count// number of partitions of// a set with n elements// into k subsets // Returns count of different// partitions of n elements// in k subsetsfunction countP($n, $k){ // Base cases if ($n == 0 || $k == 0 || $k > $n) return 0; if ($k == 1 || $k == $n) return 1; // S(n+1, k) = k*S(n, k) // + S(n, k-1) return $k * countP($n - 1, $k) + countP($n - 1, $k - 1);} // Driver Code echo countP(3, 2); // This code is contributed by aj_36?>",
"e": 30671,
"s": 30157,
"text": null
},
{
"code": "<script>// Javascript program to count number// of partitions of a set with// n elements into k subsets // Returns count of different // partitions of n elements in // k subsets function countP(n, k) { // Base cases if (n == 0 || k == 0 || k > n) return 0; if (k == 1 || k == n) return 1; // S(n + 1, k) = k*S(n, k) + S(n, k - 1) return (k * countP(n - 1, k) + countP(n - 1, k - 1)); } // Driver program document.write(countP(3, 2)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 31281,
"s": 30671,
"text": null
},
{
"code": null,
"e": 31289,
"s": 31281,
"text": "Output:"
},
{
"code": null,
"e": 31291,
"s": 31289,
"text": "3"
},
{
"code": null,
"e": 31491,
"s": 31291,
"text": "Complexity Analysis: Time complexity: O(2^n). For every value of n, two recursive function is called. More specifically the Time complexity is exponential.Space complexity: O(n)(Due to call stack). "
},
{
"code": null,
"e": 31626,
"s": 31491,
"text": "Time complexity: O(2^n). For every value of n, two recursive function is called. More specifically the Time complexity is exponential."
},
{
"code": null,
"e": 31671,
"s": 31626,
"text": "Space complexity: O(n)(Due to call stack). "
},
{
"code": null,
"e": 31692,
"s": 31671,
"text": "Efficient Solution "
},
{
"code": null,
"e": 31942,
"s": 31692,
"text": "Approach: The time complexity of above recursive solution is exponential. The solution can be optimized by reducing the overlapping subproblems. Below is recursion tree of countP(10,7). The subproblem countP(8,6) or CP(8,6) is called multiple times."
},
{
"code": null,
"e": 32855,
"s": 31942,
"text": "So this problem has both properties (see Type 1 and Type 2) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array dp[][] in bottom up manner using the shown recursive formula.Next comes the reduction of the sub-problems to optimize the complexity of the problem. This can be done in two ways: bottom-up manner: This keeps the recursive structure intact and stores the values in a hashmap or a 2D array. Then compute the value only once and when the function is called next return the value.top-down manner: This keeps a 2D array of size n*k, where dp[i][j] represents a total number of partitions of i elements into j sets. Fill in the base cases for dp[i][0] and dp[0][i]. For a value (i,j), the values of dp[i-1][j] and dp[i-1][j-1] is needed. So fill the DP from row 0 to n and column 0 to k."
},
{
"code": null,
"e": 33358,
"s": 32855,
"text": "bottom-up manner: This keeps the recursive structure intact and stores the values in a hashmap or a 2D array. Then compute the value only once and when the function is called next return the value.top-down manner: This keeps a 2D array of size n*k, where dp[i][j] represents a total number of partitions of i elements into j sets. Fill in the base cases for dp[i][0] and dp[0][i]. For a value (i,j), the values of dp[i-1][j] and dp[i-1][j-1] is needed. So fill the DP from row 0 to n and column 0 to k."
},
{
"code": null,
"e": 33556,
"s": 33358,
"text": "bottom-up manner: This keeps the recursive structure intact and stores the values in a hashmap or a 2D array. Then compute the value only once and when the function is called next return the value."
},
{
"code": null,
"e": 33862,
"s": 33556,
"text": "top-down manner: This keeps a 2D array of size n*k, where dp[i][j] represents a total number of partitions of i elements into j sets. Fill in the base cases for dp[i][0] and dp[0][i]. For a value (i,j), the values of dp[i-1][j] and dp[i-1][j-1] is needed. So fill the DP from row 0 to n and column 0 to k."
},
{
"code": null,
"e": 34330,
"s": 33862,
"text": "Algorithm: Create a Dp array dp[n+1][k+1] of size ( n + 1 )* ( k + 1 ) .Fill the values of basic cases. For all values of i from 0 to n fill dp[i][0] = 0 and for all values of i from 0 to k fill dp[0][k] = 0Run a nested loop, the outer loop from 1 to n, and inner loop from 1 to k.For index i and j (outer loop and inner loop respectively), calculate dp[i][j] = j * dp[i – 1][j] + dp[i – 1][j – 1] and if j == 1 or i == j, calculate dp[i][j] = 1.Print values dp[n][k]"
},
{
"code": null,
"e": 34787,
"s": 34330,
"text": "Create a Dp array dp[n+1][k+1] of size ( n + 1 )* ( k + 1 ) .Fill the values of basic cases. For all values of i from 0 to n fill dp[i][0] = 0 and for all values of i from 0 to k fill dp[0][k] = 0Run a nested loop, the outer loop from 1 to n, and inner loop from 1 to k.For index i and j (outer loop and inner loop respectively), calculate dp[i][j] = j * dp[i – 1][j] + dp[i – 1][j – 1] and if j == 1 or i == j, calculate dp[i][j] = 1.Print values dp[n][k]"
},
{
"code": null,
"e": 34849,
"s": 34787,
"text": "Create a Dp array dp[n+1][k+1] of size ( n + 1 )* ( k + 1 ) ."
},
{
"code": null,
"e": 34985,
"s": 34849,
"text": "Fill the values of basic cases. For all values of i from 0 to n fill dp[i][0] = 0 and for all values of i from 0 to k fill dp[0][k] = 0"
},
{
"code": null,
"e": 35060,
"s": 34985,
"text": "Run a nested loop, the outer loop from 1 to n, and inner loop from 1 to k."
},
{
"code": null,
"e": 35226,
"s": 35060,
"text": "For index i and j (outer loop and inner loop respectively), calculate dp[i][j] = j * dp[i – 1][j] + dp[i – 1][j – 1] and if j == 1 or i == j, calculate dp[i][j] = 1."
},
{
"code": null,
"e": 35248,
"s": 35226,
"text": "Print values dp[n][k]"
},
{
"code": null,
"e": 35264,
"s": 35248,
"text": "Implementation:"
},
{
"code": null,
"e": 35268,
"s": 35264,
"text": "C++"
},
{
"code": null,
"e": 35273,
"s": 35268,
"text": "Java"
},
{
"code": null,
"e": 35281,
"s": 35273,
"text": "Python3"
},
{
"code": null,
"e": 35284,
"s": 35281,
"text": "C#"
},
{
"code": null,
"e": 35288,
"s": 35284,
"text": "PHP"
},
{
"code": null,
"e": 35299,
"s": 35288,
"text": "Javascript"
},
{
"code": "// A Dynamic Programming based C++ program to count// number of partitions of a set with n elements// into k subsets#include<iostream>using namespace std; // Returns count of different partitions of n// elements in k subsetsint countP(int n, int k){ // Table to store results of subproblems int dp[n+1][k+1]; // Base cases for (int i = 0; i <= n; i++) dp[i][0] = 0; for (int i = 0; i <= k; i++) dp[0][k] = 0; // Fill rest of the entries in dp[][] // in bottom up manner for (int i = 1; i <= n; i++) for (int j = 1; j <= i; j++) if (j == 1 || i == j) dp[i][j] = 1; else dp[i][j] = j * dp[i - 1][j] + dp[i - 1][j - 1]; return dp[n][k];} // Driver programint main(){ cout << countP(5, 2); return 0;}",
"e": 36055,
"s": 35299,
"text": null
},
{
"code": "// A Dynamic Programming based Java program to count// number of partitions of a set with n elements// into k subsetsclass GFG{ // Returns count of different partitions of n// elements in k subsetsstatic int countP(int n, int k){ // Table to store results of subproblems int[][] dp = new int[n+1][k+1]; // Base cases for (int i = 0; i <= n; i++) dp[i][0] = 0; for (int i = 0; i <= k; i++) dp[0][k] = 0; // Fill rest of the entries in dp[][] // in bottom up manner for (int i = 1; i <= n; i++) for (int j = 1; j <= k; j++) if (j == 1 || i == j) dp[i][j] = 1; else dp[i][j] = j * dp[i - 1][j] + dp[i - 1][j - 1]; return dp[n][k]; } // Driver programpublic static void main(String[] args ){ System.out.println(countP(5, 2));}} // This code is contributed by Rajput-Ji",
"e": 36906,
"s": 36055,
"text": null
},
{
"code": "# A Dynamic Programming based Python3 program# to count number of partitions of a set with# n elements into k subsets # Returns count of different partitions# of n elements in k subsetsdef countP(n, k): # Table to store results of subproblems dp = [[0 for i in range(k + 1)] for j in range(n + 1)] # Base cases for i in range(n + 1): dp[i][0] = 0 for i in range(k + 1): dp[0][k] = 0 # Fill rest of the entries in # dp[][] in bottom up manner for i in range(1, n + 1): for j in range(1, k + 1): if (j == 1 or i == j): dp[i][j] = 1 else: dp[i][j] = (j * dp[i - 1][j] + dp[i - 1][j - 1]) return dp[n][k] # Driver Codeif __name__ == '__main__': print(countP(5, 2)) # This code is contributed by# Surendra_Gangwar",
"e": 37786,
"s": 36906,
"text": null
},
{
"code": "// A Dynamic Programming based C# program // to count number of partitions of a // set with n elements into k subsetsusing System; class GFG{ // Returns count of different partitions of n// elements in k subsetsstatic int countP(int n, int k){ // Table to store results of subproblems int[,] dp = new int[n + 1, k + 1]; // Base cases for (int i = 0; i <= n; i++) dp[i, 0] = 0; for (int i = 0; i <= k; i++) dp[0, k] = 0; // Fill rest of the entries in dp[][] // in bottom up manner for (int i = 1; i <= n; i++) for (int j = 1; j <= k; j++) if (j == 1 || i == j) dp[i, j] = 1; else dp[i, j] = j * dp[i - 1, j] + dp[i - 1, j - 1]; return dp[n, k]; } // Driver codepublic static void Main( ){ Console.Write(countP(5, 2));}} // This code is contributed by Ita_c.",
"e": 38678,
"s": 37786,
"text": null
},
{
"code": "<?php// A Dynamic Programming based PHP// program to count number of// partitions of a set with n // elements into k subsets // Returns count of different// partitions of n elements in// k subsetsfunction countP($n, $k){ // Table to store results// of subproblems$dp[$n + 1][$k + 1] = array(array()); // Base casesfor ($i = 0; $i <= $n; $i++) $dp[$i][0] = 0;for ($i = 0; $i <= $k; $i++) $dp[0][$k] = 0; // Fill rest of the entries in// dp[][] in bottom up mannerfor ($i = 1; $i <= $n; $i++) for ($j = 1; $j <= $i; $j++) if ($j == 1 || $i == $j) $dp[$i][$j] = 1; else $dp[$i][$j] = $j * $dp[$i - 1][$j] + $dp[$i - 1][$j - 1]; return $dp[$n][$k];} // Driver Codeecho countP(5, 2); // This code is contributed by jit_t?>",
"e": 39455,
"s": 38678,
"text": null
},
{
"code": "<script>// A Dynamic Programming based Javascript program to count// number of partitions of a set with n elements// into k subsets // Returns count of different partitions of n // elements in k subsets function countP(n,k) { // Table to store results of subproblems let dp = new Array(n+1); for(let i = 0; i < n + 1; i++) { dp[i] = new Array(k+1); for(let j = 0; j < k + 1; j++) { dp[i][j] = -1; } } // Base cases for (let i = 0; i <= n; i++) dp[i][0] = 0; for (let i = 0; i <= k; i++) dp[0][k] = 0; // Fill rest of the entries in dp[][] // in bottom up manner for (let i = 1; i <= n; i++) for (let j = 1; j <= k; j++) if (j == 1 || i == j) dp[i][j] = 1; else dp[i][j] = j * dp[i - 1][j] + dp[i - 1][j - 1]; return dp[n][k]; } // Driver program document.write(countP(5, 2)) // This code is contributed by rag2127</script>",
"e": 40588,
"s": 39455,
"text": null
},
{
"code": null,
"e": 40596,
"s": 40588,
"text": "Output:"
},
{
"code": null,
"e": 40599,
"s": 40596,
"text": "15"
},
{
"code": null,
"e": 40775,
"s": 40599,
"text": "Complexity Analysis: Time complexity:O(n*k). The 2D dp array of size n*k is filled, so the time Complexity is O(n*k).Space complexity:O(n*k). An extra 2D DP array is required."
},
{
"code": null,
"e": 40872,
"s": 40775,
"text": "Time complexity:O(n*k). The 2D dp array of size n*k is filled, so the time Complexity is O(n*k)."
},
{
"code": null,
"e": 40931,
"s": 40872,
"text": "Space complexity:O(n*k). An extra 2D DP array is required."
},
{
"code": null,
"e": 41133,
"s": 40931,
"text": "Similar Article: Bell Numbers This article is contributed by Rajeev Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 41139,
"s": 41133,
"text": "jit_t"
},
{
"code": null,
"e": 41144,
"s": 41139,
"text": "vt_m"
},
{
"code": null,
"e": 41157,
"s": 41144,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 41167,
"s": 41157,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 41173,
"s": 41167,
"text": "ukasp"
},
{
"code": null,
"e": 41190,
"s": 41173,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 41201,
"s": 41190,
"text": "andrew1234"
},
{
"code": null,
"e": 41218,
"s": 41201,
"text": "almasashruffkhan"
},
{
"code": null,
"e": 41231,
"s": 41218,
"text": "satyampd5340"
},
{
"code": null,
"e": 41252,
"s": 41231,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 41260,
"s": 41252,
"text": "rag2127"
},
{
"code": null,
"e": 41279,
"s": 41260,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 41299,
"s": 41279,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 41309,
"s": 41299,
"text": "Recursion"
},
{
"code": null,
"e": 41329,
"s": 41309,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 41339,
"s": 41329,
"text": "Recursion"
},
{
"code": null,
"e": 41358,
"s": 41339,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 41456,
"s": 41358,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41487,
"s": 41456,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 41520,
"s": 41487,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 41555,
"s": 41520,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 41623,
"s": 41555,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 41645,
"s": 41623,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 41705,
"s": 41645,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 41790,
"s": 41705,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 41817,
"s": 41790,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 41827,
"s": 41817,
"text": "Recursion"
}
] |
How to write an image file in external storage with runtime permission in android?
|
This example demonstrates How to write an image file in external storage with runtime permission in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<Button
android:id = "@+id/save"
android:text = "save"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken a button. When user click on button, it will store data in external storage.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 100;
Button save;
Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Drawable drawable = getResources().getDrawable(R.drawable.mario);
bitmap = ((BitmapDrawable)drawable).getBitmap();
save = findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
if (Build.VERSION.SDK_INT > = 23) {
if (checkPermission()) {
String path = Environment.getExternalStorageDirectory().toString();
File file = new File(path, "UniqueFileName"+".jpg");
if (!file.exists()) {
Log.d("path", file.toString());
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
requestPermission(); // Code for permission
}
} else {
String path = Environment.getExternalStorageDirectory().toString();
File file = new File(path, "UniqueFileName"+".jpg");
if (!file.exists()) {
Log.d("path", file.toString());
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
}
}
});
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result = = PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Write External Storage permission allows us to save files. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] = = PackageManager.PERMISSION_GRANTED) {
Log.e("value", "Permission Granted, Now you can use local drive .");
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
break;
}
}
}
Step 4 − Add the following code to manifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.andy.myapplication">
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE"/>
<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 –
In the above result, click on save button to store image in external storage as shown below –
Click here to download the project code
|
[
{
"code": null,
"e": 1171,
"s": 1062,
"text": "This example demonstrates How to write an image file in external storage with runtime permission in android."
},
{
"code": null,
"e": 1300,
"s": 1171,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1365,
"s": 1300,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1868,
"s": 1365,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <Button\n android:id = \"@+id/save\"\n android:text = \"save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1978,
"s": 1868,
"text": "In the above code, we have taken a button. When user click on button, it will store data in external storage."
},
{
"code": null,
"e": 2035,
"s": 1978,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 6475,
"s": 2035,
"text": "package com.example.andy.myapplication;\n\nimport android.annotation.TargetApi;\nimport android.content.pm.PackageManager;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.graphics.drawable.Drawable;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.support.annotation.NonNull;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v4.content.ContextCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport android.widget.Toast;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\n\npublic class MainActivity extends AppCompatActivity {\n private static final int PERMISSION_REQUEST_CODE = 100;\n Button save;\n Bitmap bitmap;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Drawable drawable = getResources().getDrawable(R.drawable.mario);\n bitmap = ((BitmapDrawable)drawable).getBitmap();\n save = findViewById(R.id.save);\n save.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String state = Environment.getExternalStorageState();\n if (Environment.MEDIA_MOUNTED.equals(state)) {\n if (Build.VERSION.SDK_INT > = 23) {\n if (checkPermission()) {\n String path = Environment.getExternalStorageDirectory().toString();\n File file = new File(path, \"UniqueFileName\"+\".jpg\");\n if (!file.exists()) {\n Log.d(\"path\", file.toString());\n try {\n FileOutputStream fos = new FileOutputStream(file);\n bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);\n fos.flush();\n fos.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n } else {\n requestPermission(); // Code for permission\n }\n } else {\n String path = Environment.getExternalStorageDirectory().toString();\n File file = new File(path, \"UniqueFileName\"+\".jpg\");\n if (!file.exists()) {\n Log.d(\"path\", file.toString());\n FileOutputStream fos = null;\n try {\n fos = new FileOutputStream(file);\n bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);\n fos.flush();\n fos.close();\n } catch (java.io.IOException e) {\n e.printStackTrace();\n }\n }\n }\n }\n }\n });\n }\n \n private boolean checkPermission() {\n int result = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);\n if (result = = PackageManager.PERMISSION_GRANTED) {\n return true;\n } else {\n return false;\n }\n }\n\n private void requestPermission() {\n if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {\n Toast.makeText(MainActivity.this, \"Write External Storage permission allows us to save files. Please allow this permission in App Settings.\", Toast.LENGTH_LONG).show();\n } else {\n ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);\n }\n }\n\n @Override\n public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {\n switch (requestCode) {\n case PERMISSION_REQUEST_CODE:\n if (grantResults.length > 0 && grantResults[0] = = PackageManager.PERMISSION_GRANTED) {\n Log.e(\"value\", \"Permission Granted, Now you can use local drive .\");\n } else {\n Log.e(\"value\", \"Permission Denied, You cannot use local drive .\");\n }\n break;\n }\n }\n}"
},
{
"code": null,
"e": 6523,
"s": 6475,
"text": "Step 4 − Add the following code to manifest.xml"
},
{
"code": null,
"e": 7398,
"s": 6523,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n <uses-permission android:name = \"android.permission.WRITE_EXTERNAL_STORAGE\"/>\n <uses-permission android:name = \"android.permission.READ_EXTERNAL_STORAGE\"/>\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": 7745,
"s": 7398,
"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": 7839,
"s": 7745,
"text": "In the above result, click on save button to store image in external storage as shown below –"
},
{
"code": null,
"e": 7879,
"s": 7839,
"text": "Click here to download the project code"
}
] |
Convert Integer to Hex String in Java
|
The Integer.toHexString() method in Java converts Integer to hex string.
Let’s say the following are our integer values.
int val1 = 5;
int val2 = 7;
int val3 = 13;
Convert the above int values to hex string.
Integer.toHexString(val1);
Integer.toHexString(val2);
Integer.toHexString(val3);
Live Demo
public class Demo {
public static void main(String[] args) {
int val1 = 5;
int val2 = 7;
int val3 = 13;
int val4 = 23;
int val5 = 30;
System.out.println("Converting integer "+val1+" to Hex String: "+Integer.toHexString(val1));
System.out.println("Converting integer "+val2+" to Hex String: "+Integer.toHexString(val2));
System.out.println("Converting integer "+val3+" to Hex String: "+Integer.toHexString(val3));
System.out.println("Converting integer "+val4+" to Hex String: "+Integer.toHexString(val4));
System.out.println("Converting integer "+val5+" to Hex String: "+Integer.toHexString(val5));
}
}
Converting integer 5 to Hex String: 5
Converting integer 7 to Hex String: 7
Converting integer 13 to Hex String: d
Converting integer 23 to Hex String: 17
Converting integer 30 to Hex String: 1e
|
[
{
"code": null,
"e": 1135,
"s": 1062,
"text": "The Integer.toHexString() method in Java converts Integer to hex string."
},
{
"code": null,
"e": 1183,
"s": 1135,
"text": "Let’s say the following are our integer values."
},
{
"code": null,
"e": 1226,
"s": 1183,
"text": "int val1 = 5;\nint val2 = 7;\nint val3 = 13;"
},
{
"code": null,
"e": 1270,
"s": 1226,
"text": "Convert the above int values to hex string."
},
{
"code": null,
"e": 1351,
"s": 1270,
"text": "Integer.toHexString(val1);\nInteger.toHexString(val2);\nInteger.toHexString(val3);"
},
{
"code": null,
"e": 1362,
"s": 1351,
"text": " Live Demo"
},
{
"code": null,
"e": 2031,
"s": 1362,
"text": "public class Demo {\n public static void main(String[] args) {\n int val1 = 5;\n int val2 = 7;\n int val3 = 13;\n int val4 = 23;\n int val5 = 30;\n System.out.println(\"Converting integer \"+val1+\" to Hex String: \"+Integer.toHexString(val1));\n System.out.println(\"Converting integer \"+val2+\" to Hex String: \"+Integer.toHexString(val2));\n System.out.println(\"Converting integer \"+val3+\" to Hex String: \"+Integer.toHexString(val3));\n System.out.println(\"Converting integer \"+val4+\" to Hex String: \"+Integer.toHexString(val4));\n System.out.println(\"Converting integer \"+val5+\" to Hex String: \"+Integer.toHexString(val5));\n }\n}"
},
{
"code": null,
"e": 2226,
"s": 2031,
"text": "Converting integer 5 to Hex String: 5\nConverting integer 7 to Hex String: 7\nConverting integer 13 to Hex String: d\nConverting integer 23 to Hex String: 17\nConverting integer 30 to Hex String: 1e"
}
] |
Find a Fixed Point (Value equal to index) in a given array | Duplicates Allowed - GeeksforGeeks
|
17 Nov, 2021
Given an array of n integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in array can be negative. Examples:
Input: arr[] = {-10, -5, 0, 3, 7}
Output: 3 // arr[3] == 3
Input: arr[] = {-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13}
Output: 2 // arr[2] == 2
Input: arr[] = {-10, -5, 3, 4, 7, 9}
Output: -1 // No Fixed Point
We have a solution to find fixed point in an array of distinct elements. In this post, solution for array with duplicate values is discussed.Consider the arr[] = {-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13}, arr[mid] = 3If elements are not distinct, then we see arr[mid] < mid, we cannot conclude which side the fixed is on. It could be on left side or on the right side.We know for sure that since arr[5] = 3, arr[4] couldn’t be magic index because arr[4] must be less than or equal to arr[5] (the array is Sorted).So, the general pattern of our search would be:
Left Side: start = start, end = min(arr[midIndex], midIndex-1)
Right Side: start = max(arr[midIndex], midIndex+1), end = end
Below is the code for above Algorithm.
C++
Java
Python 3
C#
PHP
Javascript
// CPP Program to find magic index.#include <bits/stdc++.h>using namespace std; int magicIndex(int* arr, int start, int end){ // If No Magic Index return -1; if (start > end) return -1; int midIndex = (start + end) / 2; int midValue = arr[midIndex]; // Magic Index Found, return it. if (midIndex == midValue) return midIndex; // Search on Left side int left = magicIndex(arr, start, min(midValue, midIndex - 1)); // If Found on left side, return. if (left >= 0) return left; // Return ans from right side. return magicIndex(arr, max(midValue, midIndex + 1), end);} // Driver programint main(){ int arr[] = { -10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13 }; int n = sizeof(arr) / sizeof(arr[0]); int index = magicIndex(arr, 0, n - 1); if (index == -1) cout << "No Magic Index"; else cout << "Magic Index is : " << index; return 0;}
// Java Program to find magic index. class GFG { static int magicIndex(int arr[], int start, int end) { // If No Magic Index return -1; if (start > end) return -1; int midIndex = (start + end) / 2; int midValue = arr[midIndex]; // Magic Index Found, return it. if (midIndex == midValue) return midIndex; // Search on Left side int left = magicIndex(arr, start, Math.min(midValue, midIndex - 1)); // If Found on left side, return. if (left >= 0) return left; // Return ans from right side. return magicIndex(arr, Math.max(midValue, midIndex + 1),end); } // Driver code public static void main (String[] args) { int arr[] = { -10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13 }; int n = arr.length; int index = magicIndex(arr, 0, n - 1); if (index == -1) System.out.print("No Magic Index"); else System.out.print("Magic Index is : "+index); }} // This code is contributed by Anant Agarwal.
# Python 3 Program to find# magic index. def magicIndex(arr, start, end): # If No Magic Index return -1 if (start > end): return -1 midIndex = int((start + end) / 2) midValue = arr[midIndex] # Magic Index Found, return it. if (midIndex == midValue): return midIndex # Search on Left side left = magicIndex(arr, start, min(midValue, midIndex - 1)) # If Found on left side, return. if (left >= 0): return left # Return ans from right side. return magicIndex(arr, max(midValue, midIndex + 1), end) # Driver programarr = [-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13]n = len(arr) index = magicIndex(arr, 0, n - 1) if (index == -1): print("No Magic Index")else: print("Magic Index is :", index) # This code is contributed by Smitha Dinesh Semwal
// C# Program to find magic index.using System; class GFG { static int magicIndex(int []arr, int start, int end) { // If No Magic Index return -1; if (start > end) return -1; int midIndex = (start + end) / 2; int midValue = arr[midIndex]; // Magic Index Found, return it. if (midIndex == midValue) return midIndex; // Search on Left side int left = magicIndex(arr, start, Math.Min(midValue, midIndex - 1)); // If Found on left side, return. if (left >= 0) return left; // Return ans from right side. return magicIndex(arr, Math.Max(midValue, midIndex + 1),end); } // Driver code public static void Main () { int []arr = { -10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13 }; int n = arr.Length; int index = magicIndex(arr, 0, n - 1); if (index == -1) Console.WriteLine("No Magic Index"); else Console.WriteLine("Magic Index is : " + index); }} // This code is contributed by vt_m.
<?php// PHP Program to find magic index. function magicIndex($arr, $start, $end){ // If No Magic Index return -1; if ($start > $end) return -1; $midIndex = floor(($start + $end) / 2); $midValue = $arr[$midIndex]; // Magic Index Found, return it. if ($midIndex == $midValue) return $midIndex; // Search on Left side $left = magicIndex($arr, $start, min($midValue, $midIndex - 1)); // If Found on left side, return. if ($left >= 0) return $left; // Return ans from right side. return magicIndex($arr, max($midValue, $midIndex + 1), $end);} // Driver Code $arr = array(-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13); $n = sizeof($arr); $index = magicIndex($arr, 0, $n - 1); if ($index == -1) echo "No Magic Index"; else echo "Magic Index is : " , $index; // This code is contributed by nitin mittal?>
<script>// JavaScript Program to find magic index. function magicIndex(arr, start, end){ // If No Magic Index return -1; if (start > end) return -1; let midIndex = Math.floor((start + end) / 2); let midValue = arr[midIndex]; // Magic Index Found, return it. if (midIndex == midValue) return midIndex; // Search on Left side let left = magicIndex(arr, start, Math.min(midValue, midIndex - 1)); // If Found on left side, return. if (left >= 0) return left; // Return ans from right side. return magicIndex(arr, Math.max(midValue, midIndex + 1), end);} // Driver program let arr = [ -10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13 ]; let n = arr.length; let index = magicIndex(arr, 0, n - 1); if (index == -1) document.write("No Magic Index"); else document.write("Magic Index is : " + index); // This code is contributed by Surbhi Tyagi.</script>
Output:
Magic Index is : 2
Time Complexity: O(N)
Auxiliary Space: O(1)
Smitha Dinesh Semwal
nitin mittal
surbhityagi15
rohitsingh07052
Binary Search
Arrays
Arrays
Binary Search
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
Program to find sum of elements in a given array
Move all negative numbers to beginning and positive to end with constant extra space
Find duplicates in O(n) time and O(1) extra space | Set 1
Count pairs with given sum
Remove duplicates from sorted array
Next Greater Element
|
[
{
"code": null,
"e": 24822,
"s": 24794,
"text": "\n17 Nov, 2021"
},
{
"code": null,
"e": 25126,
"s": 24822,
"text": "Given an array of n integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in array can be negative. Examples: "
},
{
"code": null,
"e": 25349,
"s": 25126,
"text": " Input: arr[] = {-10, -5, 0, 3, 7}\n Output: 3 // arr[3] == 3 \n\n Input: arr[] = {-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13}\n Output: 2 // arr[2] == 2 \n\n Input: arr[] = {-10, -5, 3, 4, 7, 9}\n Output: -1 // No Fixed Point"
},
{
"code": null,
"e": 25911,
"s": 25351,
"text": "We have a solution to find fixed point in an array of distinct elements. In this post, solution for array with duplicate values is discussed.Consider the arr[] = {-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13}, arr[mid] = 3If elements are not distinct, then we see arr[mid] < mid, we cannot conclude which side the fixed is on. It could be on left side or on the right side.We know for sure that since arr[5] = 3, arr[4] couldn’t be magic index because arr[4] must be less than or equal to arr[5] (the array is Sorted).So, the general pattern of our search would be: "
},
{
"code": null,
"e": 25974,
"s": 25911,
"text": "Left Side: start = start, end = min(arr[midIndex], midIndex-1)"
},
{
"code": null,
"e": 26036,
"s": 25974,
"text": "Right Side: start = max(arr[midIndex], midIndex+1), end = end"
},
{
"code": null,
"e": 26077,
"s": 26036,
"text": "Below is the code for above Algorithm. "
},
{
"code": null,
"e": 26081,
"s": 26077,
"text": "C++"
},
{
"code": null,
"e": 26086,
"s": 26081,
"text": "Java"
},
{
"code": null,
"e": 26095,
"s": 26086,
"text": "Python 3"
},
{
"code": null,
"e": 26098,
"s": 26095,
"text": "C#"
},
{
"code": null,
"e": 26102,
"s": 26098,
"text": "PHP"
},
{
"code": null,
"e": 26113,
"s": 26102,
"text": "Javascript"
},
{
"code": "// CPP Program to find magic index.#include <bits/stdc++.h>using namespace std; int magicIndex(int* arr, int start, int end){ // If No Magic Index return -1; if (start > end) return -1; int midIndex = (start + end) / 2; int midValue = arr[midIndex]; // Magic Index Found, return it. if (midIndex == midValue) return midIndex; // Search on Left side int left = magicIndex(arr, start, min(midValue, midIndex - 1)); // If Found on left side, return. if (left >= 0) return left; // Return ans from right side. return magicIndex(arr, max(midValue, midIndex + 1), end);} // Driver programint main(){ int arr[] = { -10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13 }; int n = sizeof(arr) / sizeof(arr[0]); int index = magicIndex(arr, 0, n - 1); if (index == -1) cout << \"No Magic Index\"; else cout << \"Magic Index is : \" << index; return 0;}",
"e": 27146,
"s": 26113,
"text": null
},
{
"code": "// Java Program to find magic index. class GFG { static int magicIndex(int arr[], int start, int end) { // If No Magic Index return -1; if (start > end) return -1; int midIndex = (start + end) / 2; int midValue = arr[midIndex]; // Magic Index Found, return it. if (midIndex == midValue) return midIndex; // Search on Left side int left = magicIndex(arr, start, Math.min(midValue, midIndex - 1)); // If Found on left side, return. if (left >= 0) return left; // Return ans from right side. return magicIndex(arr, Math.max(midValue, midIndex + 1),end); } // Driver code public static void main (String[] args) { int arr[] = { -10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13 }; int n = arr.length; int index = magicIndex(arr, 0, n - 1); if (index == -1) System.out.print(\"No Magic Index\"); else System.out.print(\"Magic Index is : \"+index); }} // This code is contributed by Anant Agarwal.",
"e": 28340,
"s": 27146,
"text": null
},
{
"code": "# Python 3 Program to find# magic index. def magicIndex(arr, start, end): # If No Magic Index return -1 if (start > end): return -1 midIndex = int((start + end) / 2) midValue = arr[midIndex] # Magic Index Found, return it. if (midIndex == midValue): return midIndex # Search on Left side left = magicIndex(arr, start, min(midValue, midIndex - 1)) # If Found on left side, return. if (left >= 0): return left # Return ans from right side. return magicIndex(arr, max(midValue, midIndex + 1), end) # Driver programarr = [-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13]n = len(arr) index = magicIndex(arr, 0, n - 1) if (index == -1): print(\"No Magic Index\")else: print(\"Magic Index is :\", index) # This code is contributed by Smitha Dinesh Semwal",
"e": 29231,
"s": 28340,
"text": null
},
{
"code": "// C# Program to find magic index.using System; class GFG { static int magicIndex(int []arr, int start, int end) { // If No Magic Index return -1; if (start > end) return -1; int midIndex = (start + end) / 2; int midValue = arr[midIndex]; // Magic Index Found, return it. if (midIndex == midValue) return midIndex; // Search on Left side int left = magicIndex(arr, start, Math.Min(midValue, midIndex - 1)); // If Found on left side, return. if (left >= 0) return left; // Return ans from right side. return magicIndex(arr, Math.Max(midValue, midIndex + 1),end); } // Driver code public static void Main () { int []arr = { -10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13 }; int n = arr.Length; int index = magicIndex(arr, 0, n - 1); if (index == -1) Console.WriteLine(\"No Magic Index\"); else Console.WriteLine(\"Magic Index is : \" + index); }} // This code is contributed by vt_m.",
"e": 30527,
"s": 29231,
"text": null
},
{
"code": "<?php// PHP Program to find magic index. function magicIndex($arr, $start, $end){ // If No Magic Index return -1; if ($start > $end) return -1; $midIndex = floor(($start + $end) / 2); $midValue = $arr[$midIndex]; // Magic Index Found, return it. if ($midIndex == $midValue) return $midIndex; // Search on Left side $left = magicIndex($arr, $start, min($midValue, $midIndex - 1)); // If Found on left side, return. if ($left >= 0) return $left; // Return ans from right side. return magicIndex($arr, max($midValue, $midIndex + 1), $end);} // Driver Code $arr = array(-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13); $n = sizeof($arr); $index = magicIndex($arr, 0, $n - 1); if ($index == -1) echo \"No Magic Index\"; else echo \"Magic Index is : \" , $index; // This code is contributed by nitin mittal?>",
"e": 31475,
"s": 30527,
"text": null
},
{
"code": "<script>// JavaScript Program to find magic index. function magicIndex(arr, start, end){ // If No Magic Index return -1; if (start > end) return -1; let midIndex = Math.floor((start + end) / 2); let midValue = arr[midIndex]; // Magic Index Found, return it. if (midIndex == midValue) return midIndex; // Search on Left side let left = magicIndex(arr, start, Math.min(midValue, midIndex - 1)); // If Found on left side, return. if (left >= 0) return left; // Return ans from right side. return magicIndex(arr, Math.max(midValue, midIndex + 1), end);} // Driver program let arr = [ -10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13 ]; let n = arr.length; let index = magicIndex(arr, 0, n - 1); if (index == -1) document.write(\"No Magic Index\"); else document.write(\"Magic Index is : \" + index); // This code is contributed by Surbhi Tyagi.</script>",
"e": 32516,
"s": 31475,
"text": null
},
{
"code": null,
"e": 32526,
"s": 32516,
"text": "Output: "
},
{
"code": null,
"e": 32545,
"s": 32526,
"text": "Magic Index is : 2"
},
{
"code": null,
"e": 32568,
"s": 32545,
"text": " Time Complexity: O(N)"
},
{
"code": null,
"e": 32590,
"s": 32568,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 32611,
"s": 32590,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 32624,
"s": 32611,
"text": "nitin mittal"
},
{
"code": null,
"e": 32638,
"s": 32624,
"text": "surbhityagi15"
},
{
"code": null,
"e": 32654,
"s": 32638,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 32668,
"s": 32654,
"text": "Binary Search"
},
{
"code": null,
"e": 32675,
"s": 32668,
"text": "Arrays"
},
{
"code": null,
"e": 32682,
"s": 32675,
"text": "Arrays"
},
{
"code": null,
"e": 32696,
"s": 32682,
"text": "Binary Search"
},
{
"code": null,
"e": 32794,
"s": 32696,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32819,
"s": 32794,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32839,
"s": 32819,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 32877,
"s": 32839,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32902,
"s": 32877,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 32951,
"s": 32902,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33036,
"s": 32951,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 33094,
"s": 33036,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 33121,
"s": 33094,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 33157,
"s": 33121,
"text": "Remove duplicates from sorted array"
}
] |
How to check the properties of the Windows PowerShell Console?
|
You can check the Powershell console properties in two ways. The first method is by right-clicking on the title bar and open the properties.
For Example,
You can find various properties there. Like Windows Size, Cursor size, Font Size, font colors, etc. But you can dynamically change the properties when the script runs using the RawUI properties in the $host UIconfiguration. You can view the properties of the console using the below command, which is the second method.
$host.UI.RawUI
ForegroundColor : DarkYellow
BackgroundColor : Black
CursorPosition : 0,6
WindowPosition : 0,0
CursorSize : 25
BufferSize : 120,3000
WindowSize : 120,43
MaxWindowSize : 120,44
MaxPhysicalWindowSize : 151,44
KeyAvailable : False
WindowTitle : Administrator: Windows PowerShell
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "You can check the Powershell console properties in two ways. The first method is by right-clicking on the title bar and open the properties."
},
{
"code": null,
"e": 1216,
"s": 1203,
"text": "For Example,"
},
{
"code": null,
"e": 1536,
"s": 1216,
"text": "You can find various properties there. Like Windows Size, Cursor size, Font Size, font colors, etc. But you can dynamically change the properties when the script runs using the RawUI properties in the $host UIconfiguration. You can view the properties of the console using the below command, which is the second method."
},
{
"code": null,
"e": 1551,
"s": 1536,
"text": "$host.UI.RawUI"
},
{
"code": null,
"e": 1913,
"s": 1551,
"text": "ForegroundColor : DarkYellow\nBackgroundColor : Black\nCursorPosition : 0,6\nWindowPosition : 0,0\nCursorSize : 25\nBufferSize : 120,3000\nWindowSize : 120,43\nMaxWindowSize : 120,44\nMaxPhysicalWindowSize : 151,44\nKeyAvailable : False\nWindowTitle : Administrator: Windows PowerShell"
}
] |
Maximum Bitwise AND pair from given range in C++
|
Given a range [L, R], the task is to find a pair (X, Y) such that L ≤ X < Y ≤ R and X & Y is maximum among all the possible pairs then print the bitwise AND of the found pair.
If L = 1 and R = 10 then maximum bitwise AND value is 8 which can be formed as follows −
1000 # Binary representation of 8
Bitwise AND
1001 # Binary representation of 9
----
1000 # Final result
Iterate from L to R and check the bitwise AND for every possible pair and print the maximum value in the ends
Let us now see an example −
Live Demo
#include <bits/stdc++.h>
using namespace std;
int getMaxBitwiseAndValue(int L, int R) {
int maxValue = L & R;
for (int i = L; i < R; ++i) {
for (int j = i + 1; j <= R; ++j) {
maxValue = max(maxValue, (i & j));
}
}
return maxValue;
}
int main() {
int L = 1, R = 10;
cout << "Maximum value = " << getMaxBitwiseAndValue(L, R) << endl;
return 0;
}
Maximum value = 8
|
[
{
"code": null,
"e": 1238,
"s": 1062,
"text": "Given a range [L, R], the task is to find a pair (X, Y) such that L ≤ X < Y ≤ R and X & Y is maximum among all the possible pairs then print the bitwise AND of the found pair."
},
{
"code": null,
"e": 1327,
"s": 1238,
"text": "If L = 1 and R = 10 then maximum bitwise AND value is 8 which can be formed as follows −"
},
{
"code": null,
"e": 1432,
"s": 1327,
"text": "1000 # Binary representation of 8\nBitwise AND\n1001 # Binary representation of 9\n----\n1000 # Final result"
},
{
"code": null,
"e": 1542,
"s": 1432,
"text": "Iterate from L to R and check the bitwise AND for every possible pair and print the maximum value in the ends"
},
{
"code": null,
"e": 1570,
"s": 1542,
"text": "Let us now see an example −"
},
{
"code": null,
"e": 1581,
"s": 1570,
"text": " Live Demo"
},
{
"code": null,
"e": 1967,
"s": 1581,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint getMaxBitwiseAndValue(int L, int R) {\n int maxValue = L & R;\n for (int i = L; i < R; ++i) {\n for (int j = i + 1; j <= R; ++j) {\n maxValue = max(maxValue, (i & j));\n }\n }\n return maxValue;\n}\nint main() {\n int L = 1, R = 10;\n cout << \"Maximum value = \" << getMaxBitwiseAndValue(L, R) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 1985,
"s": 1967,
"text": "Maximum value = 8"
}
] |
React-Bootstrap Image Component
|
26 Apr, 2021
React-Bootstrap is a front-end framework that was designed keeping react in mind. Image Component provides a way to put images in our application with the help of this Image Component. We can use the following approach in ReactJS to use the react-bootstrap Image Component.
Image Props:
fluid: It provides a way to set our image as fluid image.
rounded: It provides a way to set our image as a rounded shape.
roundedCircle: It provides a way to set our image as a circle shape.
thumbnail: It provides a way to set our image as a thumbnail shape.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap
npm install bootstrap
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install react-bootstrap
npm install bootstrap
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import "bootstrap/dist/css/bootstrap.css"; import Image from "react-bootstrap/Image"; export default function App() { return ( <div style={{ display: "block", width: 700, padding: 30 }}> <h4>React-Bootstrap Image Component</h4> <Image src="https://media.geeksforgeeks.org/wp-content/uploads/20210425000233/test-300x297.png" rounded /> <Image src="https://media.geeksforgeeks.org/wp-content/uploads/20210425000233/test-300x297.png" roundedCircle /> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://react-bootstrap.github.io/components/images/
React-Bootstrap
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS Functional Components
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Image Component provides a way to put images in our application with the help of this Image Component. We can use the following approach in ReactJS to use the react-bootstrap Image Component."
},
{
"code": null,
"e": 315,
"s": 302,
"text": "Image Props:"
},
{
"code": null,
"e": 373,
"s": 315,
"text": "fluid: It provides a way to set our image as fluid image."
},
{
"code": null,
"e": 437,
"s": 373,
"text": "rounded: It provides a way to set our image as a rounded shape."
},
{
"code": null,
"e": 506,
"s": 437,
"text": "roundedCircle: It provides a way to set our image as a circle shape."
},
{
"code": null,
"e": 574,
"s": 506,
"text": "thumbnail: It provides a way to set our image as a thumbnail shape."
},
{
"code": null,
"e": 658,
"s": 574,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 708,
"s": 658,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 803,
"s": 708,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 867,
"s": 803,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 899,
"s": 867,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 1012,
"s": 899,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 1112,
"s": 1012,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 1126,
"s": 1112,
"text": "cd foldername"
},
{
"code": null,
"e": 1281,
"s": 1126,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap"
},
{
"code": null,
"e": 1386,
"s": 1281,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 1437,
"s": 1386,
"text": "npm install react-bootstrap \nnpm install bootstrap"
},
{
"code": null,
"e": 1489,
"s": 1437,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1507,
"s": 1489,
"text": "Project Structure"
},
{
"code": null,
"e": 1637,
"s": 1507,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 1644,
"s": 1637,
"text": "App.js"
},
{
"code": "import React from \"react\";import \"bootstrap/dist/css/bootstrap.css\"; import Image from \"react-bootstrap/Image\"; export default function App() { return ( <div style={{ display: \"block\", width: 700, padding: 30 }}> <h4>React-Bootstrap Image Component</h4> <Image src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210425000233/test-300x297.png\" rounded /> <Image src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210425000233/test-300x297.png\" roundedCircle /> </div> );}",
"e": 2192,
"s": 1644,
"text": null
},
{
"code": null,
"e": 2305,
"s": 2192,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2315,
"s": 2305,
"text": "npm start"
},
{
"code": null,
"e": 2414,
"s": 2315,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 2478,
"s": 2414,
"text": "Reference: https://react-bootstrap.github.io/components/images/"
},
{
"code": null,
"e": 2494,
"s": 2478,
"text": "React-Bootstrap"
},
{
"code": null,
"e": 2505,
"s": 2494,
"text": "JavaScript"
},
{
"code": null,
"e": 2513,
"s": 2505,
"text": "ReactJS"
},
{
"code": null,
"e": 2530,
"s": 2513,
"text": "Web Technologies"
},
{
"code": null,
"e": 2628,
"s": 2530,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2689,
"s": 2628,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2761,
"s": 2689,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2801,
"s": 2761,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2842,
"s": 2801,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2894,
"s": 2842,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2937,
"s": 2894,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2982,
"s": 2937,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 3020,
"s": 2982,
"text": "Axios in React: A Guide for Beginners"
}
] |
Number of pairs in an array with the sum greater than 0
|
14 Jun, 2021
Given an array arr[] of size N, the task is to find the number of distinct pairs in the array whose sum is > 0.
Examples:
Input: arr[] = { 3, -2, 1 } Output: 2 Explanation: There are two pairs of elements in the array whose sum is positive. They are: {3, -2} = 1 {3, 1} = 4
Input: arr[] = { -1, -1, -1, 0 } Output: 0 Explanation: There are no pairs of elements in the array whose sum is positive.
Naive Approach: The naive approach for this problem is to consider all the unique pairs of elements in the array. For every pair, check if the sum is positive or not. Time Complexity: O(N2)
Efficient Approach:
The idea is to use the concept of sorting and two pointer technique.
For this problem, sorting is used because for the sum arr[i] + arr[j] > 0 where i, j are some random indices in the array, either arr[i] > 0 or arr[j] > 0 or both arr[i] and arr[j] > 0.
Therefore, once the array is sorted, since we need to find the unique pairs. For every ‘i’ such that arr[i] > 0, we need to find the number of j’s such that arr[j] + arr[j] > 0.
Here, it is easy to find the count of pairs by using two pointer technique because the array is sorted. We just need to find the leftmost position of ‘j’ for which the condition holds true. This is found using the lower_bound of -arr[i] + 1.
For example, let the array arr[] = {-4, 4, -5, 5, 3, -2, -3, -1, 2, 1}. This array is sorted. Therefore, the array becomes, {-5, -4, -3, -2, -1, 1, 2, 3, 4, 5}. For some random i, lets assume arr[i] = 4. Therefore, the index of -3 is found in the array which is 2. Now, we can be sure that for all the values between the indices 2 and 8, the value of arr[i] + arr[j] > 0.
Below is the implementation of the above approach:
CPP
Java
Python3
C#
Javascript
// C++ program to find the// number of pairs in the// array with the sum > 0 #include <bits/stdc++.h>using namespace std; // Function to find the number// of pairs in the array with// sum > 0int findNumOfPair(int* a, int n){ // Sorting the given array sort(a, a + n); // Variable to store the count of pairs int ans = 0; // Loop to iterate through the array for (int i = 0; i < n; ++i) { // Ignore if the value is negative if (a[i] <= 0) continue; // Finding the index using lower_bound int j = lower_bound(a, a + n, -a[i] + 1) - a; // Finding the number of pairs between // two indices i and j ans += i - j; } return ans;} // Driver codeint main(){ int a[] = { 3, -2, 1 }; int n = sizeof(a) / sizeof(a[0]); int ans = findNumOfPair(a, n); cout << ans << endl; return 0;}
// Java program to find the// number of pairs in the// array with the sum > 0import java.util.*; class GFG { // Function to find the number // of pairs in the array with // sum > 0 static int findNumOfPair(int arr[], int n) { // Sorting the given array Arrays.sort(arr); // Variable to store the count of pairs int ans = 0; // Loop to iterate through the array for (int i = 0; i < n; ++i) { // Ignore if the value is negative if (arr[i] <= 0) continue; /* minReqVal val is the min value ,which will give >=1 after adding with the arr[i] */ int minReqVal = -arr[i] + 1; int j = lower_bound(arr, minReqVal); if (j >= 0) ans += i - j; } return ans; } /* it return the index of a minimum Number in the array which is just >= val */ static int lower_bound(int arr[], int val) { int start = 0, end = arr.length; /* using the Binary search technique , since our array is sorted */ while (start < end) { int mid = (start + end) >> 1; if (val > arr[mid]) start = mid + 1; else end = mid; } // when we dont find the answer return -1 if (start == arr.length) return -1; return start; } // Driver code public static void main(String[] args) { int a[] = {-2,-1,-1,-1,-1,0 ,1,2,3}; int n = a.length; int ans = findNumOfPair(a, n); System.out.println(ans); }} // This code is contributed by Pradeep Mondal P
# Python3 program to find the# number of pairs in the# array with the sum > 0from bisect import bisect_left as lower_bound # Function to find the number# of pairs in the array with# sum > 0 def findNumOfPair(a, n): # Sorting the given array a = sorted(a) # Variable to store the count of pairs ans = 0 # Loop to iterate through the array for i in range(n): # Ignore if the value is negative if (a[i] <= 0): continue # Finding the index using lower_bound j = lower_bound(a, -a[i] + 1) # Finding the number of pairs between # two indices i and j ans += i - j return ans # Driver codeif __name__ == '__main__': a = [3, -2, 1] n = len(a) ans = findNumOfPair(a, n) print(ans) # This code is contributed by mohit kumar 29
// C# program to find the// number of pairs in the// array with the sum > 0using System; class GFG { // Function to find the number // of pairs in the array with // sum > 0 static int findNumOfPair(int[] arr, int n) { // Sorting the given array Array.Sort(arr); // Variable to store the count of pairs int ans = 0; // Loop to iterate through the array for (int i = 0; i < n; ++i) { // Ignore if the value is negative if (arr[i] <= 0) continue; /* minReqVal val is the min value ,which will give >=1 after adding with the arr[i] */ int minReqVal = -arr[i] + 1; int j = lower_bound(arr, minReqVal); if (j >= 0) ans += i - j; } return ans; } /* it return the index of a minimum Number in the array which is just >= val */ static int lower_bound(int[] arr, int val) { int start = 0, end = arr.Length; /* using the Binary search technique , since our array is sorted */ while (start < end) { int mid = (start + end) >> 1; if (val > arr[mid]) start = mid + 1; else end = mid; } // when we dont find the answer return -1 if (start == arr.Length) return -1; return start; } // Driver code public static void Main() { int[] a = { -2, 1, 3 }; int n = a.Length; int ans = findNumOfPair(a, n); Console.Write(ans); }} // This code is contributed by Pradeep Mondal P
<script>// Javascript program to find the// number of pairs in the// array with the sum > 0 // Function to find the number // of pairs in the array with // sum > 0function findNumOfPair(arr, n){ // Sorting the given array arr.sort(function(a,b){return a-b;}); // Variable to store the count of pairs let ans = 0; // Loop to iterate through the array for (let i = 0; i < n; ++i) { // Ignore if the value is negative if (arr[i] <= 0) continue; /* minReqVal val is the min value ,which will give >=1 after adding with the arr[i] */ let minReqVal = -arr[i] + 1; let j = lower_bound(arr, minReqVal); if (j >= 0) ans += i - j; } return ans;} /* it return the index of a minimum Number in the array which is just >= val */function lower_bound(arr,val){ let start = 0, end = arr.length; /* using the Binary search technique , since our array is sorted */ while (start < end) { let mid = (start + end) >> 1; if (val > arr[mid]) start = mid + 1; else end = mid; } // when we dont find the answer return -1 if (start == arr.length) return -1; return start;} // Driver codelet a=[3, -2, 1];let n = a.length;let ans = findNumOfPair(a, n);document.write(ans); // This code is contributed by unknown2108</script>
2
Time Complexity: O(N * log(N))
mohit kumar 29
abhaysingh290895
pradeepmondalp
unknown2108
Arrays
Greedy
Searching
Sorting
Arrays
Searching
Greedy
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Jun, 2021"
},
{
"code": null,
"e": 166,
"s": 54,
"text": "Given an array arr[] of size N, the task is to find the number of distinct pairs in the array whose sum is > 0."
},
{
"code": null,
"e": 177,
"s": 166,
"text": "Examples: "
},
{
"code": null,
"e": 329,
"s": 177,
"text": "Input: arr[] = { 3, -2, 1 } Output: 2 Explanation: There are two pairs of elements in the array whose sum is positive. They are: {3, -2} = 1 {3, 1} = 4"
},
{
"code": null,
"e": 454,
"s": 329,
"text": "Input: arr[] = { -1, -1, -1, 0 } Output: 0 Explanation: There are no pairs of elements in the array whose sum is positive. "
},
{
"code": null,
"e": 644,
"s": 454,
"text": "Naive Approach: The naive approach for this problem is to consider all the unique pairs of elements in the array. For every pair, check if the sum is positive or not. Time Complexity: O(N2)"
},
{
"code": null,
"e": 665,
"s": 644,
"text": "Efficient Approach: "
},
{
"code": null,
"e": 734,
"s": 665,
"text": "The idea is to use the concept of sorting and two pointer technique."
},
{
"code": null,
"e": 920,
"s": 734,
"text": "For this problem, sorting is used because for the sum arr[i] + arr[j] > 0 where i, j are some random indices in the array, either arr[i] > 0 or arr[j] > 0 or both arr[i] and arr[j] > 0."
},
{
"code": null,
"e": 1098,
"s": 920,
"text": "Therefore, once the array is sorted, since we need to find the unique pairs. For every ‘i’ such that arr[i] > 0, we need to find the number of j’s such that arr[j] + arr[j] > 0."
},
{
"code": null,
"e": 1340,
"s": 1098,
"text": "Here, it is easy to find the count of pairs by using two pointer technique because the array is sorted. We just need to find the leftmost position of ‘j’ for which the condition holds true. This is found using the lower_bound of -arr[i] + 1."
},
{
"code": null,
"e": 1712,
"s": 1340,
"text": "For example, let the array arr[] = {-4, 4, -5, 5, 3, -2, -3, -1, 2, 1}. This array is sorted. Therefore, the array becomes, {-5, -4, -3, -2, -1, 1, 2, 3, 4, 5}. For some random i, lets assume arr[i] = 4. Therefore, the index of -3 is found in the array which is 2. Now, we can be sure that for all the values between the indices 2 and 8, the value of arr[i] + arr[j] > 0."
},
{
"code": null,
"e": 1764,
"s": 1712,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1768,
"s": 1764,
"text": "CPP"
},
{
"code": null,
"e": 1773,
"s": 1768,
"text": "Java"
},
{
"code": null,
"e": 1781,
"s": 1773,
"text": "Python3"
},
{
"code": null,
"e": 1784,
"s": 1781,
"text": "C#"
},
{
"code": null,
"e": 1795,
"s": 1784,
"text": "Javascript"
},
{
"code": "// C++ program to find the// number of pairs in the// array with the sum > 0 #include <bits/stdc++.h>using namespace std; // Function to find the number// of pairs in the array with// sum > 0int findNumOfPair(int* a, int n){ // Sorting the given array sort(a, a + n); // Variable to store the count of pairs int ans = 0; // Loop to iterate through the array for (int i = 0; i < n; ++i) { // Ignore if the value is negative if (a[i] <= 0) continue; // Finding the index using lower_bound int j = lower_bound(a, a + n, -a[i] + 1) - a; // Finding the number of pairs between // two indices i and j ans += i - j; } return ans;} // Driver codeint main(){ int a[] = { 3, -2, 1 }; int n = sizeof(a) / sizeof(a[0]); int ans = findNumOfPair(a, n); cout << ans << endl; return 0;}",
"e": 2673,
"s": 1795,
"text": null
},
{
"code": "// Java program to find the// number of pairs in the// array with the sum > 0import java.util.*; class GFG { // Function to find the number // of pairs in the array with // sum > 0 static int findNumOfPair(int arr[], int n) { // Sorting the given array Arrays.sort(arr); // Variable to store the count of pairs int ans = 0; // Loop to iterate through the array for (int i = 0; i < n; ++i) { // Ignore if the value is negative if (arr[i] <= 0) continue; /* minReqVal val is the min value ,which will give >=1 after adding with the arr[i] */ int minReqVal = -arr[i] + 1; int j = lower_bound(arr, minReqVal); if (j >= 0) ans += i - j; } return ans; } /* it return the index of a minimum Number in the array which is just >= val */ static int lower_bound(int arr[], int val) { int start = 0, end = arr.length; /* using the Binary search technique , since our array is sorted */ while (start < end) { int mid = (start + end) >> 1; if (val > arr[mid]) start = mid + 1; else end = mid; } // when we dont find the answer return -1 if (start == arr.length) return -1; return start; } // Driver code public static void main(String[] args) { int a[] = {-2,-1,-1,-1,-1,0 ,1,2,3}; int n = a.length; int ans = findNumOfPair(a, n); System.out.println(ans); }} // This code is contributed by Pradeep Mondal P",
"e": 4414,
"s": 2673,
"text": null
},
{
"code": "# Python3 program to find the# number of pairs in the# array with the sum > 0from bisect import bisect_left as lower_bound # Function to find the number# of pairs in the array with# sum > 0 def findNumOfPair(a, n): # Sorting the given array a = sorted(a) # Variable to store the count of pairs ans = 0 # Loop to iterate through the array for i in range(n): # Ignore if the value is negative if (a[i] <= 0): continue # Finding the index using lower_bound j = lower_bound(a, -a[i] + 1) # Finding the number of pairs between # two indices i and j ans += i - j return ans # Driver codeif __name__ == '__main__': a = [3, -2, 1] n = len(a) ans = findNumOfPair(a, n) print(ans) # This code is contributed by mohit kumar 29",
"e": 5232,
"s": 4414,
"text": null
},
{
"code": "// C# program to find the// number of pairs in the// array with the sum > 0using System; class GFG { // Function to find the number // of pairs in the array with // sum > 0 static int findNumOfPair(int[] arr, int n) { // Sorting the given array Array.Sort(arr); // Variable to store the count of pairs int ans = 0; // Loop to iterate through the array for (int i = 0; i < n; ++i) { // Ignore if the value is negative if (arr[i] <= 0) continue; /* minReqVal val is the min value ,which will give >=1 after adding with the arr[i] */ int minReqVal = -arr[i] + 1; int j = lower_bound(arr, minReqVal); if (j >= 0) ans += i - j; } return ans; } /* it return the index of a minimum Number in the array which is just >= val */ static int lower_bound(int[] arr, int val) { int start = 0, end = arr.Length; /* using the Binary search technique , since our array is sorted */ while (start < end) { int mid = (start + end) >> 1; if (val > arr[mid]) start = mid + 1; else end = mid; } // when we dont find the answer return -1 if (start == arr.Length) return -1; return start; } // Driver code public static void Main() { int[] a = { -2, 1, 3 }; int n = a.Length; int ans = findNumOfPair(a, n); Console.Write(ans); }} // This code is contributed by Pradeep Mondal P",
"e": 6929,
"s": 5232,
"text": null
},
{
"code": "<script>// Javascript program to find the// number of pairs in the// array with the sum > 0 // Function to find the number // of pairs in the array with // sum > 0function findNumOfPair(arr, n){ // Sorting the given array arr.sort(function(a,b){return a-b;}); // Variable to store the count of pairs let ans = 0; // Loop to iterate through the array for (let i = 0; i < n; ++i) { // Ignore if the value is negative if (arr[i] <= 0) continue; /* minReqVal val is the min value ,which will give >=1 after adding with the arr[i] */ let minReqVal = -arr[i] + 1; let j = lower_bound(arr, minReqVal); if (j >= 0) ans += i - j; } return ans;} /* it return the index of a minimum Number in the array which is just >= val */function lower_bound(arr,val){ let start = 0, end = arr.length; /* using the Binary search technique , since our array is sorted */ while (start < end) { let mid = (start + end) >> 1; if (val > arr[mid]) start = mid + 1; else end = mid; } // when we dont find the answer return -1 if (start == arr.length) return -1; return start;} // Driver codelet a=[3, -2, 1];let n = a.length;let ans = findNumOfPair(a, n);document.write(ans); // This code is contributed by unknown2108</script>",
"e": 8511,
"s": 6929,
"text": null
},
{
"code": null,
"e": 8513,
"s": 8511,
"text": "2"
},
{
"code": null,
"e": 8545,
"s": 8513,
"text": "Time Complexity: O(N * log(N)) "
},
{
"code": null,
"e": 8560,
"s": 8545,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8577,
"s": 8560,
"text": "abhaysingh290895"
},
{
"code": null,
"e": 8592,
"s": 8577,
"text": "pradeepmondalp"
},
{
"code": null,
"e": 8604,
"s": 8592,
"text": "unknown2108"
},
{
"code": null,
"e": 8611,
"s": 8604,
"text": "Arrays"
},
{
"code": null,
"e": 8618,
"s": 8611,
"text": "Greedy"
},
{
"code": null,
"e": 8628,
"s": 8618,
"text": "Searching"
},
{
"code": null,
"e": 8636,
"s": 8628,
"text": "Sorting"
},
{
"code": null,
"e": 8643,
"s": 8636,
"text": "Arrays"
},
{
"code": null,
"e": 8653,
"s": 8643,
"text": "Searching"
},
{
"code": null,
"e": 8660,
"s": 8653,
"text": "Greedy"
},
{
"code": null,
"e": 8668,
"s": 8660,
"text": "Sorting"
}
] |
Smallest N digit number divisible by N
|
27 Jun, 2021
Given a positive integers N, the task is to find the smallest N digit number divisible by N.
Examples:
Input: N = 2 Output: 10 Explanation: 10 is the smallest 2-digit number which is divisible by 2.
Input: N = 3 Output: 102 Explanation: 102 is the smallest 3-digit number which is divisible by 3.
Naive Approach: The naive approach is to iterate from smallest N-digit number(say S) to largest N-digit number(say L). The first number between [S, L] divisible by N is the required result.
Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>#include <math.h>using namespace std; // Function to find the smallest// N-digit number divisible by Nvoid smallestNumber(int N){ // Find largest n digit number int L = pow(10, N) - 1; // Find smallest n digit number int S = pow(10, N - 1); for (int i = S; i <= L; i++) { // If i is divisible by N, // then print i and return ; if (i % N == 0) { cout << i; return; } }} // Driver Codeint main(){ // Given Number int N = 2; // Function Call smallestNumber(N); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to find the smallest// N-digit number divisible by Nstatic void smallestNumber(int N){ // Find largest n digit number int L = (int) (Math.pow(10, N) - 1); // Find smallest n digit number int S = (int) Math.pow(10, N - 1); for (int i = S; i <= L; i++) { // If i is divisible by N, // then print i and return ; if (i % N == 0) { System.out.print(i); return; } }} // Driver Codepublic static void main(String[] args){ // Given Number int N = 2; // Function Call smallestNumber(N);}} // This code is contributed by Amit Katiyar
# Python3 program for the above approach # Function to find the smallest# N-digit number divisible by Ndef smallestNumber(N): # Find largest n digit number L = pow(10, N) - 1; # Find smallest n digit number S = pow(10, N - 1); for i in range(S, L): # If i is divisible by N, # then print i and return ; if (i % N == 0): print(i); return; # Driver Codeif __name__ == "__main__" : # Given number N = 2; # Function call smallestNumber(N) # This code is contributed by rock_cool
// C# program for the above approachusing System;class GFG{ // Function to find the smallest// N-digit number divisible by Nstatic void smallestNumber(int N){ // Find largest n digit number int L = (int)(Math.Pow(10, N) - 1); // Find smallest n digit number int S = (int)Math.Pow(10, N - 1); for(int i = S; i <= L; i++) { // If i is divisible by N, // then print i and return ; if (i % N == 0) { Console.Write(i); return; } }} // Driver Codepublic static void Main(){ // Given number int N = 2; // Function call smallestNumber(N);}} // This code is contributed by Nidhi_biet
<script> // Javascript program for the above approach // Function to find the smallest// N-digit number divisible by Nfunction smallestNumber(N){ // Find largest n digit number let L = Math.pow(10, N) - 1; // Find smallest n digit number let S = Math.pow(10, N - 1); for(let i = S; i <= L; i++) { // If i is divisible by N, // then print i and return ; if (i % N == 0) { document.write(i); return; } }} // Driver code // Given Numberlet N = 2; // Function CallsmallestNumber(N); // This code is contributed by divyeshrabadiya07 </script>
10
Time Complexity: O(L – S), where L and S is the largest and smallest N-digit number respectively.
Efficient Approach: If the number divisible by N, then the number will be of the form N * X for some positive integer X. Since it has to be smallest N-digit number, then X will be given by:
. Therefore, the smallest number N-digit number is given by:
For Example:
For N = 3, the smallest 3-digit number is given by: =>
=>
=>
=> 102
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>#include <math.h>using namespace std; // Function to find the smallest// N-digit number divisible by Nint smallestNumber(int N){ // Return the smallest N-digit // number calculated using above // formula return N * ceil(pow(10, (N - 1)) / N);} // Driver Codeint main(){ // Given N int N = 2; // Function Call cout << smallestNumber(N); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to find the smallest// N-digit number divisible by Nstatic int smallestNumber(int N){ // Return the smallest N-digit // number calculated using above // formula return (int) (N * Math.ceil(Math.pow(10, (N - 1)) / N));} // Driver Codepublic static void main(String[] args){ // Given N int N = 2; // Function Call System.out.print(smallestNumber(N));}} // This code is contributed by Princi Singh
# Python3 program for the above approachimport math # Function to find the smallest# N-digit number divisible by Ndef smallestNumber(N): # Return the smallest N-digit # number calculated using above # formula return N * math.ceil(pow(10, (N - 1)) // N); # Driver Code # Given NN = 2; # Function Callprint(smallestNumber(N)); # This code is contributed by Code_Mech
// C# program for the above approachusing System;class GFG{ // Function to find the smallest// N-digit number divisible by Nstatic int smallestNumber(int N){ // Return the smallest N-digit // number calculated using above // formula return (int) (N * Math.Ceiling(Math.Pow(10, (N - 1)) / N));} // Driver Codepublic static void Main(){ // Given N int N = 2; // Function Call Console.Write(smallestNumber(N));}} // This code is contributed by Code_Mech
<script> // Javascript program for the above approach // Function to find the smallest // N-digit number divisible by N function smallestNumber(N) { // Return the smallest N-digit // number calculated using above // formula return N * Math.ceil(Math.pow(10, (N - 1)) / N); } // Given N let N = 2; // Function Call document.write(smallestNumber(N)); // This code is contributed by divyesh072019.</script>
10
Time Complexity: O(1)Auxiliary Space: O(1)
amit143katiyar
nidhi_biet
rock_cool
princi singh
Code_Mech
ciderpapi
divyeshrabadiya07
divyesh072019
subhammahato348
divisibility
Number Divisibility
number-digits
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jun, 2021"
},
{
"code": null,
"e": 121,
"s": 28,
"text": "Given a positive integers N, the task is to find the smallest N digit number divisible by N."
},
{
"code": null,
"e": 133,
"s": 121,
"text": "Examples: "
},
{
"code": null,
"e": 229,
"s": 133,
"text": "Input: N = 2 Output: 10 Explanation: 10 is the smallest 2-digit number which is divisible by 2."
},
{
"code": null,
"e": 328,
"s": 229,
"text": "Input: N = 3 Output: 102 Explanation: 102 is the smallest 3-digit number which is divisible by 3. "
},
{
"code": null,
"e": 518,
"s": 328,
"text": "Naive Approach: The naive approach is to iterate from smallest N-digit number(say S) to largest N-digit number(say L). The first number between [S, L] divisible by N is the required result."
},
{
"code": null,
"e": 566,
"s": 518,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 570,
"s": 566,
"text": "C++"
},
{
"code": null,
"e": 575,
"s": 570,
"text": "Java"
},
{
"code": null,
"e": 583,
"s": 575,
"text": "Python3"
},
{
"code": null,
"e": 586,
"s": 583,
"text": "C#"
},
{
"code": null,
"e": 597,
"s": 586,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <iostream>#include <math.h>using namespace std; // Function to find the smallest// N-digit number divisible by Nvoid smallestNumber(int N){ // Find largest n digit number int L = pow(10, N) - 1; // Find smallest n digit number int S = pow(10, N - 1); for (int i = S; i <= L; i++) { // If i is divisible by N, // then print i and return ; if (i % N == 0) { cout << i; return; } }} // Driver Codeint main(){ // Given Number int N = 2; // Function Call smallestNumber(N); return 0;}",
"e": 1211,
"s": 597,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the smallest// N-digit number divisible by Nstatic void smallestNumber(int N){ // Find largest n digit number int L = (int) (Math.pow(10, N) - 1); // Find smallest n digit number int S = (int) Math.pow(10, N - 1); for (int i = S; i <= L; i++) { // If i is divisible by N, // then print i and return ; if (i % N == 0) { System.out.print(i); return; } }} // Driver Codepublic static void main(String[] args){ // Given Number int N = 2; // Function Call smallestNumber(N);}} // This code is contributed by Amit Katiyar",
"e": 1910,
"s": 1211,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the smallest# N-digit number divisible by Ndef smallestNumber(N): # Find largest n digit number L = pow(10, N) - 1; # Find smallest n digit number S = pow(10, N - 1); for i in range(S, L): # If i is divisible by N, # then print i and return ; if (i % N == 0): print(i); return; # Driver Codeif __name__ == \"__main__\" : # Given number N = 2; # Function call smallestNumber(N) # This code is contributed by rock_cool",
"e": 2473,
"s": 1910,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to find the smallest// N-digit number divisible by Nstatic void smallestNumber(int N){ // Find largest n digit number int L = (int)(Math.Pow(10, N) - 1); // Find smallest n digit number int S = (int)Math.Pow(10, N - 1); for(int i = S; i <= L; i++) { // If i is divisible by N, // then print i and return ; if (i % N == 0) { Console.Write(i); return; } }} // Driver Codepublic static void Main(){ // Given number int N = 2; // Function call smallestNumber(N);}} // This code is contributed by Nidhi_biet",
"e": 3148,
"s": 2473,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the smallest// N-digit number divisible by Nfunction smallestNumber(N){ // Find largest n digit number let L = Math.pow(10, N) - 1; // Find smallest n digit number let S = Math.pow(10, N - 1); for(let i = S; i <= L; i++) { // If i is divisible by N, // then print i and return ; if (i % N == 0) { document.write(i); return; } }} // Driver code // Given Numberlet N = 2; // Function CallsmallestNumber(N); // This code is contributed by divyeshrabadiya07 </script>",
"e": 3784,
"s": 3148,
"text": null
},
{
"code": null,
"e": 3787,
"s": 3784,
"text": "10"
},
{
"code": null,
"e": 3888,
"s": 3789,
"text": "Time Complexity: O(L – S), where L and S is the largest and smallest N-digit number respectively. "
},
{
"code": null,
"e": 4079,
"s": 3888,
"text": "Efficient Approach: If the number divisible by N, then the number will be of the form N * X for some positive integer X. Since it has to be smallest N-digit number, then X will be given by: "
},
{
"code": null,
"e": 4141,
"s": 4079,
"text": ". Therefore, the smallest number N-digit number is given by: "
},
{
"code": null,
"e": 4156,
"s": 4141,
"text": "For Example: "
},
{
"code": null,
"e": 4212,
"s": 4156,
"text": "For N = 3, the smallest 3-digit number is given by: => "
},
{
"code": null,
"e": 4216,
"s": 4212,
"text": "=> "
},
{
"code": null,
"e": 4220,
"s": 4216,
"text": "=> "
},
{
"code": null,
"e": 4227,
"s": 4220,
"text": "=> 102"
},
{
"code": null,
"e": 4279,
"s": 4227,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 4283,
"s": 4279,
"text": "C++"
},
{
"code": null,
"e": 4288,
"s": 4283,
"text": "Java"
},
{
"code": null,
"e": 4296,
"s": 4288,
"text": "Python3"
},
{
"code": null,
"e": 4299,
"s": 4296,
"text": "C#"
},
{
"code": null,
"e": 4310,
"s": 4299,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <iostream>#include <math.h>using namespace std; // Function to find the smallest// N-digit number divisible by Nint smallestNumber(int N){ // Return the smallest N-digit // number calculated using above // formula return N * ceil(pow(10, (N - 1)) / N);} // Driver Codeint main(){ // Given N int N = 2; // Function Call cout << smallestNumber(N); return 0;}",
"e": 4742,
"s": 4310,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the smallest// N-digit number divisible by Nstatic int smallestNumber(int N){ // Return the smallest N-digit // number calculated using above // formula return (int) (N * Math.ceil(Math.pow(10, (N - 1)) / N));} // Driver Codepublic static void main(String[] args){ // Given N int N = 2; // Function Call System.out.print(smallestNumber(N));}} // This code is contributed by Princi Singh",
"e": 5243,
"s": 4742,
"text": null
},
{
"code": "# Python3 program for the above approachimport math # Function to find the smallest# N-digit number divisible by Ndef smallestNumber(N): # Return the smallest N-digit # number calculated using above # formula return N * math.ceil(pow(10, (N - 1)) // N); # Driver Code # Given NN = 2; # Function Callprint(smallestNumber(N)); # This code is contributed by Code_Mech",
"e": 5621,
"s": 5243,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to find the smallest// N-digit number divisible by Nstatic int smallestNumber(int N){ // Return the smallest N-digit // number calculated using above // formula return (int) (N * Math.Ceiling(Math.Pow(10, (N - 1)) / N));} // Driver Codepublic static void Main(){ // Given N int N = 2; // Function Call Console.Write(smallestNumber(N));}} // This code is contributed by Code_Mech",
"e": 6098,
"s": 5621,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the smallest // N-digit number divisible by N function smallestNumber(N) { // Return the smallest N-digit // number calculated using above // formula return N * Math.ceil(Math.pow(10, (N - 1)) / N); } // Given N let N = 2; // Function Call document.write(smallestNumber(N)); // This code is contributed by divyesh072019.</script>",
"e": 6581,
"s": 6098,
"text": null
},
{
"code": null,
"e": 6584,
"s": 6581,
"text": "10"
},
{
"code": null,
"e": 6629,
"s": 6586,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6644,
"s": 6629,
"text": "amit143katiyar"
},
{
"code": null,
"e": 6655,
"s": 6644,
"text": "nidhi_biet"
},
{
"code": null,
"e": 6665,
"s": 6655,
"text": "rock_cool"
},
{
"code": null,
"e": 6678,
"s": 6665,
"text": "princi singh"
},
{
"code": null,
"e": 6688,
"s": 6678,
"text": "Code_Mech"
},
{
"code": null,
"e": 6698,
"s": 6688,
"text": "ciderpapi"
},
{
"code": null,
"e": 6716,
"s": 6698,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 6730,
"s": 6716,
"text": "divyesh072019"
},
{
"code": null,
"e": 6746,
"s": 6730,
"text": "subhammahato348"
},
{
"code": null,
"e": 6759,
"s": 6746,
"text": "divisibility"
},
{
"code": null,
"e": 6779,
"s": 6759,
"text": "Number Divisibility"
},
{
"code": null,
"e": 6793,
"s": 6779,
"text": "number-digits"
},
{
"code": null,
"e": 6806,
"s": 6793,
"text": "Mathematical"
},
{
"code": null,
"e": 6819,
"s": 6806,
"text": "Mathematical"
}
] |
hexdump command in Linux with examples
|
21 May, 2019
The hd or hexdump command in Linux is used to filter and display the specified files, or standard input in a human readable specified format. For example, if you want to view an executable code of a program, you can use hexdump to do so.
Syntax:
hd [OPTIONS...] [FILES...]
Options:
-b : One-byte octal display. Display the input offset in hexadecimal, followed by sixteen space-separated, three column, zero-filled, bytes of input data, in octal, per line.Syntax:hd -b input.txtThe first column of the output represents the input offset in file.
Syntax:
hd -b input.txt
The first column of the output represents the input offset in file.
-c : One-byte character display. Display the input offset in hexadecimal, followed by sixteen space-separated, three column, space-filled, characters of input data per line.Syntax:hd -c input.txt
Syntax:
hd -c input.txt
-C : Canonical hex+ASCII display. Display the input offset in hexadecimal, followed by sixteen space-separated, two column, hexadecimal bytes, followed by the same sixteen bytes in %_p format enclosed in “|” characters.Syntax:hexdump -C input.txt
Syntax:
hexdump -C input.txt
-d : Two-byte decimal display. Display the input offset in hexadecimal, followed by eight space-separated, five column, zero-filled, two-byte units of input data, in unsigned decimal, per line.Syntax:hd -d input.txt
Syntax:
hd -d input.txt
-n length : Where length is an integer. Interprets only ‘length’ bytes of output.Syntax:hd -n length input.txt
Syntax:
hd -n length input.txt
-o: Two-byte octal display. Display the input offset in hexadecimal, followed by eight space-separated, six column, zero-filled, two byte quantities of input data, in octal, per line.Syntax:hd -o input.txt
Syntax:
hd -o input.txt
-s offset : Skip ‘offset’ bytes from the beginning of the input. By default, offset is interpreted as a decimal number. With a leading 0x or 0X, offset is interpreted as a hexadecimal number, otherwise, with a leading 0, offset is interpreted as an octal number. Appending the character b, k, or m to offset causes it to be interpreted as a multiple of 512, 1024, or 1048576, respectively.Syntax:hd -s offset input.txtAs you can see, in the output, first 6 characters, i.e. ‘Hello ‘ are skipped.
Syntax:
hd -s offset input.txt
As you can see, in the output, first 6 characters, i.e. ‘Hello ‘ are skipped.
-v : Cause hexdump to display all input data. Without the -v option, any number of groups of output lines, which would be identical to the immediately preceding group of output lines (except for the input offsets), are replaced with a line comprised of a single asterisk.Syntax:hd -v input.txtWe will see the use of this option as we display the output using -c flag.As you can observe, when we use hd for the first time, without -v, when similar output appears, it prints out an asterisk (*). But when we pass a -v flag, we get all the output lines.
Syntax:
hd -v input.txt
We will see the use of this option as we display the output using -c flag.
As you can observe, when we use hd for the first time, without -v, when similar output appears, it prints out an asterisk (*). But when we pass a -v flag, we get all the output lines.
-x : Two-byte hexadecimal display. Display the input offset in hexadecimal, followed by eight, space separated, four column, zero-filled, two-byte quantities of input data, in hexadecimal, per line.Syntax:hd -x input.txt
Syntax:
hd -x input.txt
linux-command
Linux-file-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Tail command in Linux with examples
Conditional Statements | Shell Script
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
echo command in Linux with Examples
Cat command in Linux with examples
touch command in Linux with Examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 May, 2019"
},
{
"code": null,
"e": 266,
"s": 28,
"text": "The hd or hexdump command in Linux is used to filter and display the specified files, or standard input in a human readable specified format. For example, if you want to view an executable code of a program, you can use hexdump to do so."
},
{
"code": null,
"e": 274,
"s": 266,
"text": "Syntax:"
},
{
"code": null,
"e": 301,
"s": 274,
"text": "hd [OPTIONS...] [FILES...]"
},
{
"code": null,
"e": 310,
"s": 301,
"text": "Options:"
},
{
"code": null,
"e": 574,
"s": 310,
"text": "-b : One-byte octal display. Display the input offset in hexadecimal, followed by sixteen space-separated, three column, zero-filled, bytes of input data, in octal, per line.Syntax:hd -b input.txtThe first column of the output represents the input offset in file."
},
{
"code": null,
"e": 582,
"s": 574,
"text": "Syntax:"
},
{
"code": null,
"e": 598,
"s": 582,
"text": "hd -b input.txt"
},
{
"code": null,
"e": 666,
"s": 598,
"text": "The first column of the output represents the input offset in file."
},
{
"code": null,
"e": 862,
"s": 666,
"text": "-c : One-byte character display. Display the input offset in hexadecimal, followed by sixteen space-separated, three column, space-filled, characters of input data per line.Syntax:hd -c input.txt"
},
{
"code": null,
"e": 870,
"s": 862,
"text": "Syntax:"
},
{
"code": null,
"e": 886,
"s": 870,
"text": "hd -c input.txt"
},
{
"code": null,
"e": 1133,
"s": 886,
"text": "-C : Canonical hex+ASCII display. Display the input offset in hexadecimal, followed by sixteen space-separated, two column, hexadecimal bytes, followed by the same sixteen bytes in %_p format enclosed in “|” characters.Syntax:hexdump -C input.txt"
},
{
"code": null,
"e": 1141,
"s": 1133,
"text": "Syntax:"
},
{
"code": null,
"e": 1162,
"s": 1141,
"text": "hexdump -C input.txt"
},
{
"code": null,
"e": 1378,
"s": 1162,
"text": "-d : Two-byte decimal display. Display the input offset in hexadecimal, followed by eight space-separated, five column, zero-filled, two-byte units of input data, in unsigned decimal, per line.Syntax:hd -d input.txt"
},
{
"code": null,
"e": 1386,
"s": 1378,
"text": "Syntax:"
},
{
"code": null,
"e": 1402,
"s": 1386,
"text": "hd -d input.txt"
},
{
"code": null,
"e": 1513,
"s": 1402,
"text": "-n length : Where length is an integer. Interprets only ‘length’ bytes of output.Syntax:hd -n length input.txt"
},
{
"code": null,
"e": 1521,
"s": 1513,
"text": "Syntax:"
},
{
"code": null,
"e": 1544,
"s": 1521,
"text": "hd -n length input.txt"
},
{
"code": null,
"e": 1750,
"s": 1544,
"text": "-o: Two-byte octal display. Display the input offset in hexadecimal, followed by eight space-separated, six column, zero-filled, two byte quantities of input data, in octal, per line.Syntax:hd -o input.txt"
},
{
"code": null,
"e": 1758,
"s": 1750,
"text": "Syntax:"
},
{
"code": null,
"e": 1774,
"s": 1758,
"text": "hd -o input.txt"
},
{
"code": null,
"e": 2270,
"s": 1774,
"text": "-s offset : Skip ‘offset’ bytes from the beginning of the input. By default, offset is interpreted as a decimal number. With a leading 0x or 0X, offset is interpreted as a hexadecimal number, otherwise, with a leading 0, offset is interpreted as an octal number. Appending the character b, k, or m to offset causes it to be interpreted as a multiple of 512, 1024, or 1048576, respectively.Syntax:hd -s offset input.txtAs you can see, in the output, first 6 characters, i.e. ‘Hello ‘ are skipped."
},
{
"code": null,
"e": 2278,
"s": 2270,
"text": "Syntax:"
},
{
"code": null,
"e": 2301,
"s": 2278,
"text": "hd -s offset input.txt"
},
{
"code": null,
"e": 2379,
"s": 2301,
"text": "As you can see, in the output, first 6 characters, i.e. ‘Hello ‘ are skipped."
},
{
"code": null,
"e": 2930,
"s": 2379,
"text": "-v : Cause hexdump to display all input data. Without the -v option, any number of groups of output lines, which would be identical to the immediately preceding group of output lines (except for the input offsets), are replaced with a line comprised of a single asterisk.Syntax:hd -v input.txtWe will see the use of this option as we display the output using -c flag.As you can observe, when we use hd for the first time, without -v, when similar output appears, it prints out an asterisk (*). But when we pass a -v flag, we get all the output lines."
},
{
"code": null,
"e": 2938,
"s": 2930,
"text": "Syntax:"
},
{
"code": null,
"e": 2954,
"s": 2938,
"text": "hd -v input.txt"
},
{
"code": null,
"e": 3029,
"s": 2954,
"text": "We will see the use of this option as we display the output using -c flag."
},
{
"code": null,
"e": 3213,
"s": 3029,
"text": "As you can observe, when we use hd for the first time, without -v, when similar output appears, it prints out an asterisk (*). But when we pass a -v flag, we get all the output lines."
},
{
"code": null,
"e": 3434,
"s": 3213,
"text": "-x : Two-byte hexadecimal display. Display the input offset in hexadecimal, followed by eight, space separated, four column, zero-filled, two-byte quantities of input data, in hexadecimal, per line.Syntax:hd -x input.txt"
},
{
"code": null,
"e": 3442,
"s": 3434,
"text": "Syntax:"
},
{
"code": null,
"e": 3458,
"s": 3442,
"text": "hd -x input.txt"
},
{
"code": null,
"e": 3472,
"s": 3458,
"text": "linux-command"
},
{
"code": null,
"e": 3492,
"s": 3472,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 3499,
"s": 3492,
"text": "Picked"
},
{
"code": null,
"e": 3510,
"s": 3499,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3608,
"s": 3510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3643,
"s": 3608,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 3679,
"s": 3643,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 3715,
"s": 3679,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 3753,
"s": 3715,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 3779,
"s": 3753,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3814,
"s": 3779,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3852,
"s": 3814,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 3888,
"s": 3852,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 3923,
"s": 3888,
"text": "Cat command in Linux with examples"
}
] |
Fetch fields from table or structure in ABAP SAP
|
If you need to identify the fields and number of fields in a structure, then you should use runtime type services. Using runtime type services makes more sense in this case as if we have some data in our environment, then it’s not ideal to call database for fetching the same.
DATA(structure) = VALUE <your structure>( )
DATA(Descriptor) = CAST cl_abap_structdescr( cl_abap_datadescr=>describe_by_data
(structure) )
DATA(Fields = LINES(Descriptor ->components )
This will give you the count of the components of the table or structure.
You can also try another option if you do not want to use runtime type services. Below query can get you’re the count
SELECT COUNT(*) INTO @data(count)
FROM DD03l (// this table stores the fields information of SAP tables)
WHERE tabname = <Structure name>
AND AS4LOCAL = 'A'
|
[
{
"code": null,
"e": 1464,
"s": 1187,
"text": "If you need to identify the fields and number of fields in a structure, then you should use runtime type services. Using runtime type services makes more sense in this case as if we have some data in our environment, then it’s not ideal to call database for fetching the same."
},
{
"code": null,
"e": 1669,
"s": 1464,
"text": "DATA(structure) = VALUE <your structure>( )\nDATA(Descriptor) = CAST cl_abap_structdescr( cl_abap_datadescr=>describe_by_data\n (structure) )\nDATA(Fields = LINES(Descriptor ->components ) "
},
{
"code": null,
"e": 1743,
"s": 1669,
"text": "This will give you the count of the components of the table or structure."
},
{
"code": null,
"e": 1861,
"s": 1743,
"text": "You can also try another option if you do not want to use runtime type services. Below query can get you’re the count"
},
{
"code": null,
"e": 2034,
"s": 1861,
"text": "SELECT COUNT(*) INTO @data(count)\nFROM DD03l (// this table stores the fields information of SAP tables)\nWHERE tabname = <Structure name>\n AND AS4LOCAL = 'A'"
}
] |
TensorFlow – How to create a numpy ndarray from a tensor
|
01 Aug, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks.
To create a numpy array from Tensor, Tensor is converted to a proto tensor first.
Method Used:
make_ndarray: This method accepts a TensorProto as input and returns a numpy array with same content as TensorProto.
Example 1:
Python3
# importing the libraryimport tensorflow as tf # Initializing Inputvalue = tf.constant([1, 15, 10], dtype = tf.float64) # Printing the Inputprint("Value: ", value) # Converting Tensor to TensorProtoproto = tf.make_tensor_proto(value) # Generating numpy arrayres = tf.make_ndarray(proto) # Printing the resulting numpy arrayprint("Result: ", res)
Output:
Value: tf.Tensor([ 1. 15. 10.], shape=(3, ), dtype=float64)
Result: [ 1. 15. 10.]
Example 2: This example uses a Tensor with shape (2, 2) so the shape of resulting array will be (2, 2).
Python3
# importing the libraryimport tensorflow as tf # Initializing Inputvalue = tf.constant([[1, 2], [3, 4]], dtype = tf.float64) # Printing the Inputprint("Value: ", value) # Converting Tensor to TensorProtoproto = tf.make_tensor_proto(value) # Generating numpy arrayres = tf.make_ndarray(proto) # Printing the resulting numpy arrayprint("Result: ", res)
Output:
Value: tf.Tensor(
[[1. 2.]
[3. 4.]], shape=(2, 2), dtype=float64)
Result: [[1. 2.]
[3. 4.]]
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 159,
"s": 28,
"text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks."
},
{
"code": null,
"e": 241,
"s": 159,
"text": "To create a numpy array from Tensor, Tensor is converted to a proto tensor first."
},
{
"code": null,
"e": 254,
"s": 241,
"text": "Method Used:"
},
{
"code": null,
"e": 371,
"s": 254,
"text": "make_ndarray: This method accepts a TensorProto as input and returns a numpy array with same content as TensorProto."
},
{
"code": null,
"e": 382,
"s": 371,
"text": "Example 1:"
},
{
"code": null,
"e": 390,
"s": 382,
"text": "Python3"
},
{
"code": "# importing the libraryimport tensorflow as tf # Initializing Inputvalue = tf.constant([1, 15, 10], dtype = tf.float64) # Printing the Inputprint(\"Value: \", value) # Converting Tensor to TensorProtoproto = tf.make_tensor_proto(value) # Generating numpy arrayres = tf.make_ndarray(proto) # Printing the resulting numpy arrayprint(\"Result: \", res)",
"e": 741,
"s": 390,
"text": null
},
{
"code": null,
"e": 749,
"s": 741,
"text": "Output:"
},
{
"code": null,
"e": 835,
"s": 749,
"text": "Value: tf.Tensor([ 1. 15. 10.], shape=(3, ), dtype=float64)\nResult: [ 1. 15. 10.]\n\n"
},
{
"code": null,
"e": 939,
"s": 835,
"text": "Example 2: This example uses a Tensor with shape (2, 2) so the shape of resulting array will be (2, 2)."
},
{
"code": null,
"e": 947,
"s": 939,
"text": "Python3"
},
{
"code": "# importing the libraryimport tensorflow as tf # Initializing Inputvalue = tf.constant([[1, 2], [3, 4]], dtype = tf.float64) # Printing the Inputprint(\"Value: \", value) # Converting Tensor to TensorProtoproto = tf.make_tensor_proto(value) # Generating numpy arrayres = tf.make_ndarray(proto) # Printing the resulting numpy arrayprint(\"Result: \", res)",
"e": 1303,
"s": 947,
"text": null
},
{
"code": null,
"e": 1311,
"s": 1303,
"text": "Output:"
},
{
"code": null,
"e": 1410,
"s": 1311,
"text": "Value: tf.Tensor(\n[[1. 2.]\n [3. 4.]], shape=(2, 2), dtype=float64)\nResult: [[1. 2.]\n [3. 4.]]\n\n\n"
},
{
"code": null,
"e": 1428,
"s": 1410,
"text": "Python-Tensorflow"
},
{
"code": null,
"e": 1435,
"s": 1428,
"text": "Python"
}
] |
How to use the canvas drawImage() method in HTML5 ?
|
02 Sep, 2020
The canvas drawImage() method of the Canvas 2D API is used to draw an image in various ways on a canvas element. This method has additional parameters that can be used to display the image or a part of the image.
Syntax:
context.drawImage(img, x, y, swidth, sheight, sx, sy, width, height);
Approach:
Add image using the <img> tag.
Draw the canvas using <canvas> tag.
Load the canvas and get the context.
Select the image to be used,
Draw the image along with additional optional parameters, if required.
Example 1: In this example, the position of the image in the canvas is set using additional parameters.
html
<!DOCTYPE html><html> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <p>Image:</p> <img id="gfg_image" src="https://media.geeksforgeeks.org/wp-content/uploads/20200604000733/gfg199.png" /> <p>Canvas:</p> <canvas id="myGFGCanvas" width="500" height="300" style="border: 5px solid black"> </canvas> <script> window.onload = function () { // Get the canvas element from the page var canvas = document.getElementById("myGFGCanvas"); // Get the 2D context of the canvas var ctx = canvas.getContext("2d"); // Get the image to be drawn on the canvas var image = document.getElementById("gfg_image"); // Draw the image using drawImage() function // The first parameter is the image to be drawn // The second and third parameter is the // x and y position of the image in the canvas ctx.drawImage(image, 100, 20); }; </script></body> </html>
Output:
Example 2: In this example, the position and dimensions of the image is set using additional parameters.
HTML
<!DOCTYPE html><html> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <p>Image:</p> <img id="gfg_image" src="https://media.geeksforgeeks.org/wp-content/uploads/20200604000733/gfg199.png" /> <p>Canvas:</p> <canvas id="myGFGCanvas" width="500" height="300" style="border: 5px solid black"> </canvas> <script> window.onload = function () { // Get the canvas element from the page var canvas = document.getElementById("myGFGCanvas"); // Get the 2D context of the canvas var ctx = canvas.getContext("2d"); // Get the image to be drawn on the canvas var image = document.getElementById("gfg_image"); // Draw the image using drawImage() function // The first parameter is the image to be drawn // The second and third parameter is the // x and y position of the image in the canvas // The fourth and fifth parameter is the // width and height of the image to be drawn // in the canvas ctx.drawImage(image, 20, 20, 400, 200); }; </script></body> </html>
CSS-Misc
HTML-Canvas
HTML-Misc
JavaScript-Misc
HTML
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Design a Tribute Page using HTML & CSS
Remove elements from a JavaScript Array
How to Open URL in New Tab using JavaScript ?
File uploading in React.js
How to execute PHP code using command line ?
How to get character array from string in JavaScript?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 241,
"s": 28,
"text": "The canvas drawImage() method of the Canvas 2D API is used to draw an image in various ways on a canvas element. This method has additional parameters that can be used to display the image or a part of the image."
},
{
"code": null,
"e": 249,
"s": 241,
"text": "Syntax:"
},
{
"code": null,
"e": 320,
"s": 249,
"text": "context.drawImage(img, x, y, swidth, sheight, sx, sy, width, height);\n"
},
{
"code": null,
"e": 331,
"s": 320,
"text": "Approach: "
},
{
"code": null,
"e": 362,
"s": 331,
"text": "Add image using the <img> tag."
},
{
"code": null,
"e": 398,
"s": 362,
"text": "Draw the canvas using <canvas> tag."
},
{
"code": null,
"e": 435,
"s": 398,
"text": "Load the canvas and get the context."
},
{
"code": null,
"e": 464,
"s": 435,
"text": "Select the image to be used,"
},
{
"code": null,
"e": 535,
"s": 464,
"text": "Draw the image along with additional optional parameters, if required."
},
{
"code": null,
"e": 639,
"s": 535,
"text": "Example 1: In this example, the position of the image in the canvas is set using additional parameters."
},
{
"code": null,
"e": 644,
"s": 639,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p>Image:</p> <img id=\"gfg_image\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200604000733/gfg199.png\" /> <p>Canvas:</p> <canvas id=\"myGFGCanvas\" width=\"500\" height=\"300\" style=\"border: 5px solid black\"> </canvas> <script> window.onload = function () { // Get the canvas element from the page var canvas = document.getElementById(\"myGFGCanvas\"); // Get the 2D context of the canvas var ctx = canvas.getContext(\"2d\"); // Get the image to be drawn on the canvas var image = document.getElementById(\"gfg_image\"); // Draw the image using drawImage() function // The first parameter is the image to be drawn // The second and third parameter is the // x and y position of the image in the canvas ctx.drawImage(image, 100, 20); }; </script></body> </html>",
"e": 1690,
"s": 644,
"text": null
},
{
"code": null,
"e": 1698,
"s": 1690,
"text": "Output:"
},
{
"code": null,
"e": 1803,
"s": 1698,
"text": "Example 2: In this example, the position and dimensions of the image is set using additional parameters."
},
{
"code": null,
"e": 1808,
"s": 1803,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p>Image:</p> <img id=\"gfg_image\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200604000733/gfg199.png\" /> <p>Canvas:</p> <canvas id=\"myGFGCanvas\" width=\"500\" height=\"300\" style=\"border: 5px solid black\"> </canvas> <script> window.onload = function () { // Get the canvas element from the page var canvas = document.getElementById(\"myGFGCanvas\"); // Get the 2D context of the canvas var ctx = canvas.getContext(\"2d\"); // Get the image to be drawn on the canvas var image = document.getElementById(\"gfg_image\"); // Draw the image using drawImage() function // The first parameter is the image to be drawn // The second and third parameter is the // x and y position of the image in the canvas // The fourth and fifth parameter is the // width and height of the image to be drawn // in the canvas ctx.drawImage(image, 20, 20, 400, 200); }; </script></body> </html>",
"e": 3001,
"s": 1808,
"text": null
},
{
"code": null,
"e": 3010,
"s": 3001,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3022,
"s": 3010,
"text": "HTML-Canvas"
},
{
"code": null,
"e": 3032,
"s": 3022,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3048,
"s": 3032,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3053,
"s": 3048,
"text": "HTML"
},
{
"code": null,
"e": 3080,
"s": 3053,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3085,
"s": 3080,
"text": "HTML"
},
{
"code": null,
"e": 3183,
"s": 3085,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3207,
"s": 3183,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3257,
"s": 3207,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 3294,
"s": 3257,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 3322,
"s": 3294,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 3361,
"s": 3322,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3401,
"s": 3361,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3447,
"s": 3401,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 3474,
"s": 3447,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 3519,
"s": 3474,
"text": "How to execute PHP code using command line ?"
}
] |
Longest valid Parentheses | Practice | GeeksforGeeks
|
Given a string S consisting of opening and closing parenthesis '(' and ')'. Find length of the longest valid parenthesis substring.
A parenthesis string is valid if:
For every opening parenthesis, there is a closing parenthesis.
Opening parenthesis must be closed in the correct order.
Example 1:
Input: S = ((()
Output: 2
Explaination: The longest valid
parenthesis substring is "()".
Example 2:
Input: S = )()())
Output: 4
Explaination: The longest valid
parenthesis substring is "()()".
Your Task:
You do not need to read input or print anything. Your task is to complete the function maxLength() which takes string S as input parameter and returns the length of the maximum valid parenthesis substring.
Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(|S|)
Constraints:
1 ≤ |S| ≤ 105
0
chessnoobdjin 4 hours
C++
int maxLength(string S){
stack <int> st;
st.push(-1);
int ans = 0, n = S.size();
for(int i=0; i<n; i++){
if(st.top() != -1
&& S[st.top()] == '(' && S[i] == ')'){
st.pop();
ans = max(ans, i-st.top());
}
else
st.push(i);
}
return ans;
}
0
mihirchavda13621 week ago
java simple solution Tc o(n) and constant space o(1)
easy to understand
static int maxLength(String s){ int l = 0; int r = 0; int ans =0; for(int i=0;i<s.length();i++){ if(s.charAt(i) == '(') l++; else r++; if(l == r) ans = Math.max(ans , l*2); else if(r > l){ l =0; r =0; } } l=0; r=0; for(int i = s.length() -1;i >= 0;i--){ if(s.charAt(i) == '(') l++; else r++; if( l == r) ans = Math.max(ans,l * 2); else if(l > r){ l=0; r=0; }
} return ans; }
0
karanrajkkr953 weeks ago
int maxLength(string S){ stack<int>st; st.push(-1); int count=0; int n=S.size(); for(int i=0;i<n;i++){ if(S[i]=='('){ st.push(i); } else{ st.pop(); if(st.empty()){ st.push(i); } else{ int k=i-st.top(); count=max(count,k); } } } return count; }
+1
conceptcodcbue3 weeks ago
Detail Explanation and Java Code link: https://youtu.be/N7Flx0qA9Ro
Logic:1) when going from left to right, if ')' is more than '(', then it is an invalid case and restart count.2) when going from right to left '(' is more than ')', then it is an invalid case and restart count.Step 2 is needed because step 1 will give the wrong answer in this example, "(()"
+1
shubhamrikhari86514 weeks ago
int maxLength(string s){ int l = 0, r = 0, maxi = INT_MIN, maxi1 = INT_MIN; bool x = false; for(int i=0; i<s.size(); i++) { if(s[i] == '(') { l++; } else if(s[i] == ')') { r++; } if(l==r) { maxi = max(maxi, 2*l); x = true; } else if(r > l) { l = 0, r = 0; } } l = 0, r = 0; for(int i=s.size()-1; i>=0; i--) { if(s[i] == '(') { l++; } else if(s[i] == ')') { r++; } if(l == r) { maxi1 = max(maxi1, 2*l); x = true; } else if(l > r) { l = 0, r = 0; } } if(x == true) return max(maxi,maxi1); return 0; }
0
hridayguna4 weeks ago
Easy java soln || 0.2sec
static int maxLength(String s){ int len = 0; int[] dp = new int[s.length()+1]; Stack<Integer> stack = new Stack<>(); for(int i=0;i<s.length();i++){ if(s.charAt(i)=='('){ dp[i]=0; stack.push(i); }else if(s.charAt(i)==')'){ if(stack.isEmpty()){ dp[i] = 0; }else{ int j = stack.pop(); if(j>0){ dp[i] = dp[i-1]+dp[j-1]+2;} else{ dp[i] = dp[i-1]+2; } } } len = Math.max(dp[i],len); } return len; }
0
anis231 month ago
C++ Solution || Stack || Short & Simple:
class Solution{
public:
int maxLength(string S){
// code here
int n = S.length();
stack<int> st;
st.push(-1);
int m = 0;
for (int i = 0; i < n; i++)
{
int p = st.size();
if (S[i] == '(')
{
st.push(i);
}
else
{
st.pop();
if (st.empty())
{
st.push(i);
}
else
{
int k = i - st.top();
m = max(m, k);
}
}
}
return m;
}
};
0
mondaltarakes1 month ago
int maxLength(string S){
// code here
stack<int>st;
int prev[S.length()];
for(int i=0;i<S.length();i++)
prev[i]=0;
int i=0,count=0,maxcount=0;
while(i<S.length()){
if(!st.empty() && S[st.top()]=='(' && S[i]==')'){
prev[st.top()]=1;
prev[i]=1;
st.pop();
i++;
}else{
st.push(i);
i++;
}
}
//find maximum consecutive 1's
for(int i=0;i<S.length();i++){
if(prev[i]==0){
count=0;
}else{
count++;
maxcount=max(maxcount,count);
}
}
maxcount=max(maxcount,count);
return maxcount;
}
0
kumaarsahab4321 month ago
//Using Stack
int maxLength(string S){
stack<int> s;
s.push(-1) ;
int len=0, n=S.length() ;
for(int i=0 ; i<n ; i++)
{
if(S[i]=='(') s.push(i) ;
if(S[i]==')'){
s.pop() ;
if(s.empty()) s.push(i) ;
else{
int temp=i-s.top() ;
len=max(temp,len) ;
}
}
}
return len ;
}
0
ashwinkumar99311 month ago
Simple C++ understandable solution
int maxLength(string S){
// code here
int n = S.length();
stack<pair<int, char>> stk;
stk.push({0, 'B'}); // for base condn
for(int i=0;i<n;i++){
char ch = S[i];
int x = stk.top().first;
char t = stk.top().second;
if(t=='(' && ch==')'){
stk.pop();
int x2 = stk.top().first;
char t2 = stk.top().second;
stk.pop();
// insert sum of previous sequences in stack
stk.push({x+1+x2, t2});
}
else{
stk.push({0, ch}); // insert '0' since rule is breaked;
}
}
int ans = 0;
while(!stk.empty()){
int k = stk.top().first;
ans = max(ans, k);
stk.pop();
}
return ans*2;
}
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 370,
"s": 238,
"text": "Given a string S consisting of opening and closing parenthesis '(' and ')'. Find length of the longest valid parenthesis substring."
},
{
"code": null,
"e": 404,
"s": 370,
"text": "A parenthesis string is valid if:"
},
{
"code": null,
"e": 467,
"s": 404,
"text": "For every opening parenthesis, there is a closing parenthesis."
},
{
"code": null,
"e": 524,
"s": 467,
"text": "Opening parenthesis must be closed in the correct order."
},
{
"code": null,
"e": 535,
"s": 524,
"text": "Example 1:"
},
{
"code": null,
"e": 625,
"s": 535,
"text": "Input: S = ((()\nOutput: 2\nExplaination: The longest valid \nparenthesis substring is \"()\"."
},
{
"code": null,
"e": 636,
"s": 625,
"text": "Example 2:"
},
{
"code": null,
"e": 730,
"s": 636,
"text": "Input: S = )()())\nOutput: 4\nExplaination: The longest valid \nparenthesis substring is \"()()\"."
},
{
"code": null,
"e": 947,
"s": 730,
"text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function maxLength() which takes string S as input parameter and returns the length of the maximum valid parenthesis substring."
},
{
"code": null,
"e": 1013,
"s": 947,
"text": "Expected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(|S|)"
},
{
"code": null,
"e": 1042,
"s": 1013,
"text": "Constraints:\n1 ≤ |S| ≤ 105 "
},
{
"code": null,
"e": 1044,
"s": 1042,
"text": "0"
},
{
"code": null,
"e": 1066,
"s": 1044,
"text": "chessnoobdjin 4 hours"
},
{
"code": null,
"e": 1071,
"s": 1066,
"text": "C++ "
},
{
"code": null,
"e": 1399,
"s": 1071,
"text": "int maxLength(string S){\n stack <int> st;\n st.push(-1);\n int ans = 0, n = S.size();\n for(int i=0; i<n; i++){\n if(st.top() != -1 \n && S[st.top()] == '(' && S[i] == ')'){\n st.pop();\n ans = max(ans, i-st.top());\n }\n else\n st.push(i);\n }\n return ans;\n}"
},
{
"code": null,
"e": 1401,
"s": 1399,
"text": "0"
},
{
"code": null,
"e": 1427,
"s": 1401,
"text": "mihirchavda13621 week ago"
},
{
"code": null,
"e": 1480,
"s": 1427,
"text": "java simple solution Tc o(n) and constant space o(1)"
},
{
"code": null,
"e": 1499,
"s": 1480,
"text": "easy to understand"
},
{
"code": null,
"e": 2158,
"s": 1499,
"text": " static int maxLength(String s){ int l = 0; int r = 0; int ans =0; for(int i=0;i<s.length();i++){ if(s.charAt(i) == '(') l++; else r++; if(l == r) ans = Math.max(ans , l*2); else if(r > l){ l =0; r =0; } } l=0; r=0; for(int i = s.length() -1;i >= 0;i--){ if(s.charAt(i) == '(') l++; else r++; if( l == r) ans = Math.max(ans,l * 2); else if(l > r){ l=0; r=0; }"
},
{
"code": null,
"e": 2189,
"s": 2158,
"text": " } return ans; }"
},
{
"code": null,
"e": 2193,
"s": 2191,
"text": "0"
},
{
"code": null,
"e": 2218,
"s": 2193,
"text": "karanrajkkr953 weeks ago"
},
{
"code": null,
"e": 2684,
"s": 2218,
"text": "int maxLength(string S){ stack<int>st; st.push(-1); int count=0; int n=S.size(); for(int i=0;i<n;i++){ if(S[i]=='('){ st.push(i); } else{ st.pop(); if(st.empty()){ st.push(i); } else{ int k=i-st.top(); count=max(count,k); } } } return count; }"
},
{
"code": null,
"e": 2687,
"s": 2684,
"text": "+1"
},
{
"code": null,
"e": 2713,
"s": 2687,
"text": "conceptcodcbue3 weeks ago"
},
{
"code": null,
"e": 2781,
"s": 2713,
"text": "Detail Explanation and Java Code link: https://youtu.be/N7Flx0qA9Ro"
},
{
"code": null,
"e": 3073,
"s": 2781,
"text": "Logic:1) when going from left to right, if ')' is more than '(', then it is an invalid case and restart count.2) when going from right to left '(' is more than ')', then it is an invalid case and restart count.Step 2 is needed because step 1 will give the wrong answer in this example, \"(()\""
},
{
"code": null,
"e": 3078,
"s": 3075,
"text": "+1"
},
{
"code": null,
"e": 3108,
"s": 3078,
"text": "shubhamrikhari86514 weeks ago"
},
{
"code": null,
"e": 3979,
"s": 3108,
"text": "int maxLength(string s){ int l = 0, r = 0, maxi = INT_MIN, maxi1 = INT_MIN; bool x = false; for(int i=0; i<s.size(); i++) { if(s[i] == '(') { l++; } else if(s[i] == ')') { r++; } if(l==r) { maxi = max(maxi, 2*l); x = true; } else if(r > l) { l = 0, r = 0; } } l = 0, r = 0; for(int i=s.size()-1; i>=0; i--) { if(s[i] == '(') { l++; } else if(s[i] == ')') { r++; } if(l == r) { maxi1 = max(maxi1, 2*l); x = true; } else if(l > r) { l = 0, r = 0; } } if(x == true) return max(maxi,maxi1); return 0; }"
},
{
"code": null,
"e": 3981,
"s": 3979,
"text": "0"
},
{
"code": null,
"e": 4003,
"s": 3981,
"text": "hridayguna4 weeks ago"
},
{
"code": null,
"e": 4028,
"s": 4003,
"text": "Easy java soln || 0.2sec"
},
{
"code": null,
"e": 4701,
"s": 4030,
"text": "static int maxLength(String s){ int len = 0; int[] dp = new int[s.length()+1]; Stack<Integer> stack = new Stack<>(); for(int i=0;i<s.length();i++){ if(s.charAt(i)=='('){ dp[i]=0; stack.push(i); }else if(s.charAt(i)==')'){ if(stack.isEmpty()){ dp[i] = 0; }else{ int j = stack.pop(); if(j>0){ dp[i] = dp[i-1]+dp[j-1]+2;} else{ dp[i] = dp[i-1]+2; } } } len = Math.max(dp[i],len); } return len; }"
},
{
"code": null,
"e": 4703,
"s": 4701,
"text": "0"
},
{
"code": null,
"e": 4721,
"s": 4703,
"text": "anis231 month ago"
},
{
"code": null,
"e": 4762,
"s": 4721,
"text": "C++ Solution || Stack || Short & Simple:"
},
{
"code": null,
"e": 5434,
"s": 4764,
"text": "\nclass Solution{\npublic:\n int maxLength(string S){\n // code here\n int n = S.length();\n stack<int> st;\n st.push(-1);\n int m = 0;\n for (int i = 0; i < n; i++)\n {\n int p = st.size();\n if (S[i] == '(')\n {\n st.push(i);\n }\n else\n {\n st.pop();\n if (st.empty())\n {\n st.push(i);\n }\n else\n {\n int k = i - st.top();\n m = max(m, k);\n }\n }\n }\n return m;\n }\n};"
},
{
"code": null,
"e": 5436,
"s": 5434,
"text": "0"
},
{
"code": null,
"e": 5461,
"s": 5436,
"text": "mondaltarakes1 month ago"
},
{
"code": null,
"e": 6246,
"s": 5461,
"text": " int maxLength(string S){\n // code here\n stack<int>st;\n int prev[S.length()];\n for(int i=0;i<S.length();i++)\n prev[i]=0;\n int i=0,count=0,maxcount=0;\n \n while(i<S.length()){\n if(!st.empty() && S[st.top()]=='(' && S[i]==')'){\n prev[st.top()]=1;\n prev[i]=1;\n st.pop();\n i++;\n }else{\n st.push(i);\n i++;\n }\n }\n \n //find maximum consecutive 1's\n for(int i=0;i<S.length();i++){\n if(prev[i]==0){\n count=0;\n }else{\n count++;\n maxcount=max(maxcount,count);\n \n }\n }\n \n maxcount=max(maxcount,count);\n \n return maxcount;\n }\n\n "
},
{
"code": null,
"e": 6248,
"s": 6246,
"text": "0"
},
{
"code": null,
"e": 6274,
"s": 6248,
"text": "kumaarsahab4321 month ago"
},
{
"code": null,
"e": 6747,
"s": 6274,
"text": "//Using Stack\nint maxLength(string S){\n stack<int> s;\n s.push(-1) ;\n int len=0, n=S.length() ;\n for(int i=0 ; i<n ; i++)\n {\n if(S[i]=='(') s.push(i) ;\n if(S[i]==')'){\n s.pop() ;\n if(s.empty()) s.push(i) ;\n else{\n int temp=i-s.top() ;\n len=max(temp,len) ;\n }\n }\n }\n \n return len ;\n }"
},
{
"code": null,
"e": 6749,
"s": 6747,
"text": "0"
},
{
"code": null,
"e": 6776,
"s": 6749,
"text": "ashwinkumar99311 month ago"
},
{
"code": null,
"e": 6811,
"s": 6776,
"text": "Simple C++ understandable solution"
},
{
"code": null,
"e": 7814,
"s": 6811,
"text": "int maxLength(string S){\n // code here\n \n int n = S.length();\n \n stack<pair<int, char>> stk;\n \n stk.push({0, 'B'}); // for base condn\n \n for(int i=0;i<n;i++){\n \n char ch = S[i];\n \n int x = stk.top().first;\n char t = stk.top().second;\n \n if(t=='(' && ch==')'){ \n stk.pop();\n int x2 = stk.top().first;\n char t2 = stk.top().second;\n stk.pop();\n // insert sum of previous sequences in stack\n stk.push({x+1+x2, t2});\n }\n else{\n stk.push({0, ch}); // insert '0' since rule is breaked;\n }\n }\n \n int ans = 0;\n \n while(!stk.empty()){\n int k = stk.top().first;\n \n ans = max(ans, k);\n \n stk.pop();\n }\n \n return ans*2;\n }"
},
{
"code": null,
"e": 7960,
"s": 7814,
"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": 7996,
"s": 7960,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8006,
"s": 7996,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8016,
"s": 8006,
"text": "\nContest\n"
},
{
"code": null,
"e": 8079,
"s": 8016,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8264,
"s": 8079,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8548,
"s": 8264,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 8694,
"s": 8548,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 8771,
"s": 8694,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 8812,
"s": 8771,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 8840,
"s": 8812,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 8911,
"s": 8840,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 9098,
"s": 8911,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Matplotlib.colors.rgb_to_hsv() in Python
|
07 Oct, 2021
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.colors.rgb_to_hsv() function belongs to the matplotlib.colors module. The matplotlib.colors.rgb_to_hsv() function is used to convert float rgb in the range of 0 to 1 into a numpy array of hsv values.
Syntax: matplotlib.colors.rgb_to_hsv(arr)
Parameters:
arr: It is an array-like argument in the form of (..., 3) where all values must to be in the range of 0 to 1.
Returns:
hsv: It returns an ndarray in the form of (..., 3) that comprises of colors converted to hsv values within the range of 0 to 1.
Example 1:
import matplotlib.pyplot as pltimport matplotlib.colors as mcolors # helper function to plot a # color tabledef colortable(colors, title, colors_sort = True, emptycols=0): # cell dimensions width = 212 height = 22 swatch_width = 48 margin = 12 topmargin = 40 # Sorting colors based on hue, # saturation, value and name. if colors_sort is True: to_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(color))), name) for name, color in colors.items()) names = [name for hsv, name in to_hsv] else: names = list(colors) length_of_names = len(names) length_cols = 4 - emptycols length_rows = length_of_names // length_cols + int(length_of_names % length_cols > 0) width2 = width * 4 + 2 * margin height2 = height * length_rows + margin + topmargin dpi = 72 figure, axes = plt.subplots(figsize=(width2 / dpi, height2 / dpi), dpi=dpi) figure.subplots_adjust(margin/width2, margin/height2, (width2-margin)/width2, (height2-topmargin)/height2) axes.set_xlim(0, width * 4) axes.set_ylim(height * (length_rows-0.5), -height/2.) axes.yaxis.set_visible(False) axes.xaxis.set_visible(False) axes.set_axis_off() axes.set_title(title, fontsize=24, loc="left", pad=10) for i, name in enumerate(names): rows = i % length_rows cols = i // length_rows y = rows * height swatch_start_x = width * cols swatch_end_x = width * cols + swatch_width text_pos_x = width * cols + swatch_width + 7 axes.text(text_pos_x, y, name, fontsize=14, horizontalalignment='left', verticalalignment='center') axes.hlines(y, swatch_start_x, swatch_end_x, color=colors[name], linewidth=18) return figure colortable(mcolors.BASE_COLORS, "Base Colors", colors_sort=False, emptycols=1)colortable(mcolors.TABLEAU_COLORS, "Tableau Palette", colors_sort=False, emptycols=2)colortable(mcolors.CSS4_COLORS, "CSS Colors") plt.show()
Output:
Example 2:
Image Used:
import matplotlibimport matplotlib.pyplot as pltimport matplotlib.image as mpimg image = mpimg.imread('food.jpeg')plt.title("Output image") hsv = matplotlib.colors.rgb_to_hsv(image)plt.imshow(hsv)
Output:
adnanirshad158
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 264,
"s": 52,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack."
},
{
"code": null,
"e": 479,
"s": 264,
"text": "The matplotlib.colors.rgb_to_hsv() function belongs to the matplotlib.colors module. The matplotlib.colors.rgb_to_hsv() function is used to convert float rgb in the range of 0 to 1 into a numpy array of hsv values."
},
{
"code": null,
"e": 521,
"s": 479,
"text": "Syntax: matplotlib.colors.rgb_to_hsv(arr)"
},
{
"code": null,
"e": 533,
"s": 521,
"text": "Parameters:"
},
{
"code": null,
"e": 643,
"s": 533,
"text": "arr: It is an array-like argument in the form of (..., 3) where all values must to be in the range of 0 to 1."
},
{
"code": null,
"e": 652,
"s": 643,
"text": "Returns:"
},
{
"code": null,
"e": 780,
"s": 652,
"text": "hsv: It returns an ndarray in the form of (..., 3) that comprises of colors converted to hsv values within the range of 0 to 1."
},
{
"code": null,
"e": 791,
"s": 780,
"text": "Example 1:"
},
{
"code": "import matplotlib.pyplot as pltimport matplotlib.colors as mcolors # helper function to plot a # color tabledef colortable(colors, title, colors_sort = True, emptycols=0): # cell dimensions width = 212 height = 22 swatch_width = 48 margin = 12 topmargin = 40 # Sorting colors based on hue, # saturation, value and name. if colors_sort is True: to_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(color))), name) for name, color in colors.items()) names = [name for hsv, name in to_hsv] else: names = list(colors) length_of_names = len(names) length_cols = 4 - emptycols length_rows = length_of_names // length_cols + int(length_of_names % length_cols > 0) width2 = width * 4 + 2 * margin height2 = height * length_rows + margin + topmargin dpi = 72 figure, axes = plt.subplots(figsize=(width2 / dpi, height2 / dpi), dpi=dpi) figure.subplots_adjust(margin/width2, margin/height2, (width2-margin)/width2, (height2-topmargin)/height2) axes.set_xlim(0, width * 4) axes.set_ylim(height * (length_rows-0.5), -height/2.) axes.yaxis.set_visible(False) axes.xaxis.set_visible(False) axes.set_axis_off() axes.set_title(title, fontsize=24, loc=\"left\", pad=10) for i, name in enumerate(names): rows = i % length_rows cols = i // length_rows y = rows * height swatch_start_x = width * cols swatch_end_x = width * cols + swatch_width text_pos_x = width * cols + swatch_width + 7 axes.text(text_pos_x, y, name, fontsize=14, horizontalalignment='left', verticalalignment='center') axes.hlines(y, swatch_start_x, swatch_end_x, color=colors[name], linewidth=18) return figure colortable(mcolors.BASE_COLORS, \"Base Colors\", colors_sort=False, emptycols=1)colortable(mcolors.TABLEAU_COLORS, \"Tableau Palette\", colors_sort=False, emptycols=2)colortable(mcolors.CSS4_COLORS, \"CSS Colors\") plt.show()",
"e": 3016,
"s": 791,
"text": null
},
{
"code": null,
"e": 3024,
"s": 3016,
"text": "Output:"
},
{
"code": null,
"e": 3035,
"s": 3024,
"text": "Example 2:"
},
{
"code": null,
"e": 3047,
"s": 3035,
"text": "Image Used:"
},
{
"code": "import matplotlibimport matplotlib.pyplot as pltimport matplotlib.image as mpimg image = mpimg.imread('food.jpeg')plt.title(\"Output image\") hsv = matplotlib.colors.rgb_to_hsv(image)plt.imshow(hsv)",
"e": 3250,
"s": 3047,
"text": null
},
{
"code": null,
"e": 3258,
"s": 3250,
"text": "Output:"
},
{
"code": null,
"e": 3273,
"s": 3258,
"text": "adnanirshad158"
},
{
"code": null,
"e": 3291,
"s": 3273,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 3298,
"s": 3291,
"text": "Python"
},
{
"code": null,
"e": 3314,
"s": 3298,
"text": "Write From Home"
}
] |
Randomized Algorithms | Set 0 (Mathematical Background)
|
21 Sep, 2021
Conditional Probability Conditional probability P(A | B) indicates the probability of even ‘A’ happening given that the even B happened.
We can easily understand above formula using below diagram. Since B has already happened, the sample space reduces to B. So the probability of A happening becomes P(A ∩ B) divided by P(B)
Below is Bayes’s formula for conditional probability.
The formula provides relationship between P(A|B) and P(B|A). It is mainly derived form conditional probability formula discussed in the previous post.
Consider the below formulas for conditional probabilities P(A|B) and P(B|A)
Since P(B ∩ A) = P(A ∩ B), we can replace P(A ∩ B) in first formula with P(B|A)P(A) After replacing, we get the given formula. Refer this for examples of Bayes’s formula.
Random Variables: A random variable is actually a function that maps outcome of a random event (like coin toss) to a real value.
Example :
Coin tossing game :
A player pays 50 bucks if result of coin
toss is "Head"
The person gets 50 bucks if the result is
Tail.
A random variable profit for person can
be defined as below :
Profit = +50 if Head
-50 if Tail
Generally gambling games are not fair for players,
the organizer takes a share of profit for all
arrangements. So expected profit is negative for
a player in gambling and positive for the organizer.
That is how organizers make money.
Expected Value of Random Variable : Expected value of a random variable R can be defined as following
E[R] = r1*p1 + r2*p2 + ... rk*pk
ri ==> Value of R with probability pi
Expected value is basically sum of product of following two terms (for all possible events) a) Probability of an event. b) Value of R at that even
Example 1:
In above example of coin toss,
Expected value of profit = 50 * (1/2) +
(-50) * (1/2)
= 0
Example 2:
Expected value of six faced dice throw is
= 1*(1/6) + 2*(1/6) + .... + 6*(1/6)
= 3.5
Linearity of Expectation: Let R1 and R2 be two discrete random variables on some probability space, then
E[R1 + R2] = E[R1] + E[R2]
For example, expected value of sum for 3 dice throws is = 3 * 7/2 = 7
Refer this for more detailed explanation and examples.
Expected Number of Trials until Success If probability of success is p in every trial, then expected number of trials until success is 1/p. For example, consider 6 faced fair dice is thrown until a ‘5’ is seen as result of dice throw. The expected number of throws before seeing a 5 is 6. Note that 1/6 is probability of getting a 5 in every trial. So number of trials is 1/(1/6) = 6. As another example, consider a QuickSort version that keeps on looking for pivots until one of the middle n/2 elements is picked. The expected time number of trials for finding middle pivot would be 2 as probability of picking one of the middle n/2 elements is 1/2. This example is discussed in more detail in Set 1. Refer this for more detailed explanation and examples.
More on Randomized Algorithms:
Randomized Algorithms | Set 1 (Introduction and Analysis)
Randomized Algorithms | Set 2 (Classification and Applications)
Randomized Algorithms | Set 3 (1/2 Approximate Median)
All Randomized Algorithm Topics
This article is contributed by Shivam Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
ChandanKumar9
s01183
simmytarika5
Randomized
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
Shuffle a given array using Fisher–Yates shuffle Algorithm
Shuffle or Randomize a list in Java
Generating Random String Using PHP
Estimating the value of Pi using Monte Carlo
Operations on Sparse Matrices
Reservoir Sampling
Shuffle a deck of cards
Expected Number of Trials until Success
Randomized Binary Search Algorithm
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 189,
"s": 52,
"text": "Conditional Probability Conditional probability P(A | B) indicates the probability of even ‘A’ happening given that the even B happened."
},
{
"code": null,
"e": 378,
"s": 189,
"text": "We can easily understand above formula using below diagram. Since B has already happened, the sample space reduces to B. So the probability of A happening becomes P(A ∩ B) divided by P(B) "
},
{
"code": null,
"e": 433,
"s": 378,
"text": "Below is Bayes’s formula for conditional probability. "
},
{
"code": null,
"e": 585,
"s": 433,
"text": "The formula provides relationship between P(A|B) and P(B|A). It is mainly derived form conditional probability formula discussed in the previous post. "
},
{
"code": null,
"e": 662,
"s": 585,
"text": "Consider the below formulas for conditional probabilities P(A|B) and P(B|A) "
},
{
"code": null,
"e": 834,
"s": 662,
"text": "Since P(B ∩ A) = P(A ∩ B), we can replace P(A ∩ B) in first formula with P(B|A)P(A) After replacing, we get the given formula. Refer this for examples of Bayes’s formula. "
},
{
"code": null,
"e": 964,
"s": 834,
"text": "Random Variables: A random variable is actually a function that maps outcome of a random event (like coin toss) to a real value. "
},
{
"code": null,
"e": 975,
"s": 964,
"text": "Example : "
},
{
"code": null,
"e": 1452,
"s": 975,
"text": "Coin tossing game : \nA player pays 50 bucks if result of coin\ntoss is \"Head\" \n\nThe person gets 50 bucks if the result is\nTail. \n\nA random variable profit for person can \nbe defined as below : \n\nProfit = +50 if Head\n -50 if Tail \n\nGenerally gambling games are not fair for players, \nthe organizer takes a share of profit for all \narrangements. So expected profit is negative for \na player in gambling and positive for the organizer. \nThat is how organizers make money."
},
{
"code": null,
"e": 1554,
"s": 1452,
"text": "Expected Value of Random Variable : Expected value of a random variable R can be defined as following"
},
{
"code": null,
"e": 1639,
"s": 1554,
"text": " E[R] = r1*p1 + r2*p2 + ... rk*pk \n \n ri ==> Value of R with probability pi"
},
{
"code": null,
"e": 1787,
"s": 1639,
"text": "Expected value is basically sum of product of following two terms (for all possible events) a) Probability of an event. b) Value of R at that even "
},
{
"code": null,
"e": 2041,
"s": 1787,
"text": "Example 1:\nIn above example of coin toss,\nExpected value of profit = 50 * (1/2) + \n (-50) * (1/2)\n = 0\n\nExample 2:\nExpected value of six faced dice throw is \n = 1*(1/6) + 2*(1/6) + .... + 6*(1/6)\n = 3.5"
},
{
"code": null,
"e": 2147,
"s": 2041,
"text": "Linearity of Expectation: Let R1 and R2 be two discrete random variables on some probability space, then "
},
{
"code": null,
"e": 2180,
"s": 2147,
"text": " E[R1 + R2] = E[R1] + E[R2] "
},
{
"code": null,
"e": 2251,
"s": 2180,
"text": "For example, expected value of sum for 3 dice throws is = 3 * 7/2 = 7 "
},
{
"code": null,
"e": 2307,
"s": 2251,
"text": "Refer this for more detailed explanation and examples. "
},
{
"code": null,
"e": 3065,
"s": 2307,
"text": "Expected Number of Trials until Success If probability of success is p in every trial, then expected number of trials until success is 1/p. For example, consider 6 faced fair dice is thrown until a ‘5’ is seen as result of dice throw. The expected number of throws before seeing a 5 is 6. Note that 1/6 is probability of getting a 5 in every trial. So number of trials is 1/(1/6) = 6. As another example, consider a QuickSort version that keeps on looking for pivots until one of the middle n/2 elements is picked. The expected time number of trials for finding middle pivot would be 2 as probability of picking one of the middle n/2 elements is 1/2. This example is discussed in more detail in Set 1. Refer this for more detailed explanation and examples. "
},
{
"code": null,
"e": 3097,
"s": 3065,
"text": "More on Randomized Algorithms: "
},
{
"code": null,
"e": 3155,
"s": 3097,
"text": "Randomized Algorithms | Set 1 (Introduction and Analysis)"
},
{
"code": null,
"e": 3219,
"s": 3155,
"text": "Randomized Algorithms | Set 2 (Classification and Applications)"
},
{
"code": null,
"e": 3274,
"s": 3219,
"text": "Randomized Algorithms | Set 3 (1/2 Approximate Median)"
},
{
"code": null,
"e": 3307,
"s": 3274,
"text": "All Randomized Algorithm Topics "
},
{
"code": null,
"e": 3477,
"s": 3307,
"text": "This article is contributed by Shivam Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 3491,
"s": 3477,
"text": "ChandanKumar9"
},
{
"code": null,
"e": 3498,
"s": 3491,
"text": "s01183"
},
{
"code": null,
"e": 3511,
"s": 3498,
"text": "simmytarika5"
},
{
"code": null,
"e": 3522,
"s": 3511,
"text": "Randomized"
},
{
"code": null,
"e": 3620,
"s": 3522,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3699,
"s": 3620,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)"
},
{
"code": null,
"e": 3758,
"s": 3699,
"text": "Shuffle a given array using Fisher–Yates shuffle Algorithm"
},
{
"code": null,
"e": 3794,
"s": 3758,
"text": "Shuffle or Randomize a list in Java"
},
{
"code": null,
"e": 3829,
"s": 3794,
"text": "Generating Random String Using PHP"
},
{
"code": null,
"e": 3874,
"s": 3829,
"text": "Estimating the value of Pi using Monte Carlo"
},
{
"code": null,
"e": 3904,
"s": 3874,
"text": "Operations on Sparse Matrices"
},
{
"code": null,
"e": 3923,
"s": 3904,
"text": "Reservoir Sampling"
},
{
"code": null,
"e": 3947,
"s": 3923,
"text": "Shuffle a deck of cards"
},
{
"code": null,
"e": 3987,
"s": 3947,
"text": "Expected Number of Trials until Success"
}
] |
Dijkstra’s Algorithm for Adjacency List Representation
|
There is a given graph G(V, E) with its adjacency list representation, and a source vertex is also provided. Dijkstra’s algorithm to find the minimum shortest path between source vertex to any other vertex of the graph G.
To Solve this problem, we will use two lists. One is to store vertices which have been considered as the shortest path tree, and another will hold the vertices which are not considered yet. In each phase of the algorithm, we find the unconsidered vertex and which has the minimum distance from the source.
Another list is used to hold the predecessor node. Using the predecessor node, we can find the path from source and destination.
The complexity of Dijkstra’s shortest path algorithm is O(E log V) as the graph is represented using adjacency list. Here the E is the number of edges, and V is Number of vertices.
Input:
The adjacency list of the graph with the cost of each edge.
Output:
0 to 1, Cost: 3 Previous: 0
0 to 2, Cost: 5 Previous: 1
0 to 3, Cost: 4 Previous: 1
0 to 4, Cost: 6 Previous: 3
0 to 5, Cost: 7 Previous: 2
0 to 6, Cost: 7 Previous: 4
dijkstraShortestPath(g : Graph, dist, prev, start : node)
Input − The graph g, dist list to store distance, prev list for predecessor nodes, and start vertex.
Output − The shortest paths from start to all other vertices.
Begin
for all vertices u in (V - start) do
dist[u] := ∞
prev[u] := φ
done
set dist[start] = 0 and prev[start] := φ
for all node u in V do
insert u into queue ‘Q’.
done
while Q is not empty do
u := minimum element from Queue
delete u from Q
insert u into set S
for each node v adjacent with node u do
if dist[u]+cost(v) < dist[v] then
dist[v] := dist[u]+cost(v)
prev[v] := u
done
done
End
#include<iostream>
#include<set>
#include<list>
#include<algorithm>
using namespace std;
typedef struct nodes {
int dest;
int cost;
}node;
class Graph {
int n;
list<node> *adjList;
private:
void showList(int src, list<node> lt) {
list<node> :: iterator i;
node tempNode;
for(i = lt.begin(); i != lt.end(); i++) {
tempNode = *i;
cout << "(" << src << ")---("<<tempNode.dest << "|"<<tempNode.cost<<") ";
}
cout << endl;
}
public:
Graph() {
n = 0;
}
Graph(int nodeCount) {
n = nodeCount;
adjList = new list<node>[n];
}
void addEdge(int source, int dest, int cost) {
node newNode;
newNode.dest = dest;
newNode.cost = cost;
adjList[source].push_back(newNode);
}
void displayEdges() {
for(int i = 0; i<n; i++) {
list<node> tempList = adjList[i];
showList(i, tempList);
}
}
friend void dijkstra(Graph g, int *dist, int *prev, int start);
};
void dijkstra(Graph g, int *dist, int *prev, int start) {
int n = g.n;
for(int u = 0; u<n; u++) {
dist[u] = 9999; //set as infinity
prev[u] = -1; //undefined previous
}
dist[start] = 0; //distance of start is 0
set<int> S; //create empty set S
list<int> Q;
for(int u = 0; u<n; u++) {
Q.push_back(u); //add each node into queue
}
while(!Q.empty()) {
list<int> :: iterator i;
i = min_element(Q.begin(), Q.end());
int u = *i; //the minimum element from queue
Q.remove(u);
S.insert(u); //add u in the set
list<node> :: iterator it;
for(it = g.adjList[u].begin(); it != g.adjList[u].end();it++) {
if((dist[u]+(it->cost)) < dist[it->dest]) { //relax (u,v)
dist[it->dest] = (dist[u]+(it->cost));
prev[it->dest] = u;
}
}
}
}
main() {
int n = 7;
Graph g(n);
int dist[n], prev[n];
int start = 0;
g.addEdge(0, 1, 3);
g.addEdge(0, 2, 6);
g.addEdge(1, 0, 3);
g.addEdge(1, 2, 2);
g.addEdge(1, 3, 1);
g.addEdge(2, 1, 6);
g.addEdge(2, 1, 2);
g.addEdge(2, 3, 1);
g.addEdge(2, 4, 4);
g.addEdge(2, 5, 2);
g.addEdge(3, 1, 1);
g.addEdge(3, 2, 1);
g.addEdge(3, 4, 2);
g.addEdge(3, 6, 4);
g.addEdge(4, 2, 4);
g.addEdge(4, 3, 2);
g.addEdge(4, 5, 2);
g.addEdge(4, 6, 1);
g.addEdge(5, 2, 2);
g.addEdge(5, 4, 2);
g.addEdge(5, 6, 1);
g.addEdge(6, 3, 4);
g.addEdge(6, 4, 1);
g.addEdge(6, 5, 1);
dijkstra(g, dist, prev, start);
for(int i = 0; i<n; i++)
if(i != start)
cout<<start<<" to "<<i<<", Cost: "<<dist[i]<<" Previous: "<<prev[i]<<endl;
}
0 to 1, Cost: 3 Previous: 0
0 to 2, Cost: 5 Previous: 1
0 to 3, Cost: 4 Previous: 1
0 to 4, Cost: 6 Previous: 3
0 to 5, Cost: 7 Previous: 2
0 to 6, Cost: 7 Previous: 4
|
[
{
"code": null,
"e": 1409,
"s": 1187,
"text": "There is a given graph G(V, E) with its adjacency list representation, and a source vertex is also provided. Dijkstra’s algorithm to find the minimum shortest path between source vertex to any other vertex of the graph G."
},
{
"code": null,
"e": 1715,
"s": 1409,
"text": "To Solve this problem, we will use two lists. One is to store vertices which have been considered as the shortest path tree, and another will hold the vertices which are not considered yet. In each phase of the algorithm, we find the unconsidered vertex and which has the minimum distance from the source."
},
{
"code": null,
"e": 1844,
"s": 1715,
"text": "Another list is used to hold the predecessor node. Using the predecessor node, we can find the path from source and destination."
},
{
"code": null,
"e": 2025,
"s": 1844,
"text": "The complexity of Dijkstra’s shortest path algorithm is O(E log V) as the graph is represented using adjacency list. Here the E is the number of edges, and V is Number of vertices."
},
{
"code": null,
"e": 2269,
"s": 2025,
"text": "Input:\nThe adjacency list of the graph with the cost of each edge.\n\nOutput:\n0 to 1, Cost: 3 Previous: 0\n0 to 2, Cost: 5 Previous: 1\n0 to 3, Cost: 4 Previous: 1\n0 to 4, Cost: 6 Previous: 3\n0 to 5, Cost: 7 Previous: 2\n0 to 6, Cost: 7 Previous: 4"
},
{
"code": null,
"e": 2327,
"s": 2269,
"text": "dijkstraShortestPath(g : Graph, dist, prev, start : node)"
},
{
"code": null,
"e": 2428,
"s": 2327,
"text": "Input − The graph g, dist list to store distance, prev list for predecessor nodes, and start vertex."
},
{
"code": null,
"e": 2490,
"s": 2428,
"text": "Output − The shortest paths from start to all other vertices."
},
{
"code": null,
"e": 2984,
"s": 2490,
"text": "Begin\n for all vertices u in (V - start) do\n dist[u] := ∞\n prev[u] := φ\n done\n\n set dist[start] = 0 and prev[start] := φ\n\n for all node u in V do\n insert u into queue ‘Q’.\n done\n\n while Q is not empty do\n u := minimum element from Queue\n delete u from Q\n insert u into set S\n\n for each node v adjacent with node u do\n if dist[u]+cost(v) < dist[v] then\n dist[v] := dist[u]+cost(v)\n prev[v] := u\n done\n done\nEnd"
},
{
"code": null,
"e": 5768,
"s": 2984,
"text": "#include<iostream>\n#include<set>\n#include<list>\n#include<algorithm>\nusing namespace std;\n\ntypedef struct nodes {\n int dest;\n int cost;\n}node;\n\nclass Graph {\n int n;\n list<node> *adjList;\n private:\n void showList(int src, list<node> lt) {\n list<node> :: iterator i;\n node tempNode;\n\n for(i = lt.begin(); i != lt.end(); i++) {\n tempNode = *i;\n cout << \"(\" << src << \")---(\"<<tempNode.dest << \"|\"<<tempNode.cost<<\") \";\n }\n cout << endl;\n }\n public:\n Graph() {\n n = 0;\n }\n\n Graph(int nodeCount) {\n n = nodeCount;\n adjList = new list<node>[n];\n }\n\n void addEdge(int source, int dest, int cost) {\n node newNode;\n newNode.dest = dest;\n newNode.cost = cost;\n adjList[source].push_back(newNode);\n }\n\n void displayEdges() {\n for(int i = 0; i<n; i++) {\n list<node> tempList = adjList[i];\n showList(i, tempList);\n }\n }\n\n friend void dijkstra(Graph g, int *dist, int *prev, int start);\n};\n\nvoid dijkstra(Graph g, int *dist, int *prev, int start) {\n int n = g.n;\n\n for(int u = 0; u<n; u++) {\n dist[u] = 9999; //set as infinity\n prev[u] = -1; //undefined previous\n }\n\n dist[start] = 0; //distance of start is 0\n set<int> S; //create empty set S\n list<int> Q;\n\n for(int u = 0; u<n; u++) {\n Q.push_back(u); //add each node into queue\n }\n\n while(!Q.empty()) {\n list<int> :: iterator i;\n i = min_element(Q.begin(), Q.end());\n int u = *i; //the minimum element from queue\n Q.remove(u);\n S.insert(u); //add u in the set\n list<node> :: iterator it;\n\n for(it = g.adjList[u].begin(); it != g.adjList[u].end();it++) {\n if((dist[u]+(it->cost)) < dist[it->dest]) { //relax (u,v)\n dist[it->dest] = (dist[u]+(it->cost));\n prev[it->dest] = u;\n }\n }\n }\n}\n\nmain() {\n int n = 7;\n Graph g(n);\n int dist[n], prev[n];\n int start = 0;\n\n g.addEdge(0, 1, 3);\n g.addEdge(0, 2, 6);\n g.addEdge(1, 0, 3);\n g.addEdge(1, 2, 2);\n g.addEdge(1, 3, 1);\n g.addEdge(2, 1, 6);\n g.addEdge(2, 1, 2);\n g.addEdge(2, 3, 1);\n g.addEdge(2, 4, 4);\n\n g.addEdge(2, 5, 2);\n g.addEdge(3, 1, 1);\n g.addEdge(3, 2, 1);\n g.addEdge(3, 4, 2);\n g.addEdge(3, 6, 4);\n g.addEdge(4, 2, 4);\n g.addEdge(4, 3, 2);\n g.addEdge(4, 5, 2);\n g.addEdge(4, 6, 1);\n g.addEdge(5, 2, 2);\n g.addEdge(5, 4, 2);\n g.addEdge(5, 6, 1);\n g.addEdge(6, 3, 4);\n g.addEdge(6, 4, 1);\n g.addEdge(6, 5, 1);\n\n dijkstra(g, dist, prev, start);\n\n for(int i = 0; i<n; i++)\n if(i != start)\n cout<<start<<\" to \"<<i<<\", Cost: \"<<dist[i]<<\" Previous: \"<<prev[i]<<endl;\n}"
},
{
"code": null,
"e": 5936,
"s": 5768,
"text": "0 to 1, Cost: 3 Previous: 0\n0 to 2, Cost: 5 Previous: 1\n0 to 3, Cost: 4 Previous: 1\n0 to 4, Cost: 6 Previous: 3\n0 to 5, Cost: 7 Previous: 2\n0 to 6, Cost: 7 Previous: 4"
}
] |
Sort a binary array using one traversal
|
09 Jul, 2022
Given a binary array, sort it using one traversal and no extra space.Examples :
Input : 1 0 0 1 0 1 0 1 1 1 1 1 1 0 0 1 1 0 1 0 0
Output : 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1
Explanation: The output is a sorted array of 0 and 1
Input : 1 0 1 0 1 0 1 0
Output : 0 0 0 0 1 1 1 1
Explanation: The output is a sorted array of 0 and 1
Approach: This concept is related to partition of quick sort . In quick sort partition, after one scan, the left of the array is smallest and right of the array is the largest of selected pivot element.Algorithm:
Create a variable index say j = -1Traverse the array from start to endIf the element is 0 then swap the current element with the element at index( jth ) position and increment the index (j) by 1.If the element is 1 keep the element as it is.
Create a variable index say j = -1
Traverse the array from start to end
If the element is 0 then swap the current element with the element at index( jth ) position and increment the index (j) by 1.
If the element is 1 keep the element as it is.
Implementation:
CPP
Java
Python3
C#
PHP
Javascript
// CPP program to sort a binary array#include <iostream>using namespace std; void sortBinaryArray(int a[], int n){ int j = -1; for (int i = 0; i < n; i++) { // if number is smaller than 1 // then swap it with j-th number if (a[i] < 1) { j++; swap(a[i], a[j]); } }} // Driver codeint main(){ int a[] = { 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0 }; int n = sizeof(a) / sizeof(a[0]); sortBinaryArray(a, n); for (int i = 0; i < n; i++) cout << a[i] << " "; return 0;}
// JAVA Code for Sort a binary// array using one traversalimport java.util.*; class GFG { static void sortBinaryArray(int a[], int n) { int j = -1; for (int i = 0; i < n; i++) { // if number is smaller than 1 // then swap it with j-th number if (a[i] < 1) { j++; int temp = a[j]; a[j] = a[i]; a[i] = temp; } } } /* Driver program to test above function */ public static void main(String[] args) { int a[] = { 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0 }; int n = a.length; sortBinaryArray(a, n); for (int i = 0; i < n; i++) System.out.print(a[i] + " "); }}
# A Python program to sort a# binary arraydef sortBinaryArray(a, n): j = -1 for i in range(n): # if number is smaller # than 1 then swap it # with j-th number if a[i] < 1: j = j + 1 # swap a[i], a[j] = a[j], a[i] # Driver programa = [1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0]n = len(a) sortBinaryArray(a, n) for i in range(n): print(a[i], end = " ") # This code is contributed by Shrikant13.
// C# Code for Sort a binary// array using one traversalusing System; class GFG { static void sortBinaryArray(int[] a, int n) { int j = -1; for (int i = 0; i < n; i++) { // if number is smaller than // 1 then swap it with j-th // number if (a[i] < 1) { j++; int temp = a[j]; a[j] = a[i]; a[i] = temp; } } } /* Driver program to test above function */ public static void Main() { int[] a = { 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0 }; int n = a.Length; sortBinaryArray(a, n); for (int i = 0; i < n; i++) Console.Write(a[i] + " "); }} // This code is contributed by vt_m.
<?php// PHP Code for Sort a binary// array using one traversalfunction sortBinaryArray($a, $n){ $j = -1; for ($i = 0; $i < $n; $i++) { // if number is smaller than // 1 then swap it with j-th // number if ($a[$i] < 1) { $j++; $temp = $a[$j]; $a[$j] = $a[$i]; $a[$i] = $temp; } }for ($i = 0; $i < $n; $i++) echo $a[$i] . " "; } // Driver Code$a = array(1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0); $n = count($a);sortBinaryArray($a, $n); // This code is contributed by Sam007?>
<script>// Javascript Code for Sort a binary// array using one traversal function sortBinaryArray(a, n) { let j = -1; for (let i = 0; i < n; i++) { // if number is smaller than 1 // then swap it with j-th number if (a[i] < 1) { j++; let temp = a[j]; a[j] = a[i]; a[i] = temp; } } } // driver function let a = [ 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0 ]; let n = a.length; sortBinaryArray(a, n); for (let i = 0; i < n; i++) document.write(a[i] + " "); // This code is contributed by code_hunt.</script>
Output :
0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1
Complexity Analysis:
Time Complexity: O(n). Only one traversal of the array is needed, So time Complexity is O(n).
Space Complexity:O(1). The space required is constant.
This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
shrikanth13
Sam007
andrew1234
code_hunt
navihere
binary-string
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexities of all Sorting Algorithms
Count Inversions in an array | Set 1 (Using Merge Sort)
Merge two sorted arrays
Radix Sort
Chocolate Distribution Problem
Find a triplet that sum to a given value
k largest(or smallest) elements in an array
Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)
Minimum number of swaps required to sort an array
sort() in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jul, 2022"
},
{
"code": null,
"e": 134,
"s": 52,
"text": "Given a binary array, sort it using one traversal and no extra space.Examples : "
},
{
"code": null,
"e": 393,
"s": 134,
"text": "Input : 1 0 0 1 0 1 0 1 1 1 1 1 1 0 0 1 1 0 1 0 0 \nOutput : 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1\nExplanation: The output is a sorted array of 0 and 1\n\nInput : 1 0 1 0 1 0 1 0 \nOutput : 0 0 0 0 1 1 1 1\nExplanation: The output is a sorted array of 0 and 1"
},
{
"code": null,
"e": 610,
"s": 395,
"text": "Approach: This concept is related to partition of quick sort . In quick sort partition, after one scan, the left of the array is smallest and right of the array is the largest of selected pivot element.Algorithm: "
},
{
"code": null,
"e": 852,
"s": 610,
"text": "Create a variable index say j = -1Traverse the array from start to endIf the element is 0 then swap the current element with the element at index( jth ) position and increment the index (j) by 1.If the element is 1 keep the element as it is."
},
{
"code": null,
"e": 887,
"s": 852,
"text": "Create a variable index say j = -1"
},
{
"code": null,
"e": 924,
"s": 887,
"text": "Traverse the array from start to end"
},
{
"code": null,
"e": 1050,
"s": 924,
"text": "If the element is 0 then swap the current element with the element at index( jth ) position and increment the index (j) by 1."
},
{
"code": null,
"e": 1097,
"s": 1050,
"text": "If the element is 1 keep the element as it is."
},
{
"code": null,
"e": 1115,
"s": 1097,
"text": "Implementation: "
},
{
"code": null,
"e": 1119,
"s": 1115,
"text": "CPP"
},
{
"code": null,
"e": 1124,
"s": 1119,
"text": "Java"
},
{
"code": null,
"e": 1132,
"s": 1124,
"text": "Python3"
},
{
"code": null,
"e": 1135,
"s": 1132,
"text": "C#"
},
{
"code": null,
"e": 1139,
"s": 1135,
"text": "PHP"
},
{
"code": null,
"e": 1150,
"s": 1139,
"text": "Javascript"
},
{
"code": "// CPP program to sort a binary array#include <iostream>using namespace std; void sortBinaryArray(int a[], int n){ int j = -1; for (int i = 0; i < n; i++) { // if number is smaller than 1 // then swap it with j-th number if (a[i] < 1) { j++; swap(a[i], a[j]); } }} // Driver codeint main(){ int a[] = { 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0 }; int n = sizeof(a) / sizeof(a[0]); sortBinaryArray(a, n); for (int i = 0; i < n; i++) cout << a[i] << \" \"; return 0;}",
"e": 1733,
"s": 1150,
"text": null
},
{
"code": "// JAVA Code for Sort a binary// array using one traversalimport java.util.*; class GFG { static void sortBinaryArray(int a[], int n) { int j = -1; for (int i = 0; i < n; i++) { // if number is smaller than 1 // then swap it with j-th number if (a[i] < 1) { j++; int temp = a[j]; a[j] = a[i]; a[i] = temp; } } } /* Driver program to test above function */ public static void main(String[] args) { int a[] = { 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0 }; int n = a.length; sortBinaryArray(a, n); for (int i = 0; i < n; i++) System.out.print(a[i] + \" \"); }}",
"e": 2520,
"s": 1733,
"text": null
},
{
"code": "# A Python program to sort a# binary arraydef sortBinaryArray(a, n): j = -1 for i in range(n): # if number is smaller # than 1 then swap it # with j-th number if a[i] < 1: j = j + 1 # swap a[i], a[j] = a[j], a[i] # Driver programa = [1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0]n = len(a) sortBinaryArray(a, n) for i in range(n): print(a[i], end = \" \") # This code is contributed by Shrikant13.",
"e": 3033,
"s": 2520,
"text": null
},
{
"code": "// C# Code for Sort a binary// array using one traversalusing System; class GFG { static void sortBinaryArray(int[] a, int n) { int j = -1; for (int i = 0; i < n; i++) { // if number is smaller than // 1 then swap it with j-th // number if (a[i] < 1) { j++; int temp = a[j]; a[j] = a[i]; a[i] = temp; } } } /* Driver program to test above function */ public static void Main() { int[] a = { 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0 }; int n = a.Length; sortBinaryArray(a, n); for (int i = 0; i < n; i++) Console.Write(a[i] + \" \"); }} // This code is contributed by vt_m.",
"e": 3909,
"s": 3033,
"text": null
},
{
"code": "<?php// PHP Code for Sort a binary// array using one traversalfunction sortBinaryArray($a, $n){ $j = -1; for ($i = 0; $i < $n; $i++) { // if number is smaller than // 1 then swap it with j-th // number if ($a[$i] < 1) { $j++; $temp = $a[$j]; $a[$j] = $a[$i]; $a[$i] = $temp; } }for ($i = 0; $i < $n; $i++) echo $a[$i] . \" \"; } // Driver Code$a = array(1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0); $n = count($a);sortBinaryArray($a, $n); // This code is contributed by Sam007?>",
"e": 4536,
"s": 3909,
"text": null
},
{
"code": "<script>// Javascript Code for Sort a binary// array using one traversal function sortBinaryArray(a, n) { let j = -1; for (let i = 0; i < n; i++) { // if number is smaller than 1 // then swap it with j-th number if (a[i] < 1) { j++; let temp = a[j]; a[j] = a[i]; a[i] = temp; } } } // driver function let a = [ 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0 ]; let n = a.length; sortBinaryArray(a, n); for (let i = 0; i < n; i++) document.write(a[i] + \" \"); // This code is contributed by code_hunt.</script> ",
"e": 5274,
"s": 4536,
"text": null
},
{
"code": null,
"e": 5285,
"s": 5274,
"text": "Output : "
},
{
"code": null,
"e": 5327,
"s": 5285,
"text": "0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1"
},
{
"code": null,
"e": 5350,
"s": 5327,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 5444,
"s": 5350,
"text": "Time Complexity: O(n). Only one traversal of the array is needed, So time Complexity is O(n)."
},
{
"code": null,
"e": 5501,
"s": 5446,
"text": "Space Complexity:O(1). The space required is constant."
},
{
"code": null,
"e": 5926,
"s": 5501,
"text": "This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 5931,
"s": 5926,
"text": "vt_m"
},
{
"code": null,
"e": 5943,
"s": 5931,
"text": "shrikanth13"
},
{
"code": null,
"e": 5950,
"s": 5943,
"text": "Sam007"
},
{
"code": null,
"e": 5961,
"s": 5950,
"text": "andrew1234"
},
{
"code": null,
"e": 5971,
"s": 5961,
"text": "code_hunt"
},
{
"code": null,
"e": 5980,
"s": 5971,
"text": "navihere"
},
{
"code": null,
"e": 5994,
"s": 5980,
"text": "binary-string"
},
{
"code": null,
"e": 6002,
"s": 5994,
"text": "Sorting"
},
{
"code": null,
"e": 6010,
"s": 6002,
"text": "Sorting"
},
{
"code": null,
"e": 6108,
"s": 6010,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6152,
"s": 6108,
"text": "Time Complexities of all Sorting Algorithms"
},
{
"code": null,
"e": 6208,
"s": 6152,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 6232,
"s": 6208,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 6243,
"s": 6232,
"text": "Radix Sort"
},
{
"code": null,
"e": 6274,
"s": 6243,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 6315,
"s": 6274,
"text": "Find a triplet that sum to a given value"
},
{
"code": null,
"e": 6359,
"s": 6315,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 6425,
"s": 6359,
"text": "Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)"
},
{
"code": null,
"e": 6475,
"s": 6425,
"text": "Minimum number of swaps required to sort an array"
}
] |
Python | Pandas Series.div()
|
01 Oct, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Python Series.div() is used to divide series or list like objects with same length by the caller series.
Syntax: Series.div(other, level=None, fill_value=None, axis=0)
Parameters:other: other series or list type to be divided by the caller seriesfill_value: Value to be replaced by NaN in series/list before divisionlevel: integer value of level in case of multi index
Return type: Caller series with divided values
To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1: Dividing Series by list
In this example, the top 5 rows are stored in new variable using .head() method. After that a list of same length is created and the age column is divided by the list column using .div() method
# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # creating short data of 5 rowsshort_data = data.head() # creating list with 5 valueslist =[1, 2, 3, 4, 5] # Dividing by list data# creating new columnshort_data["Divided Age values"]= short_data["Age"].div(list) # displayshort_data
Output:As shown in the output image, it can be compared that the Divided age value column is having the Divided values of (Age)/(list). Example #2: Dividing series by series having null values
In this example, the Salary column is divided by the Age column. Since the salary column contains null values too, by default it returns NaN no matter what is divided. In this example, 200000 is passed to replace null values with 200000.
# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # passing age series to variableage = data["Age"] # na replacementna = 200000 # Dividing values# storing to new columndata["Divided values"]= data["Salary"].div(other = age, fill_value = na) # displaydata.head(10)
Output:As shown in the output image, the Divided values column has divided age column with 200000 in case of Null values.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Oct, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 347,
"s": 242,
"text": "Python Series.div() is used to divide series or list like objects with same length by the caller series."
},
{
"code": null,
"e": 410,
"s": 347,
"text": "Syntax: Series.div(other, level=None, fill_value=None, axis=0)"
},
{
"code": null,
"e": 611,
"s": 410,
"text": "Parameters:other: other series or list type to be divided by the caller seriesfill_value: Value to be replaced by NaN in series/list before divisionlevel: integer value of level in case of multi index"
},
{
"code": null,
"e": 658,
"s": 611,
"text": "Return type: Caller series with divided values"
},
{
"code": null,
"e": 868,
"s": 658,
"text": "To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below."
},
{
"code": null,
"e": 904,
"s": 868,
"text": "Example #1: Dividing Series by list"
},
{
"code": null,
"e": 1098,
"s": 904,
"text": "In this example, the top 5 rows are stored in new variable using .head() method. After that a list of same length is created and the age column is divided by the list column using .div() method"
},
{
"code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # creating short data of 5 rowsshort_data = data.head() # creating list with 5 valueslist =[1, 2, 3, 4, 5] # Dividing by list data# creating new columnshort_data[\"Divided Age values\"]= short_data[\"Age\"].div(list) # displayshort_data",
"e": 1491,
"s": 1098,
"text": null
},
{
"code": null,
"e": 1684,
"s": 1491,
"text": "Output:As shown in the output image, it can be compared that the Divided age value column is having the Divided values of (Age)/(list). Example #2: Dividing series by series having null values"
},
{
"code": null,
"e": 1922,
"s": 1684,
"text": "In this example, the Salary column is divided by the Age column. Since the salary column contains null values too, by default it returns NaN no matter what is divided. In this example, 200000 is passed to replace null values with 200000."
},
{
"code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # passing age series to variableage = data[\"Age\"] # na replacementna = 200000 # Dividing values# storing to new columndata[\"Divided values\"]= data[\"Salary\"].div(other = age, fill_value = na) # displaydata.head(10)",
"e": 2296,
"s": 1922,
"text": null
},
{
"code": null,
"e": 2418,
"s": 2296,
"text": "Output:As shown in the output image, the Divided values column has divided age column with 200000 in case of Null values."
},
{
"code": null,
"e": 2439,
"s": 2418,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2468,
"s": 2439,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2482,
"s": 2468,
"text": "Python-pandas"
},
{
"code": null,
"e": 2489,
"s": 2482,
"text": "Python"
}
] |
How to disable scrollbar without hiding using jQuery ?
|
28 Nov, 2019
A vertical or horizontal bar that is located at the corners of the page helps us to scroll the pages or containers upwards, downwards or sideways. So, the process is to disable the scroll bar but the scroll bar should be visible. In this article, we will disable the scroll bar by using .on() function. With the click of the button, we will make the scroll-bar visible but disable.
Disable using jQuery with a button: Here once we disable the scroll event the scroll won’t work whether we want to make the scrollbar visible or not. We gonna trigger the disable function with the click of the button.
Syntax:
$(“selector”).on(event, function)
Example: This example illustrates the approach of disabling the scroll using visibility.
<!DOCTYPE html><html> <head> <title> How to disable scrollbar without hiding using jQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> // On click of button the scroll // gets disabled, still visible. $(document).ready(function() { $("button").click(function() { $("p").text("Scroll-bar is disabled" + " but still visible.") $('#element').on("mousewheel touchmove", function(e) { e.preventDefault(); }); }); }); </script> <style> /*visible active scrollbar*/ #element { height: 150px; width: 400px; border: 2px solid black; overflow: scroll; } </style></head> <body> <center> <h1 style="color: green">GeeksforGeeks</h1> <h3>A Computer Science portal for Geeks</h3> <div id="element"> <b style="font-size:26px;">jQuery:</b> <article style="font-size:18px; text-align:left;"> jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development. </article> </div> <br> <button>Click</button> <p style="color:red"></p> </center></body> </html>
Output:
Before clicking the button scroll is working:
After clicking the button scroll is not working:
Note: Mouse scroll is disabled but if you click scroll down or up button, the frame will shift.
jQuery-Misc
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
jQuery | children() with Examples
How to Dynamically Add/Remove Table Rows using jQuery ?
How to get the value in an input text box using jQuery ?
How to prevent Body from scrolling when a modal is opened using jQuery ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2019"
},
{
"code": null,
"e": 410,
"s": 28,
"text": "A vertical or horizontal bar that is located at the corners of the page helps us to scroll the pages or containers upwards, downwards or sideways. So, the process is to disable the scroll bar but the scroll bar should be visible. In this article, we will disable the scroll bar by using .on() function. With the click of the button, we will make the scroll-bar visible but disable."
},
{
"code": null,
"e": 628,
"s": 410,
"text": "Disable using jQuery with a button: Here once we disable the scroll event the scroll won’t work whether we want to make the scrollbar visible or not. We gonna trigger the disable function with the click of the button."
},
{
"code": null,
"e": 636,
"s": 628,
"text": "Syntax:"
},
{
"code": null,
"e": 670,
"s": 636,
"text": "$(“selector”).on(event, function)"
},
{
"code": null,
"e": 759,
"s": 670,
"text": "Example: This example illustrates the approach of disabling the scroll using visibility."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to disable scrollbar without hiding using jQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> // On click of button the scroll // gets disabled, still visible. $(document).ready(function() { $(\"button\").click(function() { $(\"p\").text(\"Scroll-bar is disabled\" + \" but still visible.\") $('#element').on(\"mousewheel touchmove\", function(e) { e.preventDefault(); }); }); }); </script> <style> /*visible active scrollbar*/ #element { height: 150px; width: 400px; border: 2px solid black; overflow: scroll; } </style></head> <body> <center> <h1 style=\"color: green\">GeeksforGeeks</h1> <h3>A Computer Science portal for Geeks</h3> <div id=\"element\"> <b style=\"font-size:26px;\">jQuery:</b> <article style=\"font-size:18px; text-align:left;\"> jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development. </article> </div> <br> <button>Click</button> <p style=\"color:red\"></p> </center></body> </html>",
"e": 2607,
"s": 759,
"text": null
},
{
"code": null,
"e": 2615,
"s": 2607,
"text": "Output:"
},
{
"code": null,
"e": 2661,
"s": 2615,
"text": "Before clicking the button scroll is working:"
},
{
"code": null,
"e": 2710,
"s": 2661,
"text": "After clicking the button scroll is not working:"
},
{
"code": null,
"e": 2806,
"s": 2710,
"text": "Note: Mouse scroll is disabled but if you click scroll down or up button, the frame will shift."
},
{
"code": null,
"e": 2818,
"s": 2806,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 2825,
"s": 2818,
"text": "Picked"
},
{
"code": null,
"e": 2832,
"s": 2825,
"text": "JQuery"
},
{
"code": null,
"e": 2849,
"s": 2832,
"text": "Web Technologies"
},
{
"code": null,
"e": 2876,
"s": 2849,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2974,
"s": 2876,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3003,
"s": 2974,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 3037,
"s": 3003,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 3093,
"s": 3037,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 3150,
"s": 3093,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 3223,
"s": 3150,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 3285,
"s": 3223,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3318,
"s": 3285,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3379,
"s": 3318,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3429,
"s": 3379,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Relational Operators in Python
|
29 Aug, 2020
Relational operators are used for comparing the values. It either returns True or False according to the condition. These operators are also known as Comparison Operators.
Description
>
<
==
!=
>=
<=
Now Let’s see each Relational Operator one by one.
1) Greater than: This operator returns True if the left operand is greater than the right operand.
Syntax:
x > y
Example:
Python3
a = 9b = 5 # Outputprint(a > b)
Output:
True
2) Less than: This operator returns True if the left operand is less than the right operand.
Syntax:
x < y
Example:
Python3
a = 9b = 5 # Outputprint(a < b)
Output:
False
3) Equal to: This operator returns True if both the operands are equal i.e. if both the left and the right operand are equal to each other.
Example:
Python3
a = 9b = 5 # Outputprint(a == b)
Output:
False
4) Not equal to: This operator returns True if both the operands are not equal.
Syntax:
x != y
Example:
Python3
a = 9b = 5 # Outputprint(a != b)
Output:
True
5) Greater than or equal to: This operator returns True if the left operand is greater than or equal to the right operand.
Syntax:
x >= y
Example:
Python3
a = 9b = 5 # Outputprint(a >= b)
Output:
True
6) Less than or equal to: This operator returns True if the left operand is less than or equal to the right operand.
Syntax:
x <= y
Example:
Python3
a = 9b = 5 # Outputprint(a <= b)
Output:
False
Python-Operators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 226,
"s": 54,
"text": "Relational operators are used for comparing the values. It either returns True or False according to the condition. These operators are also known as Comparison Operators."
},
{
"code": null,
"e": 238,
"s": 226,
"text": "Description"
},
{
"code": null,
"e": 240,
"s": 238,
"text": ">"
},
{
"code": null,
"e": 242,
"s": 240,
"text": "<"
},
{
"code": null,
"e": 245,
"s": 242,
"text": "=="
},
{
"code": null,
"e": 248,
"s": 245,
"text": "!="
},
{
"code": null,
"e": 251,
"s": 248,
"text": ">="
},
{
"code": null,
"e": 254,
"s": 251,
"text": "<="
},
{
"code": null,
"e": 305,
"s": 254,
"text": "Now Let’s see each Relational Operator one by one."
},
{
"code": null,
"e": 404,
"s": 305,
"text": "1) Greater than: This operator returns True if the left operand is greater than the right operand."
},
{
"code": null,
"e": 412,
"s": 404,
"text": "Syntax:"
},
{
"code": null,
"e": 419,
"s": 412,
"text": "x > y\n"
},
{
"code": null,
"e": 428,
"s": 419,
"text": "Example:"
},
{
"code": null,
"e": 436,
"s": 428,
"text": "Python3"
},
{
"code": "a = 9b = 5 # Outputprint(a > b)",
"e": 469,
"s": 436,
"text": null
},
{
"code": null,
"e": 477,
"s": 469,
"text": "Output:"
},
{
"code": null,
"e": 483,
"s": 477,
"text": "True\n"
},
{
"code": null,
"e": 576,
"s": 483,
"text": "2) Less than: This operator returns True if the left operand is less than the right operand."
},
{
"code": null,
"e": 584,
"s": 576,
"text": "Syntax:"
},
{
"code": null,
"e": 591,
"s": 584,
"text": "x < y\n"
},
{
"code": null,
"e": 600,
"s": 591,
"text": "Example:"
},
{
"code": null,
"e": 608,
"s": 600,
"text": "Python3"
},
{
"code": "a = 9b = 5 # Outputprint(a < b)",
"e": 641,
"s": 608,
"text": null
},
{
"code": null,
"e": 649,
"s": 641,
"text": "Output:"
},
{
"code": null,
"e": 656,
"s": 649,
"text": "False\n"
},
{
"code": null,
"e": 796,
"s": 656,
"text": "3) Equal to: This operator returns True if both the operands are equal i.e. if both the left and the right operand are equal to each other."
},
{
"code": null,
"e": 805,
"s": 796,
"text": "Example:"
},
{
"code": null,
"e": 813,
"s": 805,
"text": "Python3"
},
{
"code": "a = 9b = 5 # Outputprint(a == b)",
"e": 847,
"s": 813,
"text": null
},
{
"code": null,
"e": 855,
"s": 847,
"text": "Output:"
},
{
"code": null,
"e": 862,
"s": 855,
"text": "False\n"
},
{
"code": null,
"e": 942,
"s": 862,
"text": "4) Not equal to: This operator returns True if both the operands are not equal."
},
{
"code": null,
"e": 950,
"s": 942,
"text": "Syntax:"
},
{
"code": null,
"e": 958,
"s": 950,
"text": "x != y\n"
},
{
"code": null,
"e": 967,
"s": 958,
"text": "Example:"
},
{
"code": null,
"e": 975,
"s": 967,
"text": "Python3"
},
{
"code": "a = 9b = 5 # Outputprint(a != b)",
"e": 1009,
"s": 975,
"text": null
},
{
"code": null,
"e": 1017,
"s": 1009,
"text": "Output:"
},
{
"code": null,
"e": 1023,
"s": 1017,
"text": "True\n"
},
{
"code": null,
"e": 1146,
"s": 1023,
"text": "5) Greater than or equal to: This operator returns True if the left operand is greater than or equal to the right operand."
},
{
"code": null,
"e": 1154,
"s": 1146,
"text": "Syntax:"
},
{
"code": null,
"e": 1162,
"s": 1154,
"text": "x >= y\n"
},
{
"code": null,
"e": 1171,
"s": 1162,
"text": "Example:"
},
{
"code": null,
"e": 1179,
"s": 1171,
"text": "Python3"
},
{
"code": "a = 9b = 5 # Outputprint(a >= b)",
"e": 1213,
"s": 1179,
"text": null
},
{
"code": null,
"e": 1221,
"s": 1213,
"text": "Output:"
},
{
"code": null,
"e": 1227,
"s": 1221,
"text": "True\n"
},
{
"code": null,
"e": 1344,
"s": 1227,
"text": "6) Less than or equal to: This operator returns True if the left operand is less than or equal to the right operand."
},
{
"code": null,
"e": 1353,
"s": 1344,
"text": "Syntax: "
},
{
"code": null,
"e": 1361,
"s": 1353,
"text": "x <= y\n"
},
{
"code": null,
"e": 1370,
"s": 1361,
"text": "Example:"
},
{
"code": null,
"e": 1378,
"s": 1370,
"text": "Python3"
},
{
"code": "a = 9b = 5 # Outputprint(a <= b)",
"e": 1412,
"s": 1378,
"text": null
},
{
"code": null,
"e": 1420,
"s": 1412,
"text": "Output:"
},
{
"code": null,
"e": 1427,
"s": 1420,
"text": "False\n"
},
{
"code": null,
"e": 1444,
"s": 1427,
"text": "Python-Operators"
},
{
"code": null,
"e": 1451,
"s": 1444,
"text": "Python"
},
{
"code": null,
"e": 1549,
"s": 1451,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1567,
"s": 1549,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1609,
"s": 1567,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1631,
"s": 1609,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1666,
"s": 1631,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1692,
"s": 1666,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1724,
"s": 1692,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1753,
"s": 1724,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1783,
"s": 1753,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1810,
"s": 1783,
"text": "Python Classes and Objects"
}
] |
Python dictionary with keys having multiple inputs
|
22 Sep, 2021
Prerequisite: Python-Dictionary.
How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets.
Example 1:
Python3
# Python code to demonstrate a dictionary# with multiple inputs in a key.import random as rn # creating an empty dictionarydict = {} # Insert first triplet in dictionaryx, y, z = 10, 20, 30dict[x, y, z] = x + y - z; # Insert second triplet in dictionaryx, y, z = 5, 2, 4dict[x, y, z] = x + y - z; # print the dictionaryprint(dict)
Example 2: Let’s get access to the keys. Let us consider a dictionary where longitude and latitude are the keys and the place to which they belong to is the value.
Python3
# dictionary containing longitude and latitude of placesplaces = {("19.07'53.2", "72.54'51.0"):"Mumbai", \ ("28.33'34.1", "77.06'16.6"):"Delhi"} print(places)print('\n') # Traversing dictionary with multi-keys and creating# different lists from itlat = []long = []plc = []for i in places: lat.append(i[0]) long.append(i[1]) plc.append(places[i[0], i[1]]) print(lat)print(long)print(plc)
Now that the keys(latitude, longitude) and values(place) are stored in a list, we can access it easily.
gabaa406
Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 87,
"s": 53,
"text": "Prerequisite: Python-Dictionary. "
},
{
"code": null,
"e": 306,
"s": 87,
"text": "How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets."
},
{
"code": null,
"e": 318,
"s": 306,
"text": "Example 1: "
},
{
"code": null,
"e": 326,
"s": 318,
"text": "Python3"
},
{
"code": "# Python code to demonstrate a dictionary# with multiple inputs in a key.import random as rn # creating an empty dictionarydict = {} # Insert first triplet in dictionaryx, y, z = 10, 20, 30dict[x, y, z] = x + y - z; # Insert second triplet in dictionaryx, y, z = 5, 2, 4dict[x, y, z] = x + y - z; # print the dictionaryprint(dict)",
"e": 657,
"s": 326,
"text": null
},
{
"code": null,
"e": 821,
"s": 657,
"text": "Example 2: Let’s get access to the keys. Let us consider a dictionary where longitude and latitude are the keys and the place to which they belong to is the value."
},
{
"code": null,
"e": 829,
"s": 821,
"text": "Python3"
},
{
"code": "# dictionary containing longitude and latitude of placesplaces = {(\"19.07'53.2\", \"72.54'51.0\"):\"Mumbai\", \\ (\"28.33'34.1\", \"77.06'16.6\"):\"Delhi\"} print(places)print('\\n') # Traversing dictionary with multi-keys and creating# different lists from itlat = []long = []plc = []for i in places: lat.append(i[0]) long.append(i[1]) plc.append(places[i[0], i[1]]) print(lat)print(long)print(plc)",
"e": 1234,
"s": 829,
"text": null
},
{
"code": null,
"e": 1339,
"s": 1234,
"text": "Now that the keys(latitude, longitude) and values(place) are stored in a list, we can access it easily. "
},
{
"code": null,
"e": 1348,
"s": 1339,
"text": "gabaa406"
},
{
"code": null,
"e": 1375,
"s": 1348,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 1387,
"s": 1375,
"text": "python-dict"
},
{
"code": null,
"e": 1394,
"s": 1387,
"text": "Python"
},
{
"code": null,
"e": 1406,
"s": 1394,
"text": "python-dict"
},
{
"code": null,
"e": 1504,
"s": 1406,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1546,
"s": 1504,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1568,
"s": 1546,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1603,
"s": 1568,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1629,
"s": 1603,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1661,
"s": 1629,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1690,
"s": 1661,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1717,
"s": 1690,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1747,
"s": 1717,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1768,
"s": 1747,
"text": "Python OOPs Concepts"
}
] |
Select the maximum for each value in a MySQL table?
|
For this, use GROUP BY clause along with MAX(). Let us first create a table −
mysql> create table DemoTable
-> (
-> CountryName varchar(20),
-> Population int
-> );
Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('US',560);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('UK',10090);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('UK',8794);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('US',1090);
Query OK, 1 row affected (0.21 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------------+------------+
| CountryName | Population |
+-------------+------------+
| US | 560 |
| UK | 10090 |
| UK | 8794 |
| US | 1090 |
+-------------+------------+
4 rows in set (0.00 sec)
Following is the query to select the maximum for each value in a MySQL table −
mysql> select CountryName,max(Population) from DemoTable group by CountryName;
This will produce the following output −
+-------------+-----------------+
| CountryName | max(Population) |
+-------------+-----------------+
| US | 1090 |
| UK | 10090 |
+-------------+-----------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "For this, use GROUP BY clause along with MAX(). Let us first create a table −"
},
{
"code": null,
"e": 1276,
"s": 1140,
"text": "mysql> create table DemoTable\n -> (\n -> CountryName varchar(20),\n -> Population int\n -> );\nQuery OK, 0 rows affected (0.56 sec)"
},
{
"code": null,
"e": 1332,
"s": 1276,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1668,
"s": 1332,
"text": "mysql> insert into DemoTable values('US',560);\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable values('UK',10090);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values('UK',8794);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values('US',1090);\nQuery OK, 1 row affected (0.21 sec)"
},
{
"code": null,
"e": 1728,
"s": 1668,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1759,
"s": 1728,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1800,
"s": 1759,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2057,
"s": 1800,
"text": "+-------------+------------+\n| CountryName | Population |\n+-------------+------------+\n| US | 560 |\n| UK | 10090 |\n| UK | 8794 |\n| US | 1090 |\n+-------------+------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2136,
"s": 2057,
"text": "Following is the query to select the maximum for each value in a MySQL table −"
},
{
"code": null,
"e": 2215,
"s": 2136,
"text": "mysql> select CountryName,max(Population) from DemoTable group by CountryName;"
},
{
"code": null,
"e": 2256,
"s": 2215,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2485,
"s": 2256,
"text": "+-------------+-----------------+\n| CountryName | max(Population) |\n+-------------+-----------------+\n| US | 1090 |\n| UK | 10090 |\n+-------------+-----------------+\n2 rows in set (0.00 sec)"
}
] |
PostgreSQL - SELECT - GeeksforGeeks
|
28 Aug, 2020
In this article we will be looking into the basic use of PostgreSQL SELECT statement to query data from the database table. For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link.
The SELECT statement is as complex and flexible as it can get for a query statement. It can be used with various clauses which increases it’s flexibility and use cases to query data from a table.The various clauses that can be used with the SELECT statement are listed below:
DISTINCT operator: It is used to select distinct rows from a table.
ORDER BY clause: It is used to sort table rows.
WHERE clause: It is used to filter rows from a table.
>LIMIT clause: It is used to select a subset of rows from the table.
FETCH clause: It is also used to select subset of rows from the table.
GROUP BY clause: It is used to group different rows into a single group.
HAVING clause: It is used to filter rows from a table with specified attributes or features.
FROM clause: It is used to specify a column in a table.
joins: It is used to join two or more tables together using joins such as INNER JOIN, LEFT JOIN, FULL OUTER JOIN, CROSS JOIN clauses.
Set operators: These operators such as UNION, INTERSECT, and EXCEPT are used to manipulate the different sets of data.
For the sake of simplicity we will be looking into the use of SELECT statement with FROM clause in our sample DVD rental database.
The syntax for using the SELECT statement is as follows:
Syntax: SELECT select_list FROM table_name;
Now, let’s evaluate the SELECT statement in more detail,
Firstly, we need to specify a particular column or a list of columns from where the data is to be retrieved. Commas are used to separate multiple columns, if a list of column is selected as below:SELECT select_list1, select_list2, select_list3 FROM table_name;For selecting all columns from the database, use asterisk(‘*’) as below:SELECT * FROM table_name;
SELECT select_list1, select_list2, select_list3 FROM table_name;
For selecting all columns from the database, use asterisk(‘*’) as below:
SELECT * FROM table_name;
Secondly, we need to specify the name of the table from which data is to be retrieved, after the FROM keyword.
Now let us look into a few examples of using SELECT statement in our sample database:Example 1:Using SELECT statement to query data from one column
SELECT first_name FROM customer;
Output:
Example 2:Using SELECT statement to query data from multiple columns
SELECT first_name, email FROM customer;
Output:
Example 3:Using SELECT statement to query data in all columns of a table
SELECT * FROM customer;
Output:
Example 4:Using SELECT statement with expressions
SELECT first_name || ' ' || last_name AS full_name, email FROM customer;
Output:
postgreSQL-basics
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Change Column Type
PostgreSQL - Psql commands
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - Interval Data Type
PostgreSQL - Record type variable
|
[
{
"code": null,
"e": 28000,
"s": 27972,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 28274,
"s": 28000,
"text": "In this article we will be looking into the basic use of PostgreSQL SELECT statement to query data from the database table. For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link."
},
{
"code": null,
"e": 28550,
"s": 28274,
"text": "The SELECT statement is as complex and flexible as it can get for a query statement. It can be used with various clauses which increases it’s flexibility and use cases to query data from a table.The various clauses that can be used with the SELECT statement are listed below:"
},
{
"code": null,
"e": 28618,
"s": 28550,
"text": "DISTINCT operator: It is used to select distinct rows from a table."
},
{
"code": null,
"e": 28666,
"s": 28618,
"text": "ORDER BY clause: It is used to sort table rows."
},
{
"code": null,
"e": 28789,
"s": 28666,
"text": "WHERE clause: It is used to filter rows from a table.\n>LIMIT clause: It is used to select a subset of rows from the table."
},
{
"code": null,
"e": 28860,
"s": 28789,
"text": "FETCH clause: It is also used to select subset of rows from the table."
},
{
"code": null,
"e": 28933,
"s": 28860,
"text": "GROUP BY clause: It is used to group different rows into a single group."
},
{
"code": null,
"e": 29026,
"s": 28933,
"text": "HAVING clause: It is used to filter rows from a table with specified attributes or features."
},
{
"code": null,
"e": 29082,
"s": 29026,
"text": "FROM clause: It is used to specify a column in a table."
},
{
"code": null,
"e": 29216,
"s": 29082,
"text": "joins: It is used to join two or more tables together using joins such as INNER JOIN, LEFT JOIN, FULL OUTER JOIN, CROSS JOIN clauses."
},
{
"code": null,
"e": 29335,
"s": 29216,
"text": "Set operators: These operators such as UNION, INTERSECT, and EXCEPT are used to manipulate the different sets of data."
},
{
"code": null,
"e": 29466,
"s": 29335,
"text": "For the sake of simplicity we will be looking into the use of SELECT statement with FROM clause in our sample DVD rental database."
},
{
"code": null,
"e": 29523,
"s": 29466,
"text": "The syntax for using the SELECT statement is as follows:"
},
{
"code": null,
"e": 29567,
"s": 29523,
"text": "Syntax: SELECT select_list FROM table_name;"
},
{
"code": null,
"e": 29624,
"s": 29567,
"text": "Now, let’s evaluate the SELECT statement in more detail,"
},
{
"code": null,
"e": 29982,
"s": 29624,
"text": "Firstly, we need to specify a particular column or a list of columns from where the data is to be retrieved. Commas are used to separate multiple columns, if a list of column is selected as below:SELECT select_list1, select_list2, select_list3 FROM table_name;For selecting all columns from the database, use asterisk(‘*’) as below:SELECT * FROM table_name;"
},
{
"code": null,
"e": 30047,
"s": 29982,
"text": "SELECT select_list1, select_list2, select_list3 FROM table_name;"
},
{
"code": null,
"e": 30120,
"s": 30047,
"text": "For selecting all columns from the database, use asterisk(‘*’) as below:"
},
{
"code": null,
"e": 30146,
"s": 30120,
"text": "SELECT * FROM table_name;"
},
{
"code": null,
"e": 30257,
"s": 30146,
"text": "Secondly, we need to specify the name of the table from which data is to be retrieved, after the FROM keyword."
},
{
"code": null,
"e": 30405,
"s": 30257,
"text": "Now let us look into a few examples of using SELECT statement in our sample database:Example 1:Using SELECT statement to query data from one column"
},
{
"code": null,
"e": 30438,
"s": 30405,
"text": "SELECT first_name FROM customer;"
},
{
"code": null,
"e": 30446,
"s": 30438,
"text": "Output:"
},
{
"code": null,
"e": 30515,
"s": 30446,
"text": "Example 2:Using SELECT statement to query data from multiple columns"
},
{
"code": null,
"e": 30555,
"s": 30515,
"text": "SELECT first_name, email FROM customer;"
},
{
"code": null,
"e": 30563,
"s": 30555,
"text": "Output:"
},
{
"code": null,
"e": 30636,
"s": 30563,
"text": "Example 3:Using SELECT statement to query data in all columns of a table"
},
{
"code": null,
"e": 30660,
"s": 30636,
"text": "SELECT * FROM customer;"
},
{
"code": null,
"e": 30668,
"s": 30660,
"text": "Output:"
},
{
"code": null,
"e": 30718,
"s": 30668,
"text": "Example 4:Using SELECT statement with expressions"
},
{
"code": null,
"e": 30791,
"s": 30718,
"text": "SELECT first_name || ' ' || last_name AS full_name, email FROM customer;"
},
{
"code": null,
"e": 30799,
"s": 30791,
"text": "Output:"
},
{
"code": null,
"e": 30817,
"s": 30799,
"text": "postgreSQL-basics"
},
{
"code": null,
"e": 30828,
"s": 30817,
"text": "PostgreSQL"
},
{
"code": null,
"e": 30926,
"s": 30828,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30958,
"s": 30926,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 30985,
"s": 30958,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 31008,
"s": 30985,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 31048,
"s": 31008,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 31103,
"s": 31048,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 31137,
"s": 31103,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 31161,
"s": 31137,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 31185,
"s": 31161,
"text": "PostgreSQL - Copy Table"
},
{
"code": null,
"e": 31217,
"s": 31185,
"text": "PostgreSQL - Interval Data Type"
}
] |
Mass Storage Management
|
Disks are the mainly used mass storage devices. They provide the bulk of secondary storage in operating systems today.
Each modern disk contains concentric tracks and each track is divided into multiple sectors. The disks are usually arranged as a one dimensional array of blocks, where blocks are the smallest storage unit.Blocks can also be called as sectors. For each surface of the disk, there is a read/write desk available. The same tracks on all the surfaces is known as a cylinder.
There are many disk scheduling algorithms that provide the total head movement for various requests to the disk. Here are the types of disk scheduling algorithms −
All these algorithms are explained using the following requests for the disk −
10,95,23,78,80
In first come first served scheduling, the requests are serviced in their coming order. This algorithm is fair as it allows all requests a chance but it does not provide the fastest possible service. An example of FCFS scheduling is given below −
In the above example, the requests are serviced in the order they appear i.e 10, 95, 23, 78, 80. The seek head is initially positioned at 50 and it starts from there.
The requests that are closest to the current head are served first before moving away in shortest seek time first scheduling algorithm. A problem with SSTF algorithm is that it may cause starvation for some requests. An example of Shortest Seek Time First Scheduling is given below −
In the above example, the requests are serviced in the order 23, 10, 78, 80, 95. The seek head is initially positioned at 50 and it starts from there. 23 is closest to 50 so it is services first. Then 10 is closer to 23 than 78 so it is services next. After this 78, 80 and 95 are serviced.
In this scheduling algorithm, the head moves towards one direction while servicing all the requests in that direction until it reaches the end of the disk. After that it starts moving towards the other direction. In this way, the head continuously scans back and forth across the disk. An example of SCAN scheduling is given below −
In the above example, the requests are serviced in the order 23, 10, 78, 80, 95. The head is initially at 50 and moves towards the left while servicing requests 23 and 10. When it reaches the end of the disk, it starts moving right and services 78, 80 and 95 as they occur.
LOOK scheduling algorithm is similar to SCAN scheduling but is its practical version. In this algorithm, the head moves towards one direction while servicing all the requests in that direction until it reaches the last request. After that it starts moving towards the other direction. An example of LOOK scheduling is given below −
In the above example, the requests are serviced in the order 23, 10, 78, 80, 95. The head is initially at 50 and moves towards the left while servicing requests 23 and 10. When it reaches the last request on the left i.e. 10, it starts moving right and services 78, 80 and 95 as they occur.
|
[
{
"code": null,
"e": 1181,
"s": 1062,
"text": "Disks are the mainly used mass storage devices. They provide the bulk of secondary storage in operating systems today."
},
{
"code": null,
"e": 1552,
"s": 1181,
"text": "Each modern disk contains concentric tracks and each track is divided into multiple sectors. The disks are usually arranged as a one dimensional array of blocks, where blocks are the smallest storage unit.Blocks can also be called as sectors. For each surface of the disk, there is a read/write desk available. The same tracks on all the surfaces is known as a cylinder."
},
{
"code": null,
"e": 1716,
"s": 1552,
"text": "There are many disk scheduling algorithms that provide the total head movement for various requests to the disk. Here are the types of disk scheduling algorithms −"
},
{
"code": null,
"e": 1795,
"s": 1716,
"text": "All these algorithms are explained using the following requests for the disk −"
},
{
"code": null,
"e": 1810,
"s": 1795,
"text": "10,95,23,78,80"
},
{
"code": null,
"e": 2057,
"s": 1810,
"text": "In first come first served scheduling, the requests are serviced in their coming order. This algorithm is fair as it allows all requests a chance but it does not provide the fastest possible service. An example of FCFS scheduling is given below −"
},
{
"code": null,
"e": 2224,
"s": 2057,
"text": "In the above example, the requests are serviced in the order they appear i.e 10, 95, 23, 78, 80. The seek head is initially positioned at 50 and it starts from there."
},
{
"code": null,
"e": 2508,
"s": 2224,
"text": "The requests that are closest to the current head are served first before moving away in shortest seek time first scheduling algorithm. A problem with SSTF algorithm is that it may cause starvation for some requests. An example of Shortest Seek Time First Scheduling is given below −"
},
{
"code": null,
"e": 2799,
"s": 2508,
"text": "In the above example, the requests are serviced in the order 23, 10, 78, 80, 95. The seek head is initially positioned at 50 and it starts from there. 23 is closest to 50 so it is services first. Then 10 is closer to 23 than 78 so it is services next. After this 78, 80 and 95 are serviced."
},
{
"code": null,
"e": 3132,
"s": 2799,
"text": "In this scheduling algorithm, the head moves towards one direction while servicing all the requests in that direction until it reaches the end of the disk. After that it starts moving towards the other direction. In this way, the head continuously scans back and forth across the disk. An example of SCAN scheduling is given below −"
},
{
"code": null,
"e": 3406,
"s": 3132,
"text": "In the above example, the requests are serviced in the order 23, 10, 78, 80, 95. The head is initially at 50 and moves towards the left while servicing requests 23 and 10. When it reaches the end of the disk, it starts moving right and services 78, 80 and 95 as they occur."
},
{
"code": null,
"e": 3738,
"s": 3406,
"text": "LOOK scheduling algorithm is similar to SCAN scheduling but is its practical version. In this algorithm, the head moves towards one direction while servicing all the requests in that direction until it reaches the last request. After that it starts moving towards the other direction. An example of LOOK scheduling is given below −"
},
{
"code": null,
"e": 4029,
"s": 3738,
"text": "In the above example, the requests are serviced in the order 23, 10, 78, 80, 95. The head is initially at 50 and moves towards the left while servicing requests 23 and 10. When it reaches the last request on the left i.e. 10, it starts moving right and services 78, 80 and 95 as they occur."
}
] |
MATLAB - Basic Syntax
|
MATLAB environment behaves like a super-complex calculator. You can enter commands at the >> command prompt.
MATLAB is an interpreted environment. In other words, you give a command and MATLAB executes it right away.
Type a valid expression, for example,
5 + 5
And press ENTER
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 10
Let us take up few more examples −
3 ^ 2 % 3 raised to the power of 2
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 9
Another example,
sin(pi /2) % sine of angle 90o
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 1
Another example,
7/0 % Divide by zero
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = Inf
warning: division by zero
Another example,
732 * 20.3
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 1.4860e+04
MATLAB provides some special expressions for some mathematical symbols, like pi for π, Inf for ∞, i (and j) for √-1 etc. Nan stands for 'not a number'.
Semicolon (;) indicates end of statement. However, if you want to suppress and hide the MATLAB output for an expression, add a semicolon after the expression.
For example,
x = 3;
y = x + 5
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
y = 8
The percent symbol (%) is used for indicating a comment line. For example,
x = 9 % assign the value 9 to x
You can also write a block of comments using the block comment operators % { and % }.
The MATLAB editor includes tools and context menu items to help you add, remove, or change the format of comments.
MATLAB supports the following commonly used operators and special characters −
MATLAB supports the following special variables and constants −
Variable names consist of a letter followed by any number of letters, digits or underscore.
MATLAB is case-sensitive.
Variable names can be of any length, however, MATLAB uses only first N characters, where N is given by the function namelengthmax.
The save command is used for saving all the variables in the workspace, as a file with .mat extension, in the current directory.
For example,
save myfile
You can reload the file anytime later using the load command.
load myfile
30 Lectures
4 hours
Nouman Azam
127 Lectures
12 hours
Nouman Azam
17 Lectures
3 hours
Sanjeev
37 Lectures
5 hours
TELCOMA Global
22 Lectures
4 hours
TELCOMA Global
18 Lectures
3 hours
Phinite Academy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2250,
"s": 2141,
"text": "MATLAB environment behaves like a super-complex calculator. You can enter commands at the >> command prompt."
},
{
"code": null,
"e": 2358,
"s": 2250,
"text": "MATLAB is an interpreted environment. In other words, you give a command and MATLAB executes it right away."
},
{
"code": null,
"e": 2396,
"s": 2358,
"text": "Type a valid expression, for example,"
},
{
"code": null,
"e": 2402,
"s": 2396,
"text": "5 + 5"
},
{
"code": null,
"e": 2418,
"s": 2402,
"text": "And press ENTER"
},
{
"code": null,
"e": 2529,
"s": 2418,
"text": "When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −"
},
{
"code": null,
"e": 2539,
"s": 2529,
"text": "ans = 10\n"
},
{
"code": null,
"e": 2574,
"s": 2539,
"text": "Let us take up few more examples −"
},
{
"code": null,
"e": 2616,
"s": 2574,
"text": "3 ^ 2\t % 3 raised to the power of 2"
},
{
"code": null,
"e": 2727,
"s": 2616,
"text": "When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −"
},
{
"code": null,
"e": 2736,
"s": 2727,
"text": "ans = 9\n"
},
{
"code": null,
"e": 2753,
"s": 2736,
"text": "Another example,"
},
{
"code": null,
"e": 2787,
"s": 2753,
"text": "sin(pi /2)\t % sine of angle 90o\n"
},
{
"code": null,
"e": 2898,
"s": 2787,
"text": "When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −"
},
{
"code": null,
"e": 2907,
"s": 2898,
"text": "ans = 1\n"
},
{
"code": null,
"e": 2924,
"s": 2907,
"text": "Another example,"
},
{
"code": null,
"e": 2952,
"s": 2924,
"text": "7/0\t\t % Divide by zero"
},
{
"code": null,
"e": 3063,
"s": 2952,
"text": "When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −"
},
{
"code": null,
"e": 3100,
"s": 3063,
"text": "ans = Inf\nwarning: division by zero\n"
},
{
"code": null,
"e": 3117,
"s": 3100,
"text": "Another example,"
},
{
"code": null,
"e": 3129,
"s": 3117,
"text": "732 * 20.3\t"
},
{
"code": null,
"e": 3240,
"s": 3129,
"text": "When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −"
},
{
"code": null,
"e": 3259,
"s": 3240,
"text": "ans = 1.4860e+04\n"
},
{
"code": null,
"e": 3411,
"s": 3259,
"text": "MATLAB provides some special expressions for some mathematical symbols, like pi for π, Inf for ∞, i (and j) for √-1 etc. Nan stands for 'not a number'."
},
{
"code": null,
"e": 3570,
"s": 3411,
"text": "Semicolon (;) indicates end of statement. However, if you want to suppress and hide the MATLAB output for an expression, add a semicolon after the expression."
},
{
"code": null,
"e": 3583,
"s": 3570,
"text": "For example,"
},
{
"code": null,
"e": 3600,
"s": 3583,
"text": "x = 3;\ny = x + 5"
},
{
"code": null,
"e": 3711,
"s": 3600,
"text": "When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −"
},
{
"code": null,
"e": 3719,
"s": 3711,
"text": "y = 8\n"
},
{
"code": null,
"e": 3794,
"s": 3719,
"text": "The percent symbol (%) is used for indicating a comment line. For example,"
},
{
"code": null,
"e": 3831,
"s": 3794,
"text": "x = 9\t % assign the value 9 to x"
},
{
"code": null,
"e": 3918,
"s": 3831,
"text": "You can also write a block of comments using the block comment operators % { and % }."
},
{
"code": null,
"e": 4033,
"s": 3918,
"text": "The MATLAB editor includes tools and context menu items to help you add, remove, or change the format of comments."
},
{
"code": null,
"e": 4112,
"s": 4033,
"text": "MATLAB supports the following commonly used operators and special characters −"
},
{
"code": null,
"e": 4176,
"s": 4112,
"text": "MATLAB supports the following special variables and constants −"
},
{
"code": null,
"e": 4268,
"s": 4176,
"text": "Variable names consist of a letter followed by any number of letters, digits or underscore."
},
{
"code": null,
"e": 4294,
"s": 4268,
"text": "MATLAB is case-sensitive."
},
{
"code": null,
"e": 4425,
"s": 4294,
"text": "Variable names can be of any length, however, MATLAB uses only first N characters, where N is given by the function namelengthmax."
},
{
"code": null,
"e": 4554,
"s": 4425,
"text": "The save command is used for saving all the variables in the workspace, as a file with .mat extension, in the current directory."
},
{
"code": null,
"e": 4567,
"s": 4554,
"text": "For example,"
},
{
"code": null,
"e": 4580,
"s": 4567,
"text": "save myfile\n"
},
{
"code": null,
"e": 4642,
"s": 4580,
"text": "You can reload the file anytime later using the load command."
},
{
"code": null,
"e": 4655,
"s": 4642,
"text": "load myfile\n"
},
{
"code": null,
"e": 4688,
"s": 4655,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4701,
"s": 4688,
"text": " Nouman Azam"
},
{
"code": null,
"e": 4736,
"s": 4701,
"text": "\n 127 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 4749,
"s": 4736,
"text": " Nouman Azam"
},
{
"code": null,
"e": 4782,
"s": 4749,
"text": "\n 17 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4791,
"s": 4782,
"text": " Sanjeev"
},
{
"code": null,
"e": 4824,
"s": 4791,
"text": "\n 37 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4840,
"s": 4824,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 4873,
"s": 4840,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4889,
"s": 4873,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 4922,
"s": 4889,
"text": "\n 18 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4939,
"s": 4922,
"text": " Phinite Academy"
},
{
"code": null,
"e": 4946,
"s": 4939,
"text": " Print"
},
{
"code": null,
"e": 4957,
"s": 4946,
"text": " Add Notes"
}
] |
Largest sum subarray of size K containing consecutive elements - GeeksforGeeks
|
20 Jul, 2021
Given an array arr[] consisting of N positive integers and a positive integer K, the task is to find the maximum sum of the subarray of size K such that it contains K consecutive elements in any combination.
Examples:
Input: arr[] = {10, 12, 9, 8, 10, 15, 1, 3, 2}, K = 3Output: 27Explanation:The subarray having K (= 3) consecutive elements is {9, 8, 10} whose sum of elements is 9 + 8 + 10 = 27, which is maximum.
Input: arr[] = {7, 20, 2, 3, 4}, K = 2Output: 7
Approach: The given problem can be solved by checking every subarray of size K whether it contains consecutive elements or not and then maximize the sum of the subarray accordingly. Follow the steps below to solve the problem:
Initialize a variable, say currSum to store the sum of the current subarray of K elements if the elements are consecutive.
Initialize a variable maxSum that stores the maximum resultant sum of any subarray of size K.
Iterate over the range [0, N – K] using the variable i and perform the following steps:Store the K elements starting from i in an array V[].Sort the array V[] in increasing order.Traverse the array V[] to check if all the elements are consecutive or not. If found to be true, then store the sum of the current subarray in currSum and update the maxSum to the maximum of maxSum and currSum.
Store the K elements starting from i in an array V[].
Sort the array V[] in increasing order.
Traverse the array V[] to check if all the elements are consecutive or not. If found to be true, then store the sum of the current subarray in currSum and update the maxSum to the maximum of maxSum and currSum.
After completing the above steps, print the value of maxSum as the result.
Below is the implementation of the above approach.
C++
Java
Python3
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the largest sum// subarray such that it contains K// consecutive elementsint maximumSum(vector<int> A, int N, int K){ // Stores sum of subarray having // K consecutive elements int curr_sum = 0; // Stores the maximum sum among all // subarrays of size K having // consecutive elements int max_sum = INT_MIN; // Traverse the array for (int i = 0; i < N - K + 1; i++) { // Store K elements of one // subarray at a time vector<int> dupl_arr( A.begin() + i, A.begin() + i + K); // Sort the duplicate array // in ascending order sort(dupl_arr.begin(), dupl_arr.end()); // Checks if elements in subarray // are consecutive or not bool flag = true; // Traverse the k elements for (int j = 1; j < K; j++) { // If not consecutive, break if (dupl_arr[j] - dupl_arr[j - 1] != 1) { flag = false; break; } } // If flag is true update the // maximum sum if (flag) { int temp = 0; // Stores the sum of elements // of the current subarray curr_sum = accumulate( dupl_arr.begin(), dupl_arr.end(), temp); // Update the max_sum max_sum = max(max_sum, curr_sum); // Reset curr_sum curr_sum = 0; } } // Return the result return max_sum;} // Driver Codeint main(){ vector<int> arr = { 10, 12, 9, 8, 10, 15, 1, 3, 2 }; int K = 3; int N = arr.size(); cout << maximumSum(arr, N, K); return 0;}
// Java program for the above approachimport java.util.Arrays; class GFG{ // Function to find the largest sum // subarray such that it contains K // consecutive elementspublic static Integer maximumSum(int[] A, int N, int K){ // Stores sum of subarray having // K consecutive elements int curr_sum = 0; // Stores the maximum sum among all // subarrays of size K having // consecutive elements int max_sum = Integer.MIN_VALUE; // Traverse the array for (int i = 0; i < N - K + 1; i++) { // Store K elements of one // subarray at a time int[] dupl_arr = Arrays.copyOfRange(A, i, i + K); // Sort the duplicate array // in ascending order Arrays.sort(dupl_arr); // Checks if elements in subarray // are consecutive or not Boolean flag = true; // Traverse the k elements for (int j = 1; j < K; j++) { // If not consecutive, break if (dupl_arr[j] - dupl_arr[j - 1] != 1) { flag = false; break; } } // If flag is true update the // maximum sum if (flag) { int temp = 0; // Stores the sum of elements // of the current subarray curr_sum = 0; for(int x = 0; x < dupl_arr.length; x++){ curr_sum += dupl_arr[x]; } // Update the max_sum max_sum = Math.max(max_sum, curr_sum); // Reset curr_sum curr_sum = 0; } } // Return the result return max_sum;} // Driver Codepublic static void main(String args[]) { int[] arr = { 10, 12, 9, 8, 10, 15, 1, 3, 2 }; int K = 3; int N = arr.length; System.out.println(maximumSum(arr, N, K)); } } // This code is contributed by _saurabh_jaiswal.
# Python3 program for the above approachimport sys # Function to find the largest sum# subarray such that it contains K# consecutive elementsdef maximumSum(A, N, K): # Stores sum of subarray having # K consecutive elements curr_sum = 0 # Stores the maximum sum among all # subarrays of size K having # consecutive elements max_sum = -sys.maxsize - 1 # Traverse the array for i in range(N - K + 1): # Store K elements of one # subarray at a time dupl_arr = A[i:i + K] # Sort the duplicate array # in ascending order dupl_arr.sort() # Checks if elements in subarray # are consecutive or not flag = True # Traverse the k elements for j in range(1, K, 1): # If not consecutive, break if (dupl_arr[j] - dupl_arr[j - 1] != 1): flag = False break # If flag is true update the # maximum sum if (flag): temp = 0 # Stores the sum of elements # of the current subarray curr_sum = temp curr_sum = sum(dupl_arr) # Update the max_sum max_sum = max(max_sum, curr_sum) # Reset curr_sum curr_sum = 0 # Return the result return max_sum # Driver Codeif __name__ == '__main__': arr = [ 10, 12, 9, 8, 10, 15, 1, 3, 2 ] K = 3 N = len(arr) print(maximumSum(arr, N, K)) # This code is contributed by SURENDRA_GANGWAR
<script> // JavaScript program for the above approach // Function to find the largest sum// subarray such that it contains K// consecutive elementsfunction maximumSum(A, N, K) { // Stores sum of subarray having // K consecutive elements let curr_sum = 0; // Stores the maximum sum among all // subarrays of size K having // consecutive elements let max_sum = Number.MIN_SAFE_INTEGER; // Traverse the array for (let i = 0; i < N - K + 1; i++) { // Store K elements of one // subarray at a time let dupl_arr = [...A.slice(i, i + K)]; // Sort the duplicate array // in ascending order dupl_arr.sort((a, b) => a - b) // Checks if elements in subarray // are consecutive or not let flag = true; // Traverse the k elements for (let j = 1; j < K; j++) { // If not consecutive, break if (dupl_arr[j] - dupl_arr[j - 1] != 1) { flag = false; break; } } // If flag is true update the // maximum sum if (flag) { let temp = 0; // Stores the sum of elements // of the current subarray curr_sum = dupl_arr.reduce((acc, cur) => acc + cur, 0) // Update the max_sum max_sum = Math.max(max_sum, curr_sum); // Reset curr_sum curr_sum = 0; } } // Return the result return max_sum;} // Driver Code let arr = [10, 12, 9, 8, 10, 15, 1, 3, 2];let K = 3;let N = arr.length;document.write(maximumSum(arr, N, K)); </script>
27
Time Complexity: O(N*K*log K)Auxiliary Space: O(K)
SURENDRA_GANGWAR
_saurabh_jaiswal
sliding-window
subarray
Arrays
Mathematical
sliding-window
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Reversal algorithm for array rotation
Window Sliding Technique
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 26177,
"s": 26149,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 26385,
"s": 26177,
"text": "Given an array arr[] consisting of N positive integers and a positive integer K, the task is to find the maximum sum of the subarray of size K such that it contains K consecutive elements in any combination."
},
{
"code": null,
"e": 26395,
"s": 26385,
"text": "Examples:"
},
{
"code": null,
"e": 26593,
"s": 26395,
"text": "Input: arr[] = {10, 12, 9, 8, 10, 15, 1, 3, 2}, K = 3Output: 27Explanation:The subarray having K (= 3) consecutive elements is {9, 8, 10} whose sum of elements is 9 + 8 + 10 = 27, which is maximum."
},
{
"code": null,
"e": 26641,
"s": 26593,
"text": "Input: arr[] = {7, 20, 2, 3, 4}, K = 2Output: 7"
},
{
"code": null,
"e": 26868,
"s": 26641,
"text": "Approach: The given problem can be solved by checking every subarray of size K whether it contains consecutive elements or not and then maximize the sum of the subarray accordingly. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26991,
"s": 26868,
"text": "Initialize a variable, say currSum to store the sum of the current subarray of K elements if the elements are consecutive."
},
{
"code": null,
"e": 27085,
"s": 26991,
"text": "Initialize a variable maxSum that stores the maximum resultant sum of any subarray of size K."
},
{
"code": null,
"e": 27475,
"s": 27085,
"text": "Iterate over the range [0, N – K] using the variable i and perform the following steps:Store the K elements starting from i in an array V[].Sort the array V[] in increasing order.Traverse the array V[] to check if all the elements are consecutive or not. If found to be true, then store the sum of the current subarray in currSum and update the maxSum to the maximum of maxSum and currSum."
},
{
"code": null,
"e": 27529,
"s": 27475,
"text": "Store the K elements starting from i in an array V[]."
},
{
"code": null,
"e": 27569,
"s": 27529,
"text": "Sort the array V[] in increasing order."
},
{
"code": null,
"e": 27780,
"s": 27569,
"text": "Traverse the array V[] to check if all the elements are consecutive or not. If found to be true, then store the sum of the current subarray in currSum and update the maxSum to the maximum of maxSum and currSum."
},
{
"code": null,
"e": 27855,
"s": 27780,
"text": "After completing the above steps, print the value of maxSum as the result."
},
{
"code": null,
"e": 27906,
"s": 27855,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 27910,
"s": 27906,
"text": "C++"
},
{
"code": null,
"e": 27915,
"s": 27910,
"text": "Java"
},
{
"code": null,
"e": 27923,
"s": 27915,
"text": "Python3"
},
{
"code": null,
"e": 27934,
"s": 27923,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the largest sum// subarray such that it contains K// consecutive elementsint maximumSum(vector<int> A, int N, int K){ // Stores sum of subarray having // K consecutive elements int curr_sum = 0; // Stores the maximum sum among all // subarrays of size K having // consecutive elements int max_sum = INT_MIN; // Traverse the array for (int i = 0; i < N - K + 1; i++) { // Store K elements of one // subarray at a time vector<int> dupl_arr( A.begin() + i, A.begin() + i + K); // Sort the duplicate array // in ascending order sort(dupl_arr.begin(), dupl_arr.end()); // Checks if elements in subarray // are consecutive or not bool flag = true; // Traverse the k elements for (int j = 1; j < K; j++) { // If not consecutive, break if (dupl_arr[j] - dupl_arr[j - 1] != 1) { flag = false; break; } } // If flag is true update the // maximum sum if (flag) { int temp = 0; // Stores the sum of elements // of the current subarray curr_sum = accumulate( dupl_arr.begin(), dupl_arr.end(), temp); // Update the max_sum max_sum = max(max_sum, curr_sum); // Reset curr_sum curr_sum = 0; } } // Return the result return max_sum;} // Driver Codeint main(){ vector<int> arr = { 10, 12, 9, 8, 10, 15, 1, 3, 2 }; int K = 3; int N = arr.size(); cout << maximumSum(arr, N, K); return 0;}",
"e": 29793,
"s": 27934,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.Arrays; class GFG{ // Function to find the largest sum // subarray such that it contains K // consecutive elementspublic static Integer maximumSum(int[] A, int N, int K){ // Stores sum of subarray having // K consecutive elements int curr_sum = 0; // Stores the maximum sum among all // subarrays of size K having // consecutive elements int max_sum = Integer.MIN_VALUE; // Traverse the array for (int i = 0; i < N - K + 1; i++) { // Store K elements of one // subarray at a time int[] dupl_arr = Arrays.copyOfRange(A, i, i + K); // Sort the duplicate array // in ascending order Arrays.sort(dupl_arr); // Checks if elements in subarray // are consecutive or not Boolean flag = true; // Traverse the k elements for (int j = 1; j < K; j++) { // If not consecutive, break if (dupl_arr[j] - dupl_arr[j - 1] != 1) { flag = false; break; } } // If flag is true update the // maximum sum if (flag) { int temp = 0; // Stores the sum of elements // of the current subarray curr_sum = 0; for(int x = 0; x < dupl_arr.length; x++){ curr_sum += dupl_arr[x]; } // Update the max_sum max_sum = Math.max(max_sum, curr_sum); // Reset curr_sum curr_sum = 0; } } // Return the result return max_sum;} // Driver Codepublic static void main(String args[]) { int[] arr = { 10, 12, 9, 8, 10, 15, 1, 3, 2 }; int K = 3; int N = arr.length; System.out.println(maximumSum(arr, N, K)); } } // This code is contributed by _saurabh_jaiswal.",
"e": 31702,
"s": 29793,
"text": null
},
{
"code": "# Python3 program for the above approachimport sys # Function to find the largest sum# subarray such that it contains K# consecutive elementsdef maximumSum(A, N, K): # Stores sum of subarray having # K consecutive elements curr_sum = 0 # Stores the maximum sum among all # subarrays of size K having # consecutive elements max_sum = -sys.maxsize - 1 # Traverse the array for i in range(N - K + 1): # Store K elements of one # subarray at a time dupl_arr = A[i:i + K] # Sort the duplicate array # in ascending order dupl_arr.sort() # Checks if elements in subarray # are consecutive or not flag = True # Traverse the k elements for j in range(1, K, 1): # If not consecutive, break if (dupl_arr[j] - dupl_arr[j - 1] != 1): flag = False break # If flag is true update the # maximum sum if (flag): temp = 0 # Stores the sum of elements # of the current subarray curr_sum = temp curr_sum = sum(dupl_arr) # Update the max_sum max_sum = max(max_sum, curr_sum) # Reset curr_sum curr_sum = 0 # Return the result return max_sum # Driver Codeif __name__ == '__main__': arr = [ 10, 12, 9, 8, 10, 15, 1, 3, 2 ] K = 3 N = len(arr) print(maximumSum(arr, N, K)) # This code is contributed by SURENDRA_GANGWAR",
"e": 33251,
"s": 31702,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find the largest sum// subarray such that it contains K// consecutive elementsfunction maximumSum(A, N, K) { // Stores sum of subarray having // K consecutive elements let curr_sum = 0; // Stores the maximum sum among all // subarrays of size K having // consecutive elements let max_sum = Number.MIN_SAFE_INTEGER; // Traverse the array for (let i = 0; i < N - K + 1; i++) { // Store K elements of one // subarray at a time let dupl_arr = [...A.slice(i, i + K)]; // Sort the duplicate array // in ascending order dupl_arr.sort((a, b) => a - b) // Checks if elements in subarray // are consecutive or not let flag = true; // Traverse the k elements for (let j = 1; j < K; j++) { // If not consecutive, break if (dupl_arr[j] - dupl_arr[j - 1] != 1) { flag = false; break; } } // If flag is true update the // maximum sum if (flag) { let temp = 0; // Stores the sum of elements // of the current subarray curr_sum = dupl_arr.reduce((acc, cur) => acc + cur, 0) // Update the max_sum max_sum = Math.max(max_sum, curr_sum); // Reset curr_sum curr_sum = 0; } } // Return the result return max_sum;} // Driver Code let arr = [10, 12, 9, 8, 10, 15, 1, 3, 2];let K = 3;let N = arr.length;document.write(maximumSum(arr, N, K)); </script>",
"e": 34907,
"s": 33251,
"text": null
},
{
"code": null,
"e": 34910,
"s": 34907,
"text": "27"
},
{
"code": null,
"e": 34963,
"s": 34912,
"text": "Time Complexity: O(N*K*log K)Auxiliary Space: O(K)"
},
{
"code": null,
"e": 34980,
"s": 34963,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 34997,
"s": 34980,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 35012,
"s": 34997,
"text": "sliding-window"
},
{
"code": null,
"e": 35021,
"s": 35012,
"text": "subarray"
},
{
"code": null,
"e": 35028,
"s": 35021,
"text": "Arrays"
},
{
"code": null,
"e": 35041,
"s": 35028,
"text": "Mathematical"
},
{
"code": null,
"e": 35056,
"s": 35041,
"text": "sliding-window"
},
{
"code": null,
"e": 35063,
"s": 35056,
"text": "Arrays"
},
{
"code": null,
"e": 35076,
"s": 35063,
"text": "Mathematical"
},
{
"code": null,
"e": 35174,
"s": 35076,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35205,
"s": 35174,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 35243,
"s": 35205,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 35268,
"s": 35243,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 35289,
"s": 35268,
"text": "Next Greater Element"
},
{
"code": null,
"e": 35347,
"s": 35289,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 35377,
"s": 35347,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 35437,
"s": 35377,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35452,
"s": 35437,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35495,
"s": 35452,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
C++ Program to Find the smallest missing number - GeeksforGeeks
|
17 Dec, 2021
Given a sorted array of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array.
Examples
Input: {0, 1, 2, 6, 9}, n = 5, m = 10
Output: 3
Input: {4, 5, 10, 11}, n = 4, m = 12
Output: 0
Input: {0, 1, 2, 3}, n = 4, m = 5
Output: 4
Input: {0, 1, 2, 3, 4, 5, 6, 7, 10}, n = 9, m = 11
Output: 8
Thanks to Ravichandra for suggesting following two methods.
Method 1 (Use Binary Search) For i = 0 to m-1, do binary search for i in the array. If i is not present in the array then return i.Time Complexity: O(m log n)
Method 2 (Linear Search) If arr[0] is not 0, return 0. Otherwise traverse the input array starting from index 0, and for each pair of elements a[i] and a[i+1], find the difference between them. if the difference is greater than 1 then a[i]+1 is the missing number. Time Complexity: O(n)
Method 3 (Use Modified Binary Search) Thanks to yasein and Jams for suggesting this method. In the standard Binary Search process, the element to be searched is compared with the middle element and on the basis of comparison result, we decide whether to search is over or to go to left half or right half. In this method, we modify the standard Binary Search algorithm to compare the middle element with its index and make decision on the basis of this comparison.
If the first element is not same as its index then return first index
Else get the middle index say midIf arr[mid] greater than mid then the required element lies in left half.Else the required element lies in right half.
If arr[mid] greater than mid then the required element lies in left half.
Else the required element lies in right half.
C++
// C++ program to find the smallest elements// missing in a sorted array.#include<bits/stdc++.h>using namespace std; int findFirstMissing(int array[], int start, int end){ if (start > end) return end + 1; if (start != array[start]) return start; int mid = (start + end) / 2; // Left half has all elements // from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid);} // Driver codeint main(){ int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Smallest missing element is " << findFirstMissing(arr, 0, n-1) << endl;} // This code is contributed by// Shivi_Aggarwal
Smallest missing element is 8
Note: This method doesn’t work if there are duplicate elements in the array.Time Complexity: O(Logn)
Another Method: The idea is to use Recursive Binary Search to find the smallest missing number. Below is the illustration with the help of steps:
If the first element of the array is not 0, then the smallest missing number is 0.
If the last elements of the array is N-1, then the smallest missing number is N.
Otherwise, find the middle element from the first and last index and check if the middle element is equal to the desired element. i.e. first + middle_index.If the middle element is the desired element, then the smallest missing element is in the right search space of the middle.Otherwise, the smallest missing number is in the left search space of the middle.
If the middle element is the desired element, then the smallest missing element is in the right search space of the middle.
Otherwise, the smallest missing number is in the left search space of the middle.
Below is the implementation of the above approach:
C++
//C++ program for the above approach#include <bits/stdc++.h> using namespace std; // Program to find missing elementint findFirstMissing(vector<int> arr , int start , int end,int first){ if (start < end) { int mid = (start + end) / 2; /** Index matches with value at that index, means missing element cannot be upto that po*/ if (arr[mid] != mid+first) return findFirstMissing(arr, start, mid , first); else return findFirstMissing(arr, mid + 1, end , first); } return start + first; } // Program to find Smallest// Missing in Sorted Arrayint findSmallestMissinginSortedArray(vector<int> arr){ // Check if 0 is missing // in the array if(arr[0] != 0) return 0; // Check is all numbers 0 to n - 1 // are present in array if(arr[arr.size() - 1] == arr.size() - 1) return arr.size(); int first = arr[0]; return findFirstMissing(arr, 0, arr.size() - 1, first);} // Driver program to test the above functionint main(){ vector<int> arr = {0, 1, 2, 3, 4, 5, 7}; int n = arr.size(); // Function Call cout<<"First Missing element is : "<<findSmallestMissinginSortedArray(arr);} // This code is contributed by mohit kumar 29.
First Missing element is : 6
Time Complexity: O(Logn)
Please refer complete article on Find the smallest missing number for more details!
Binary Search
Arrays
C++
C++ Programs
Arrays
Binary Search
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Find duplicates in O(n) time and O(1) extra space | Set 1
Trapping Rain Water
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
Socket Programming in C/C++
|
[
{
"code": null,
"e": 24716,
"s": 24688,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 24878,
"s": 24716,
"text": "Given a sorted array of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array. "
},
{
"code": null,
"e": 24888,
"s": 24878,
"text": "Examples "
},
{
"code": null,
"e": 25095,
"s": 24888,
"text": "Input: {0, 1, 2, 6, 9}, n = 5, m = 10 \nOutput: 3\n\nInput: {4, 5, 10, 11}, n = 4, m = 12 \nOutput: 0\n\nInput: {0, 1, 2, 3}, n = 4, m = 5 \nOutput: 4\n\nInput: {0, 1, 2, 3, 4, 5, 6, 7, 10}, n = 9, m = 11 \nOutput: 8"
},
{
"code": null,
"e": 25155,
"s": 25095,
"text": "Thanks to Ravichandra for suggesting following two methods."
},
{
"code": null,
"e": 25315,
"s": 25155,
"text": "Method 1 (Use Binary Search) For i = 0 to m-1, do binary search for i in the array. If i is not present in the array then return i.Time Complexity: O(m log n) "
},
{
"code": null,
"e": 25602,
"s": 25315,
"text": "Method 2 (Linear Search) If arr[0] is not 0, return 0. Otherwise traverse the input array starting from index 0, and for each pair of elements a[i] and a[i+1], find the difference between them. if the difference is greater than 1 then a[i]+1 is the missing number. Time Complexity: O(n)"
},
{
"code": null,
"e": 26067,
"s": 25602,
"text": "Method 3 (Use Modified Binary Search) Thanks to yasein and Jams for suggesting this method. In the standard Binary Search process, the element to be searched is compared with the middle element and on the basis of comparison result, we decide whether to search is over or to go to left half or right half. In this method, we modify the standard Binary Search algorithm to compare the middle element with its index and make decision on the basis of this comparison."
},
{
"code": null,
"e": 26137,
"s": 26067,
"text": "If the first element is not same as its index then return first index"
},
{
"code": null,
"e": 26289,
"s": 26137,
"text": "Else get the middle index say midIf arr[mid] greater than mid then the required element lies in left half.Else the required element lies in right half."
},
{
"code": null,
"e": 26363,
"s": 26289,
"text": "If arr[mid] greater than mid then the required element lies in left half."
},
{
"code": null,
"e": 26409,
"s": 26363,
"text": "Else the required element lies in right half."
},
{
"code": null,
"e": 26413,
"s": 26409,
"text": "C++"
},
{
"code": "// C++ program to find the smallest elements// missing in a sorted array.#include<bits/stdc++.h>using namespace std; int findFirstMissing(int array[], int start, int end){ if (start > end) return end + 1; if (start != array[start]) return start; int mid = (start + end) / 2; // Left half has all elements // from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid);} // Driver codeint main(){ int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Smallest missing element is \" << findFirstMissing(arr, 0, n-1) << endl;} // This code is contributed by// Shivi_Aggarwal ",
"e": 27200,
"s": 26413,
"text": null
},
{
"code": null,
"e": 27230,
"s": 27200,
"text": "Smallest missing element is 8"
},
{
"code": null,
"e": 27331,
"s": 27230,
"text": "Note: This method doesn’t work if there are duplicate elements in the array.Time Complexity: O(Logn)"
},
{
"code": null,
"e": 27477,
"s": 27331,
"text": "Another Method: The idea is to use Recursive Binary Search to find the smallest missing number. Below is the illustration with the help of steps:"
},
{
"code": null,
"e": 27560,
"s": 27477,
"text": "If the first element of the array is not 0, then the smallest missing number is 0."
},
{
"code": null,
"e": 27641,
"s": 27560,
"text": "If the last elements of the array is N-1, then the smallest missing number is N."
},
{
"code": null,
"e": 28002,
"s": 27641,
"text": "Otherwise, find the middle element from the first and last index and check if the middle element is equal to the desired element. i.e. first + middle_index.If the middle element is the desired element, then the smallest missing element is in the right search space of the middle.Otherwise, the smallest missing number is in the left search space of the middle."
},
{
"code": null,
"e": 28126,
"s": 28002,
"text": "If the middle element is the desired element, then the smallest missing element is in the right search space of the middle."
},
{
"code": null,
"e": 28208,
"s": 28126,
"text": "Otherwise, the smallest missing number is in the left search space of the middle."
},
{
"code": null,
"e": 28259,
"s": 28208,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28263,
"s": 28259,
"text": "C++"
},
{
"code": "//C++ program for the above approach#include <bits/stdc++.h> using namespace std; // Program to find missing elementint findFirstMissing(vector<int> arr , int start , int end,int first){ if (start < end) { int mid = (start + end) / 2; /** Index matches with value at that index, means missing element cannot be upto that po*/ if (arr[mid] != mid+first) return findFirstMissing(arr, start, mid , first); else return findFirstMissing(arr, mid + 1, end , first); } return start + first; } // Program to find Smallest// Missing in Sorted Arrayint findSmallestMissinginSortedArray(vector<int> arr){ // Check if 0 is missing // in the array if(arr[0] != 0) return 0; // Check is all numbers 0 to n - 1 // are present in array if(arr[arr.size() - 1] == arr.size() - 1) return arr.size(); int first = arr[0]; return findFirstMissing(arr, 0, arr.size() - 1, first);} // Driver program to test the above functionint main(){ vector<int> arr = {0, 1, 2, 3, 4, 5, 7}; int n = arr.size(); // Function Call cout<<\"First Missing element is : \"<<findSmallestMissinginSortedArray(arr);} // This code is contributed by mohit kumar 29.",
"e": 29553,
"s": 28263,
"text": null
},
{
"code": null,
"e": 29582,
"s": 29553,
"text": "First Missing element is : 6"
},
{
"code": null,
"e": 29608,
"s": 29582,
"text": "Time Complexity: O(Logn) "
},
{
"code": null,
"e": 29692,
"s": 29608,
"text": "Please refer complete article on Find the smallest missing number for more details!"
},
{
"code": null,
"e": 29706,
"s": 29692,
"text": "Binary Search"
},
{
"code": null,
"e": 29713,
"s": 29706,
"text": "Arrays"
},
{
"code": null,
"e": 29717,
"s": 29713,
"text": "C++"
},
{
"code": null,
"e": 29730,
"s": 29717,
"text": "C++ Programs"
},
{
"code": null,
"e": 29737,
"s": 29730,
"text": "Arrays"
},
{
"code": null,
"e": 29751,
"s": 29737,
"text": "Binary Search"
},
{
"code": null,
"e": 29755,
"s": 29751,
"text": "CPP"
},
{
"code": null,
"e": 29853,
"s": 29755,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29862,
"s": 29853,
"text": "Comments"
},
{
"code": null,
"e": 29875,
"s": 29862,
"text": "Old Comments"
},
{
"code": null,
"e": 29900,
"s": 29875,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 29949,
"s": 29900,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 29987,
"s": 29949,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 30045,
"s": 29987,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 30065,
"s": 30045,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 30083,
"s": 30065,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 30129,
"s": 30083,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 30148,
"s": 30129,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30191,
"s": 30148,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
How to append data in JSON file through HTML form using PHP ? - GeeksforGeeks
|
23 Sep, 2020
The purpose of this article is to append data to a JSON file through HTML form using PHP.
Approach 1: If the JSON file is not created then we create a new JSON file, send data to it, and append data in it. To see how to create a JSON file by taking data from the HTML form, refer this link.
Approach 2: If the JSON file is already created then we directly append data to the JSON file. To send data from HTML form to JSON file we are using json_encode() function which returns a JSON encoded string.
We are making an array of values that the user fills in the HTML form. Then we pass this array into json_encode() function. The json_encode() function returns a JSON encoded string. To create a JSON file we used PHP file_put_contents() which is used to write data to a file. We pass 2 arguments in file_put_contents() function. The first parameter is our file name in which we want to store data in the JSON format and the second is our PHP get_data() function.
According to the first approach, we will successfully create a JSON file using the json_encode() function. Now our JSON file is created. The next task is to append data to that JSON file. To append data to the JSON file we have to store the previous data to a variable. To get the data of our JSON file we will be using the file_get_contents() function. The file_get_contents() reads a file into a string. To decode the string, the json_decode() function is used which is an in-built function in PHP used to decode a JSON string. The function converts a JSON encoded string into a PHP variable. The HTML data in an array is assigned to our decoded string. The json_encode() function and file_put_contents() are used to encode string and put the contents to JSON file respectively.
Example: The following HTML and PHP code demonstrates the above approach.
HTML
<html> <head> <meta charset="UTF-8"> <style> h3 { text-align: center; } img { display: block; margin: auto; height: 150px; width: 150px; } .input { margin: 6px; padding: 10px; display: block; margin: auto; color: palevioletred; font-size: 30px; } input { width: 90%; display: block; margin-left: 12px; background: none; background-color: lightyellow; } select { width: 90%; display: block; margin-left: 12px; background: none; background-color: lightyellow; } #heading { font-family: cursive; text-align: center; color: green; padding-top: 20px; } #form_page { height: 500px; width: 50%; display: flex; flex-wrap: wrap; flex-direction: row; margin: auto; } #form_body { border-radius: 12px; height: 330px; width: 450px; background-color: beige; border: 1px solid pink; margin: auto; margin-top: 12px; } #text { color: red; width: 100px; } #head { border-bottom: 2px solid red; height: 100px; background-color: aliceblue; } #submit { background-color: white; width: 70px; } </style> </head> <body> <form method="post" action="gfg.php"> <div id="form_page"> <div id="form_body"> <div id="head"> <h1 id="heading">GFG</h1> </div> <br /> <div id="input_name" class="input"> <input id="name" type="text" Placeholder="Name" name="name" required> </div> <div id="input_class" class="input"> <input type="text" placeholder= "Branch" name="branch" required> </div> <div id="input_year" class="input"> <input id="school" type="text" name="year" placeholder="Year"> </div> <div class="id input"> <input id="submit" type="submit" name="submit" value="submit" onclick="on_submit()"> </div> </div> </div> </form> </body> </html>
PHP Code: The following is the “gfg.php” file used in the above HTML file.
PHP
<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { function get_data() { $name = $_POST['name']; $file_name='StudentsData'. '.json'; if(file_exists("$file_name")) { $current_data=file_get_contents("$file_name"); $array_data=json_decode($current_data, true); $extra=array( 'Name' => $_POST['name'], 'Branch' => $_POST['branch'], 'Year' => $_POST['year'], ); $array_data[]=$extra; echo "file exist<br/>"; return json_encode($array_data); } else { $datae=array(); $datae[]=array( 'Name' => $_POST['name'], 'Branch' => $_POST['branch'], 'Year' => $_POST['year'], ); echo "file not exist<br/>"; return json_encode($datae); } } $file_name='StudentsData'. '.json'; if(file_put_contents("$file_name", get_data())) { echo 'success'; } else { echo 'There is some error'; }} ?>
Output: The content of the “StudentsData.json” file shows the data in JSON format.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
PHP-Misc
CSS
HTML
PHP
PHP Programs
Web Technologies
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
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": 25706,
"s": 25678,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 25796,
"s": 25706,
"text": "The purpose of this article is to append data to a JSON file through HTML form using PHP."
},
{
"code": null,
"e": 25997,
"s": 25796,
"text": "Approach 1: If the JSON file is not created then we create a new JSON file, send data to it, and append data in it. To see how to create a JSON file by taking data from the HTML form, refer this link."
},
{
"code": null,
"e": 26206,
"s": 25997,
"text": "Approach 2: If the JSON file is already created then we directly append data to the JSON file. To send data from HTML form to JSON file we are using json_encode() function which returns a JSON encoded string."
},
{
"code": null,
"e": 26668,
"s": 26206,
"text": "We are making an array of values that the user fills in the HTML form. Then we pass this array into json_encode() function. The json_encode() function returns a JSON encoded string. To create a JSON file we used PHP file_put_contents() which is used to write data to a file. We pass 2 arguments in file_put_contents() function. The first parameter is our file name in which we want to store data in the JSON format and the second is our PHP get_data() function."
},
{
"code": null,
"e": 27449,
"s": 26668,
"text": "According to the first approach, we will successfully create a JSON file using the json_encode() function. Now our JSON file is created. The next task is to append data to that JSON file. To append data to the JSON file we have to store the previous data to a variable. To get the data of our JSON file we will be using the file_get_contents() function. The file_get_contents() reads a file into a string. To decode the string, the json_decode() function is used which is an in-built function in PHP used to decode a JSON string. The function converts a JSON encoded string into a PHP variable. The HTML data in an array is assigned to our decoded string. The json_encode() function and file_put_contents() are used to encode string and put the contents to JSON file respectively."
},
{
"code": null,
"e": 27523,
"s": 27449,
"text": "Example: The following HTML and PHP code demonstrates the above approach."
},
{
"code": null,
"e": 27528,
"s": 27523,
"text": "HTML"
},
{
"code": "<html> <head> <meta charset=\"UTF-8\"> <style> h3 { text-align: center; } img { display: block; margin: auto; height: 150px; width: 150px; } .input { margin: 6px; padding: 10px; display: block; margin: auto; color: palevioletred; font-size: 30px; } input { width: 90%; display: block; margin-left: 12px; background: none; background-color: lightyellow; } select { width: 90%; display: block; margin-left: 12px; background: none; background-color: lightyellow; } #heading { font-family: cursive; text-align: center; color: green; padding-top: 20px; } #form_page { height: 500px; width: 50%; display: flex; flex-wrap: wrap; flex-direction: row; margin: auto; } #form_body { border-radius: 12px; height: 330px; width: 450px; background-color: beige; border: 1px solid pink; margin: auto; margin-top: 12px; } #text { color: red; width: 100px; } #head { border-bottom: 2px solid red; height: 100px; background-color: aliceblue; } #submit { background-color: white; width: 70px; } </style> </head> <body> <form method=\"post\" action=\"gfg.php\"> <div id=\"form_page\"> <div id=\"form_body\"> <div id=\"head\"> <h1 id=\"heading\">GFG</h1> </div> <br /> <div id=\"input_name\" class=\"input\"> <input id=\"name\" type=\"text\" Placeholder=\"Name\" name=\"name\" required> </div> <div id=\"input_class\" class=\"input\"> <input type=\"text\" placeholder= \"Branch\" name=\"branch\" required> </div> <div id=\"input_year\" class=\"input\"> <input id=\"school\" type=\"text\" name=\"year\" placeholder=\"Year\"> </div> <div class=\"id input\"> <input id=\"submit\" type=\"submit\" name=\"submit\" value=\"submit\" onclick=\"on_submit()\"> </div> </div> </div> </form> </body> </html> ",
"e": 30396,
"s": 27528,
"text": null
},
{
"code": null,
"e": 30471,
"s": 30396,
"text": "PHP Code: The following is the “gfg.php” file used in the above HTML file."
},
{
"code": null,
"e": 30475,
"s": 30471,
"text": "PHP"
},
{
"code": "<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { function get_data() { $name = $_POST['name']; $file_name='StudentsData'. '.json'; if(file_exists(\"$file_name\")) { $current_data=file_get_contents(\"$file_name\"); $array_data=json_decode($current_data, true); $extra=array( 'Name' => $_POST['name'], 'Branch' => $_POST['branch'], 'Year' => $_POST['year'], ); $array_data[]=$extra; echo \"file exist<br/>\"; return json_encode($array_data); } else { $datae=array(); $datae[]=array( 'Name' => $_POST['name'], 'Branch' => $_POST['branch'], 'Year' => $_POST['year'], ); echo \"file not exist<br/>\"; return json_encode($datae); } } $file_name='StudentsData'. '.json'; if(file_put_contents(\"$file_name\", get_data())) { echo 'success'; } else { echo 'There is some error'; }} ?>",
"e": 31649,
"s": 30475,
"text": null
},
{
"code": null,
"e": 31732,
"s": 31649,
"text": "Output: The content of the “StudentsData.json” file shows the data in JSON format."
},
{
"code": null,
"e": 31869,
"s": 31732,
"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": 31878,
"s": 31869,
"text": "CSS-Misc"
},
{
"code": null,
"e": 31888,
"s": 31878,
"text": "HTML-Misc"
},
{
"code": null,
"e": 31897,
"s": 31888,
"text": "PHP-Misc"
},
{
"code": null,
"e": 31901,
"s": 31897,
"text": "CSS"
},
{
"code": null,
"e": 31906,
"s": 31901,
"text": "HTML"
},
{
"code": null,
"e": 31910,
"s": 31906,
"text": "PHP"
},
{
"code": null,
"e": 31923,
"s": 31910,
"text": "PHP Programs"
},
{
"code": null,
"e": 31940,
"s": 31923,
"text": "Web Technologies"
},
{
"code": null,
"e": 31945,
"s": 31940,
"text": "HTML"
},
{
"code": null,
"e": 31949,
"s": 31945,
"text": "PHP"
},
{
"code": null,
"e": 32047,
"s": 31949,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32086,
"s": 32047,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 32123,
"s": 32086,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32152,
"s": 32123,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32194,
"s": 32152,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 32229,
"s": 32194,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 32289,
"s": 32229,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 32330,
"s": 32289,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 32383,
"s": 32330,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 32444,
"s": 32383,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
C Program For Deleting A Given Node In Linked List Under Given Constraints - GeeksforGeeks
|
20 Dec, 2021
Given a Singly Linked List, write a function to delete a given node. Your function must follow the following constraints:
It must accept a pointer to the start node as the first parameter and node to be deleted as the second parameter i.e., a pointer to the head node is not global.It should not return a pointer to the head node.It should not accept pointer to pointer to the head node.
It must accept a pointer to the start node as the first parameter and node to be deleted as the second parameter i.e., a pointer to the head node is not global.
It should not return a pointer to the head node.
It should not accept pointer to pointer to the head node.
You may assume that the Linked List never becomes empty.Let the function name be deleteNode(). In a straightforward implementation, the function needs to modify the head pointer when the node to be deleted is the first node. As discussed in previous post, when a function modifies the head pointer, the function must use one of the given approaches, we can’t use any of those approaches here. Solution We explicitly handle the case when the node to be deleted is the first node, we copy the data of the next node to head and delete the next node. The cases when a deleted node is not the head node can be handled normally by finding the previous node and changing next of the previous node. The following are the implementation.
C
#include <stdio.h>#include <stdlib.h> // Structure of a linked list // nodestruct Node{ int data; struct Node *next;}; void deleteNode(struct Node *head, struct Node *n){ // When node to be deleted is // head node if(head == n) { if(head->next == NULL) { printf("There is only one node. " , "The list can't be made empty "); return; } // Copy the data of next node to head head->data = head->next->data; // store address of next node n = head->next; // Remove the link of next node head->next = head->next->next; // free memory free(n); return; } // When not first node, follow the // normal deletion process // Find the previous node struct Node *prev = head; while(prev->next != NULL && prev->next != n) prev = prev->next; // Check if node really exists in // Linked List if(prev->next == NULL) { printf( "Given node is not present in Linked List"); return; } // Remove node from Linked List prev->next = prev->next->next; // Free memory free(n); return; } /* Utility function to insert a node at the beginning */void push(struct Node **head_ref, int new_data){ struct Node *new_node = (struct Node *)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = *head_ref; *head_ref = new_node;} /* Utility function to print a linked list */void printList(struct Node *head){ while(head!=NULL) { printf("%d ",head->data); head=head->next; } printf("");} // Driver codeint main(){ struct Node *head = NULL; /* Create following linked list 12->15->10->11->5->6->2->3 */ push(&head,3); push(&head,2); push(&head,6); push(&head,5); push(&head,11); push(&head,10); push(&head,15); push(&head,12); printf("Given Linked List: "); printList(head); /* Let us delete the node with value 10 */ printf(" Deleting node %d: ", head->next->next->data); deleteNode(head, head->next->next); printf( "Modified Linked List: "); printList(head); // Let us delete the first node printf( "Deleting first node "); deleteNode(head, head); printf( "Modified Linked List: "); printList(head); getchar(); return 0;}
Output:
Given Linked List: 12 15 10 11 5 6 2 3
Deleting node 10:
Modified Linked List: 12 15 11 5 6 2 3
Deleting first node
Modified Linked List: 15 11 5 6 2 3
Please refer complete article on Delete a given node in Linked List under given constraints for more details!
Linked Lists
C Language
C Programs
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Strings in C
UDP Server-Client implementation in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
|
[
{
"code": null,
"e": 24286,
"s": 24258,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 24409,
"s": 24286,
"text": "Given a Singly Linked List, write a function to delete a given node. Your function must follow the following constraints: "
},
{
"code": null,
"e": 24675,
"s": 24409,
"text": "It must accept a pointer to the start node as the first parameter and node to be deleted as the second parameter i.e., a pointer to the head node is not global.It should not return a pointer to the head node.It should not accept pointer to pointer to the head node."
},
{
"code": null,
"e": 24836,
"s": 24675,
"text": "It must accept a pointer to the start node as the first parameter and node to be deleted as the second parameter i.e., a pointer to the head node is not global."
},
{
"code": null,
"e": 24885,
"s": 24836,
"text": "It should not return a pointer to the head node."
},
{
"code": null,
"e": 24943,
"s": 24885,
"text": "It should not accept pointer to pointer to the head node."
},
{
"code": null,
"e": 25672,
"s": 24943,
"text": "You may assume that the Linked List never becomes empty.Let the function name be deleteNode(). In a straightforward implementation, the function needs to modify the head pointer when the node to be deleted is the first node. As discussed in previous post, when a function modifies the head pointer, the function must use one of the given approaches, we can’t use any of those approaches here. Solution We explicitly handle the case when the node to be deleted is the first node, we copy the data of the next node to head and delete the next node. The cases when a deleted node is not the head node can be handled normally by finding the previous node and changing next of the previous node. The following are the implementation."
},
{
"code": null,
"e": 25674,
"s": 25672,
"text": "C"
},
{
"code": "#include <stdio.h>#include <stdlib.h> // Structure of a linked list // nodestruct Node{ int data; struct Node *next;}; void deleteNode(struct Node *head, struct Node *n){ // When node to be deleted is // head node if(head == n) { if(head->next == NULL) { printf(\"There is only one node. \" , \"The list can't be made empty \"); return; } // Copy the data of next node to head head->data = head->next->data; // store address of next node n = head->next; // Remove the link of next node head->next = head->next->next; // free memory free(n); return; } // When not first node, follow the // normal deletion process // Find the previous node struct Node *prev = head; while(prev->next != NULL && prev->next != n) prev = prev->next; // Check if node really exists in // Linked List if(prev->next == NULL) { printf( \"Given node is not present in Linked List\"); return; } // Remove node from Linked List prev->next = prev->next->next; // Free memory free(n); return; } /* Utility function to insert a node at the beginning */void push(struct Node **head_ref, int new_data){ struct Node *new_node = (struct Node *)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = *head_ref; *head_ref = new_node;} /* Utility function to print a linked list */void printList(struct Node *head){ while(head!=NULL) { printf(\"%d \",head->data); head=head->next; } printf(\"\");} // Driver codeint main(){ struct Node *head = NULL; /* Create following linked list 12->15->10->11->5->6->2->3 */ push(&head,3); push(&head,2); push(&head,6); push(&head,5); push(&head,11); push(&head,10); push(&head,15); push(&head,12); printf(\"Given Linked List: \"); printList(head); /* Let us delete the node with value 10 */ printf(\" Deleting node %d: \", head->next->next->data); deleteNode(head, head->next->next); printf( \"Modified Linked List: \"); printList(head); // Let us delete the first node printf( \"Deleting first node \"); deleteNode(head, head); printf( \"Modified Linked List: \"); printList(head); getchar(); return 0;}",
"e": 28142,
"s": 25674,
"text": null
},
{
"code": null,
"e": 28150,
"s": 28142,
"text": "Output:"
},
{
"code": null,
"e": 28304,
"s": 28150,
"text": "Given Linked List: 12 15 10 11 5 6 2 3\n\nDeleting node 10:\nModified Linked List: 12 15 11 5 6 2 3\n\nDeleting first node\nModified Linked List: 15 11 5 6 2 3"
},
{
"code": null,
"e": 28414,
"s": 28304,
"text": "Please refer complete article on Delete a given node in Linked List under given constraints for more details!"
},
{
"code": null,
"e": 28427,
"s": 28414,
"text": "Linked Lists"
},
{
"code": null,
"e": 28438,
"s": 28427,
"text": "C Language"
},
{
"code": null,
"e": 28449,
"s": 28438,
"text": "C Programs"
},
{
"code": null,
"e": 28461,
"s": 28449,
"text": "Linked List"
},
{
"code": null,
"e": 28473,
"s": 28461,
"text": "Linked List"
},
{
"code": null,
"e": 28571,
"s": 28473,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28580,
"s": 28571,
"text": "Comments"
},
{
"code": null,
"e": 28593,
"s": 28580,
"text": "Old Comments"
},
{
"code": null,
"e": 28631,
"s": 28593,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 28657,
"s": 28631,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 28677,
"s": 28657,
"text": "Multithreading in C"
},
{
"code": null,
"e": 28699,
"s": 28677,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 28737,
"s": 28699,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 28750,
"s": 28737,
"text": "Strings in C"
},
{
"code": null,
"e": 28788,
"s": 28750,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 28829,
"s": 28788,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 28870,
"s": 28829,
"text": "C Program to read contents of Whole File"
}
] |
mailq Command in Linux with Examples - GeeksforGeeks
|
10 May, 2020
The name itself suggests, mailq i.e. “mail-queue”, this command in Linux prints the mail queue i.e the list of messages that are there in the mail queue. You should have a mail-server setup on your Linux machine, in order to use this command, there are ways i.e MTA’s(Mail Transfer agent) you can use like sendmail that uses the service smtp.
The output of mailq command is similar to the sendmail -bp command that also prints the mail queue.
Syntax:
mailq [options]
Examples:
1. maliq without any option: Simply prints the messages in the mail queue.
$ mailq
Output
Mail Queue (1 request)
---QID---- --Size-- -----Q-Time----- ------Sender/Recipient-----
SS04506 5 Tue Nov 12 09:01 root
(User unknown)
2. Prints along with priority specified: Simply prints the messages in the mail queue.
$ mailq -v
Output
Mail Queue (1 request)
---QID---- --Size-- -Priority- -----Q-Time----- ------Sender/Recipient-----
SS04506 5 2005 Tue Nov 12 09:01 root
(User unknown)
Here,
QID: Specific ID alloted to message.
Size: Number of bytes contained in body of message.
Q-Time Time at which message entered the queue.
Applications: In large applications at production env, email queuing is necessary as recipients are quite good in number, so sending the email to all at the same time becomes a risky thing, so mailq helps in looking out the sequence as per the priority.
linux-command
Picked
Linux-Unix
Write From Home
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
chown command in Linux with Examples
Docker - COPY Instruction
nohup Command in Linux with Examples
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
|
[
{
"code": null,
"e": 26202,
"s": 26174,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 26545,
"s": 26202,
"text": "The name itself suggests, mailq i.e. “mail-queue”, this command in Linux prints the mail queue i.e the list of messages that are there in the mail queue. You should have a mail-server setup on your Linux machine, in order to use this command, there are ways i.e MTA’s(Mail Transfer agent) you can use like sendmail that uses the service smtp."
},
{
"code": null,
"e": 26645,
"s": 26545,
"text": "The output of mailq command is similar to the sendmail -bp command that also prints the mail queue."
},
{
"code": null,
"e": 26653,
"s": 26645,
"text": "Syntax:"
},
{
"code": null,
"e": 26669,
"s": 26653,
"text": "mailq [options]"
},
{
"code": null,
"e": 26679,
"s": 26669,
"text": "Examples:"
},
{
"code": null,
"e": 26754,
"s": 26679,
"text": "1. maliq without any option: Simply prints the messages in the mail queue."
},
{
"code": null,
"e": 26763,
"s": 26754,
"text": "$ mailq\n"
},
{
"code": null,
"e": 26770,
"s": 26763,
"text": "Output"
},
{
"code": null,
"e": 26940,
"s": 26770,
"text": " Mail Queue (1 request)\n---QID---- --Size-- -----Q-Time----- ------Sender/Recipient-----\nSS04506 5 Tue Nov 12 09:01 root\n (User unknown)\n"
},
{
"code": null,
"e": 27027,
"s": 26940,
"text": "2. Prints along with priority specified: Simply prints the messages in the mail queue."
},
{
"code": null,
"e": 27039,
"s": 27027,
"text": "$ mailq -v\n"
},
{
"code": null,
"e": 27046,
"s": 27039,
"text": "Output"
},
{
"code": null,
"e": 27238,
"s": 27046,
"text": " Mail Queue (1 request)\n---QID---- --Size-- -Priority- -----Q-Time----- ------Sender/Recipient-----\nSS04506 5 2005 Tue Nov 12 09:01 root\n (User unknown)\n"
},
{
"code": null,
"e": 27244,
"s": 27238,
"text": "Here,"
},
{
"code": null,
"e": 27281,
"s": 27244,
"text": "QID: Specific ID alloted to message."
},
{
"code": null,
"e": 27333,
"s": 27281,
"text": "Size: Number of bytes contained in body of message."
},
{
"code": null,
"e": 27381,
"s": 27333,
"text": "Q-Time Time at which message entered the queue."
},
{
"code": null,
"e": 27635,
"s": 27381,
"text": "Applications: In large applications at production env, email queuing is necessary as recipients are quite good in number, so sending the email to all at the same time becomes a risky thing, so mailq helps in looking out the sequence as per the priority."
},
{
"code": null,
"e": 27649,
"s": 27635,
"text": "linux-command"
},
{
"code": null,
"e": 27656,
"s": 27649,
"text": "Picked"
},
{
"code": null,
"e": 27667,
"s": 27656,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27683,
"s": 27667,
"text": "Write From Home"
},
{
"code": null,
"e": 27781,
"s": 27683,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27816,
"s": 27781,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27850,
"s": 27816,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27887,
"s": 27850,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27913,
"s": 27887,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27950,
"s": 27913,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27986,
"s": 27950,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 28022,
"s": 27986,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 28083,
"s": 28022,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 28099,
"s": 28083,
"text": "Python infinity"
}
] |
How to get parameter value from query string in ReactJS? - GeeksforGeeks
|
28 Dec, 2020
We can access query string via this.props.location.search then we can parse it using a library called query-string. This library has a parse() function that parses the query string and returns an object.
For example, the query string is ?site=gfg&subject=react then after parsing object will be:
{
Site:"gfg",
Subject:"react"
}
Module Installation: Install the library using the following command:
npm install query-string
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Filename: App.js
Javascript
import React, { Component } from "react";// Importing Moduleimport queryString from 'query-string' class App extends Component { state = { site: 'unknown', subject: 'i dont know' } handleQueryString = () => { // Parsing the query string // Using parse method let queries = queryString.parse(this.props.location.search) console.log(queries) this.setState(queries) } render() { return ( <div style={{ margin: 200 }}> <p> WebSite: {this.state.site} </p> <p> Subject: {this.state.subject} </p> <button onClick={this.handleQueryString} className='btn btn-primary'> click me </button> </div> ); }} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
You will see the following button and text on the screen:
You will see the following button and text on the screen:
After clicking on the button, the following will be the output:
After clicking on the button, the following will be the output:
Picked
react-js
JavaScript
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 ?
How to filter object array based on attributes?
Remove elements from a JavaScript Array
How to detect browser or tab closing in JavaScript ?
Lodash _.debounce() Method
Angular File Upload
|
[
{
"code": null,
"e": 25218,
"s": 25190,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 25422,
"s": 25218,
"text": "We can access query string via this.props.location.search then we can parse it using a library called query-string. This library has a parse() function that parses the query string and returns an object."
},
{
"code": null,
"e": 25515,
"s": 25422,
"text": " For example, the query string is ?site=gfg&subject=react then after parsing object will be:"
},
{
"code": null,
"e": 25549,
"s": 25515,
"text": "{\n Site:\"gfg\",\n Subject:\"react\"\n}"
},
{
"code": null,
"e": 25619,
"s": 25549,
"text": "Module Installation: Install the library using the following command:"
},
{
"code": null,
"e": 25645,
"s": 25619,
"text": "npm install query-string "
},
{
"code": null,
"e": 25673,
"s": 25645,
"text": "Creating React Application:"
},
{
"code": null,
"e": 25737,
"s": 25673,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 25769,
"s": 25737,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 25870,
"s": 25769,
"text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:"
},
{
"code": null,
"e": 25884,
"s": 25870,
"text": "cd foldername"
},
{
"code": null,
"e": 25936,
"s": 25884,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 25953,
"s": 25936,
"text": "Filename: App.js"
},
{
"code": null,
"e": 25964,
"s": 25953,
"text": "Javascript"
},
{
"code": "import React, { Component } from \"react\";// Importing Moduleimport queryString from 'query-string' class App extends Component { state = { site: 'unknown', subject: 'i dont know' } handleQueryString = () => { // Parsing the query string // Using parse method let queries = queryString.parse(this.props.location.search) console.log(queries) this.setState(queries) } render() { return ( <div style={{ margin: 200 }}> <p> WebSite: {this.state.site} </p> <p> Subject: {this.state.subject} </p> <button onClick={this.handleQueryString} className='btn btn-primary'> click me </button> </div> ); }} export default App;",
"e": 26684,
"s": 25964,
"text": null
},
{
"code": null,
"e": 26797,
"s": 26684,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 26807,
"s": 26797,
"text": "npm start"
},
{
"code": null,
"e": 26815,
"s": 26807,
"text": "Output:"
},
{
"code": null,
"e": 26873,
"s": 26815,
"text": "You will see the following button and text on the screen:"
},
{
"code": null,
"e": 26931,
"s": 26873,
"text": "You will see the following button and text on the screen:"
},
{
"code": null,
"e": 26995,
"s": 26931,
"text": "After clicking on the button, the following will be the output:"
},
{
"code": null,
"e": 27059,
"s": 26995,
"text": "After clicking on the button, the following will be the output:"
},
{
"code": null,
"e": 27066,
"s": 27059,
"text": "Picked"
},
{
"code": null,
"e": 27075,
"s": 27066,
"text": "react-js"
},
{
"code": null,
"e": 27086,
"s": 27075,
"text": "JavaScript"
},
{
"code": null,
"e": 27184,
"s": 27086,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27193,
"s": 27184,
"text": "Comments"
},
{
"code": null,
"e": 27206,
"s": 27193,
"text": "Old Comments"
},
{
"code": null,
"e": 27267,
"s": 27206,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27308,
"s": 27267,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27362,
"s": 27308,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27419,
"s": 27362,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 27481,
"s": 27419,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27529,
"s": 27481,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27569,
"s": 27529,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27622,
"s": 27569,
"text": "How to detect browser or tab closing in JavaScript ?"
},
{
"code": null,
"e": 27649,
"s": 27622,
"text": "Lodash _.debounce() Method"
}
] |
Iterate over a set in Python - GeeksforGeeks
|
12 Jul, 2021
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements.There are numerous ways that can be used to iterate over a Set. Some of these ways provide faster time execution as compared to others. Some of these ways include, iterating using for/while loops, comprehensions, iterators and their variations. Let’s see all the different ways we can iterate over a set in Python.Analysis of each method: For explaining the working of each way/technique, time per set(randomly generated set) has been calculated for 5-times to get a rough estimate on how much time every technique takes for iterating over a given set. random.seed(21) has been added to each script to fixate over the random numbers that are generated every time the program is executed. Using constant seed helps us to determine which technique is best for a given particular randomly generated set.Method #1: Iterating over a set using simple for loop.
Python3
# Creating a set using stringtest_set = set("geEks") # Iterating using for loopfor val in test_set: print(val)
Output:
k
s
e
g
E
Analysis:
Python3
# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): for val in test_set: _ = val # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))
Output:
0.06303901899809716
0.06756918999963091
0.06692574200133095
0.067220498000097
0.06748137499744189
Method #2: Iterating over a set using enumerated for loop.
Python3
# Creating a set using stringtest_set = set("geEks") # Iterating using enumerated for loopfor id,val in enumerate(test_set): print(id, val)
Output:
0 E
1 e
2 k
3 g
4 s
Analysis:
Python3
# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): for id, val in enumerate(test_set): _ = val # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))
Output:
0.1306622320007591
0.13657568199778325
0.13797824799985392
0.1386374360008631
0.1424286179972114
Method #3: Iterating over a set as indexed list.
Python3
# Creating a set using stringtest_set = set("geEks") test_list = list(test_set) # Iterating over a set as a indexed listfor id in range(len(test_list)): print(test_list[id])
Output:
g
k
E
s
e
Analysis:
Python3
# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): test_list = list(test_set) for id in range(len(test_list)): _ = test_list[id] # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))
Output:
0.20036015100049553
0.2557020290005312
0.4601482660000329
0.2161413249996258
0.18769703499856405
Method #4: Iterating over a set using comprehension and list constructor/initializer.
Python3
# Creating a set using stringtest_set = set("geEks") # Iterating using list-comprehensioncom = list(val for val in test_set)print(*com)
Output:
k s e g E
Analysis:
Python3
# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): list(val for val in test_set) # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))
Output:
0.1662169310002355
0.1783527520019561
0.21661155100082397
0.19131610199838178
0.19931397800246486
Method #5: Iterating over a set using comprehension.
Python3
# Creating a set using stringtest_set = set("geEks") # Iterating using list-comprehensioncom = [print(val) for val in test_set]
Output:
e
E
g
s
k
Analysis:
Python3
# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): [val for val in test_set] # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))
Output:
0.11386321299869451
0.111869686999853
0.1092844699996931
0.11223735699968529
0.10928539399901638
Method #6: Iterating over a set using map, lambda and list comprehension
Python3
# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): [map(lambda val: val, test_set)] # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))
Output:
1.0756000847322866e-05
1.310199877480045e-05
1.269100175704807e-05
1.1588999768719077e-05
1.2522999895736575e-05
Method #7: Iterating over a set using iterator.
Python3
# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): for val in iter(test_set): _ = val # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))
Output:
0.0676155920009478
0.07111633900058223
0.06994135700006154
0.0732101009998587
0.08668379899972933
Method #8: Iterating over a set using iterator and while loop.
Python3
# Creating a set using stringtest_set = set("geEks") iter_gen = iter(test_set) while True: try: # get the next item print(next(iter_gen)) ''' do something with element ''' except StopIteration: # if StopIteration is raised, # break from loop break
Output:
E
s
e
k
g
Analysis:
Python3
# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): iter_gen = iter(test_set) while True: try: # get the next item next(iter_gen) # do something with element except StopIteration: # if StopIteration is raised, break from loop break # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))
Output:
0.2136418699992646
0.1952157889973023
0.4234208280031453
0.255840524998348
0.24712910099697183
Conclusion: Among all the looping techniques, simple for loop iteration and looping over iterators works best, while comparing all the techniques, using map with lambda over set or iterator of set works best giving a performance of a million set iterations under 10 milliseconds. It is quite noticeable that above examples only have single access of set components per iteration, whereas if we increase the number of times a set component is accessed per iteration, it may change the time taken per iteration.Note: Values mentioned above in the example output are bound to vary. The reason behind the variation of time consumption is machine dependency of processing power of individual’s system processor.
sooda367
Picked
Python set-programs
python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25531,
"s": 25503,
"text": "\n12 Jul, 2021"
},
{
"code": null,
"e": 26498,
"s": 25531,
"text": "In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements.There are numerous ways that can be used to iterate over a Set. Some of these ways provide faster time execution as compared to others. Some of these ways include, iterating using for/while loops, comprehensions, iterators and their variations. Let’s see all the different ways we can iterate over a set in Python.Analysis of each method: For explaining the working of each way/technique, time per set(randomly generated set) has been calculated for 5-times to get a rough estimate on how much time every technique takes for iterating over a given set. random.seed(21) has been added to each script to fixate over the random numbers that are generated every time the program is executed. Using constant seed helps us to determine which technique is best for a given particular randomly generated set.Method #1: Iterating over a set using simple for loop. "
},
{
"code": null,
"e": 26506,
"s": 26498,
"text": "Python3"
},
{
"code": "# Creating a set using stringtest_set = set(\"geEks\") # Iterating using for loopfor val in test_set: print(val)",
"e": 26620,
"s": 26506,
"text": null
},
{
"code": null,
"e": 26628,
"s": 26620,
"text": "Output:"
},
{
"code": null,
"e": 26638,
"s": 26628,
"text": "k\ns\ne\ng\nE"
},
{
"code": null,
"e": 26650,
"s": 26638,
"text": "Analysis: "
},
{
"code": null,
"e": 26658,
"s": 26650,
"text": "Python3"
},
{
"code": "# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): for val in test_set: _ = val # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))",
"e": 27196,
"s": 26658,
"text": null
},
{
"code": null,
"e": 27206,
"s": 27196,
"text": "Output: "
},
{
"code": null,
"e": 27304,
"s": 27206,
"text": "0.06303901899809716\n0.06756918999963091\n0.06692574200133095\n0.067220498000097\n0.06748137499744189"
},
{
"code": null,
"e": 27365,
"s": 27304,
"text": " Method #2: Iterating over a set using enumerated for loop. "
},
{
"code": null,
"e": 27373,
"s": 27365,
"text": "Python3"
},
{
"code": "# Creating a set using stringtest_set = set(\"geEks\") # Iterating using enumerated for loopfor id,val in enumerate(test_set): print(id, val)",
"e": 27516,
"s": 27373,
"text": null
},
{
"code": null,
"e": 27526,
"s": 27516,
"text": "Output: "
},
{
"code": null,
"e": 27546,
"s": 27526,
"text": "0 E\n1 e\n2 k\n3 g\n4 s"
},
{
"code": null,
"e": 27558,
"s": 27546,
"text": "Analysis: "
},
{
"code": null,
"e": 27566,
"s": 27558,
"text": "Python3"
},
{
"code": "# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): for id, val in enumerate(test_set): _ = val # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))",
"e": 28118,
"s": 27566,
"text": null
},
{
"code": null,
"e": 28128,
"s": 28118,
"text": "Output: "
},
{
"code": null,
"e": 28225,
"s": 28128,
"text": "0.1306622320007591\n0.13657568199778325\n0.13797824799985392\n0.1386374360008631\n0.1424286179972114"
},
{
"code": null,
"e": 28278,
"s": 28225,
"text": " Method #3: Iterating over a set as indexed list. "
},
{
"code": null,
"e": 28286,
"s": 28278,
"text": "Python3"
},
{
"code": "# Creating a set using stringtest_set = set(\"geEks\") test_list = list(test_set) # Iterating over a set as a indexed listfor id in range(len(test_list)): print(test_list[id])",
"e": 28467,
"s": 28286,
"text": null
},
{
"code": null,
"e": 28477,
"s": 28467,
"text": "Output: "
},
{
"code": null,
"e": 28487,
"s": 28477,
"text": "g\nk\nE\ns\ne"
},
{
"code": null,
"e": 28499,
"s": 28487,
"text": "Analysis: "
},
{
"code": null,
"e": 28507,
"s": 28499,
"text": "Python3"
},
{
"code": "# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): test_list = list(test_set) for id in range(len(test_list)): _ = test_list[id] # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))",
"e": 29097,
"s": 28507,
"text": null
},
{
"code": null,
"e": 29107,
"s": 29097,
"text": "Output: "
},
{
"code": null,
"e": 29204,
"s": 29107,
"text": "0.20036015100049553\n0.2557020290005312\n0.4601482660000329\n0.2161413249996258\n0.18769703499856405"
},
{
"code": null,
"e": 29293,
"s": 29204,
"text": " Method #4: Iterating over a set using comprehension and list constructor/initializer. "
},
{
"code": null,
"e": 29301,
"s": 29293,
"text": "Python3"
},
{
"code": "# Creating a set using stringtest_set = set(\"geEks\") # Iterating using list-comprehensioncom = list(val for val in test_set)print(*com)",
"e": 29437,
"s": 29301,
"text": null
},
{
"code": null,
"e": 29447,
"s": 29437,
"text": "Output: "
},
{
"code": null,
"e": 29457,
"s": 29447,
"text": "k s e g E"
},
{
"code": null,
"e": 29469,
"s": 29457,
"text": "Analysis: "
},
{
"code": null,
"e": 29477,
"s": 29469,
"text": "Python3"
},
{
"code": "# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): list(val for val in test_set) # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))",
"e": 30008,
"s": 29477,
"text": null
},
{
"code": null,
"e": 30018,
"s": 30008,
"text": "Output: "
},
{
"code": null,
"e": 30116,
"s": 30018,
"text": "0.1662169310002355\n0.1783527520019561\n0.21661155100082397\n0.19131610199838178\n0.19931397800246486"
},
{
"code": null,
"e": 30173,
"s": 30116,
"text": " Method #5: Iterating over a set using comprehension. "
},
{
"code": null,
"e": 30181,
"s": 30173,
"text": "Python3"
},
{
"code": "# Creating a set using stringtest_set = set(\"geEks\") # Iterating using list-comprehensioncom = [print(val) for val in test_set]",
"e": 30309,
"s": 30181,
"text": null
},
{
"code": null,
"e": 30317,
"s": 30309,
"text": "Output:"
},
{
"code": null,
"e": 30327,
"s": 30317,
"text": "e\nE\ng\ns\nk"
},
{
"code": null,
"e": 30339,
"s": 30327,
"text": "Analysis: "
},
{
"code": null,
"e": 30347,
"s": 30339,
"text": "Python3"
},
{
"code": "# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): [val for val in test_set] # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))",
"e": 30874,
"s": 30347,
"text": null
},
{
"code": null,
"e": 30884,
"s": 30874,
"text": "Output: "
},
{
"code": null,
"e": 30981,
"s": 30884,
"text": "0.11386321299869451\n0.111869686999853\n0.1092844699996931\n0.11223735699968529\n0.10928539399901638"
},
{
"code": null,
"e": 31058,
"s": 30981,
"text": " Method #6: Iterating over a set using map, lambda and list comprehension "
},
{
"code": null,
"e": 31066,
"s": 31058,
"text": "Python3"
},
{
"code": "# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): [map(lambda val: val, test_set)] # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))",
"e": 31600,
"s": 31066,
"text": null
},
{
"code": null,
"e": 31610,
"s": 31600,
"text": "Output: "
},
{
"code": null,
"e": 31723,
"s": 31610,
"text": "1.0756000847322866e-05\n1.310199877480045e-05\n1.269100175704807e-05\n1.1588999768719077e-05\n1.2522999895736575e-05"
},
{
"code": null,
"e": 31775,
"s": 31723,
"text": " Method #7: Iterating over a set using iterator. "
},
{
"code": null,
"e": 31783,
"s": 31775,
"text": "Python3"
},
{
"code": "# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): for val in iter(test_set): _ = val # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))",
"e": 32326,
"s": 31783,
"text": null
},
{
"code": null,
"e": 32336,
"s": 32326,
"text": "Output: "
},
{
"code": null,
"e": 32434,
"s": 32336,
"text": "0.0676155920009478\n0.07111633900058223\n0.06994135700006154\n0.0732101009998587\n0.08668379899972933"
},
{
"code": null,
"e": 32499,
"s": 32434,
"text": " Method #8: Iterating over a set using iterator and while loop. "
},
{
"code": null,
"e": 32507,
"s": 32499,
"text": "Python3"
},
{
"code": "# Creating a set using stringtest_set = set(\"geEks\") iter_gen = iter(test_set) while True: try: # get the next item print(next(iter_gen)) ''' do something with element ''' except StopIteration: # if StopIteration is raised, # break from loop break",
"e": 32821,
"s": 32507,
"text": null
},
{
"code": null,
"e": 32830,
"s": 32821,
"text": "Output: "
},
{
"code": null,
"e": 32840,
"s": 32830,
"text": "E\ns\ne\nk\ng"
},
{
"code": null,
"e": 32852,
"s": 32840,
"text": "Analysis: "
},
{
"code": null,
"e": 32860,
"s": 32852,
"text": "Python3"
},
{
"code": "# importing librariesfrom timeit import default_timer as timerimport itertoolsimport random # Function under evaluationdef test_func(test_set): iter_gen = iter(test_set) while True: try: # get the next item next(iter_gen) # do something with element except StopIteration: # if StopIteration is raised, break from loop break # Driver functionif __name__ == '__main__': random.seed(21) for _ in range(5): test_set = set() # generating a set of random numbers for el in range(int(1e6)): el = random.random() test_set.add(el) start = timer() test_func(test_set) end = timer() print(str(end - start))",
"e": 33613,
"s": 32860,
"text": null
},
{
"code": null,
"e": 33623,
"s": 33613,
"text": "Output: "
},
{
"code": null,
"e": 33718,
"s": 33623,
"text": "0.2136418699992646\n0.1952157889973023\n0.4234208280031453\n0.255840524998348\n0.24712910099697183"
},
{
"code": null,
"e": 34426,
"s": 33718,
"text": "Conclusion: Among all the looping techniques, simple for loop iteration and looping over iterators works best, while comparing all the techniques, using map with lambda over set or iterator of set works best giving a performance of a million set iterations under 10 milliseconds. It is quite noticeable that above examples only have single access of set components per iteration, whereas if we increase the number of times a set component is accessed per iteration, it may change the time taken per iteration.Note: Values mentioned above in the example output are bound to vary. The reason behind the variation of time consumption is machine dependency of processing power of individual’s system processor. "
},
{
"code": null,
"e": 34435,
"s": 34426,
"text": "sooda367"
},
{
"code": null,
"e": 34442,
"s": 34435,
"text": "Picked"
},
{
"code": null,
"e": 34462,
"s": 34442,
"text": "Python set-programs"
},
{
"code": null,
"e": 34473,
"s": 34462,
"text": "python-set"
},
{
"code": null,
"e": 34480,
"s": 34473,
"text": "Python"
},
{
"code": null,
"e": 34491,
"s": 34480,
"text": "python-set"
},
{
"code": null,
"e": 34589,
"s": 34491,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34621,
"s": 34589,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 34643,
"s": 34621,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 34685,
"s": 34643,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 34711,
"s": 34685,
"text": "Python String | replace()"
},
{
"code": null,
"e": 34755,
"s": 34711,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 34784,
"s": 34755,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 34821,
"s": 34784,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 34863,
"s": 34821,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 34899,
"s": 34863,
"text": "Convert integer to string in Python"
}
] |
CSS - Links
|
This chapter teaches you how to set different properties of a hyper link using CSS. You can set following properties of a hyper link −
We will revisit the same properties when we will discuss Pseudo-Classes of CSS.
The :link signifies unvisited hyperlinks.
The :link signifies unvisited hyperlinks.
The :visited signifies visited hyperlinks.
The :visited signifies visited hyperlinks.
The :hover signifies an element that currently has the user's mouse pointer hovering over it.
The :hover signifies an element that currently has the user's mouse pointer hovering over it.
The :active signifies an element on which the user is currently clicking.
The :active signifies an element on which the user is currently clicking.
Usually, all these properties are kept in the header part of the HTML document.
Remember a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective. Also, a:active MUST come after a:hover in the CSS definition as follows −
<style type = "text/css">
a:link {color: #000000}
a:visited {color: #006600}
a:hover {color: #FFCC00}
a:active {color: #FF00CC}
</style>
Now, we will see how to use these properties to give different effects to hyperlinks.
The following example demonstrates how to set the link color. Possible values could be any color name in any valid format.
<html>
<head>
<style type = "text/css">
a:link {color:#000000}
</style>
</head>
<body>
<a href = "">Link</a>
</body>
</html>
It will produce the following black link −
The following example demonstrates how to set the color of visited links. Possible values could be any color name in any valid format.
<html>
<head>
<style type = "text/css">
a:visited {color: #006600}
</style>
</head>
<body>
<a href = ""> link</a>
</body>
</html>
It will produce the following link. Once you will click this link, it will change its color to green.
The following example demonstrates how to change the color of links when we bring a mouse pointer over that link. Possible values could be any color name in any valid format.
<html>
<head>
<style type = "text/css">
a:hover {color: #FFCC00}
</style>
</head>
<body>
<a href = "">Link</a>
</body>
</html>
It will produce the following link. Now, you bring your mouse over this link and you will see that it changes its color to yellow.
The following example demonstrates how to change the color of active links. Possible values could be any color name in any valid format.
<html>
<head>
<style type = "text/css">
a:active {color: #FF00CC}
</style>
</head>
<body>
<a href = "">Link</a>
</body>
</html>
It will produce the following link. It will change its color to pink when the user clicks it.
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2762,
"s": 2626,
"text": "This chapter teaches you how to set different properties of a hyper link using CSS. You can set following properties of a hyper link −"
},
{
"code": null,
"e": 2842,
"s": 2762,
"text": "We will revisit the same properties when we will discuss Pseudo-Classes of CSS."
},
{
"code": null,
"e": 2884,
"s": 2842,
"text": "The :link signifies unvisited hyperlinks."
},
{
"code": null,
"e": 2926,
"s": 2884,
"text": "The :link signifies unvisited hyperlinks."
},
{
"code": null,
"e": 2969,
"s": 2926,
"text": "The :visited signifies visited hyperlinks."
},
{
"code": null,
"e": 3012,
"s": 2969,
"text": "The :visited signifies visited hyperlinks."
},
{
"code": null,
"e": 3106,
"s": 3012,
"text": "The :hover signifies an element that currently has the user's mouse pointer hovering over it."
},
{
"code": null,
"e": 3200,
"s": 3106,
"text": "The :hover signifies an element that currently has the user's mouse pointer hovering over it."
},
{
"code": null,
"e": 3274,
"s": 3200,
"text": "The :active signifies an element on which the user is currently clicking."
},
{
"code": null,
"e": 3348,
"s": 3274,
"text": "The :active signifies an element on which the user is currently clicking."
},
{
"code": null,
"e": 3428,
"s": 3348,
"text": "Usually, all these properties are kept in the header part of the HTML document."
},
{
"code": null,
"e": 3604,
"s": 3428,
"text": "Remember a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective. Also, a:active MUST come after a:hover in the CSS definition as follows −"
},
{
"code": null,
"e": 3754,
"s": 3604,
"text": "<style type = \"text/css\">\n a:link {color: #000000}\n a:visited {color: #006600}\n a:hover {color: #FFCC00}\n a:active {color: #FF00CC}\n</style>\n"
},
{
"code": null,
"e": 3840,
"s": 3754,
"text": "Now, we will see how to use these properties to give different effects to hyperlinks."
},
{
"code": null,
"e": 3963,
"s": 3840,
"text": "The following example demonstrates how to set the link color. Possible values could be any color name in any valid format."
},
{
"code": null,
"e": 4128,
"s": 3963,
"text": "<html>\n <head>\n <style type = \"text/css\">\n a:link {color:#000000}\n </style>\n </head>\n\n <body>\n <a href = \"\">Link</a>\n </body>\n</html> "
},
{
"code": null,
"e": 4171,
"s": 4128,
"text": "It will produce the following black link −"
},
{
"code": null,
"e": 4306,
"s": 4171,
"text": "The following example demonstrates how to set the color of visited links. Possible values could be any color name in any valid format."
},
{
"code": null,
"e": 4478,
"s": 4306,
"text": "<html>\n <head>\n <style type = \"text/css\">\n a:visited {color: #006600}\n </style>\n </head>\n\n <body>\n <a href = \"\"> link</a> \n </body>\n</html> "
},
{
"code": null,
"e": 4580,
"s": 4478,
"text": "It will produce the following link. Once you will click this link, it will change its color to green."
},
{
"code": null,
"e": 4755,
"s": 4580,
"text": "The following example demonstrates how to change the color of links when we bring a mouse pointer over that link. Possible values could be any color name in any valid format."
},
{
"code": null,
"e": 4923,
"s": 4755,
"text": "<html>\n <head>\n <style type = \"text/css\">\n a:hover {color: #FFCC00}\n </style>\n </head>\n\n <body>\n <a href = \"\">Link</a>\n </body>\n</html> "
},
{
"code": null,
"e": 5054,
"s": 4923,
"text": "It will produce the following link. Now, you bring your mouse over this link and you will see that it changes its color to yellow."
},
{
"code": null,
"e": 5191,
"s": 5054,
"text": "The following example demonstrates how to change the color of active links. Possible values could be any color name in any valid format."
},
{
"code": null,
"e": 5360,
"s": 5191,
"text": "<html>\n <head>\n <style type = \"text/css\">\n a:active {color: #FF00CC}\n </style>\n </head>\n\n <body>\n <a href = \"\">Link</a>\n </body>\n</html> "
},
{
"code": null,
"e": 5454,
"s": 5360,
"text": "It will produce the following link. It will change its color to pink when the user clicks it."
},
{
"code": null,
"e": 5489,
"s": 5454,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5503,
"s": 5489,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5538,
"s": 5503,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5555,
"s": 5538,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5590,
"s": 5555,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5621,
"s": 5590,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5656,
"s": 5621,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5687,
"s": 5656,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5722,
"s": 5687,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5753,
"s": 5722,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5786,
"s": 5753,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5817,
"s": 5786,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5824,
"s": 5817,
"text": " Print"
},
{
"code": null,
"e": 5835,
"s": 5824,
"text": " Add Notes"
}
] |
What are Getters/Setters methods for Python Class?
|
Getters and setters are used in many object oriented programming languages to ensure the principle of data encapsulation. They are known as mutator methods as well. Data encapsulation is seen as the bundling of data with the methods that operate on these data. These methods are of course the getter for retrieving the data and the setter for changing the data. According to this principle, the attributes of a class are made private to hide and protect them from other code.
Unfortunately, it is widespread belief that a proper Python class should encapsulate private attributes by using getters and setters. Using getters and setters is not easy and elegant. The pythonic way to do this is to use properties or a class with property . A method which is used for getting a value is decorated with "@property". The method which has to function as the setter is decorated with "@x.setter".
An example of using getters and setters is as follows
class P:
def __init__(self,x):
self.__set_x(x)
def __get_x(self):
return self.__x
def __set_x(self, x):
if x < 0:
self.__x = 0
elif x > 1000:
self.__x = 1000
else:
self.__x = x
x = property(__get_x, __set_x)
|
[
{
"code": null,
"e": 1538,
"s": 1062,
"text": "Getters and setters are used in many object oriented programming languages to ensure the principle of data encapsulation. They are known as mutator methods as well. Data encapsulation is seen as the bundling of data with the methods that operate on these data. These methods are of course the getter for retrieving the data and the setter for changing the data. According to this principle, the attributes of a class are made private to hide and protect them from other code."
},
{
"code": null,
"e": 1952,
"s": 1538,
"text": "Unfortunately, it is widespread belief that a proper Python class should encapsulate private attributes by using getters and setters. Using getters and setters is not easy and elegant. The pythonic way to do this is to use properties or a class with property . A method which is used for getting a value is decorated with \"@property\". The method which has to function as the setter is decorated with \"@x.setter\". "
},
{
"code": null,
"e": 2006,
"s": 1952,
"text": "An example of using getters and setters is as follows"
},
{
"code": null,
"e": 2362,
"s": 2006,
"text": "class P:\n def __init__(self,x): \n self.__set_x(x)\n def __get_x(self): \n return self.__x\n def __set_x(self, x): \n if x < 0: \n self.__x = 0 \n elif x > 1000: \n self.__x = 1000 \n else: \n self.__x = x\n x = property(__get_x, __set_x)"
}
] |
Java 8 how to remove duplicates from list - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorials, I am going to show you how to remove duplicate elements from the list using Java 8 syntax.
Here I am creating a Department class, it holds department details.
Department.java
public class Department {
private int deptId;
private String deptName;
public Department(int deptId, String deptName) {
super();
this.deptId = deptId;
this.deptName = deptName;
}
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
}
We can remove the duplicate elements from a list in following 2 different ways.
Preparing a list containing duplicate Department objects, and remove those duplicate departments using Java8 stream.
Here to remove the duplicate elements, by assigning a list to TreeSet. As TreeSet doesn’t allow the duplicate elements, it removes.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class RemoveDuplicates {
public static void main(String[] args) {
List deptList = new ArrayList();
deptList.add(new Department(1, "IT"));
deptList.add(new Department(2, "HR"));
deptList.add(new Department(1, "IT"));
deptList.add(new Department(4, "Development"));
deptList.add(new Department(2, "HR"));
// Removing the Elements by assigning list to TreeSet
Set deptSet = deptList.stream()
.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Department::getDeptName))));
deptSet.forEach(dept -> System.out.println("DeptId (" + dept.getDeptId() + ") Name :" + dept.getDeptName()));
}
}
Output :
DeptId (4) Name :Development
DeptId (2) Name :HR
DeptId (1) Name :IT
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RemoveDuplicates {
public static void main(String[] args) {
List deptList = new ArrayList();
deptList.add(new Department(1, "IT"));
deptList.add(new Department(2, "HR"));
deptList.add(new Department(1, "IT"));
deptList.add(new Department(4, "Development"));
deptList.add(new Department(2, "HR"));
Set deptSet = new HashSet<>();
// directly removing the elements from list if already existed in set
deptList.removeIf(p -> !deptSet.add(p.getDeptName()));
deptList.forEach(dept->System.out.println(dept.getDeptId() +" : "+dept.getDeptName()));
}
}
Output :
1 : IT
2 : HR
4 : Development
Happy Learning 🙂
Resolve NullPointerException in Collectors.toMap
Spring Collection Dependency List Example
How to Merge Streams in Java 8
How to Filter null values from Java8 Stream
@Qualifier annotation example in Spring
How to Rotate Elements in List
How to calculate Employees Salaries Java 8 summingInt
How to get Stream count in Java 8
Difference between HashSet vs TreeSet in Java
Spring Collection Map Dependency Example
TreeSet with Customizable Sorting in Java
Java how to convert ArrayList to Array Example
Python – How to remove duplicate elements from List
Java 8 How to convert Stream to List
How to convert List to Map in Java 8
Resolve NullPointerException in Collectors.toMap
Spring Collection Dependency List Example
How to Merge Streams in Java 8
How to Filter null values from Java8 Stream
@Qualifier annotation example in Spring
How to Rotate Elements in List
How to calculate Employees Salaries Java 8 summingInt
How to get Stream count in Java 8
Difference between HashSet vs TreeSet in Java
Spring Collection Map Dependency Example
TreeSet with Customizable Sorting in Java
Java how to convert ArrayList to Array Example
Python – How to remove duplicate elements from List
Java 8 How to convert Stream to List
How to convert List to Map in Java 8
Δ
Java8 – Install Windows
Java8 – foreach
Java8 – forEach with index
Java8 – Stream Filter Objects
Java8 – Comparator Userdefined
Java8 – GroupingBy
Java8 – SummingInt
Java8 – walk ReadFiles
Java8 – JAVA_HOME on Windows
Howto – Install Java on Mac OS
Howto – Convert Iterable to Stream
Howto – Get common elements from two Lists
Howto – Convert List to String
Howto – Concatenate Arrays using Stream
Howto – Remove duplicates from List
Howto – Filter null values from Stream
Howto – Convert List to Map
Howto – Convert Stream to List
Howto – Sort a Map
Howto – Filter a Map
Howto – Get Current UTC Time
Howto – Verify an Array contains a specific value
Howto – Convert ArrayList to Array
Howto – Read File Line By Line
Howto – Convert Date to LocalDate
Howto – Merge Streams
Howto – Resolve NullPointerException in toMap
Howto -Get Stream count
Howto – Get Min and Max values in a Stream
Howto – Convert InputStream to String
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 508,
"s": 398,
"text": "In this tutorials, I am going to show you how to remove duplicate elements from the list using Java 8 syntax."
},
{
"code": null,
"e": 576,
"s": 508,
"text": "Here I am creating a Department class, it holds department details."
},
{
"code": null,
"e": 592,
"s": 576,
"text": "Department.java"
},
{
"code": null,
"e": 1105,
"s": 592,
"text": "public class Department {\n private int deptId;\n private String deptName;\n\n public Department(int deptId, String deptName) {\n super();\n this.deptId = deptId;\n this.deptName = deptName;\n }\n\n public int getDeptId() {\n return deptId;\n }\n\n public void setDeptId(int deptId) {\n this.deptId = deptId;\n }\n\n public String getDeptName() {\n return deptName;\n }\n\n public void setDeptName(String deptName) {\n this.deptName = deptName;\n }\n\n}"
},
{
"code": null,
"e": 1185,
"s": 1105,
"text": "We can remove the duplicate elements from a list in following 2 different ways."
},
{
"code": null,
"e": 1302,
"s": 1185,
"text": "Preparing a list containing duplicate Department objects, and remove those duplicate departments using Java8 stream."
},
{
"code": null,
"e": 1434,
"s": 1302,
"text": "Here to remove the duplicate elements, by assigning a list to TreeSet. As TreeSet doesn’t allow the duplicate elements, it removes."
},
{
"code": null,
"e": 2310,
"s": 1434,
"text": "import java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.TreeSet;\nimport java.util.stream.Collectors;\n\npublic class RemoveDuplicates {\n public static void main(String[] args) {\n List deptList = new ArrayList();\n deptList.add(new Department(1, \"IT\"));\n deptList.add(new Department(2, \"HR\"));\n deptList.add(new Department(1, \"IT\"));\n deptList.add(new Department(4, \"Development\"));\n deptList.add(new Department(2, \"HR\"));\n\n // Removing the Elements by assigning list to TreeSet\n Set deptSet = deptList.stream()\n .collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Department::getDeptName))));\n deptSet.forEach(dept -> System.out.println(\"DeptId (\" + dept.getDeptId() + \") Name :\" + dept.getDeptName()));\n\n }\n}"
},
{
"code": null,
"e": 2319,
"s": 2310,
"text": "Output :"
},
{
"code": null,
"e": 2388,
"s": 2319,
"text": "DeptId (4) Name :Development\nDeptId (2) Name :HR\nDeptId (1) Name :IT"
},
{
"code": null,
"e": 3138,
"s": 2388,
"text": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class RemoveDuplicates {\n public static void main(String[] args) {\n List deptList = new ArrayList();\n deptList.add(new Department(1, \"IT\"));\n deptList.add(new Department(2, \"HR\"));\n deptList.add(new Department(1, \"IT\"));\n deptList.add(new Department(4, \"Development\"));\n deptList.add(new Department(2, \"HR\"));\n\n Set deptSet = new HashSet<>();\n\n // directly removing the elements from list if already existed in set\n deptList.removeIf(p -> !deptSet.add(p.getDeptName()));\n\n deptList.forEach(dept->System.out.println(dept.getDeptId() +\" : \"+dept.getDeptName()));\n\n }\n}"
},
{
"code": null,
"e": 3147,
"s": 3138,
"text": "Output :"
},
{
"code": null,
"e": 3177,
"s": 3147,
"text": "1 : IT\n2 : HR\n4 : Development"
},
{
"code": null,
"e": 3194,
"s": 3177,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 3823,
"s": 3194,
"text": "\nResolve NullPointerException in Collectors.toMap\nSpring Collection Dependency List Example\nHow to Merge Streams in Java 8\nHow to Filter null values from Java8 Stream\n@Qualifier annotation example in Spring\nHow to Rotate Elements in List\nHow to calculate Employees Salaries Java 8 summingInt\nHow to get Stream count in Java 8\nDifference between HashSet vs TreeSet in Java\nSpring Collection Map Dependency Example\nTreeSet with Customizable Sorting in Java\nJava how to convert ArrayList to Array Example\nPython – How to remove duplicate elements from List\nJava 8 How to convert Stream to List\nHow to convert List to Map in Java 8\n"
},
{
"code": null,
"e": 3872,
"s": 3823,
"text": "Resolve NullPointerException in Collectors.toMap"
},
{
"code": null,
"e": 3914,
"s": 3872,
"text": "Spring Collection Dependency List Example"
},
{
"code": null,
"e": 3945,
"s": 3914,
"text": "How to Merge Streams in Java 8"
},
{
"code": null,
"e": 3989,
"s": 3945,
"text": "How to Filter null values from Java8 Stream"
},
{
"code": null,
"e": 4029,
"s": 3989,
"text": "@Qualifier annotation example in Spring"
},
{
"code": null,
"e": 4060,
"s": 4029,
"text": "How to Rotate Elements in List"
},
{
"code": null,
"e": 4114,
"s": 4060,
"text": "How to calculate Employees Salaries Java 8 summingInt"
},
{
"code": null,
"e": 4148,
"s": 4114,
"text": "How to get Stream count in Java 8"
},
{
"code": null,
"e": 4194,
"s": 4148,
"text": "Difference between HashSet vs TreeSet in Java"
},
{
"code": null,
"e": 4235,
"s": 4194,
"text": "Spring Collection Map Dependency Example"
},
{
"code": null,
"e": 4277,
"s": 4235,
"text": "TreeSet with Customizable Sorting in Java"
},
{
"code": null,
"e": 4324,
"s": 4277,
"text": "Java how to convert ArrayList to Array Example"
},
{
"code": null,
"e": 4376,
"s": 4324,
"text": "Python – How to remove duplicate elements from List"
},
{
"code": null,
"e": 4413,
"s": 4376,
"text": "Java 8 How to convert Stream to List"
},
{
"code": null,
"e": 4450,
"s": 4413,
"text": "How to convert List to Map in Java 8"
},
{
"code": null,
"e": 4456,
"s": 4454,
"text": "Δ"
},
{
"code": null,
"e": 4481,
"s": 4456,
"text": " Java8 – Install Windows"
},
{
"code": null,
"e": 4498,
"s": 4481,
"text": " Java8 – foreach"
},
{
"code": null,
"e": 4526,
"s": 4498,
"text": " Java8 – forEach with index"
},
{
"code": null,
"e": 4557,
"s": 4526,
"text": " Java8 – Stream Filter Objects"
},
{
"code": null,
"e": 4589,
"s": 4557,
"text": " Java8 – Comparator Userdefined"
},
{
"code": null,
"e": 4609,
"s": 4589,
"text": " Java8 – GroupingBy"
},
{
"code": null,
"e": 4629,
"s": 4609,
"text": " Java8 – SummingInt"
},
{
"code": null,
"e": 4653,
"s": 4629,
"text": " Java8 – walk ReadFiles"
},
{
"code": null,
"e": 4683,
"s": 4653,
"text": " Java8 – JAVA_HOME on Windows"
},
{
"code": null,
"e": 4715,
"s": 4683,
"text": " Howto – Install Java on Mac OS"
},
{
"code": null,
"e": 4751,
"s": 4715,
"text": " Howto – Convert Iterable to Stream"
},
{
"code": null,
"e": 4795,
"s": 4751,
"text": " Howto – Get common elements from two Lists"
},
{
"code": null,
"e": 4827,
"s": 4795,
"text": " Howto – Convert List to String"
},
{
"code": null,
"e": 4868,
"s": 4827,
"text": " Howto – Concatenate Arrays using Stream"
},
{
"code": null,
"e": 4905,
"s": 4868,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 4945,
"s": 4905,
"text": " Howto – Filter null values from Stream"
},
{
"code": null,
"e": 4974,
"s": 4945,
"text": " Howto – Convert List to Map"
},
{
"code": null,
"e": 5006,
"s": 4974,
"text": " Howto – Convert Stream to List"
},
{
"code": null,
"e": 5026,
"s": 5006,
"text": " Howto – Sort a Map"
},
{
"code": null,
"e": 5048,
"s": 5026,
"text": " Howto – Filter a Map"
},
{
"code": null,
"e": 5078,
"s": 5048,
"text": " Howto – Get Current UTC Time"
},
{
"code": null,
"e": 5129,
"s": 5078,
"text": " Howto – Verify an Array contains a specific value"
},
{
"code": null,
"e": 5165,
"s": 5129,
"text": " Howto – Convert ArrayList to Array"
},
{
"code": null,
"e": 5197,
"s": 5165,
"text": " Howto – Read File Line By Line"
},
{
"code": null,
"e": 5232,
"s": 5197,
"text": " Howto – Convert Date to LocalDate"
},
{
"code": null,
"e": 5255,
"s": 5232,
"text": " Howto – Merge Streams"
},
{
"code": null,
"e": 5302,
"s": 5255,
"text": " Howto – Resolve NullPointerException in toMap"
},
{
"code": null,
"e": 5327,
"s": 5302,
"text": " Howto -Get Stream count"
},
{
"code": null,
"e": 5371,
"s": 5327,
"text": " Howto – Get Min and Max values in a Stream"
}
] |
How to replace the entire HTML node using JavaScript ? - GeeksforGeeks
|
23 Jan, 2020
Given an HTML document and the job is to replace the entire HTML element by a new one with the help of JavaScript. A few approaches are discussed here.
Approach 1:
Take the new document as a form of string(eg.. Str = ‘< html > < /html > ‘).
Use .replace() method on HTML element and replace it with the new HTML Document(eg.. $(‘html’).html(Str)).
Example 1: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Replace the entire HTML node using JavaScript. </title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick="GFG_Fun();"> click here </button> <p id="GFG_DOWN" style="color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button to replace the entire HTML element."; function GFG_Fun() { var Str = '<!DOCTYPE HTML><html><head><title>Check if an element is a'+' div in JavaScript.</title></head><body style = "text-align:center;">'+'<h2 style = "color:green;">GeeksForGeeks</h2><p>This is replaced element.'+ '</p></body> </html>'; $('html').html(Str); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Take the new document as a form of string(eg.. Str = ”).
Use .open() method on document and this method takes 2 parameters(first is “text/html” and second is “replace”). If we don’t use ‘Replace’ then method will call adds page history. So we would have to click back two times to go to the previous page. So, replace is necessary argument to pass.
To this new document use .write() method and pass the new document.
Use .close() method on document for it to work.
Example 2: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Replace the entire HTML node using JavaScript. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick="GFG_Fun();"> click here </button> <p id="GFG_DOWN" style="color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button to replace the entire HTML element."; function GFG_Fun() { var Str = '<!DOCTYPE HTML><html><head><title>Check if an element is a div'+ ' in JavaScript.</title></head><body style = "text-align:center;">'+ '<h2 style = "color:green;">GeeksForGeeks</h2><p>'+ 'This is replaced element.</p></body> </html>'; var newHTML = document.open("text/html", "replace"); newHTML.write(Str); newHTML.close(); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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": 25923,
"s": 25895,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 26075,
"s": 25923,
"text": "Given an HTML document and the job is to replace the entire HTML element by a new one with the help of JavaScript. A few approaches are discussed here."
},
{
"code": null,
"e": 26087,
"s": 26075,
"text": "Approach 1:"
},
{
"code": null,
"e": 26164,
"s": 26087,
"text": "Take the new document as a form of string(eg.. Str = ‘< html > < /html > ‘)."
},
{
"code": null,
"e": 26271,
"s": 26164,
"text": "Use .replace() method on HTML element and replace it with the new HTML Document(eg.. $(‘html’).html(Str))."
},
{
"code": null,
"e": 26326,
"s": 26271,
"text": "Example 1: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Replace the entire HTML node using JavaScript. </title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"GFG_Fun();\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button to replace the entire HTML element.\"; function GFG_Fun() { var Str = '<!DOCTYPE HTML><html><head><title>Check if an element is a'+' div in JavaScript.</title></head><body style = \"text-align:center;\">'+'<h2 style = \"color:green;\">GeeksForGeeks</h2><p>This is replaced element.'+ '</p></body> </html>'; $('html').html(Str); } </script></body> </html>",
"e": 27534,
"s": 26326,
"text": null
},
{
"code": null,
"e": 27542,
"s": 27534,
"text": "Output:"
},
{
"code": null,
"e": 27573,
"s": 27542,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 27603,
"s": 27573,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 27615,
"s": 27603,
"text": "Approach 2:"
},
{
"code": null,
"e": 27672,
"s": 27615,
"text": "Take the new document as a form of string(eg.. Str = ”)."
},
{
"code": null,
"e": 27964,
"s": 27672,
"text": "Use .open() method on document and this method takes 2 parameters(first is “text/html” and second is “replace”). If we don’t use ‘Replace’ then method will call adds page history. So we would have to click back two times to go to the previous page. So, replace is necessary argument to pass."
},
{
"code": null,
"e": 28032,
"s": 27964,
"text": "To this new document use .write() method and pass the new document."
},
{
"code": null,
"e": 28080,
"s": 28032,
"text": "Use .close() method on document for it to work."
},
{
"code": null,
"e": 28135,
"s": 28080,
"text": "Example 2: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Replace the entire HTML node using JavaScript. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"GFG_Fun();\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button to replace the entire HTML element.\"; function GFG_Fun() { var Str = '<!DOCTYPE HTML><html><head><title>Check if an element is a div'+ ' in JavaScript.</title></head><body style = \"text-align:center;\">'+ '<h2 style = \"color:green;\">GeeksForGeeks</h2><p>'+ 'This is replaced element.</p></body> </html>'; var newHTML = document.open(\"text/html\", \"replace\"); newHTML.write(Str); newHTML.close(); } </script></body> </html>",
"e": 29479,
"s": 28135,
"text": null
},
{
"code": null,
"e": 29487,
"s": 29479,
"text": "Output:"
},
{
"code": null,
"e": 29518,
"s": 29487,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 29548,
"s": 29518,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 29564,
"s": 29548,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29575,
"s": 29564,
"text": "JavaScript"
},
{
"code": null,
"e": 29592,
"s": 29575,
"text": "Web Technologies"
},
{
"code": null,
"e": 29619,
"s": 29592,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29717,
"s": 29619,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29757,
"s": 29717,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29802,
"s": 29757,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29863,
"s": 29802,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29935,
"s": 29863,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29987,
"s": 29935,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 30027,
"s": 29987,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30060,
"s": 30027,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30105,
"s": 30060,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30148,
"s": 30105,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python - Fill gaps in consecutive Records - GeeksforGeeks
|
02 Jun, 2020
Sometimes, while working with Python records, we can have a problem in which we have consecutive records, but a few missing and needs to be filled with any constant K. This kind of problem can have application in domains such as web development. Let’s discuss certain ways in which we need to perform this task.
Input :test_list = [(1, 4), (9, 11)]K = NoneOutput : [(1, 4), (2, None), (3, None), (4, None), (5, None), (6, None), (7, None), (8, None), (9, 11)]
Input :test_list = [(1, 4), (2, 11)]K = NoneOutput : [(1, 4), (2, 11)]
Method #1 : Using loopThis is one way in which this problem can be solved. In this, we check at each iteration if the element exists, if no, then it is filled with required value, if yes, the original value is retained.
# Python3 code to demonstrate working of # Fill gaps in consecutive Records# Using loop # initializing listtest_list = [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)] # printing original listprint("The original list is : " + str(test_list)) # initializing K valueK = "New" # Fill gaps in consecutive Records# Using loopres = []cnt = 0for i, j in test_list: if i - cnt > 1: for k in range(cnt + 1, i): res.append((k, K)) res.append((i, j)) cnt = i # printing result print("The list after filling gaps : " + str(res))
The original list is : [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)]The list after filling gaps : [(1, 4), (2, ‘New’), (3, 5), (4, 6), (5, ‘New’), (6, ‘New’), (7, 8), (8, ‘New’), (9, 11)]
Method #2 : Using min() + max() + dict() + list comprehensionThis is yet another way in which this problem can be solved. In this, we check the range using min() and max() and use dictionary as a container of getting values that is required to fill in.
# Python3 code to demonstrate working of # Fill gaps in consecutive Records# Using min() + max() + dict() + list comprehension # initializing listtest_list = [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)] # printing original listprint("The original list is : " + str(test_list)) # initializing K valueK = "New" # Fill gaps in consecutive Records# Using min() + max() + dict() + list comprehensiontest_list = dict(test_list)mini, maxi = min(test_list), max(test_list)res = [(idx, test_list.get(idx)) for idx in range(mini, maxi + 1)] # printing result print("The list after filling gaps : " + str(res))
The original list is : [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)]The list after filling gaps : [(1, 4), (2, ‘New’), (3, 5), (4, 6), (5, ‘New’), (6, ‘New’), (7, 8), (8, ‘New’), (9, 11)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 25741,
"s": 25713,
"text": "\n02 Jun, 2020"
},
{
"code": null,
"e": 26053,
"s": 25741,
"text": "Sometimes, while working with Python records, we can have a problem in which we have consecutive records, but a few missing and needs to be filled with any constant K. This kind of problem can have application in domains such as web development. Let’s discuss certain ways in which we need to perform this task."
},
{
"code": null,
"e": 26201,
"s": 26053,
"text": "Input :test_list = [(1, 4), (9, 11)]K = NoneOutput : [(1, 4), (2, None), (3, None), (4, None), (5, None), (6, None), (7, None), (8, None), (9, 11)]"
},
{
"code": null,
"e": 26272,
"s": 26201,
"text": "Input :test_list = [(1, 4), (2, 11)]K = NoneOutput : [(1, 4), (2, 11)]"
},
{
"code": null,
"e": 26492,
"s": 26272,
"text": "Method #1 : Using loopThis is one way in which this problem can be solved. In this, we check at each iteration if the element exists, if no, then it is filled with required value, if yes, the original value is retained."
},
{
"code": "# Python3 code to demonstrate working of # Fill gaps in consecutive Records# Using loop # initializing listtest_list = [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing K valueK = \"New\" # Fill gaps in consecutive Records# Using loopres = []cnt = 0for i, j in test_list: if i - cnt > 1: for k in range(cnt + 1, i): res.append((k, K)) res.append((i, j)) cnt = i # printing result print(\"The list after filling gaps : \" + str(res)) ",
"e": 27035,
"s": 26492,
"text": null
},
{
"code": null,
"e": 27219,
"s": 27035,
"text": "The original list is : [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)]The list after filling gaps : [(1, 4), (2, ‘New’), (3, 5), (4, 6), (5, ‘New’), (6, ‘New’), (7, 8), (8, ‘New’), (9, 11)]"
},
{
"code": null,
"e": 27474,
"s": 27221,
"text": "Method #2 : Using min() + max() + dict() + list comprehensionThis is yet another way in which this problem can be solved. In this, we check the range using min() and max() and use dictionary as a container of getting values that is required to fill in."
},
{
"code": "# Python3 code to demonstrate working of # Fill gaps in consecutive Records# Using min() + max() + dict() + list comprehension # initializing listtest_list = [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing K valueK = \"New\" # Fill gaps in consecutive Records# Using min() + max() + dict() + list comprehensiontest_list = dict(test_list)mini, maxi = min(test_list), max(test_list)res = [(idx, test_list.get(idx)) for idx in range(mini, maxi + 1)] # printing result print(\"The list after filling gaps : \" + str(res)) ",
"e": 28077,
"s": 27474,
"text": null
},
{
"code": null,
"e": 28261,
"s": 28077,
"text": "The original list is : [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)]The list after filling gaps : [(1, 4), (2, ‘New’), (3, 5), (4, 6), (5, ‘New’), (6, ‘New’), (7, 8), (8, ‘New’), (9, 11)]"
},
{
"code": null,
"e": 28282,
"s": 28261,
"text": "Python list-programs"
},
{
"code": null,
"e": 28289,
"s": 28282,
"text": "Python"
},
{
"code": null,
"e": 28305,
"s": 28289,
"text": "Python Programs"
},
{
"code": null,
"e": 28403,
"s": 28305,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28421,
"s": 28403,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28456,
"s": 28421,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28488,
"s": 28456,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28530,
"s": 28488,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28556,
"s": 28530,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28599,
"s": 28556,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28621,
"s": 28599,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28660,
"s": 28621,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28706,
"s": 28660,
"text": "Python | Split string into list of characters"
}
] |
How to Train an Image Classifier in PyTorch and use it to Perform Basic Inference on Single Images | by Chris Fotache | Towards Data Science
|
If you’re just getting started with PyTorch and want to learn how to do some basic image classification, you can follow this tutorial. It will go through how to organize your training data, use a pretrained neural network to train your model, and then predict other images.
For this purpose, I’ll be using a dataset consisting of map tiles from Google Maps, and classifying them according to the land features they contain. I’ll write another story about how I use it (in brief: in order to identify safe areas for a drone to fly over or to land). But for now, I just want to use some training data in order to classify these map tiles.
The code snippets below are from a Jupyter Notebook. You can stitch them together to build your own Python script, or download the notebooks from GitHub. The notebooks are originally based on the PyTorch course from Udacity. And if you use a cloud VM for your deep learning development and don’t know how to open a notebook remotely, check out my tutorial.
Organize your training dataset
PyTorch expects the data to be organized by folders with one folder for each class. Most of the other PyTorch tutorials and examples expect you to further organize it with a training and validation folder at the top, and then the class folders inside them. But I think this is very cumbersome, to have to pick a certain number of images from each class and move them from the training to the validation folder. And since most people would do that by selecting a contiguous group of files, there might be a lot of bias in that selection.
So here’s a better way of splitting the dataset into a training and test set on the fly, like Python developers are used to from SKLearn. But first, let’s import the modules:
%matplotlib inline%config InlineBackend.figure_format = 'retina'import matplotlib.pyplot as pltimport numpy as npimport torchfrom torch import nnfrom torch import optimimport torch.nn.functional as Ffrom torchvision import datasets, transforms, models
Next we’ll define the train / validation dataset loader, using the SubsetRandomSampler for the split:
data_dir = '/data/train'def load_split_train_test(datadir, valid_size = .2): train_transforms = transforms.Compose([transforms.Resize(224), transforms.ToTensor(), ]) test_transforms = transforms.Compose([transforms.Resize(224), transforms.ToTensor(), ]) train_data = datasets.ImageFolder(datadir, transform=train_transforms) test_data = datasets.ImageFolder(datadir, transform=test_transforms) num_train = len(train_data) indices = list(range(num_train)) split = int(np.floor(valid_size * num_train)) np.random.shuffle(indices) from torch.utils.data.sampler import SubsetRandomSampler train_idx, test_idx = indices[split:], indices[:split] train_sampler = SubsetRandomSampler(train_idx) test_sampler = SubsetRandomSampler(test_idx) trainloader = torch.utils.data.DataLoader(train_data, sampler=train_sampler, batch_size=64) testloader = torch.utils.data.DataLoader(test_data, sampler=test_sampler, batch_size=64) return trainloader, testloadertrainloader, testloader = load_split_train_test(data_dir, .2)print(trainloader.dataset.classes)
Next we’ll determine whether we have GPU or not. I assume that if you’re doing this you have a GPU-powered machine, otherwise the code will be at least 10 times slower. But it’s a good idea to generalize and check for the GPU availability.
We’ll also load a pretrained model. For this case, I chose ResNet 50:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model = models.resnet50(pretrained=True)print(model)
Printing the model will show you the layer architecture of the ResNet model. It’s probably beyond mine or your comprehension but it’s still interesting to see what’s inside those deep hidden layers.
It’s up to you what model you choose, and it might be a different one based on your particular dataset. Here is a list of all the PyTorch models.
Now we’re getting into the interesting part of the deep neural network. First, we have to freeze the pre-trained layers, so we don’t backprop through them during training. Then, we re-define the final fully-connected the layer, the one that we’ll train with our images. We also create the criterion (the loss function) and pick an optimizer (Adam in this case) and learning rate.
for param in model.parameters(): param.requires_grad = False model.fc = nn.Sequential(nn.Linear(2048, 512), nn.ReLU(), nn.Dropout(0.2), nn.Linear(512, 10), nn.LogSoftmax(dim=1))criterion = nn.NLLLoss()optimizer = optim.Adam(model.fc.parameters(), lr=0.003)model.to(device)
And now finally, let’s train our model! There’s just one epoch in this example but in most cases you’ll need more. The basic process is quite intuitive from the code: You load the batches of images and do the feed forward loop. Then calculate the loss function, and use the optimizer to apply gradient descent in back-propagation.
It’s that simple with PyTorch. Most of the code below deals with displaying the losses and calculate accuracy every 10 batches, so you get an update while training is running. During validation, don’t forget to set the model to eval() mode, and then back to train() once you’re finished.
epochs = 1steps = 0running_loss = 0print_every = 10train_losses, test_losses = [], []for epoch in range(epochs): for inputs, labels in trainloader: steps += 1 inputs, labels = inputs.to(device), labels.to(device) optimizer.zero_grad() logps = model.forward(inputs) loss = criterion(logps, labels) loss.backward() optimizer.step() running_loss += loss.item() if steps % print_every == 0: test_loss = 0 accuracy = 0 model.eval() with torch.no_grad(): for inputs, labels in testloader: inputs, labels = inputs.to(device), labels.to(device) logps = model.forward(inputs) batch_loss = criterion(logps, labels) test_loss += batch_loss.item() ps = torch.exp(logps) top_p, top_class = ps.topk(1, dim=1) equals = top_class == labels.view(*top_class.shape) accuracy += torch.mean(equals.type(torch.FloatTensor)).item() train_losses.append(running_loss/len(trainloader)) test_losses.append(test_loss/len(testloader)) print(f"Epoch {epoch+1}/{epochs}.. " f"Train loss: {running_loss/print_every:.3f}.. " f"Test loss: {test_loss/len(testloader):.3f}.. " f"Test accuracy: {accuracy/len(testloader):.3f}") running_loss = 0 model.train()torch.save(model, 'aerialmodel.pth')
And... after you wait a few minutes (or more, depending on the size of your dataset and the number of epochs), training is done and the model is saved for later predictions!
There is one more thing you can do now, which is to plot the training and validation losses:
plt.plot(train_losses, label='Training loss')plt.plot(test_losses, label='Validation loss')plt.legend(frameon=False)plt.show()
As you can see, in my particular example with one epoch, the validation loss (which is what we’re interested in) flatlines towards the end of the first epoch and even starts an upward trend, so probably 1 epoch is enough. The training loss, as expected, is very low.
Now on to the second part. So you trained your model, saved it, and need to use it in an application. For that, you’ll need to be able to perform simple inference on an image. You can find this demo notebook as well in our repository. We import the same modules as in the training notebook and then define again the transforms. I only declare the image folder again so I can use some examples from there:
data_dir = '/datadrive/FastAI/data/aerial_photos/train'test_transforms = transforms.Compose([transforms.Resize(224), transforms.ToTensor(), ])
Then again we check for GPU availability, load the model and put it into evaluation mode (so parameters are not altered):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model=torch.load('aerialmodel.pth')model.eval()
The function that predicts the class of a specific image is very simple. Note that it requires a Pillow image, not a file path.
def predict_image(image): image_tensor = test_transforms(image).float() image_tensor = image_tensor.unsqueeze_(0) input = Variable(image_tensor) input = input.to(device) output = model(input) index = output.data.cpu().numpy().argmax() return index
Now for easier testing, I also created a function that will pick a number of random images from the dataset folders:
def get_random_images(num): data = datasets.ImageFolder(data_dir, transform=test_transforms) classes = data.classes indices = list(range(len(data))) np.random.shuffle(indices) idx = indices[:num] from torch.utils.data.sampler import SubsetRandomSampler sampler = SubsetRandomSampler(idx) loader = torch.utils.data.DataLoader(data, sampler=sampler, batch_size=num) dataiter = iter(loader) images, labels = dataiter.next() return images, labels
Finally, to demo the prediction function, I get the random image sample, predict them and display the results:
to_pil = transforms.ToPILImage()images, labels = get_random_images(5)fig=plt.figure(figsize=(10,10))for ii in range(len(images)): image = to_pil(images[ii]) index = predict_image(image) sub = fig.add_subplot(1, len(images), ii+1) res = int(labels[ii]) == index sub.set_title(str(classes[index]) + ":" + str(res)) plt.axis('off') plt.imshow(image)plt.show()
Here’s one example of such predictions on Google Map tiles. The label is the predicted class, and I’m also displaying whether it was a correct prediction or not.
And this is pretty much it. Go ahead and try it on your datasets. As long as you organize your images properly, this code should work as is. Soon I’ll have more stories about other cool stuff you can do with neural networks and PyTorch.
Chris Fotache is an AI researcher with CYNET.ai based in New Jersey. He covers topics related to artificial intelligence in our life, Python programming, machine learning, computer vision, natural language processing and more.
|
[
{
"code": null,
"e": 446,
"s": 172,
"text": "If you’re just getting started with PyTorch and want to learn how to do some basic image classification, you can follow this tutorial. It will go through how to organize your training data, use a pretrained neural network to train your model, and then predict other images."
},
{
"code": null,
"e": 809,
"s": 446,
"text": "For this purpose, I’ll be using a dataset consisting of map tiles from Google Maps, and classifying them according to the land features they contain. I’ll write another story about how I use it (in brief: in order to identify safe areas for a drone to fly over or to land). But for now, I just want to use some training data in order to classify these map tiles."
},
{
"code": null,
"e": 1166,
"s": 809,
"text": "The code snippets below are from a Jupyter Notebook. You can stitch them together to build your own Python script, or download the notebooks from GitHub. The notebooks are originally based on the PyTorch course from Udacity. And if you use a cloud VM for your deep learning development and don’t know how to open a notebook remotely, check out my tutorial."
},
{
"code": null,
"e": 1197,
"s": 1166,
"text": "Organize your training dataset"
},
{
"code": null,
"e": 1734,
"s": 1197,
"text": "PyTorch expects the data to be organized by folders with one folder for each class. Most of the other PyTorch tutorials and examples expect you to further organize it with a training and validation folder at the top, and then the class folders inside them. But I think this is very cumbersome, to have to pick a certain number of images from each class and move them from the training to the validation folder. And since most people would do that by selecting a contiguous group of files, there might be a lot of bias in that selection."
},
{
"code": null,
"e": 1909,
"s": 1734,
"text": "So here’s a better way of splitting the dataset into a training and test set on the fly, like Python developers are used to from SKLearn. But first, let’s import the modules:"
},
{
"code": null,
"e": 2161,
"s": 1909,
"text": "%matplotlib inline%config InlineBackend.figure_format = 'retina'import matplotlib.pyplot as pltimport numpy as npimport torchfrom torch import nnfrom torch import optimimport torch.nn.functional as Ffrom torchvision import datasets, transforms, models"
},
{
"code": null,
"e": 2263,
"s": 2161,
"text": "Next we’ll define the train / validation dataset loader, using the SubsetRandomSampler for the split:"
},
{
"code": null,
"e": 3578,
"s": 2263,
"text": "data_dir = '/data/train'def load_split_train_test(datadir, valid_size = .2): train_transforms = transforms.Compose([transforms.Resize(224), transforms.ToTensor(), ]) test_transforms = transforms.Compose([transforms.Resize(224), transforms.ToTensor(), ]) train_data = datasets.ImageFolder(datadir, transform=train_transforms) test_data = datasets.ImageFolder(datadir, transform=test_transforms) num_train = len(train_data) indices = list(range(num_train)) split = int(np.floor(valid_size * num_train)) np.random.shuffle(indices) from torch.utils.data.sampler import SubsetRandomSampler train_idx, test_idx = indices[split:], indices[:split] train_sampler = SubsetRandomSampler(train_idx) test_sampler = SubsetRandomSampler(test_idx) trainloader = torch.utils.data.DataLoader(train_data, sampler=train_sampler, batch_size=64) testloader = torch.utils.data.DataLoader(test_data, sampler=test_sampler, batch_size=64) return trainloader, testloadertrainloader, testloader = load_split_train_test(data_dir, .2)print(trainloader.dataset.classes)"
},
{
"code": null,
"e": 3818,
"s": 3578,
"text": "Next we’ll determine whether we have GPU or not. I assume that if you’re doing this you have a GPU-powered machine, otherwise the code will be at least 10 times slower. But it’s a good idea to generalize and check for the GPU availability."
},
{
"code": null,
"e": 3888,
"s": 3818,
"text": "We’ll also load a pretrained model. For this case, I chose ResNet 50:"
},
{
"code": null,
"e": 4044,
"s": 3888,
"text": "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")model = models.resnet50(pretrained=True)print(model)"
},
{
"code": null,
"e": 4243,
"s": 4044,
"text": "Printing the model will show you the layer architecture of the ResNet model. It’s probably beyond mine or your comprehension but it’s still interesting to see what’s inside those deep hidden layers."
},
{
"code": null,
"e": 4389,
"s": 4243,
"text": "It’s up to you what model you choose, and it might be a different one based on your particular dataset. Here is a list of all the PyTorch models."
},
{
"code": null,
"e": 4769,
"s": 4389,
"text": "Now we’re getting into the interesting part of the deep neural network. First, we have to freeze the pre-trained layers, so we don’t backprop through them during training. Then, we re-define the final fully-connected the layer, the one that we’ll train with our images. We also create the criterion (the loss function) and pick an optimizer (Adam in this case) and learning rate."
},
{
"code": null,
"e": 5176,
"s": 4769,
"text": "for param in model.parameters(): param.requires_grad = False model.fc = nn.Sequential(nn.Linear(2048, 512), nn.ReLU(), nn.Dropout(0.2), nn.Linear(512, 10), nn.LogSoftmax(dim=1))criterion = nn.NLLLoss()optimizer = optim.Adam(model.fc.parameters(), lr=0.003)model.to(device)"
},
{
"code": null,
"e": 5507,
"s": 5176,
"text": "And now finally, let’s train our model! There’s just one epoch in this example but in most cases you’ll need more. The basic process is quite intuitive from the code: You load the batches of images and do the feed forward loop. Then calculate the loss function, and use the optimizer to apply gradient descent in back-propagation."
},
{
"code": null,
"e": 5795,
"s": 5507,
"text": "It’s that simple with PyTorch. Most of the code below deals with displaying the losses and calculate accuracy every 10 batches, so you get an update while training is running. During validation, don’t forget to set the model to eval() mode, and then back to train() once you’re finished."
},
{
"code": null,
"e": 7463,
"s": 5795,
"text": "epochs = 1steps = 0running_loss = 0print_every = 10train_losses, test_losses = [], []for epoch in range(epochs): for inputs, labels in trainloader: steps += 1 inputs, labels = inputs.to(device), labels.to(device) optimizer.zero_grad() logps = model.forward(inputs) loss = criterion(logps, labels) loss.backward() optimizer.step() running_loss += loss.item() if steps % print_every == 0: test_loss = 0 accuracy = 0 model.eval() with torch.no_grad(): for inputs, labels in testloader: inputs, labels = inputs.to(device), labels.to(device) logps = model.forward(inputs) batch_loss = criterion(logps, labels) test_loss += batch_loss.item() ps = torch.exp(logps) top_p, top_class = ps.topk(1, dim=1) equals = top_class == labels.view(*top_class.shape) accuracy += torch.mean(equals.type(torch.FloatTensor)).item() train_losses.append(running_loss/len(trainloader)) test_losses.append(test_loss/len(testloader)) print(f\"Epoch {epoch+1}/{epochs}.. \" f\"Train loss: {running_loss/print_every:.3f}.. \" f\"Test loss: {test_loss/len(testloader):.3f}.. \" f\"Test accuracy: {accuracy/len(testloader):.3f}\") running_loss = 0 model.train()torch.save(model, 'aerialmodel.pth')"
},
{
"code": null,
"e": 7637,
"s": 7463,
"text": "And... after you wait a few minutes (or more, depending on the size of your dataset and the number of epochs), training is done and the model is saved for later predictions!"
},
{
"code": null,
"e": 7730,
"s": 7637,
"text": "There is one more thing you can do now, which is to plot the training and validation losses:"
},
{
"code": null,
"e": 7857,
"s": 7730,
"text": "plt.plot(train_losses, label='Training loss')plt.plot(test_losses, label='Validation loss')plt.legend(frameon=False)plt.show()"
},
{
"code": null,
"e": 8124,
"s": 7857,
"text": "As you can see, in my particular example with one epoch, the validation loss (which is what we’re interested in) flatlines towards the end of the first epoch and even starts an upward trend, so probably 1 epoch is enough. The training loss, as expected, is very low."
},
{
"code": null,
"e": 8529,
"s": 8124,
"text": "Now on to the second part. So you trained your model, saved it, and need to use it in an application. For that, you’ll need to be able to perform simple inference on an image. You can find this demo notebook as well in our repository. We import the same modules as in the training notebook and then define again the transforms. I only declare the image folder again so I can use some examples from there:"
},
{
"code": null,
"e": 8745,
"s": 8529,
"text": "data_dir = '/datadrive/FastAI/data/aerial_photos/train'test_transforms = transforms.Compose([transforms.Resize(224), transforms.ToTensor(), ])"
},
{
"code": null,
"e": 8867,
"s": 8745,
"text": "Then again we check for GPU availability, load the model and put it into evaluation mode (so parameters are not altered):"
},
{
"code": null,
"e": 8984,
"s": 8867,
"text": "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")model=torch.load('aerialmodel.pth')model.eval()"
},
{
"code": null,
"e": 9112,
"s": 8984,
"text": "The function that predicts the class of a specific image is very simple. Note that it requires a Pillow image, not a file path."
},
{
"code": null,
"e": 9381,
"s": 9112,
"text": "def predict_image(image): image_tensor = test_transforms(image).float() image_tensor = image_tensor.unsqueeze_(0) input = Variable(image_tensor) input = input.to(device) output = model(input) index = output.data.cpu().numpy().argmax() return index"
},
{
"code": null,
"e": 9498,
"s": 9381,
"text": "Now for easier testing, I also created a function that will pick a number of random images from the dataset folders:"
},
{
"code": null,
"e": 9993,
"s": 9498,
"text": "def get_random_images(num): data = datasets.ImageFolder(data_dir, transform=test_transforms) classes = data.classes indices = list(range(len(data))) np.random.shuffle(indices) idx = indices[:num] from torch.utils.data.sampler import SubsetRandomSampler sampler = SubsetRandomSampler(idx) loader = torch.utils.data.DataLoader(data, sampler=sampler, batch_size=num) dataiter = iter(loader) images, labels = dataiter.next() return images, labels"
},
{
"code": null,
"e": 10104,
"s": 9993,
"text": "Finally, to demo the prediction function, I get the random image sample, predict them and display the results:"
},
{
"code": null,
"e": 10482,
"s": 10104,
"text": "to_pil = transforms.ToPILImage()images, labels = get_random_images(5)fig=plt.figure(figsize=(10,10))for ii in range(len(images)): image = to_pil(images[ii]) index = predict_image(image) sub = fig.add_subplot(1, len(images), ii+1) res = int(labels[ii]) == index sub.set_title(str(classes[index]) + \":\" + str(res)) plt.axis('off') plt.imshow(image)plt.show()"
},
{
"code": null,
"e": 10644,
"s": 10482,
"text": "Here’s one example of such predictions on Google Map tiles. The label is the predicted class, and I’m also displaying whether it was a correct prediction or not."
},
{
"code": null,
"e": 10881,
"s": 10644,
"text": "And this is pretty much it. Go ahead and try it on your datasets. As long as you organize your images properly, this code should work as is. Soon I’ll have more stories about other cool stuff you can do with neural networks and PyTorch."
}
] |
Class forName() method in Java with Examples - GeeksforGeeks
|
01 Jun, 2021
The forName() method of java.lang.Class class is used to get the instance of this Class with the specified class name. This class name is specified as the string parameter.Syntax:
public static Class<T> forName(String className) throws ClassNotFoundException
Parameter: This method accepts the parameter className which is the Class for which its instance is required.Return Value: This method returns the instance of this Class with the specified class name.Exception: This method throws following Exceptions:
LinkageError: if the linkage fails
ExceptionInInitializerError: if the initialization provoked by this method fails
ClassNotFoundException: if the class cannot be located
Below programs demonstrate the forName() method.Example 1:
Java
// Java program to demonstrate forName() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // get the Class instance using forName method Class c1 = Class.forName("java.lang.String"); System.out.print("Class represented by c1: " + c1.toString()); }}
Class represented by c1: class java.lang.String
Example 2:
Java
// Java program to demonstrate forName() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // get the Class instance using forName method Class c1 = Class.forName("java.lang.Integer"); System.out.print("Class represented by c1: " + c1.toString()); }}
Class represented by c1: class java.lang.Integer
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#forName-java.lang.String-
ruhelaa48
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java
Collections in Java
|
[
{
"code": null,
"e": 25667,
"s": 25639,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 25849,
"s": 25667,
"text": "The forName() method of java.lang.Class class is used to get the instance of this Class with the specified class name. This class name is specified as the string parameter.Syntax: "
},
{
"code": null,
"e": 25928,
"s": 25849,
"text": "public static Class<T> forName(String className) throws ClassNotFoundException"
},
{
"code": null,
"e": 26182,
"s": 25928,
"text": "Parameter: This method accepts the parameter className which is the Class for which its instance is required.Return Value: This method returns the instance of this Class with the specified class name.Exception: This method throws following Exceptions: "
},
{
"code": null,
"e": 26217,
"s": 26182,
"text": "LinkageError: if the linkage fails"
},
{
"code": null,
"e": 26298,
"s": 26217,
"text": "ExceptionInInitializerError: if the initialization provoked by this method fails"
},
{
"code": null,
"e": 26353,
"s": 26298,
"text": "ClassNotFoundException: if the class cannot be located"
},
{
"code": null,
"e": 26413,
"s": 26353,
"text": "Below programs demonstrate the forName() method.Example 1: "
},
{
"code": null,
"e": 26418,
"s": 26413,
"text": "Java"
},
{
"code": "// Java program to demonstrate forName() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // get the Class instance using forName method Class c1 = Class.forName(\"java.lang.String\"); System.out.print(\"Class represented by c1: \" + c1.toString()); }}",
"e": 26778,
"s": 26418,
"text": null
},
{
"code": null,
"e": 26826,
"s": 26778,
"text": "Class represented by c1: class java.lang.String"
},
{
"code": null,
"e": 26840,
"s": 26828,
"text": "Example 2: "
},
{
"code": null,
"e": 26845,
"s": 26840,
"text": "Java"
},
{
"code": "// Java program to demonstrate forName() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // get the Class instance using forName method Class c1 = Class.forName(\"java.lang.Integer\"); System.out.print(\"Class represented by c1: \" + c1.toString()); }}",
"e": 27206,
"s": 26845,
"text": null
},
{
"code": null,
"e": 27255,
"s": 27206,
"text": "Class represented by c1: class java.lang.Integer"
},
{
"code": null,
"e": 27358,
"s": 27257,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#forName-java.lang.String- "
},
{
"code": null,
"e": 27368,
"s": 27358,
"text": "ruhelaa48"
},
{
"code": null,
"e": 27383,
"s": 27368,
"text": "Java-Functions"
},
{
"code": null,
"e": 27401,
"s": 27383,
"text": "Java-lang package"
},
{
"code": null,
"e": 27417,
"s": 27401,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 27422,
"s": 27417,
"text": "Java"
},
{
"code": null,
"e": 27427,
"s": 27422,
"text": "Java"
},
{
"code": null,
"e": 27525,
"s": 27427,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27540,
"s": 27525,
"text": "Stream In Java"
},
{
"code": null,
"e": 27559,
"s": 27540,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27591,
"s": 27559,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27609,
"s": 27591,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27629,
"s": 27609,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27653,
"s": 27629,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 27685,
"s": 27653,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27697,
"s": 27685,
"text": "Set in Java"
},
{
"code": null,
"e": 27720,
"s": 27697,
"text": "Multithreading in Java"
}
] |
Bit manipulation | Swap Endianness of a number - GeeksforGeeks
|
21 May, 2021
Prerequisite: https://www.geeksforgeeks.org/little-and-big-Endian-mystery/ Little Endian and Big Endian are ways or storing data in machines. Some machines might use Little Endian byte ordering while others might use big Endian. This creates an inconsistency when you are transferring data from a Big Endian machine to a Little Endian machine. Usually, the compiler takes care of the conversion. But, in networking, Big Endian is used as the standard for the exchange of data between networks. Therefore, Little Endian machines need to convert their data to Big Endian while sending data through a network. Similarly, Little Endian machines need to swap the byte ordering when they receive data from a network. So Endianness comes into picture when you are sending and receiving data across the network from one host to another host. If the sender and receiver computer have different Endianness, then there is a need to swap the Endianness so that it is compatible.Therefore, it is important to convert the data to little Endian or big Endian so that there is consistency and data integrity. In this article, we will look at how the Endianness of a number can be swapped. This is also a common interview question.
Get the rightmost 8 bits of the number by anding it with 0x000000FF since the last 8 bits are all ones and the rest are all zeros, the result will be rightmost 8 bits of the number. The result is stored in a variable called leftmost_byte Similarly, get the next 8 bits (from the right, right middle) of the number by anding it with 0x0000FF00. The result is stored in left_middle_byte Obtain the next 8 bits of the number by anding it with 0x00FF0000. The result is stored in right_middle_byte Finally, get the leftmost 8 bits of the number by anding it with 0xFF000000. The result is stored in rightmost_byte Now that we have all the 4 bytes of the number, we need to concatenate it in reverse order. i.e, swap the Endianness of the number. To do this, we shift the rightmost 8 bits by 24 to the left so that it becomes the leftmost 8 bits. We left shift the right middle byte by 16 (to store it as the left middle byte) We left shift the left middle byte by 8 (to store it as the right muddle byte) We finally left shift the leftmost byte by 24 to the left Now, we logically “or” (concatenate) all the variables to obtain the result.
Get the rightmost 8 bits of the number by anding it with 0x000000FF since the last 8 bits are all ones and the rest are all zeros, the result will be rightmost 8 bits of the number. The result is stored in a variable called leftmost_byte
Similarly, get the next 8 bits (from the right, right middle) of the number by anding it with 0x0000FF00. The result is stored in left_middle_byte
Obtain the next 8 bits of the number by anding it with 0x00FF0000. The result is stored in right_middle_byte
Finally, get the leftmost 8 bits of the number by anding it with 0xFF000000. The result is stored in rightmost_byte
Now that we have all the 4 bytes of the number, we need to concatenate it in reverse order. i.e, swap the Endianness of the number. To do this, we shift the rightmost 8 bits by 24 to the left so that it becomes the leftmost 8 bits. We left shift the right middle byte by 16 (to store it as the left middle byte) We left shift the left middle byte by 8 (to store it as the right muddle byte) We finally left shift the leftmost byte by 24 to the left
Now, we logically “or” (concatenate) all the variables to obtain the result.
Consider the number 0x12345678. The number is 4 bytes wide. In Big Endian, this number is represented as:
In Little Endian, the same number is represented as:
Examples:
Input : 0x12345678 Output : 0x78563412 Input : 0x87654321 Output : 0x21436587
Implementation:
C++
C
Java
Python3
C#
// C++ program to print the difference// of Alternate Nodes#include <bits/stdc++.h>using namespace std; // Function to swap a value from// big Endian to little Endian and// vice versa.int swap_Endians(int value){ // This var holds the leftmost 8 // bits of the output. int leftmost_byte; // This holds the left middle // 8 bits of the output int left_middle_byle; // This holds the right middle // 8 bits of the output int right_middle_byte; // This holds the rightmost // 8 bits of the output int rightmost_byte; // To store the result // after conversion int result; // Get the rightmost 8 bits of the number // by anding it 0x000000FF. since the last // 8 bits are all ones, the result will be the // rightmost 8 bits of the number. this will // be converted into the leftmost 8 bits for the // output (swapping) leftmost_byte = (value & 0x000000FF) >> 0; // Similarly, get the right middle and left // middle 8 bits which will become // the left_middle bits in the output left_middle_byle = (value & 0x0000FF00) >> 8; right_middle_byte = (value & 0x00FF0000) >> 16; // Get the leftmost 8 bits which will be the // rightmost 8 bits of the output rightmost_byte = (value & 0xFF000000) >> 24; // Left shift the 8 bits by 24 // so that it is shifted to the // leftmost end leftmost_byte <<= 24; // Similarly, left shift by 16 // so that it is in the left_middle // position. i.e, it starts at the // 9th bit from the left and ends at the // 16th bit from the left left_middle_byle <<= 16; right_middle_byte <<= 8; // The rightmost bit stays as it is // as it is in the correct position rightmost_byte <<= 0; // Result is the concatenation of all these values. result = (leftmost_byte | left_middle_byle | right_middle_byte | rightmost_byte); return result;} // Driver Codeint main(){ // Consider a hexadecimal value // given below. we are gonna convert // this from big Endian to little Endian // and vice versa. int big_Endian = 0x12345678; int little_Endian = 0x78563412; int result1, result2; result1 = swap_Endians(big_Endian); result2 = swap_Endians(little_Endian); printf("big Endian to little:" "0x%x\nlittle Endian to big: 0x%x\n", result1, result2); return 0;} // This code is contributed by SHUBHAMSINGH10
#include <stdio.h> // Function to swap a value from// big Endian to little Endian and// vice versa. int swap_Endians(int value){ // This var holds the leftmost 8 // bits of the output. int leftmost_byte; // This holds the left middle // 8 bits of the output int left_middle_byle; // This holds the right middle // 8 bits of the output int right_middle_byte; // This holds the rightmost // 8 bits of the output int rightmost_byte; // To store the result // after conversion int result; // Get the rightmost 8 bits of the number // by anding it 0x000000FF. since the last // 8 bits are all ones, the result will be the // rightmost 8 bits of the number. this will // be converted into the leftmost 8 bits for the // output (swapping) leftmost_byte = (value & 0x000000FF) >> 0; // Similarly, get the right middle and left // middle 8 bits which will become // the left_middle bits in the output left_middle_byle = (value & 0x0000FF00) >> 8; right_middle_byte = (value & 0x00FF0000) >> 16; // Get the leftmost 8 bits which will be the // rightmost 8 bits of the output rightmost_byte = (value & 0xFF000000) >> 24; // Left shift the 8 bits by 24 // so that it is shifted to the // leftmost end leftmost_byte <<= 24; // Similarly, left shift by 16 // so that it is in the left_middle // position. i.e, it starts at the // 9th bit from the left and ends at the // 16th bit from the left left_middle_byle <<= 16; right_middle_byte <<= 8; // The rightmost bit stays as it is // as it is in the correct position rightmost_byte <<= 0; // Result is the concatenation of all these values. result = (leftmost_byte | left_middle_byle | right_middle_byte | rightmost_byte); return result;} // Driver Codeint main(){ // Consider a hexadecimal value // given below. we are gonna convert // this from big Endian to little Endian // and vice versa. int big_Endian = 0x12345678; int little_Endian = 0x78563412; int result1, result2; result1 = swap_Endians(big_Endian); result2 = swap_Endians(little_Endian); printf("big Endian to little: 0x%x\nlittle Endian to big: 0x%x\n", result1, result2); return 0;}
// Java program to print the difference// of Alternate Nodesimport java.util.*; class GFG{ // Function to swap a value from// big Endian to little Endian and// vice versa.static int swap_Endians(int value){ // This var holds the leftmost 8 // bits of the output. int leftmost_byte; // This holds the left middle // 8 bits of the output int left_middle_byle; // This holds the right middle // 8 bits of the output int right_middle_byte; // This holds the rightmost // 8 bits of the output int rightmost_byte; // To store the result // after conversion int result; // Get the rightmost 8 bits of the number // by anding it 0x000000FF. since the last // 8 bits are all ones, the result will be the // rightmost 8 bits of the number. this will // be converted into the leftmost 8 bits for the // output (swapping) leftmost_byte = (value & 0x000000FF) >> 0; // Similarly, get the right middle and left // middle 8 bits which will become // the left_middle bits in the output left_middle_byle = (value & 0x0000FF00) >> 8; right_middle_byte = (value & 0x00FF0000) >> 16; // Get the leftmost 8 bits which will be the // rightmost 8 bits of the output rightmost_byte = (value & 0xFF000000) >> 24; // Left shift the 8 bits by 24 // so that it is shifted to the // leftmost end leftmost_byte <<= 24; // Similarly, left shift by 16 // so that it is in the left_middle // position. i.e, it starts at the // 9th bit from the left and ends at the // 16th bit from the left left_middle_byle <<= 16; right_middle_byte <<= 8; // The rightmost bit stays as it is // as it is in the correct position rightmost_byte <<= 0; // Result is the concatenation of all these values. result = (leftmost_byte | left_middle_byle | right_middle_byte | rightmost_byte); return result;} // Driver Codepublic static void main(String[] args){ // Consider a hexadecimal value // given below. we are gonna convert // this from big Endian to little Endian // and vice versa. int big_Endian = 0x12345678; int little_Endian = 0x78563412; int result1, result2; result1 = swap_Endians(big_Endian); result2 = swap_Endians(little_Endian); System.out.printf("big Endian to little: 0x%x\n" + "little Endian to big: 0x%x\n", result1, result2);}} // This code is contributed by PrinciRaj1992
# Function to swap a value from# big Endian to little Endian and# vice versa.def swap_Endians(value): # Get the rightmost 8 bits of the number # by anding it 0x000000FF. since the last # 8 bits are all ones, the result will be the # rightmost 8 bits of the number. this will # be converted into the leftmost 8 bits for the # output (swapping) leftmost_byte = (value & eval('0x000000FF')) >> 0 # Similarly, get the right middle and left # middle 8 bits which will become # the left_middle bits in the output left_middle_byle = (value & eval('0x0000FF00')) >> 8 right_middle_byte = (value & eval('0x00FF0000'))>> 16 # Get the leftmost 8 bits which will be the # rightmost 8 bits of the output rightmost_byte = (value & eval('0xFF000000'))>> 24 # Left shift the 8 bits by 24 # so that it is shifted to the # leftmost end leftmost_byte <<= 24 # Similarly, left shift by 16 # so that it is in the left_middle # position. i.e, it starts at the # 9th bit from the left and ends at the # 16th bit from the left left_middle_byle <<= 16 right_middle_byte <<= 8 # The rightmost bit stays as it is # as it is in the correct position rightmost_byte <<= 0 # Result is the concatenation of all these values result = (leftmost_byte | left_middle_byle | right_middle_byte | rightmost_byte) return result # main functionif __name__ == '__main__': # Consider a hexadecimal value # given below. we are gonna convert # this from big Endian to little Endian # and vice versa. big_Endian = eval('0x12345678') little_Endian = eval('0x78563412') result1 = swap_Endians(big_Endian) result2 = swap_Endians(little_Endian) print("big Endian to little: % s\nlittle Endian to big: % s" %(hex(result1), hex(result2)))
// C# program to print the difference// of Alternate Nodesusing System; class GFG{ // Function to swap a value from// big Endian to little Endian and// vice versa.static int swap_Endians(int value){ // This var holds the leftmost 8 // bits of the output. int leftmost_byte; // This holds the left middle // 8 bits of the output int left_middle_byle; // This holds the right middle // 8 bits of the output int right_middle_byte; // This holds the rightmost // 8 bits of the output int rightmost_byte; // To store the result // after conversion int result; // Get the rightmost 8 bits of the number // by anding it 0x000000FF. since the last // 8 bits are all ones, the result will be the // rightmost 8 bits of the number. this will // be converted into the leftmost 8 bits for the // output (swapping) leftmost_byte = (value & 0x000000FF) >> 0; // Similarly, get the right middle and left // middle 8 bits which will become // the left_middle bits in the output left_middle_byle = (value & 0x0000FF00) >> 8; right_middle_byte = (value & 0x00FF0000) >> 16; // Get the leftmost 8 bits which will be the // rightmost 8 bits of the output rightmost_byte = (int)(value & 0xFF000000) >> 24; // Left shift the 8 bits by 24 // so that it is shifted to the // leftmost end leftmost_byte <<= 24; // Similarly, left shift by 16 // so that it is in the left_middle // position. i.e, it starts at the // 9th bit from the left and ends at the // 16th bit from the left left_middle_byle <<= 16; right_middle_byte <<= 8; // The rightmost bit stays as it is // as it is in the correct position rightmost_byte <<= 0; // Result is the concatenation of all these values. result = (leftmost_byte | left_middle_byle | right_middle_byte | rightmost_byte); return result;} // Driver Codepublic static void Main(String[] args){ // Consider a hexadecimal value // given below. we are gonna convert // this from big Endian to little Endian // and vice versa. int big_Endian = 0x12345678; int little_Endian = 0x78563412; int result1, result2; result1 = swap_Endians(big_Endian); result2 = swap_Endians(little_Endian); Console.Write("big Endian to little: 0x{0:x}\n" + "little Endian to big: 0x{1:x}\n", result1, result2);}} // This code is contributed by Rajput-Ji
big Endian to little:0x78563412
little Endian to big: 0x12345678
princiraj1992
Rajput-Ji
SHUBHAMSINGH10
akshaysingh98088
Computer Organization and Architecture
Bit Magic
Computer Organization & Architecture
Data Structures
Data Structures
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Write an Efficient Method to Check if a Number is Multiple of 3
Hamming code Implementation in C/C++
Check whether K-th bit is set or not
Cache Memory in Computer Organization
Addressing Modes
Program for Decimal to Binary Conversion
Addressing modes in 8085 microprocessor
Logical and Physical Address in Operating System
|
[
{
"code": null,
"e": 24908,
"s": 24880,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 26125,
"s": 24908,
"text": "Prerequisite: https://www.geeksforgeeks.org/little-and-big-Endian-mystery/ Little Endian and Big Endian are ways or storing data in machines. Some machines might use Little Endian byte ordering while others might use big Endian. This creates an inconsistency when you are transferring data from a Big Endian machine to a Little Endian machine. Usually, the compiler takes care of the conversion. But, in networking, Big Endian is used as the standard for the exchange of data between networks. Therefore, Little Endian machines need to convert their data to Big Endian while sending data through a network. Similarly, Little Endian machines need to swap the byte ordering when they receive data from a network. So Endianness comes into picture when you are sending and receiving data across the network from one host to another host. If the sender and receiver computer have different Endianness, then there is a need to swap the Endianness so that it is compatible.Therefore, it is important to convert the data to little Endian or big Endian so that there is consistency and data integrity. In this article, we will look at how the Endianness of a number can be swapped. This is also a common interview question. "
},
{
"code": null,
"e": 27267,
"s": 26129,
"text": "Get the rightmost 8 bits of the number by anding it with 0x000000FF since the last 8 bits are all ones and the rest are all zeros, the result will be rightmost 8 bits of the number. The result is stored in a variable called leftmost_byte Similarly, get the next 8 bits (from the right, right middle) of the number by anding it with 0x0000FF00. The result is stored in left_middle_byte Obtain the next 8 bits of the number by anding it with 0x00FF0000. The result is stored in right_middle_byte Finally, get the leftmost 8 bits of the number by anding it with 0xFF000000. The result is stored in rightmost_byte Now that we have all the 4 bytes of the number, we need to concatenate it in reverse order. i.e, swap the Endianness of the number. To do this, we shift the rightmost 8 bits by 24 to the left so that it becomes the leftmost 8 bits. We left shift the right middle byte by 16 (to store it as the left middle byte) We left shift the left middle byte by 8 (to store it as the right muddle byte) We finally left shift the leftmost byte by 24 to the left Now, we logically “or” (concatenate) all the variables to obtain the result. "
},
{
"code": null,
"e": 27507,
"s": 27267,
"text": "Get the rightmost 8 bits of the number by anding it with 0x000000FF since the last 8 bits are all ones and the rest are all zeros, the result will be rightmost 8 bits of the number. The result is stored in a variable called leftmost_byte "
},
{
"code": null,
"e": 27655,
"s": 27507,
"text": "Similarly, get the next 8 bits (from the right, right middle) of the number by anding it with 0x0000FF00. The result is stored in left_middle_byte "
},
{
"code": null,
"e": 27765,
"s": 27655,
"text": "Obtain the next 8 bits of the number by anding it with 0x00FF0000. The result is stored in right_middle_byte "
},
{
"code": null,
"e": 27882,
"s": 27765,
"text": "Finally, get the leftmost 8 bits of the number by anding it with 0xFF000000. The result is stored in rightmost_byte "
},
{
"code": null,
"e": 28332,
"s": 27882,
"text": "Now that we have all the 4 bytes of the number, we need to concatenate it in reverse order. i.e, swap the Endianness of the number. To do this, we shift the rightmost 8 bits by 24 to the left so that it becomes the leftmost 8 bits. We left shift the right middle byte by 16 (to store it as the left middle byte) We left shift the left middle byte by 8 (to store it as the right muddle byte) We finally left shift the leftmost byte by 24 to the left "
},
{
"code": null,
"e": 28410,
"s": 28332,
"text": "Now, we logically “or” (concatenate) all the variables to obtain the result. "
},
{
"code": null,
"e": 28517,
"s": 28410,
"text": "Consider the number 0x12345678. The number is 4 bytes wide. In Big Endian, this number is represented as: "
},
{
"code": null,
"e": 28571,
"s": 28517,
"text": "In Little Endian, the same number is represented as: "
},
{
"code": null,
"e": 28583,
"s": 28571,
"text": "Examples: "
},
{
"code": null,
"e": 28663,
"s": 28583,
"text": "Input : 0x12345678 Output : 0x78563412 Input : 0x87654321 Output : 0x21436587 "
},
{
"code": null,
"e": 28680,
"s": 28663,
"text": "Implementation: "
},
{
"code": null,
"e": 28684,
"s": 28680,
"text": "C++"
},
{
"code": null,
"e": 28686,
"s": 28684,
"text": "C"
},
{
"code": null,
"e": 28691,
"s": 28686,
"text": "Java"
},
{
"code": null,
"e": 28699,
"s": 28691,
"text": "Python3"
},
{
"code": null,
"e": 28702,
"s": 28699,
"text": "C#"
},
{
"code": "// C++ program to print the difference// of Alternate Nodes#include <bits/stdc++.h>using namespace std; // Function to swap a value from// big Endian to little Endian and// vice versa.int swap_Endians(int value){ // This var holds the leftmost 8 // bits of the output. int leftmost_byte; // This holds the left middle // 8 bits of the output int left_middle_byle; // This holds the right middle // 8 bits of the output int right_middle_byte; // This holds the rightmost // 8 bits of the output int rightmost_byte; // To store the result // after conversion int result; // Get the rightmost 8 bits of the number // by anding it 0x000000FF. since the last // 8 bits are all ones, the result will be the // rightmost 8 bits of the number. this will // be converted into the leftmost 8 bits for the // output (swapping) leftmost_byte = (value & 0x000000FF) >> 0; // Similarly, get the right middle and left // middle 8 bits which will become // the left_middle bits in the output left_middle_byle = (value & 0x0000FF00) >> 8; right_middle_byte = (value & 0x00FF0000) >> 16; // Get the leftmost 8 bits which will be the // rightmost 8 bits of the output rightmost_byte = (value & 0xFF000000) >> 24; // Left shift the 8 bits by 24 // so that it is shifted to the // leftmost end leftmost_byte <<= 24; // Similarly, left shift by 16 // so that it is in the left_middle // position. i.e, it starts at the // 9th bit from the left and ends at the // 16th bit from the left left_middle_byle <<= 16; right_middle_byte <<= 8; // The rightmost bit stays as it is // as it is in the correct position rightmost_byte <<= 0; // Result is the concatenation of all these values. result = (leftmost_byte | left_middle_byle | right_middle_byte | rightmost_byte); return result;} // Driver Codeint main(){ // Consider a hexadecimal value // given below. we are gonna convert // this from big Endian to little Endian // and vice versa. int big_Endian = 0x12345678; int little_Endian = 0x78563412; int result1, result2; result1 = swap_Endians(big_Endian); result2 = swap_Endians(little_Endian); printf(\"big Endian to little:\" \"0x%x\\nlittle Endian to big: 0x%x\\n\", result1, result2); return 0;} // This code is contributed by SHUBHAMSINGH10",
"e": 31148,
"s": 28702,
"text": null
},
{
"code": "#include <stdio.h> // Function to swap a value from// big Endian to little Endian and// vice versa. int swap_Endians(int value){ // This var holds the leftmost 8 // bits of the output. int leftmost_byte; // This holds the left middle // 8 bits of the output int left_middle_byle; // This holds the right middle // 8 bits of the output int right_middle_byte; // This holds the rightmost // 8 bits of the output int rightmost_byte; // To store the result // after conversion int result; // Get the rightmost 8 bits of the number // by anding it 0x000000FF. since the last // 8 bits are all ones, the result will be the // rightmost 8 bits of the number. this will // be converted into the leftmost 8 bits for the // output (swapping) leftmost_byte = (value & 0x000000FF) >> 0; // Similarly, get the right middle and left // middle 8 bits which will become // the left_middle bits in the output left_middle_byle = (value & 0x0000FF00) >> 8; right_middle_byte = (value & 0x00FF0000) >> 16; // Get the leftmost 8 bits which will be the // rightmost 8 bits of the output rightmost_byte = (value & 0xFF000000) >> 24; // Left shift the 8 bits by 24 // so that it is shifted to the // leftmost end leftmost_byte <<= 24; // Similarly, left shift by 16 // so that it is in the left_middle // position. i.e, it starts at the // 9th bit from the left and ends at the // 16th bit from the left left_middle_byle <<= 16; right_middle_byte <<= 8; // The rightmost bit stays as it is // as it is in the correct position rightmost_byte <<= 0; // Result is the concatenation of all these values. result = (leftmost_byte | left_middle_byle | right_middle_byte | rightmost_byte); return result;} // Driver Codeint main(){ // Consider a hexadecimal value // given below. we are gonna convert // this from big Endian to little Endian // and vice versa. int big_Endian = 0x12345678; int little_Endian = 0x78563412; int result1, result2; result1 = swap_Endians(big_Endian); result2 = swap_Endians(little_Endian); printf(\"big Endian to little: 0x%x\\nlittle Endian to big: 0x%x\\n\", result1, result2); return 0;}",
"e": 33463,
"s": 31148,
"text": null
},
{
"code": "// Java program to print the difference// of Alternate Nodesimport java.util.*; class GFG{ // Function to swap a value from// big Endian to little Endian and// vice versa.static int swap_Endians(int value){ // This var holds the leftmost 8 // bits of the output. int leftmost_byte; // This holds the left middle // 8 bits of the output int left_middle_byle; // This holds the right middle // 8 bits of the output int right_middle_byte; // This holds the rightmost // 8 bits of the output int rightmost_byte; // To store the result // after conversion int result; // Get the rightmost 8 bits of the number // by anding it 0x000000FF. since the last // 8 bits are all ones, the result will be the // rightmost 8 bits of the number. this will // be converted into the leftmost 8 bits for the // output (swapping) leftmost_byte = (value & 0x000000FF) >> 0; // Similarly, get the right middle and left // middle 8 bits which will become // the left_middle bits in the output left_middle_byle = (value & 0x0000FF00) >> 8; right_middle_byte = (value & 0x00FF0000) >> 16; // Get the leftmost 8 bits which will be the // rightmost 8 bits of the output rightmost_byte = (value & 0xFF000000) >> 24; // Left shift the 8 bits by 24 // so that it is shifted to the // leftmost end leftmost_byte <<= 24; // Similarly, left shift by 16 // so that it is in the left_middle // position. i.e, it starts at the // 9th bit from the left and ends at the // 16th bit from the left left_middle_byle <<= 16; right_middle_byte <<= 8; // The rightmost bit stays as it is // as it is in the correct position rightmost_byte <<= 0; // Result is the concatenation of all these values. result = (leftmost_byte | left_middle_byle | right_middle_byte | rightmost_byte); return result;} // Driver Codepublic static void main(String[] args){ // Consider a hexadecimal value // given below. we are gonna convert // this from big Endian to little Endian // and vice versa. int big_Endian = 0x12345678; int little_Endian = 0x78563412; int result1, result2; result1 = swap_Endians(big_Endian); result2 = swap_Endians(little_Endian); System.out.printf(\"big Endian to little: 0x%x\\n\" + \"little Endian to big: 0x%x\\n\", result1, result2);}} // This code is contributed by PrinciRaj1992",
"e": 35951,
"s": 33463,
"text": null
},
{
"code": "# Function to swap a value from# big Endian to little Endian and# vice versa.def swap_Endians(value): # Get the rightmost 8 bits of the number # by anding it 0x000000FF. since the last # 8 bits are all ones, the result will be the # rightmost 8 bits of the number. this will # be converted into the leftmost 8 bits for the # output (swapping) leftmost_byte = (value & eval('0x000000FF')) >> 0 # Similarly, get the right middle and left # middle 8 bits which will become # the left_middle bits in the output left_middle_byle = (value & eval('0x0000FF00')) >> 8 right_middle_byte = (value & eval('0x00FF0000'))>> 16 # Get the leftmost 8 bits which will be the # rightmost 8 bits of the output rightmost_byte = (value & eval('0xFF000000'))>> 24 # Left shift the 8 bits by 24 # so that it is shifted to the # leftmost end leftmost_byte <<= 24 # Similarly, left shift by 16 # so that it is in the left_middle # position. i.e, it starts at the # 9th bit from the left and ends at the # 16th bit from the left left_middle_byle <<= 16 right_middle_byte <<= 8 # The rightmost bit stays as it is # as it is in the correct position rightmost_byte <<= 0 # Result is the concatenation of all these values result = (leftmost_byte | left_middle_byle | right_middle_byte | rightmost_byte) return result # main functionif __name__ == '__main__': # Consider a hexadecimal value # given below. we are gonna convert # this from big Endian to little Endian # and vice versa. big_Endian = eval('0x12345678') little_Endian = eval('0x78563412') result1 = swap_Endians(big_Endian) result2 = swap_Endians(little_Endian) print(\"big Endian to little: % s\\nlittle Endian to big: % s\" %(hex(result1), hex(result2)))",
"e": 37819,
"s": 35951,
"text": null
},
{
"code": "// C# program to print the difference// of Alternate Nodesusing System; class GFG{ // Function to swap a value from// big Endian to little Endian and// vice versa.static int swap_Endians(int value){ // This var holds the leftmost 8 // bits of the output. int leftmost_byte; // This holds the left middle // 8 bits of the output int left_middle_byle; // This holds the right middle // 8 bits of the output int right_middle_byte; // This holds the rightmost // 8 bits of the output int rightmost_byte; // To store the result // after conversion int result; // Get the rightmost 8 bits of the number // by anding it 0x000000FF. since the last // 8 bits are all ones, the result will be the // rightmost 8 bits of the number. this will // be converted into the leftmost 8 bits for the // output (swapping) leftmost_byte = (value & 0x000000FF) >> 0; // Similarly, get the right middle and left // middle 8 bits which will become // the left_middle bits in the output left_middle_byle = (value & 0x0000FF00) >> 8; right_middle_byte = (value & 0x00FF0000) >> 16; // Get the leftmost 8 bits which will be the // rightmost 8 bits of the output rightmost_byte = (int)(value & 0xFF000000) >> 24; // Left shift the 8 bits by 24 // so that it is shifted to the // leftmost end leftmost_byte <<= 24; // Similarly, left shift by 16 // so that it is in the left_middle // position. i.e, it starts at the // 9th bit from the left and ends at the // 16th bit from the left left_middle_byle <<= 16; right_middle_byte <<= 8; // The rightmost bit stays as it is // as it is in the correct position rightmost_byte <<= 0; // Result is the concatenation of all these values. result = (leftmost_byte | left_middle_byle | right_middle_byte | rightmost_byte); return result;} // Driver Codepublic static void Main(String[] args){ // Consider a hexadecimal value // given below. we are gonna convert // this from big Endian to little Endian // and vice versa. int big_Endian = 0x12345678; int little_Endian = 0x78563412; int result1, result2; result1 = swap_Endians(big_Endian); result2 = swap_Endians(little_Endian); Console.Write(\"big Endian to little: 0x{0:x}\\n\" + \"little Endian to big: 0x{1:x}\\n\", result1, result2);}} // This code is contributed by Rajput-Ji",
"e": 40316,
"s": 37819,
"text": null
},
{
"code": null,
"e": 40382,
"s": 40316,
"text": "big Endian to little:0x78563412\nlittle Endian to big: 0x12345678\n"
},
{
"code": null,
"e": 40396,
"s": 40382,
"text": "princiraj1992"
},
{
"code": null,
"e": 40406,
"s": 40396,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 40421,
"s": 40406,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 40438,
"s": 40421,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 40477,
"s": 40438,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 40487,
"s": 40477,
"text": "Bit Magic"
},
{
"code": null,
"e": 40524,
"s": 40487,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 40540,
"s": 40524,
"text": "Data Structures"
},
{
"code": null,
"e": 40556,
"s": 40540,
"text": "Data Structures"
},
{
"code": null,
"e": 40566,
"s": 40556,
"text": "Bit Magic"
},
{
"code": null,
"e": 40664,
"s": 40566,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40673,
"s": 40664,
"text": "Comments"
},
{
"code": null,
"e": 40686,
"s": 40673,
"text": "Old Comments"
},
{
"code": null,
"e": 40737,
"s": 40686,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 40760,
"s": 40737,
"text": "Program to find parity"
},
{
"code": null,
"e": 40824,
"s": 40760,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 40861,
"s": 40824,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 40898,
"s": 40861,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 40936,
"s": 40898,
"text": "Cache Memory in Computer Organization"
},
{
"code": null,
"e": 40953,
"s": 40936,
"text": "Addressing Modes"
},
{
"code": null,
"e": 40994,
"s": 40953,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 41034,
"s": 40994,
"text": "Addressing modes in 8085 microprocessor"
}
] |
ReactJS bind() Method - GeeksforGeeks
|
23 Dec, 2020
The bind() is an inbuilt method in React that is used to pass the data as an argument to the function of a class based component.
Syntax:
this.function.bind(this,[arg1...]);
Parameter: It accepts two parameters, the first parameter is the this keyword used for binding and the second parameter is the sequence of arguments that are passed as a parameter and are optional.
Creating React Application:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Example 1:
App.js:JavascriptJavascriptimport React from 'react';class App extends React.Component { // Initialising state state = { name: 'GFG', }; handler = (name) => { // Changing the state this.setState({ name: name }); }; render() { return ( <div> <h1>Name:{this.state.name}</h1> <h1>Click here to change the name</h1> {/* Passing the name as an argument to the handler() function */} <button onClick={this.handler.bind(this, 'GeeksForGeeks')}> Click Here </button> </div> ); }} export default App;
Javascript
import React from 'react';class App extends React.Component { // Initialising state state = { name: 'GFG', }; handler = (name) => { // Changing the state this.setState({ name: name }); }; render() { return ( <div> <h1>Name:{this.state.name}</h1> <h1>Click here to change the name</h1> {/* Passing the name as an argument to the handler() function */} <button onClick={this.handler.bind(this, 'GeeksForGeeks')}> Click Here </button> </div> ); }} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Example 2: We can also use the arrow function as provided by the modern ES6.
App.js:JavascriptJavascriptimport React from 'react';class App extends React.Component { // Initialising state state = { name: 'GFG', }; handler = (name) => { // Changing the state this.setState({ name: name }); }; render() { return ( <div> <h1>Name:{this.state.name}</h1> <h1>Click here to change the name</h1> {/* Passing the name as an argument to the handler() function with modern ES6 feature*/} <button onClick={() => this.handler('GeeksForGeeks')}> Click Here </button> </div> ); }} export default App;
App.js:JavascriptJavascriptimport React from 'react';class App extends React.Component { // Initialising state state = { name: 'GFG', }; handler = (name) => { // Changing the state this.setState({ name: name }); }; render() { return ( <div> <h1>Name:{this.state.name}</h1> <h1>Click here to change the name</h1> {/* Passing the name as an argument to the handler() function with modern ES6 feature*/} <button onClick={() => this.handler('GeeksForGeeks')}> Click Here </button> </div> ); }} export default App;
App.js:
Javascript
import React from 'react';class App extends React.Component { // Initialising state state = { name: 'GFG', }; handler = (name) => { // Changing the state this.setState({ name: name }); }; render() { return ( <div> <h1>Name:{this.state.name}</h1> <h1>Click here to change the name</h1> {/* Passing the name as an argument to the handler() function with modern ES6 feature*/} <button onClick={() => this.handler('GeeksForGeeks')}> Click Here </button> </div> ); }} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
HTML Cheat Sheet - A Basic Guide to HTML
REST API (Introduction)
Difference Between PUT and PATCH Request
How to execute PHP code using command line ?
Angular CLI | Angular Project Setup
|
[
{
"code": null,
"e": 25047,
"s": 25019,
"text": "\n23 Dec, 2020"
},
{
"code": null,
"e": 25177,
"s": 25047,
"text": "The bind() is an inbuilt method in React that is used to pass the data as an argument to the function of a class based component."
},
{
"code": null,
"e": 25185,
"s": 25177,
"text": "Syntax:"
},
{
"code": null,
"e": 25221,
"s": 25185,
"text": "this.function.bind(this,[arg1...]);"
},
{
"code": null,
"e": 25419,
"s": 25221,
"text": "Parameter: It accepts two parameters, the first parameter is the this keyword used for binding and the second parameter is the sequence of arguments that are passed as a parameter and are optional."
},
{
"code": null,
"e": 25447,
"s": 25419,
"text": "Creating React Application:"
},
{
"code": null,
"e": 25542,
"s": 25447,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 25606,
"s": 25542,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 25638,
"s": 25606,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 25751,
"s": 25638,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 25851,
"s": 25751,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 25865,
"s": 25851,
"text": "cd foldername"
},
{
"code": null,
"e": 25876,
"s": 25865,
"text": "Example 1:"
},
{
"code": null,
"e": 26462,
"s": 25876,
"text": "App.js:JavascriptJavascriptimport React from 'react';class App extends React.Component { // Initialising state state = { name: 'GFG', }; handler = (name) => { // Changing the state this.setState({ name: name }); }; render() { return ( <div> <h1>Name:{this.state.name}</h1> <h1>Click here to change the name</h1> {/* Passing the name as an argument to the handler() function */} <button onClick={this.handler.bind(this, 'GeeksForGeeks')}> Click Here </button> </div> ); }} export default App;"
},
{
"code": null,
"e": 26473,
"s": 26462,
"text": "Javascript"
},
{
"code": "import React from 'react';class App extends React.Component { // Initialising state state = { name: 'GFG', }; handler = (name) => { // Changing the state this.setState({ name: name }); }; render() { return ( <div> <h1>Name:{this.state.name}</h1> <h1>Click here to change the name</h1> {/* Passing the name as an argument to the handler() function */} <button onClick={this.handler.bind(this, 'GeeksForGeeks')}> Click Here </button> </div> ); }} export default App;",
"e": 27032,
"s": 26473,
"text": null
},
{
"code": null,
"e": 27145,
"s": 27032,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 27155,
"s": 27145,
"text": "npm start"
},
{
"code": null,
"e": 27163,
"s": 27155,
"text": "Output:"
},
{
"code": null,
"e": 27240,
"s": 27163,
"text": "Example 2: We can also use the arrow function as provided by the modern ES6."
},
{
"code": null,
"e": 27853,
"s": 27240,
"text": "App.js:JavascriptJavascriptimport React from 'react';class App extends React.Component { // Initialising state state = { name: 'GFG', }; handler = (name) => { // Changing the state this.setState({ name: name }); }; render() { return ( <div> <h1>Name:{this.state.name}</h1> <h1>Click here to change the name</h1> {/* Passing the name as an argument to the handler() function with modern ES6 feature*/} <button onClick={() => this.handler('GeeksForGeeks')}> Click Here </button> </div> ); }} export default App;"
},
{
"code": null,
"e": 28466,
"s": 27853,
"text": "App.js:JavascriptJavascriptimport React from 'react';class App extends React.Component { // Initialising state state = { name: 'GFG', }; handler = (name) => { // Changing the state this.setState({ name: name }); }; render() { return ( <div> <h1>Name:{this.state.name}</h1> <h1>Click here to change the name</h1> {/* Passing the name as an argument to the handler() function with modern ES6 feature*/} <button onClick={() => this.handler('GeeksForGeeks')}> Click Here </button> </div> ); }} export default App;"
},
{
"code": null,
"e": 28474,
"s": 28466,
"text": "App.js:"
},
{
"code": null,
"e": 28485,
"s": 28474,
"text": "Javascript"
},
{
"code": "import React from 'react';class App extends React.Component { // Initialising state state = { name: 'GFG', }; handler = (name) => { // Changing the state this.setState({ name: name }); }; render() { return ( <div> <h1>Name:{this.state.name}</h1> <h1>Click here to change the name</h1> {/* Passing the name as an argument to the handler() function with modern ES6 feature*/} <button onClick={() => this.handler('GeeksForGeeks')}> Click Here </button> </div> ); }} export default App;",
"e": 29071,
"s": 28485,
"text": null
},
{
"code": null,
"e": 29184,
"s": 29071,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 29194,
"s": 29184,
"text": "npm start"
},
{
"code": null,
"e": 29202,
"s": 29194,
"text": "Output:"
},
{
"code": null,
"e": 29211,
"s": 29202,
"text": "react-js"
},
{
"code": null,
"e": 29228,
"s": 29211,
"text": "Web Technologies"
},
{
"code": null,
"e": 29326,
"s": 29228,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29366,
"s": 29326,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29411,
"s": 29366,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29454,
"s": 29411,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29515,
"s": 29454,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29587,
"s": 29515,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29628,
"s": 29587,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 29652,
"s": 29628,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 29693,
"s": 29652,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29738,
"s": 29693,
"text": "How to execute PHP code using command line ?"
}
] |
How to set the style of the bottom border with JavaScript?
|
To set the style of the bottom border, use the JavaScript borderBottomStyle property. It allows you to add a bottom border.
You can try to run the following code to set the style of the bottom border −
<!DOCTYPE html>
<html>
<body>
<div id="box">Demo Text</div>
<br>
<button onclick="display()">Click to set style of bottom border</button>
<script>
function display() {
document.getElementById("box").style.borderBottomStyle = "dashed";
}
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1186,
"s": 1062,
"text": "To set the style of the bottom border, use the JavaScript borderBottomStyle property. It allows you to add a bottom border."
},
{
"code": null,
"e": 1264,
"s": 1186,
"text": "You can try to run the following code to set the style of the bottom border −"
},
{
"code": null,
"e": 1593,
"s": 1264,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <div id=\"box\">Demo Text</div>\n <br>\n <button onclick=\"display()\">Click to set style of bottom border</button>\n <script>\n function display() {\n document.getElementById(\"box\").style.borderBottomStyle = \"dashed\";\n }\n </script>\n </body>\n</html>"
}
] |
How to get/change the HTML with DOM element in JavaScript ?
|
02 Sep, 2021
In order to get/access the HTML for a DOM element in JavaScript, the first step is to identify the element base on its id, name or its tag name. Then, we can use inner.HTML or outer.HTML to get the HTML.
1. Using getElementById() method: This method gets/identifies the DOM elements using it’s ID and returns the element.
Example:
Javascript
<!DOCTYPE html><html> <head> <title> How to get/change the HTML with DOM element in JavaScript? </title></head> <body> <h3> Accessing HTML of a DOM element in JavaScript. </h3> <p id="iD1"> JavaScript is used for web programming. </p> <button onclick=getHtml()> Get and change the html for DOM element </button> <script> function getHtml() { var Element = document.getElementById("iD1"); alert(Element.innerHTML); Element.style.color = "orange"; Element.innerHTML = "GeeksforGeeks"; } </script></body> </html>
Output:
Before Clickin the Button:
After Clicking the Button:
2. Using getElementByName() method: This method gets/identifies the DOM element by using it’s the class name and returns the element.
Example:
Javascript
<!DOCTYPE html><html> <head> <title> How to get/change the HTML with DOM element in JavaScript? </title></head> <body> <h3> Accessing HTML of a DOM element in JavaScript. </h3> <p class="p1"> JavaScript is used for web programming. </p> <button onclick=getHtml()> Get and change the html for DOM element </button> <script> function getHtml() { var Element = document.getElementsByClassName("p1"); alert(Element[0].innerHTML); Element[0].style.color = "blue"; Element[0].innerHTML = "GeeksforGeeks"; } </script></body> </html>
Output:
Before Clicking the Button:
After Clicking the Button:
3. Using getElementsByTagName(): This method gets/identifies the DOM element using it’s tag name and returns it.
Example:
Javascript
<!DOCTYPE html><html> <head> <title> How to get/change the HTML with DOM element in JavaScript? </title></head> <body> <h3> Accessing HTML of a DOM element in JavaScript. </h3> <p>JavaScript is used for web programming.</p> <p>JavaScript was invented in 1990s.</p> <button onclick=getHtml()> Get and change the html for DOM element </button> <script> function getHtml() { var Element = document.getElementsByTagName("p"); for (var i = 0; i < Element.length; i++) { alert(Element[i].innerHTML); Element[i].innerHTML = "GeeksforGeeks."; } } </script></body> </html>
Output:
Before Clicking the button:
After Clicking the Button:
NOTE: The above three approaches use inner.HTML property of the DOM element to get the HTML and alerts it and then changes the HTML content present in the element. The property inner.HTML is mainly used to change the text or rather the content present whereas outer.HTML is used for changing the tag and the content of the text as it returns the HTML content along with its tag.
Below example illustrates the use of outer.HTML property using getElementsByTagName() method.
Javascript
<!DOCTYPE html><html> <head> <title> How to get/change the HTML with DOM element in JavaScript? </title></head> <body> <div> GeeksforGeeks </div> <button onclick=getHtml()> Get HTML for DOM element </button> <script> function getHtml() { var Element = document.getElementsByTagName("div"); alert(Element[0].outerHTML); Element[0].style.color = "red"; Element[0].outerHTML = "<h1> JavaScript. </h1>" } </script></body> </html>
Output:
Before Clicking the Button:
After Clicking the Button:
The functions getElementById(), getElementsByClassName() can also be used to get the DOM elements for accessing outerHTML in the same manner as they were used to access innerHTML. Thus, we can access HTML of a DOM using the above methods.
rajeev0719singh
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
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.
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 232,
"s": 28,
"text": "In order to get/access the HTML for a DOM element in JavaScript, the first step is to identify the element base on its id, name or its tag name. Then, we can use inner.HTML or outer.HTML to get the HTML."
},
{
"code": null,
"e": 350,
"s": 232,
"text": "1. Using getElementById() method: This method gets/identifies the DOM elements using it’s ID and returns the element."
},
{
"code": null,
"e": 360,
"s": 350,
"text": "Example: "
},
{
"code": null,
"e": 371,
"s": 360,
"text": "Javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to get/change the HTML with DOM element in JavaScript? </title></head> <body> <h3> Accessing HTML of a DOM element in JavaScript. </h3> <p id=\"iD1\"> JavaScript is used for web programming. </p> <button onclick=getHtml()> Get and change the html for DOM element </button> <script> function getHtml() { var Element = document.getElementById(\"iD1\"); alert(Element.innerHTML); Element.style.color = \"orange\"; Element.innerHTML = \"GeeksforGeeks\"; } </script></body> </html>",
"e": 1015,
"s": 371,
"text": null
},
{
"code": null,
"e": 1024,
"s": 1015,
"text": "Output: "
},
{
"code": null,
"e": 1053,
"s": 1024,
"text": "Before Clickin the Button: "
},
{
"code": null,
"e": 1082,
"s": 1053,
"text": "After Clicking the Button: "
},
{
"code": null,
"e": 1216,
"s": 1082,
"text": "2. Using getElementByName() method: This method gets/identifies the DOM element by using it’s the class name and returns the element."
},
{
"code": null,
"e": 1226,
"s": 1216,
"text": "Example: "
},
{
"code": null,
"e": 1237,
"s": 1226,
"text": "Javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to get/change the HTML with DOM element in JavaScript? </title></head> <body> <h3> Accessing HTML of a DOM element in JavaScript. </h3> <p class=\"p1\"> JavaScript is used for web programming. </p> <button onclick=getHtml()> Get and change the html for DOM element </button> <script> function getHtml() { var Element = document.getElementsByClassName(\"p1\"); alert(Element[0].innerHTML); Element[0].style.color = \"blue\"; Element[0].innerHTML = \"GeeksforGeeks\"; } </script></body> </html>",
"e": 1921,
"s": 1237,
"text": null
},
{
"code": null,
"e": 1930,
"s": 1921,
"text": "Output: "
},
{
"code": null,
"e": 1960,
"s": 1930,
"text": "Before Clicking the Button: "
},
{
"code": null,
"e": 1989,
"s": 1960,
"text": "After Clicking the Button: "
},
{
"code": null,
"e": 2102,
"s": 1989,
"text": "3. Using getElementsByTagName(): This method gets/identifies the DOM element using it’s tag name and returns it."
},
{
"code": null,
"e": 2112,
"s": 2102,
"text": "Example: "
},
{
"code": null,
"e": 2123,
"s": 2112,
"text": "Javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to get/change the HTML with DOM element in JavaScript? </title></head> <body> <h3> Accessing HTML of a DOM element in JavaScript. </h3> <p>JavaScript is used for web programming.</p> <p>JavaScript was invented in 1990s.</p> <button onclick=getHtml()> Get and change the html for DOM element </button> <script> function getHtml() { var Element = document.getElementsByTagName(\"p\"); for (var i = 0; i < Element.length; i++) { alert(Element[i].innerHTML); Element[i].innerHTML = \"GeeksforGeeks.\"; } } </script></body> </html>",
"e": 2836,
"s": 2123,
"text": null
},
{
"code": null,
"e": 2845,
"s": 2836,
"text": "Output: "
},
{
"code": null,
"e": 2874,
"s": 2845,
"text": "Before Clicking the button: "
},
{
"code": null,
"e": 2902,
"s": 2874,
"text": "After Clicking the Button: "
},
{
"code": null,
"e": 3281,
"s": 2902,
"text": "NOTE: The above three approaches use inner.HTML property of the DOM element to get the HTML and alerts it and then changes the HTML content present in the element. The property inner.HTML is mainly used to change the text or rather the content present whereas outer.HTML is used for changing the tag and the content of the text as it returns the HTML content along with its tag."
},
{
"code": null,
"e": 3376,
"s": 3281,
"text": "Below example illustrates the use of outer.HTML property using getElementsByTagName() method. "
},
{
"code": null,
"e": 3387,
"s": 3376,
"text": "Javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to get/change the HTML with DOM element in JavaScript? </title></head> <body> <div> GeeksforGeeks </div> <button onclick=getHtml()> Get HTML for DOM element </button> <script> function getHtml() { var Element = document.getElementsByTagName(\"div\"); alert(Element[0].outerHTML); Element[0].style.color = \"red\"; Element[0].outerHTML = \"<h1> JavaScript. </h1>\" } </script></body> </html>",
"e": 3920,
"s": 3387,
"text": null
},
{
"code": null,
"e": 3929,
"s": 3920,
"text": "Output: "
},
{
"code": null,
"e": 3958,
"s": 3929,
"text": "Before Clicking the Button: "
},
{
"code": null,
"e": 3986,
"s": 3958,
"text": "After Clicking the Button: "
},
{
"code": null,
"e": 4226,
"s": 3986,
"text": "The functions getElementById(), getElementsByClassName() can also be used to get the DOM elements for accessing outerHTML in the same manner as they were used to access innerHTML. Thus, we can access HTML of a DOM using the above methods. "
},
{
"code": null,
"e": 4242,
"s": 4226,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 4251,
"s": 4242,
"text": "CSS-Misc"
},
{
"code": null,
"e": 4261,
"s": 4251,
"text": "HTML-Misc"
},
{
"code": null,
"e": 4277,
"s": 4261,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 4284,
"s": 4277,
"text": "Picked"
},
{
"code": null,
"e": 4288,
"s": 4284,
"text": "CSS"
},
{
"code": null,
"e": 4293,
"s": 4288,
"text": "HTML"
},
{
"code": null,
"e": 4304,
"s": 4293,
"text": "JavaScript"
},
{
"code": null,
"e": 4321,
"s": 4304,
"text": "Web Technologies"
},
{
"code": null,
"e": 4348,
"s": 4321,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4353,
"s": 4348,
"text": "HTML"
},
{
"code": null,
"e": 4451,
"s": 4353,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4490,
"s": 4451,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 4527,
"s": 4490,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 4566,
"s": 4527,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 4630,
"s": 4566,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 4691,
"s": 4630,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 4715,
"s": 4691,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 4768,
"s": 4715,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4828,
"s": 4768,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 4889,
"s": 4828,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Saving images in Python at a very high quality
|
To save the images in Python with very high quality, you need to follow the steps given below −
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Plot the lines using plot() method.
Plot the lines using plot() method.
We can add axes labels using ylabel() and xlabel().
We can add axes labels using ylabel() and xlabel().
To get a high-quality image, we can use .eps image format.
To get a high-quality image, we can use .eps image format.
You can increase the dot per inch value, i.e., dpi.
You can increase the dot per inch value, i.e., dpi.
Using savefig() method, we can save the image locally.
Using savefig() method, we can save the image locally.
To show the figure, use plt.show().
To show the figure, use plt.show().
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.plot([0, 5], [0, 5])
plt.ylabel("Y-axis ")
plt.xlabel("X-axis ")
image_format = 'eps' # e.g .png, .svg, etc.
image_name = 'myimage.eps'
fig.savefig(image_name, format=image_format, dpi=1200)
|
[
{
"code": null,
"e": 1283,
"s": 1187,
"text": "To save the images in Python with very high quality, you need to follow the steps given below −"
},
{
"code": null,
"e": 1371,
"s": 1283,
"text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1."
},
{
"code": null,
"e": 1459,
"s": 1371,
"text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1."
},
{
"code": null,
"e": 1495,
"s": 1459,
"text": "Plot the lines using plot() method."
},
{
"code": null,
"e": 1531,
"s": 1495,
"text": "Plot the lines using plot() method."
},
{
"code": null,
"e": 1583,
"s": 1531,
"text": "We can add axes labels using ylabel() and xlabel()."
},
{
"code": null,
"e": 1635,
"s": 1583,
"text": "We can add axes labels using ylabel() and xlabel()."
},
{
"code": null,
"e": 1694,
"s": 1635,
"text": "To get a high-quality image, we can use .eps image format."
},
{
"code": null,
"e": 1753,
"s": 1694,
"text": "To get a high-quality image, we can use .eps image format."
},
{
"code": null,
"e": 1805,
"s": 1753,
"text": "You can increase the dot per inch value, i.e., dpi."
},
{
"code": null,
"e": 1857,
"s": 1805,
"text": "You can increase the dot per inch value, i.e., dpi."
},
{
"code": null,
"e": 1912,
"s": 1857,
"text": "Using savefig() method, we can save the image locally."
},
{
"code": null,
"e": 1967,
"s": 1912,
"text": "Using savefig() method, we can save the image locally."
},
{
"code": null,
"e": 2003,
"s": 1967,
"text": "To show the figure, use plt.show()."
},
{
"code": null,
"e": 2039,
"s": 2003,
"text": "To show the figure, use plt.show()."
},
{
"code": null,
"e": 2296,
"s": 2039,
"text": "import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\n\nplt.plot([0, 5], [0, 5])\n\nplt.ylabel(\"Y-axis \")\nplt.xlabel(\"X-axis \")\n\nimage_format = 'eps' # e.g .png, .svg, etc.\nimage_name = 'myimage.eps'\n\nfig.savefig(image_name, format=image_format, dpi=1200)"
}
] |
Working with Binary Data in Python
|
22 Jun, 2020
Alright, lets get this out of the way! The basics are pretty standard:
There are 8 bits in a byteBits either consist of a 0 or a 1A byte can be interpreted in different ways, like binary octal or hexadecimal
There are 8 bits in a byte
Bits either consist of a 0 or a 1
A byte can be interpreted in different ways, like binary octal or hexadecimal
Note: These are not character encodings, those come later. This is just a way to look at a set of 1’s and 0’s and see it in three different ways(or number systems).
Examples:
Input : 10011011
Output :
1001 1011 ---- 9B (in hex)
1001 1011 ---- 155 (in decimal)
1001 1011 ---- 233 (in octal)
This clearly shows a string of bits can be interpreted differently in different ways. We often use the hex representation of a byte instead of the binary one because it is shorter to write, this is just a representation and not an interpretation.
Now that we know what a byte is and what it looks like, let us see how it is interpreted, mainly in strings. Character Encodings are a way to assign values to bytes or sets of bytes that represent a certain character in that scheme. Some encodings are ASCII(probably the oldest), Latin, and UTF-8(most widely used as of today. In a sense encodings are a way for computers to represent, send and interpret human readable characters. This means that a sentence in one encoding might become completely incomprehensible in another encoding.
From a developer’s point of view, the largest change in Python 3 is the handling of strings. In Python 2, the str type was used for two different kinds of values – text and bytes, whereas in Python 3, these are separate and incompatible types. This means that before Python3 we could treat a set of bytes as a string and work from there, this is not the case now, now we have a separate data type, called bytes. This data type can be briefly explained as a string of bytes, which essentially means, once the bytes data type is initialized it is immutable.
Example:
Python3
bytestr = bytes(b'abc') # initializing a string with b# makes it a binary stringprint(bytestr)print(bytestr[0]) bytestr[0] = 97
Output:
b'abc'
97
Traceback (most recent call last):
File "bytesExample.py", line 4, in
bytestr[0] = 97
TypeError: 'bytes' object does not support item assignment
A bytestring is what it says it is simply a string of bytes, for example ‘© ? ?’ in ‘utf-8’ is
b'\xC2\xA9\x20\xF0\x9D\x8C\x86\x20\xE2\x98\x83'
This presents another problem, we need to know the encoding of a binary string, because the same string in another encoding(latin-1) looks different.
© ð â
Example:
Python3
print(b'\xC2\xA9\x20\xF0\x9D\x8C\x86\x20\xE2\x98\x83'.decode('utf-8'))print(b'\xC2\xA9\x20\xF0\x9D\x8C\x86\x20\xE2\x98\x83'.decode('latin-1'))
Output:
As seen above it is possible to encode or decode strings and binary strings using the encode() or decode() function. We need the encoding because in some encodings it is not possible to to decode the strings. This problem compounds when not using non Latin characters like Hebrew, Japanese and Chinese. Because in those languages more than one byte is assigned to each letter. But what do we use when we need to modify a set of bytes, we use a bytearray.
Example:
Python3
bytesArr = bytearray(b'\x00\x0F') # Bytearray allows modificationbytesArr[0] = 255bytesArr.append(255)print(bytesArr)
Output:
bytearray(b'\xff\x0f\xff')
In Python, bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into binary and then operations are performed on bit by bit, hence the name bitwise operators. The standard bitwise operations are demonstrated below.
Note: For more information, refer to Python Bitwise Operators
Example:
Python3
# Code to demonstrate bitwise operations# Some bytes to play withbyte1 = int('11110000', 2) # 240byte2 = int('00001111', 2) # 15byte3 = int('01010101', 2) # 85 # Ones Complement (Flip the bits)print(~byte1) # ANDprint(byte1 & byte2) # ORprint(byte1 | byte2) # XORprint(byte1 ^ byte3) # Shifting right will lose the # right-most bitprint(byte2 >> 3) # Shifting left will add a 0 bit # on the right sideprint(byte2 << 1) # See if a single bit is setbit_mask = int('00000001', 2) # Bit 1 # Is bit set in byte1?print(bit_mask & byte1) # Is bit set in byte2?print(bit_mask & byte2)
Output:
-241
0
255
165
1
30
0
1
Binary data provides several applications like we can check if the two files are similar or not using the binary data, we can also check for a whether a file is jpeg or not (or any other image format). Let’s see the below examples for better understanding.
Example 1: Checking if the two files are same or not. Here two text files are used with the data as follows –
File 1:
File 2:
Python3
with open('GFG.txt', 'rb') as file1, open('log.txt', 'rb') as file2: data1 = file1.read() data2 = file2.read() if data1 != data2: print("Files do not match.")else: print("Files match.")
Output:
Files do not match.
Example 2: Checking if the given image is jpeg or not.
Image used:
Python3
import binascii jpeg_signatures = [ binascii.unhexlify(b'FFD8FFD8'), binascii.unhexlify(b'FFD8FFE0'), binascii.unhexlify(b'FFD8FFE1')] with open('food.jpeg', 'rb') as file: first_four_bytes = file.read(4) if first_four_bytes in jpeg_signatures: print("JPEG detected.") else: print("File does not look like a JPEG.")
Output:
JPEG detected.
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 124,
"s": 52,
"text": "Alright, lets get this out of the way! The basics are pretty standard: "
},
{
"code": null,
"e": 261,
"s": 124,
"text": "There are 8 bits in a byteBits either consist of a 0 or a 1A byte can be interpreted in different ways, like binary octal or hexadecimal"
},
{
"code": null,
"e": 288,
"s": 261,
"text": "There are 8 bits in a byte"
},
{
"code": null,
"e": 322,
"s": 288,
"text": "Bits either consist of a 0 or a 1"
},
{
"code": null,
"e": 400,
"s": 322,
"text": "A byte can be interpreted in different ways, like binary octal or hexadecimal"
},
{
"code": null,
"e": 565,
"s": 400,
"text": "Note: These are not character encodings, those come later. This is just a way to look at a set of 1’s and 0’s and see it in three different ways(or number systems)."
},
{
"code": null,
"e": 576,
"s": 565,
"text": "Examples: "
},
{
"code": null,
"e": 695,
"s": 576,
"text": "Input : 10011011 \n \nOutput :\n1001 1011 ---- 9B (in hex)\n1001 1011 ---- 155 (in decimal)\n1001 1011 ---- 233 (in octal)\n"
},
{
"code": null,
"e": 942,
"s": 695,
"text": "This clearly shows a string of bits can be interpreted differently in different ways. We often use the hex representation of a byte instead of the binary one because it is shorter to write, this is just a representation and not an interpretation."
},
{
"code": null,
"e": 1479,
"s": 942,
"text": "Now that we know what a byte is and what it looks like, let us see how it is interpreted, mainly in strings. Character Encodings are a way to assign values to bytes or sets of bytes that represent a certain character in that scheme. Some encodings are ASCII(probably the oldest), Latin, and UTF-8(most widely used as of today. In a sense encodings are a way for computers to represent, send and interpret human readable characters. This means that a sentence in one encoding might become completely incomprehensible in another encoding."
},
{
"code": null,
"e": 2036,
"s": 1479,
"text": "From a developer’s point of view, the largest change in Python 3 is the handling of strings. In Python 2, the str type was used for two different kinds of values – text and bytes, whereas in Python 3, these are separate and incompatible types. This means that before Python3 we could treat a set of bytes as a string and work from there, this is not the case now, now we have a separate data type, called bytes. This data type can be briefly explained as a string of bytes, which essentially means, once the bytes data type is initialized it is immutable. "
},
{
"code": null,
"e": 2045,
"s": 2036,
"text": "Example:"
},
{
"code": null,
"e": 2053,
"s": 2045,
"text": "Python3"
},
{
"code": "bytestr = bytes(b'abc') # initializing a string with b# makes it a binary stringprint(bytestr)print(bytestr[0]) bytestr[0] = 97",
"e": 2184,
"s": 2053,
"text": null
},
{
"code": null,
"e": 2193,
"s": 2184,
"text": "Output: "
},
{
"code": null,
"e": 2356,
"s": 2193,
"text": "b'abc'\n97\nTraceback (most recent call last):\n File \"bytesExample.py\", line 4, in \n bytestr[0] = 97\nTypeError: 'bytes' object does not support item assignment\n"
},
{
"code": null,
"e": 2452,
"s": 2356,
"text": "A bytestring is what it says it is simply a string of bytes, for example ‘© ? ?’ in ‘utf-8’ is "
},
{
"code": null,
"e": 2501,
"s": 2452,
"text": "b'\\xC2\\xA9\\x20\\xF0\\x9D\\x8C\\x86\\x20\\xE2\\x98\\x83'\n"
},
{
"code": null,
"e": 2651,
"s": 2501,
"text": "This presents another problem, we need to know the encoding of a binary string, because the same string in another encoding(latin-1) looks different."
},
{
"code": null,
"e": 2661,
"s": 2651,
"text": "© ð â\n"
},
{
"code": null,
"e": 2670,
"s": 2661,
"text": "Example:"
},
{
"code": null,
"e": 2678,
"s": 2670,
"text": "Python3"
},
{
"code": "print(b'\\xC2\\xA9\\x20\\xF0\\x9D\\x8C\\x86\\x20\\xE2\\x98\\x83'.decode('utf-8'))print(b'\\xC2\\xA9\\x20\\xF0\\x9D\\x8C\\x86\\x20\\xE2\\x98\\x83'.decode('latin-1'))",
"e": 2821,
"s": 2678,
"text": null
},
{
"code": null,
"e": 2829,
"s": 2821,
"text": "Output:"
},
{
"code": null,
"e": 3285,
"s": 2829,
"text": "As seen above it is possible to encode or decode strings and binary strings using the encode() or decode() function. We need the encoding because in some encodings it is not possible to to decode the strings. This problem compounds when not using non Latin characters like Hebrew, Japanese and Chinese. Because in those languages more than one byte is assigned to each letter. But what do we use when we need to modify a set of bytes, we use a bytearray. "
},
{
"code": null,
"e": 3294,
"s": 3285,
"text": "Example:"
},
{
"code": null,
"e": 3302,
"s": 3294,
"text": "Python3"
},
{
"code": "bytesArr = bytearray(b'\\x00\\x0F') # Bytearray allows modificationbytesArr[0] = 255bytesArr.append(255)print(bytesArr)",
"e": 3421,
"s": 3302,
"text": null
},
{
"code": null,
"e": 3429,
"s": 3421,
"text": "Output:"
},
{
"code": null,
"e": 3456,
"s": 3429,
"text": "bytearray(b'\\xff\\x0f\\xff')"
},
{
"code": null,
"e": 3724,
"s": 3456,
"text": "In Python, bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into binary and then operations are performed on bit by bit, hence the name bitwise operators. The standard bitwise operations are demonstrated below. "
},
{
"code": null,
"e": 3786,
"s": 3724,
"text": "Note: For more information, refer to Python Bitwise Operators"
},
{
"code": null,
"e": 3795,
"s": 3786,
"text": "Example:"
},
{
"code": null,
"e": 3803,
"s": 3795,
"text": "Python3"
},
{
"code": "# Code to demonstrate bitwise operations# Some bytes to play withbyte1 = int('11110000', 2) # 240byte2 = int('00001111', 2) # 15byte3 = int('01010101', 2) # 85 # Ones Complement (Flip the bits)print(~byte1) # ANDprint(byte1 & byte2) # ORprint(byte1 | byte2) # XORprint(byte1 ^ byte3) # Shifting right will lose the # right-most bitprint(byte2 >> 3) # Shifting left will add a 0 bit # on the right sideprint(byte2 << 1) # See if a single bit is setbit_mask = int('00000001', 2) # Bit 1 # Is bit set in byte1?print(bit_mask & byte1) # Is bit set in byte2?print(bit_mask & byte2)",
"e": 4393,
"s": 3803,
"text": null
},
{
"code": null,
"e": 4401,
"s": 4393,
"text": "Output:"
},
{
"code": null,
"e": 4425,
"s": 4401,
"text": "-241\n0\n255\n165\n1\n30\n0\n1"
},
{
"code": null,
"e": 4682,
"s": 4425,
"text": "Binary data provides several applications like we can check if the two files are similar or not using the binary data, we can also check for a whether a file is jpeg or not (or any other image format). Let’s see the below examples for better understanding."
},
{
"code": null,
"e": 4793,
"s": 4682,
"text": "Example 1: Checking if the two files are same or not. Here two text files are used with the data as follows – "
},
{
"code": null,
"e": 4801,
"s": 4793,
"text": "File 1:"
},
{
"code": null,
"e": 4809,
"s": 4801,
"text": "File 2:"
},
{
"code": null,
"e": 4817,
"s": 4809,
"text": "Python3"
},
{
"code": "with open('GFG.txt', 'rb') as file1, open('log.txt', 'rb') as file2: data1 = file1.read() data2 = file2.read() if data1 != data2: print(\"Files do not match.\")else: print(\"Files match.\")",
"e": 5016,
"s": 4817,
"text": null
},
{
"code": null,
"e": 5024,
"s": 5016,
"text": "Output:"
},
{
"code": null,
"e": 5044,
"s": 5024,
"text": "Files do not match."
},
{
"code": null,
"e": 5099,
"s": 5044,
"text": "Example 2: Checking if the given image is jpeg or not."
},
{
"code": null,
"e": 5111,
"s": 5099,
"text": "Image used:"
},
{
"code": null,
"e": 5119,
"s": 5111,
"text": "Python3"
},
{
"code": "import binascii jpeg_signatures = [ binascii.unhexlify(b'FFD8FFD8'), binascii.unhexlify(b'FFD8FFE0'), binascii.unhexlify(b'FFD8FFE1')] with open('food.jpeg', 'rb') as file: first_four_bytes = file.read(4) if first_four_bytes in jpeg_signatures: print(\"JPEG detected.\") else: print(\"File does not look like a JPEG.\")",
"e": 5471,
"s": 5119,
"text": null
},
{
"code": null,
"e": 5479,
"s": 5471,
"text": "Output:"
},
{
"code": null,
"e": 5494,
"s": 5479,
"text": "JPEG detected."
},
{
"code": null,
"e": 5508,
"s": 5494,
"text": "python-basics"
},
{
"code": null,
"e": 5515,
"s": 5508,
"text": "Python"
}
] |
How to Use lm() Function in R to Fit Linear Models?
|
19 Dec, 2021
In this article, we will learn how to use the lm() function to fit linear models in the R Programming Language.
A linear model is used to predict the value of an unknown variable based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. The lm() function is used to fit linear models to data frames in the R Language. It can be used to carry out regression, single stratum analysis of variance, and analysis of covariance to predict the value corresponding to data that is not in the data frame. These are very helpful in predicting the price of real estate, weather forecasting, etc.
To fit a linear model in the R Language by using the lm() function, We first use data.frame() function to create a sample data frame that contains values that have to be fitted on a linear model using regression function. Then we use the lm() function to fit a certain function to a given data frame.
Syntax:
lm( fitting_formula, dataframe )
Parameter:
fitting_formula: determines the formula for the linear model.
dataframe: determines the name of the data frame that contains the data.
Then, we can use the summary() function to view the summary of the linear model. The summary() function interprets the most important statistical values for the analysis of the linear model.
Syntax:
summary( linear_model )
The summary contains the following key information:
Residual Standard Error: determines the standard deviation of the error where the square root of variance subtracts n minus 1 + # of variables involved instead of dividing by n-1.
Multiple R-Squared: determines how well your model fits the data.
Adjusted R-Squared: normalizes Multiple R-Squared by taking into account how many samples you have and how many variables you’re using.
F-Statistic: is a “global” test that checks if at least one of your coefficients is non-zero.
Example: Example to show usage of lm() function.
R
# sample data framedf <- data.frame( x= c(1,2,3,4,5), y= c(1,5,8,15,26)) # fit linear modellinear_model <- lm(y ~ x^2, data=df) # view summary of linear modelsummary(linear_model)
Output:
Call:
lm(formula = y ~ x^2, data = df)
Residuals:
1 2 3 4 5
2.000e+00 5.329e-15 -3.000e+00 -2.000e+00 3.000e+00
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -7.0000 3.0876 -2.267 0.10821
x 6.0000 0.9309 6.445 0.00757 **
—
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.944 on 3 degrees of freedom
Multiple R-squared: 0.9326, Adjusted R-squared: 0.9102
F-statistic: 41.54 on 1 and 3 DF, p-value: 0.007575
The diagnostic plots help us to view the relationship between different statistical values of the model. It helps us in analyzing the extent of outliers and the efficiency of the fitted model. To view diagnostic plots of a linear model, we use the plot() function in the R Language.
Syntax:
plot( linear_model )
Example: Diagnostic plots for the above fitted linear model.
R
# sample data framedf <- data.frame( x= c(1,2,3,4,5), y= c(1,5,8,15,26)) # fit linear modellinear_model <- lm(y ~ x^2, data=df) # view diagnostic plotplot(linear_model)
Output:
We can plot the above fitted linear model to visualize it well by using the abline() method. We first plot a scatter plot of data points and then overlay it with an abline plot of the linear model by using the abline() function.
Syntax:
plot( df$x, df$y)
abline( Linear_model )
Example: Plotting linear model
R
# sample data framedf <- data.frame( x= c(1,2,3,4,5), y= c(1,5,8,15,26)) # fit linear modellinear_model <- lm(y ~ x^2, data=df) # Plot abline plotplot( df$x, df$y )abline( linear_model)
Output:
To predict values for novel inputs using the above fitted linear model, we use predict() function. The predict() function takes the model and data frame with unknown data points and predicts the value for each data point according to the fitted model.
Syntax:
predict( model, data )
Parameter:
model: determines the linear model.
data: determines the data frame with unknown data points.
Example: Predicting novel inputs
R
# sample data framedf <- data.frame( x= c(1,2,3,4,5), y= c(1,5,8,15,26)) # fit linear modellinear_model <- lm(y ~ x^2, data=df) # Predict valuespredict( linear_model, newdata = data.frame(x=c(15,16,17)) )
Output:
1 2 3
83 89 95
Picked
R Machine-Learning
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 140,
"s": 28,
"text": "In this article, we will learn how to use the lm() function to fit linear models in the R Programming Language."
},
{
"code": null,
"e": 673,
"s": 140,
"text": "A linear model is used to predict the value of an unknown variable based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. The lm() function is used to fit linear models to data frames in the R Language. It can be used to carry out regression, single stratum analysis of variance, and analysis of covariance to predict the value corresponding to data that is not in the data frame. These are very helpful in predicting the price of real estate, weather forecasting, etc."
},
{
"code": null,
"e": 974,
"s": 673,
"text": "To fit a linear model in the R Language by using the lm() function, We first use data.frame() function to create a sample data frame that contains values that have to be fitted on a linear model using regression function. Then we use the lm() function to fit a certain function to a given data frame."
},
{
"code": null,
"e": 982,
"s": 974,
"text": "Syntax:"
},
{
"code": null,
"e": 1015,
"s": 982,
"text": "lm( fitting_formula, dataframe )"
},
{
"code": null,
"e": 1026,
"s": 1015,
"text": "Parameter:"
},
{
"code": null,
"e": 1088,
"s": 1026,
"text": "fitting_formula: determines the formula for the linear model."
},
{
"code": null,
"e": 1161,
"s": 1088,
"text": "dataframe: determines the name of the data frame that contains the data."
},
{
"code": null,
"e": 1352,
"s": 1161,
"text": "Then, we can use the summary() function to view the summary of the linear model. The summary() function interprets the most important statistical values for the analysis of the linear model."
},
{
"code": null,
"e": 1360,
"s": 1352,
"text": "Syntax:"
},
{
"code": null,
"e": 1384,
"s": 1360,
"text": "summary( linear_model )"
},
{
"code": null,
"e": 1436,
"s": 1384,
"text": "The summary contains the following key information:"
},
{
"code": null,
"e": 1616,
"s": 1436,
"text": "Residual Standard Error: determines the standard deviation of the error where the square root of variance subtracts n minus 1 + # of variables involved instead of dividing by n-1."
},
{
"code": null,
"e": 1682,
"s": 1616,
"text": "Multiple R-Squared: determines how well your model fits the data."
},
{
"code": null,
"e": 1818,
"s": 1682,
"text": "Adjusted R-Squared: normalizes Multiple R-Squared by taking into account how many samples you have and how many variables you’re using."
},
{
"code": null,
"e": 1912,
"s": 1818,
"text": "F-Statistic: is a “global” test that checks if at least one of your coefficients is non-zero."
},
{
"code": null,
"e": 1961,
"s": 1912,
"text": "Example: Example to show usage of lm() function."
},
{
"code": null,
"e": 1963,
"s": 1961,
"text": "R"
},
{
"code": "# sample data framedf <- data.frame( x= c(1,2,3,4,5), y= c(1,5,8,15,26)) # fit linear modellinear_model <- lm(y ~ x^2, data=df) # view summary of linear modelsummary(linear_model)",
"e": 2162,
"s": 1963,
"text": null
},
{
"code": null,
"e": 2170,
"s": 2162,
"text": "Output:"
},
{
"code": null,
"e": 2176,
"s": 2170,
"text": "Call:"
},
{
"code": null,
"e": 2209,
"s": 2176,
"text": "lm(formula = y ~ x^2, data = df)"
},
{
"code": null,
"e": 2220,
"s": 2209,
"text": "Residuals:"
},
{
"code": null,
"e": 2276,
"s": 2220,
"text": " 1 2 3 4 5 "
},
{
"code": null,
"e": 2332,
"s": 2276,
"text": "2.000e+00 5.329e-15 -3.000e+00 -2.000e+00 3.000e+00 "
},
{
"code": null,
"e": 2346,
"s": 2332,
"text": "Coefficients:"
},
{
"code": null,
"e": 2398,
"s": 2346,
"text": " Estimate Std. Error t value Pr(>|t|) "
},
{
"code": null,
"e": 2451,
"s": 2398,
"text": "(Intercept) -7.0000 3.0876 -2.267 0.10821 "
},
{
"code": null,
"e": 2503,
"s": 2451,
"text": "x 6.0000 0.9309 6.445 0.00757 **"
},
{
"code": null,
"e": 2505,
"s": 2503,
"text": "—"
},
{
"code": null,
"e": 2568,
"s": 2505,
"text": "Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1"
},
{
"code": null,
"e": 2623,
"s": 2568,
"text": "Residual standard error: 2.944 on 3 degrees of freedom"
},
{
"code": null,
"e": 2685,
"s": 2623,
"text": "Multiple R-squared: 0.9326, Adjusted R-squared: 0.9102 "
},
{
"code": null,
"e": 2738,
"s": 2685,
"text": "F-statistic: 41.54 on 1 and 3 DF, p-value: 0.007575"
},
{
"code": null,
"e": 3021,
"s": 2738,
"text": "The diagnostic plots help us to view the relationship between different statistical values of the model. It helps us in analyzing the extent of outliers and the efficiency of the fitted model. To view diagnostic plots of a linear model, we use the plot() function in the R Language."
},
{
"code": null,
"e": 3029,
"s": 3021,
"text": "Syntax:"
},
{
"code": null,
"e": 3050,
"s": 3029,
"text": "plot( linear_model )"
},
{
"code": null,
"e": 3111,
"s": 3050,
"text": "Example: Diagnostic plots for the above fitted linear model."
},
{
"code": null,
"e": 3113,
"s": 3111,
"text": "R"
},
{
"code": "# sample data framedf <- data.frame( x= c(1,2,3,4,5), y= c(1,5,8,15,26)) # fit linear modellinear_model <- lm(y ~ x^2, data=df) # view diagnostic plotplot(linear_model)",
"e": 3301,
"s": 3113,
"text": null
},
{
"code": null,
"e": 3309,
"s": 3301,
"text": "Output:"
},
{
"code": null,
"e": 3538,
"s": 3309,
"text": "We can plot the above fitted linear model to visualize it well by using the abline() method. We first plot a scatter plot of data points and then overlay it with an abline plot of the linear model by using the abline() function."
},
{
"code": null,
"e": 3546,
"s": 3538,
"text": "Syntax:"
},
{
"code": null,
"e": 3564,
"s": 3546,
"text": "plot( df$x, df$y)"
},
{
"code": null,
"e": 3587,
"s": 3564,
"text": "abline( Linear_model )"
},
{
"code": null,
"e": 3618,
"s": 3587,
"text": "Example: Plotting linear model"
},
{
"code": null,
"e": 3620,
"s": 3618,
"text": "R"
},
{
"code": "# sample data framedf <- data.frame( x= c(1,2,3,4,5), y= c(1,5,8,15,26)) # fit linear modellinear_model <- lm(y ~ x^2, data=df) # Plot abline plotplot( df$x, df$y )abline( linear_model)",
"e": 3825,
"s": 3620,
"text": null
},
{
"code": null,
"e": 3833,
"s": 3825,
"text": "Output:"
},
{
"code": null,
"e": 4085,
"s": 3833,
"text": "To predict values for novel inputs using the above fitted linear model, we use predict() function. The predict() function takes the model and data frame with unknown data points and predicts the value for each data point according to the fitted model."
},
{
"code": null,
"e": 4093,
"s": 4085,
"text": "Syntax:"
},
{
"code": null,
"e": 4116,
"s": 4093,
"text": "predict( model, data )"
},
{
"code": null,
"e": 4127,
"s": 4116,
"text": "Parameter:"
},
{
"code": null,
"e": 4163,
"s": 4127,
"text": "model: determines the linear model."
},
{
"code": null,
"e": 4221,
"s": 4163,
"text": "data: determines the data frame with unknown data points."
},
{
"code": null,
"e": 4254,
"s": 4221,
"text": "Example: Predicting novel inputs"
},
{
"code": null,
"e": 4256,
"s": 4254,
"text": "R"
},
{
"code": "# sample data framedf <- data.frame( x= c(1,2,3,4,5), y= c(1,5,8,15,26)) # fit linear modellinear_model <- lm(y ~ x^2, data=df) # Predict valuespredict( linear_model, newdata = data.frame(x=c(15,16,17)) )",
"e": 4480,
"s": 4256,
"text": null
},
{
"code": null,
"e": 4488,
"s": 4480,
"text": "Output:"
},
{
"code": null,
"e": 4507,
"s": 4488,
"text": "1 2 3 \n83 89 95"
},
{
"code": null,
"e": 4514,
"s": 4507,
"text": "Picked"
},
{
"code": null,
"e": 4533,
"s": 4514,
"text": "R Machine-Learning"
},
{
"code": null,
"e": 4545,
"s": 4533,
"text": "R-Functions"
},
{
"code": null,
"e": 4556,
"s": 4545,
"text": "R Language"
},
{
"code": null,
"e": 4654,
"s": 4556,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4706,
"s": 4654,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 4764,
"s": 4706,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4799,
"s": 4764,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 4837,
"s": 4799,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 4886,
"s": 4837,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 4903,
"s": 4886,
"text": "R - if statement"
},
{
"code": null,
"e": 4940,
"s": 4903,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 4983,
"s": 4940,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 5020,
"s": 4983,
"text": "How to import an Excel File into R ?"
}
] |
less command in Linux with Examples
|
31 Jul, 2021
Less command is a Linux utility that can be used to read the contents of a text file one page(one screen) at a time. It has faster access because if file is large it doesn’t access the complete file, but accesses it page by page.
For example, if it’s a large file and you are reading it using any text editor, then the complete file will be loaded to main memory. The less command doesn’t load the entire file, but loads it part by part which makes it faster.
Syntax :
less filename
Note : I’m using dmesg output as input to less command in following examples.
For Example : If you want to read contents of dmesg command, it’s better to use it with less command
dmesg | less
Output :
[ 0.000000] microcode: microcode updated early to revision 0x21, date = 2017-11-20
[ 0.000000] random: get_random_bytes called from start_kernel+0x42/0x504 with crng_init=0
[ 0.000000] Linux version 4.13.0-26-generic (buildd@lgw01-amd64-031) (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)) #29~16.04.
2-Ubuntu SMP Tue Jan 9 22:00:44 UTC 2018 (Ubuntu 4.13.0-26.29~16.04.2-generic 4.13.13)
[ 0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-4.13.0-26-generic.efi.signed root=UUID=993a37f2-7ea9-43a3-b652-5b26bb879797 ro quiet splash vt.handoff=7
[ 0.000000] KERNEL supported cpus:
[ 0.000000] Intel GenuineIntel
[ 0.000000] AMD AuthenticAMD
[ 0.000000] Centaur CentaurHauls
[ 0.000000] x86/fpu: Supporting XSAVE feature 0x001: 'x87 floating point registers'
[ 0.000000] x86/fpu: Supporting XSAVE feature 0x002: 'SSE registers'
[ 0.000000] x86/fpu: Supporting XSAVE feature 0x004: 'AVX registers'
[ 0.000000] x86/fpu: xstate_offset[2]: 576, xstate_sizes[2]: 256
[ 0.000000] x86/fpu: Enabled xstate features 0x7, context size is 832 bytes, using 'standard' format.
[ 0.000000] e820: BIOS-provided physical RAM map:
[ 0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000006efff] usable
[ 0.000000] BIOS-e820: [mem 0x000000000006f000-0x000000000006ffff] reserved
[ 0.000000] BIOS-e820: [mem 0x0000000000070000-0x0000000000087fff] usable
[ 0.000000] BIOS-e820: [mem 0x0000000000088000-0x00000000000bffff] reserved
[ 0.000000] BIOS-e820: [mem 0x0000000000100000-0x0000000094d5ffff] usable
[ 0.000000] BIOS-e820: [mem 0x0000000094d60000-0x0000000095d5ffff] reserved
[ 0.000000] BIOS-e820: [mem 0x0000000095d60000-0x000000009a36efff] usable
[ 0.000000] BIOS-e820: [mem 0x000000009a36f000-0x000000009aebefff] reserved
[ 0.000000] BIOS-e820: [mem 0x000000009aebf000-0x000000009afbefff] ACPI NVS
[ 0.000000] BIOS-e820: [mem 0x000000009afbf000-0x000000009affefff] ACPI data
[ 0.000000] BIOS-e820: [mem 0x000000009afff000-0x000000009affffff] usable
[ 0.000000] BIOS-e820: [mem 0x000000009b000000-0x000000009f9fffff] reserved
[ 0.000000] BIOS-e820: [mem 0x00000000e0000000-0x00000000efffffff] reserved
[ 0.000000] BIOS-e820: [mem 0x00000000fe101000-0x00000000fe112fff] reserved
[ 0.000000] BIOS-e820: [mem 0x00000000feb00000-0x00000000feb0ffff] reserved
[ 0.000000] BIOS-e820: [mem 0x00000000fec00000-0x00000000fec00fff] reserved
[ 0.000000] BIOS-e820: [mem 0x00000000fed00000-0x00000000fee00fff] reserved
[ 0.000000] BIOS-e820: [mem 0x00000000ffc00000-0x00000000ffffffff] reserved
[ 0.000000] BIOS-e820: [mem 0x0000000100000000-0x000000025f5fffff] usable
[ 0.000000] NX (Execute Disable) protection: active
[ 0.000000] e820: update [mem 0x93c97018-0x93ca7057] usable ==> usable
[ 0.000000] e820: update [mem 0x93c97018-0x93ca7057] usable ==> usable
[ 0.000000] e820: update [mem 0x93c8a018-0x93c96057] usable ==> usable
[ 0.000000] e820: update [mem 0x93c8a018-0x93c96057] usable ==> usable
:
mostly used Options :
-E : causes less to automatically exit the first time it reaches end of file. -f : forces non-regular file to open. -F : causes less to exit if entire file can be displayed on first screen -g : highlight the string which was found by last search command -G : suppresses all highlighting of strings found by search commands -i : cause searches to ignore case -n : suppresses line numbers -p pattern : it tells less to start at the first occurrence of pattern in the file -s : causes consecutive blank lines to be squeezed into a single blank line
Command Usage with options :
dmesg | less -p "failure"
The above command tells less to start at first occurrence of pattern “failure” in the file.
Output :
[ 368.748104] wlp2s0: failed to remove key (1, ff:ff:ff:ff:ff:ff) from hardware (-22)
[ 372.254014] wlp2s0: authenticate with a0:55:4f:27:bd:01
[ 372.257112] wlp2s0: send auth to a0:55:4f:27:bd:01 (try 1/3)
[ 372.261055] wlp2s0: authenticated
[ 372.264307] wlp2s0: associate with a0:55:4f:27:bd:01 (try 1/3)
[ 372.270621] wlp2s0: RX AssocResp from a0:55:4f:27:bd:01 (capab=0x431 status=0 aid=199)
[ 372.272312] wlp2s0: associated
[ 372.357068] wlp2s0: Limiting TX power to 30 (30 - 0) dBm as advertised by a0:55:4f:27:bd:01
[ 682.255302] wlp2s0: disassociated from a0:55:4f:27:bd:01 (Reason: 1=UNSPECIFIED)
[ 682.304134] wlp2s0: failed to remove key (1, ff:ff:ff:ff:ff:ff) from hardware (-22)
[ 685.809837] wlp2s0: authenticate with a0:55:4f:27:bd:01
dmesg | less -N
It will show output along with line numbers Output :
1 [ 0.000000] microcode: microcode updated early to revision 0x21, date = 2017-11-20
2 [ 0.000000] random: get_random_bytes called from start_kernel+0x42/0x504 with crng_init=0
3 [ 0.000000] Linux version 4.13.0-26-generic (buildd@lgw01-amd64-031) (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)) #2 3 9~16.04.2-Ubuntu SMP Tue Jan 9 22:00:44 UTC 2018 (Ubuntu 4.13.0-26.29~16.04.2-generic 4.13.13)
4 [ 0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-4.13.0-26-generic.efi.signed root=UUID=993a37f2-7ea9-43a3-b652-5b26bb879797 ro qu 4 iet splash vt.handoff=7
5 [ 0.000000] KERNEL supported cpus:
6 [ 0.000000] Intel GenuineIntel
7 [ 0.000000] AMD AuthenticAMD
8 [ 0.000000] Centaur CentaurHauls
9 [ 0.000000] x86/fpu: Supporting XSAVE feature 0x001: 'x87 floating point registers'
10 [ 0.000000] x86/fpu: Supporting XSAVE feature 0x002: 'SSE registers'
11 [ 0.000000] x86/fpu: Supporting XSAVE feature 0x004: 'AVX registers'
12 [ 0.000000] x86/fpu: xstate_offset[2]: 576, xstate_sizes[2]: 256
less -F filename
eg. less -F /home/mandeep/test/first.erl
It will not give any output, since file can be displayed in single screen.
less /home/mandeep/test/first.erl
These are the contents of above tested file, it can be displayed on single screen.
-module(first).
-export([fib/1]).
fib(X) when X
1;
fib(X) when X >= 2 ->
fib(X - 1) + fib(X - 2).
– Mandeep Singh
References : 1) wikipedia 2) linux man pages
molluskcreature
linux-command
Linux-text-processing-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
Docker - COPY Instruction
UDP Server-Client implementation in C
scp command in Linux with Examples
echo command in Linux with Examples
Cat command in Linux with examples
touch command in Linux with Examples
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 283,
"s": 52,
"text": "Less command is a Linux utility that can be used to read the contents of a text file one page(one screen) at a time. It has faster access because if file is large it doesn’t access the complete file, but accesses it page by page. "
},
{
"code": null,
"e": 514,
"s": 283,
"text": "For example, if it’s a large file and you are reading it using any text editor, then the complete file will be loaded to main memory. The less command doesn’t load the entire file, but loads it part by part which makes it faster. "
},
{
"code": null,
"e": 524,
"s": 514,
"text": "Syntax : "
},
{
"code": null,
"e": 538,
"s": 524,
"text": "less filename"
},
{
"code": null,
"e": 617,
"s": 538,
"text": "Note : I’m using dmesg output as input to less command in following examples. "
},
{
"code": null,
"e": 720,
"s": 617,
"text": "For Example : If you want to read contents of dmesg command, it’s better to use it with less command "
},
{
"code": null,
"e": 733,
"s": 720,
"text": "dmesg | less"
},
{
"code": null,
"e": 744,
"s": 733,
"text": "Output : "
},
{
"code": null,
"e": 3761,
"s": 744,
"text": "[ 0.000000] microcode: microcode updated early to revision 0x21, date = 2017-11-20\n[ 0.000000] random: get_random_bytes called from start_kernel+0x42/0x504 with crng_init=0\n[ 0.000000] Linux version 4.13.0-26-generic (buildd@lgw01-amd64-031) (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)) #29~16.04.\n2-Ubuntu SMP Tue Jan 9 22:00:44 UTC 2018 (Ubuntu 4.13.0-26.29~16.04.2-generic 4.13.13)\n[ 0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-4.13.0-26-generic.efi.signed root=UUID=993a37f2-7ea9-43a3-b652-5b26bb879797 ro quiet splash vt.handoff=7\n[ 0.000000] KERNEL supported cpus:\n[ 0.000000] Intel GenuineIntel\n[ 0.000000] AMD AuthenticAMD\n[ 0.000000] Centaur CentaurHauls\n[ 0.000000] x86/fpu: Supporting XSAVE feature 0x001: 'x87 floating point registers'\n[ 0.000000] x86/fpu: Supporting XSAVE feature 0x002: 'SSE registers'\n[ 0.000000] x86/fpu: Supporting XSAVE feature 0x004: 'AVX registers'\n[ 0.000000] x86/fpu: xstate_offset[2]: 576, xstate_sizes[2]: 256\n[ 0.000000] x86/fpu: Enabled xstate features 0x7, context size is 832 bytes, using 'standard' format.\n[ 0.000000] e820: BIOS-provided physical RAM map:\n[ 0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000006efff] usable\n[ 0.000000] BIOS-e820: [mem 0x000000000006f000-0x000000000006ffff] reserved\n[ 0.000000] BIOS-e820: [mem 0x0000000000070000-0x0000000000087fff] usable\n[ 0.000000] BIOS-e820: [mem 0x0000000000088000-0x00000000000bffff] reserved\n[ 0.000000] BIOS-e820: [mem 0x0000000000100000-0x0000000094d5ffff] usable\n[ 0.000000] BIOS-e820: [mem 0x0000000094d60000-0x0000000095d5ffff] reserved\n[ 0.000000] BIOS-e820: [mem 0x0000000095d60000-0x000000009a36efff] usable\n[ 0.000000] BIOS-e820: [mem 0x000000009a36f000-0x000000009aebefff] reserved\n[ 0.000000] BIOS-e820: [mem 0x000000009aebf000-0x000000009afbefff] ACPI NVS\n[ 0.000000] BIOS-e820: [mem 0x000000009afbf000-0x000000009affefff] ACPI data\n[ 0.000000] BIOS-e820: [mem 0x000000009afff000-0x000000009affffff] usable\n[ 0.000000] BIOS-e820: [mem 0x000000009b000000-0x000000009f9fffff] reserved\n[ 0.000000] BIOS-e820: [mem 0x00000000e0000000-0x00000000efffffff] reserved\n[ 0.000000] BIOS-e820: [mem 0x00000000fe101000-0x00000000fe112fff] reserved\n[ 0.000000] BIOS-e820: [mem 0x00000000feb00000-0x00000000feb0ffff] reserved\n[ 0.000000] BIOS-e820: [mem 0x00000000fec00000-0x00000000fec00fff] reserved\n[ 0.000000] BIOS-e820: [mem 0x00000000fed00000-0x00000000fee00fff] reserved\n[ 0.000000] BIOS-e820: [mem 0x00000000ffc00000-0x00000000ffffffff] reserved\n[ 0.000000] BIOS-e820: [mem 0x0000000100000000-0x000000025f5fffff] usable\n[ 0.000000] NX (Execute Disable) protection: active\n[ 0.000000] e820: update [mem 0x93c97018-0x93ca7057] usable ==> usable\n[ 0.000000] e820: update [mem 0x93c97018-0x93ca7057] usable ==> usable\n[ 0.000000] e820: update [mem 0x93c8a018-0x93c96057] usable ==> usable\n[ 0.000000] e820: update [mem 0x93c8a018-0x93c96057] usable ==> usable\n:"
},
{
"code": null,
"e": 3785,
"s": 3761,
"text": "mostly used Options : "
},
{
"code": null,
"e": 4333,
"s": 3785,
"text": "-E : causes less to automatically exit the first time it reaches end of file. -f : forces non-regular file to open. -F : causes less to exit if entire file can be displayed on first screen -g : highlight the string which was found by last search command -G : suppresses all highlighting of strings found by search commands -i : cause searches to ignore case -n : suppresses line numbers -p pattern : it tells less to start at the first occurrence of pattern in the file -s : causes consecutive blank lines to be squeezed into a single blank line "
},
{
"code": null,
"e": 4364,
"s": 4333,
"text": "Command Usage with options : "
},
{
"code": null,
"e": 4390,
"s": 4364,
"text": "dmesg | less -p \"failure\""
},
{
"code": null,
"e": 4483,
"s": 4390,
"text": "The above command tells less to start at first occurrence of pattern “failure” in the file. "
},
{
"code": null,
"e": 4494,
"s": 4483,
"text": "Output : "
},
{
"code": null,
"e": 5256,
"s": 4494,
"text": "[ 368.748104] wlp2s0: failed to remove key (1, ff:ff:ff:ff:ff:ff) from hardware (-22)\n[ 372.254014] wlp2s0: authenticate with a0:55:4f:27:bd:01\n[ 372.257112] wlp2s0: send auth to a0:55:4f:27:bd:01 (try 1/3)\n[ 372.261055] wlp2s0: authenticated\n[ 372.264307] wlp2s0: associate with a0:55:4f:27:bd:01 (try 1/3)\n[ 372.270621] wlp2s0: RX AssocResp from a0:55:4f:27:bd:01 (capab=0x431 status=0 aid=199)\n[ 372.272312] wlp2s0: associated\n[ 372.357068] wlp2s0: Limiting TX power to 30 (30 - 0) dBm as advertised by a0:55:4f:27:bd:01\n[ 682.255302] wlp2s0: disassociated from a0:55:4f:27:bd:01 (Reason: 1=UNSPECIFIED)\n[ 682.304134] wlp2s0: failed to remove key (1, ff:ff:ff:ff:ff:ff) from hardware (-22)\n[ 685.809837] wlp2s0: authenticate with a0:55:4f:27:bd:01"
},
{
"code": null,
"e": 5272,
"s": 5256,
"text": "dmesg | less -N"
},
{
"code": null,
"e": 5327,
"s": 5272,
"text": "It will show output along with line numbers Output : "
},
{
"code": null,
"e": 6448,
"s": 5327,
"text": "1 [ 0.000000] microcode: microcode updated early to revision 0x21, date = 2017-11-20\n 2 [ 0.000000] random: get_random_bytes called from start_kernel+0x42/0x504 with crng_init=0\n 3 [ 0.000000] Linux version 4.13.0-26-generic (buildd@lgw01-amd64-031) (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)) #2 3 9~16.04.2-Ubuntu SMP Tue Jan 9 22:00:44 UTC 2018 (Ubuntu 4.13.0-26.29~16.04.2-generic 4.13.13)\n 4 [ 0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-4.13.0-26-generic.efi.signed root=UUID=993a37f2-7ea9-43a3-b652-5b26bb879797 ro qu 4 iet splash vt.handoff=7\n 5 [ 0.000000] KERNEL supported cpus:\n 6 [ 0.000000] Intel GenuineIntel\n 7 [ 0.000000] AMD AuthenticAMD\n 8 [ 0.000000] Centaur CentaurHauls\n 9 [ 0.000000] x86/fpu: Supporting XSAVE feature 0x001: 'x87 floating point registers'\n 10 [ 0.000000] x86/fpu: Supporting XSAVE feature 0x002: 'SSE registers'\n 11 [ 0.000000] x86/fpu: Supporting XSAVE feature 0x004: 'AVX registers'\n 12 [ 0.000000] x86/fpu: xstate_offset[2]: 576, xstate_sizes[2]: 256"
},
{
"code": null,
"e": 6507,
"s": 6448,
"text": "less -F filename\n\neg. less -F /home/mandeep/test/first.erl"
},
{
"code": null,
"e": 6584,
"s": 6507,
"text": "It will not give any output, since file can be displayed in single screen. "
},
{
"code": null,
"e": 6618,
"s": 6584,
"text": "less /home/mandeep/test/first.erl"
},
{
"code": null,
"e": 6703,
"s": 6618,
"text": "These are the contents of above tested file, it can be displayed on single screen. "
},
{
"code": null,
"e": 6811,
"s": 6703,
"text": "-module(first).\n-export([fib/1]).\n\nfib(X) when X \n 1;\nfib(X) when X >= 2 ->\n fib(X - 1) + fib(X - 2)."
},
{
"code": null,
"e": 6828,
"s": 6811,
"text": "– Mandeep Singh "
},
{
"code": null,
"e": 6874,
"s": 6828,
"text": "References : 1) wikipedia 2) linux man pages "
},
{
"code": null,
"e": 6892,
"s": 6876,
"text": "molluskcreature"
},
{
"code": null,
"e": 6906,
"s": 6892,
"text": "linux-command"
},
{
"code": null,
"e": 6937,
"s": 6906,
"text": "Linux-text-processing-commands"
},
{
"code": null,
"e": 6948,
"s": 6937,
"text": "Linux-Unix"
},
{
"code": null,
"e": 7046,
"s": 6948,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7081,
"s": 7046,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 7117,
"s": 7081,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 7155,
"s": 7117,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 7191,
"s": 7155,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 7217,
"s": 7191,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 7255,
"s": 7217,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 7290,
"s": 7255,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 7326,
"s": 7290,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 7361,
"s": 7326,
"text": "Cat command in Linux with examples"
}
] |
Scala String indexOf() method with example
|
03 Oct, 2019
The indexOf() method is utilized to find the index of the first appearance of the character in the string and the character is present in the method as argument.
Method Definition: int indexOf(int ch)Return Type: It returns the index of the character stated in the argument.
Example #1:
// Scala program of int indexOf()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying indexOf method val result = "Nidhi".indexOf('i') // Displays output println(result) }}
1
So, here the first occurrence of ‘i’ is at index one So, 1 is returned as output.Example #2:
// Scala program of int indexOf()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying indexOf method val result = "Nidhi".indexOf('h') // Displays output println(result) }}
3
Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Oct, 2019"
},
{
"code": null,
"e": 190,
"s": 28,
"text": "The indexOf() method is utilized to find the index of the first appearance of the character in the string and the character is present in the method as argument."
},
{
"code": null,
"e": 303,
"s": 190,
"text": "Method Definition: int indexOf(int ch)Return Type: It returns the index of the character stated in the argument."
},
{
"code": null,
"e": 315,
"s": 303,
"text": "Example #1:"
},
{
"code": "// Scala program of int indexOf()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying indexOf method val result = \"Nidhi\".indexOf('i') // Displays output println(result) }} ",
"e": 600,
"s": 315,
"text": null
},
{
"code": null,
"e": 603,
"s": 600,
"text": "1\n"
},
{
"code": null,
"e": 696,
"s": 603,
"text": "So, here the first occurrence of ‘i’ is at index one So, 1 is returned as output.Example #2:"
},
{
"code": "// Scala program of int indexOf()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying indexOf method val result = \"Nidhi\".indexOf('h') // Displays output println(result) }} ",
"e": 981,
"s": 696,
"text": null
},
{
"code": null,
"e": 984,
"s": 981,
"text": "3\n"
},
{
"code": null,
"e": 990,
"s": 984,
"text": "Scala"
},
{
"code": null,
"e": 1003,
"s": 990,
"text": "Scala-Method"
},
{
"code": null,
"e": 1017,
"s": 1003,
"text": "Scala-Strings"
},
{
"code": null,
"e": 1023,
"s": 1017,
"text": "Scala"
}
] |
Pattern matcher() method in Java with examples
|
The java.util.regex package of java provides various classes to find particular patterns in character sequences.
The pattern class of this package is a compiled representation of a regular expression. The matcher() method of this class accepts an object of the CharSequence class representing the input string and, returns a Matcher object which matches the given string to the regular expression represented by the current (Pattern) object.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample {
public static void main(String args[]) {
//Reading string value
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string");
String input = sc.nextLine();
//Regular expression to find vowels
String regex = "[aeiou]";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Given string contains vowels");
} else {
System.out.println("Given string does not contain vowels");
}
}
}
Enter input string
RHYTHM
Given string does not contain vowels
|
[
{
"code": null,
"e": 1300,
"s": 1187,
"text": "The java.util.regex package of java provides various classes to find particular patterns in character sequences."
},
{
"code": null,
"e": 1629,
"s": 1300,
"text": "The pattern class of this package is a compiled representation of a regular expression. The matcher() method of this class accepts an object of the CharSequence class representing the input string and, returns a Matcher object which matches the given string to the regular expression represented by the current (Pattern) object."
},
{
"code": null,
"e": 2385,
"s": 1629,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class MatcherExample {\n public static void main(String args[]) {\n //Reading string value\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter input string\");\n String input = sc.nextLine();\n //Regular expression to find vowels\n String regex = \"[aeiou]\";\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex);\n //Retrieving the matcher object\n Matcher matcher = pattern.matcher(input);\n if(matcher.find()) {\n System.out.println(\"Given string contains vowels\");\n } else {\n System.out.println(\"Given string does not contain vowels\");\n }\n }\n}"
},
{
"code": null,
"e": 2448,
"s": 2385,
"text": "Enter input string\nRHYTHM\nGiven string does not contain vowels"
}
] |
How to Extract Content From a Text Document using Java?
|
03 Aug, 2021
There are several ways present in java to read the text file like BufferReader, FileReader, and Scanner. Each and every method provides a unique way of reading the text file.
Methods:
Using Files classUsing FileReader classUsing BufferReader classUsing Scanner class
Using Files class
Using FileReader class
Using BufferReader class
Using Scanner class
Let’s see each and every method in detail with an example to get a better understanding of the methods to, later on, implement the same to extract the content from a text document.
Method 1: Using Files class
As Java provides java.nio.file. API we can use java.nio.file.Files class to read all the contents of a file into an array. To read a text file we can use the readAllBytes() method of Files class with which using this method, when you need all the file contents in memory as well as when you are working on small files.
Example:
Java
// Java Program to Extract Content From a Text Document// Using Files class // Importing java.nio package for network linkingimport java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;// Importing List class from java.util packageimport java.util.List; // Main classpublic class GFG { // Method 1 // To read the file using class private static void readUsingClass(String fileName) throws IOException { // Creating an object of Path class Path path = Paths.get(fileName); // To read file to byte array byte[] bytes = Files.readAllBytes(path); // Display message only System.out.println( "Read text file using Files class"); // Reading the file to String List @SuppressWarnings("unused") // Creating a List class object of string type // as data in file to be read is words List<String> allLines = Files.readAllLines( path, StandardCharsets.UTF_8); System.out.println(new String(bytes)); } // Method 2 // Main driver method public static void main(String[] args) throws IOException { // Custom input directory passed where text String fileName = "/Users/mayanksolanki/Desktop/file.txt"; // read using FileReader, no encoding support, not // efficient readUsingClass(fileName); }}
Output:
Method 2: Using FileReader class
We can use java.io.FileReader can be used to read data (in characters) from files. This is a very efficient method to read the file line by line.
Syntax:
FileReader input = new FileReader(String name);
Example:
Java
// Java Program to Extract Content From a Text Document// Using FileReader class // Importing required librariesimport java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException; // Main classpublic class GFG { // Method // To read the file using File Reader private static void readUsingFileReader(String fileName) throws IOException { File file = new File(fileName); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; System.out.println( "Reading text file using FileReader"); while ((line = br.readLine()) != null) { // process the line System.out.println(line); } br.close(); fr.close(); } // Method 2 // Main driver method public static void main(String[] args) throws IOException { String fileName = "/Users/mayanksolanki/Desktop/file.txt"; // read using FileReader, no encoding support, not // efficient readUsingFileReader(fileName); }}
Output:
Method 3: Using BufferedReader class
If you want to read the file line by line and If you want to process on that file then you have to use BufferedReader. It is also used for processing the large file, and it supports encoding also. Reading operation is very efficient on BufferReader.
Note: Either specify the size of the BufferReader or keep the size as a Default size of BufferReader which is 8KB.
Syntax:
BufferedReader in = new BufferedReader(Reader in, int size);
Implementation:
Hello I am learning web- development.
I am writing article for GFG.
I am cloud enthusiast.
I am an open-source contributor.
Note: Before starting create a text file by using .txt extension on your local machine and use the path of that file whenever you necessary while practicing.
Example:
Java
// Java Program to Extract Content From a Text Document// Using BufferedReader class // Importing required librariesimport java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException; // Main classpublic class GFG { // Method // To read the file using Buffered Reader private static void readUsingBufferedReader(String fileName) throws IOException { File file = new File(fileName); FileReader fr = new FileReader(file); // read file line by line BufferedReader br = new BufferedReader(fr); String line; System.out.println( "Read text file using BufferedReader"); while ((line = br.readLine()) != null) { // process the line System.out.println(line); } // close resources br.close(); fr.close(); } // Method 2 // Main driver method public static void main(String[] args) throws IOException { String fileName = "/Users/mayanksolanki/Desktop/file.txt"; // read using FileReader, no encoding support, not // efficient readUsingBufferedReader(fileName); }}
Output:
Method 4: Using Scanner class
If we want to read the document based on some expression & If you want to read the document line by line then we use Scanner class. A Scanner breaks the input into tokens, which by default matches the white space.
Example :
Java
// Java Program to Extract Content From a Text Document// Using Scanner class // Importing required librariesimport java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths;import java.util.Scanner; // Main classpublic class GFG { // Method 1 // To read the file using Scanner private static void readUsingScanner(String fileName) throws IOException { // Again, creating Path class object in main() // method Path path = Paths.get(fileName); // Creating Scanner class object to take input Scanner scanner = new Scanner(path); // Display message for readability System.out.println("Read text file using Scanner"); // Now reading file line by line // using hasNextLine() method while (scanner.hasNextLine()) { // Processing each line String line = scanner.nextLine(); // Printing processed lines System.out.println(line); } // close() method is used to close all the read // write connections scanner.close(); } // Method 2 // Main driver method public static void main(String[] args) throws IOException { // Custom input text document // present already on the machine String fileName = "/Users/mayanksolanki/Desktop/file.txt"; // Now lastly reading using FileReader // no encoding support, not efficient readUsingScanner(fileName); }}
Output:
Implementation:
Here “my_file.txt” is a demo file used for the program demonstrated below where sample lines are as follows:
Hello I am learning web- development.
I am writing article of GFG.
I am cloud enthusiast.
I am an open-source contributor.
Example 1:
Java
// Java Program to Implement Extraction of Content// From a Text Document // Importing required librariesimport java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileReader;import java.io.IOException;import java.io.InputStreamReader;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.util.List;import java.util.Scanner; // Main classpublic class read_file { // Method 1 // To read the file using File Reader private static void readUsingFileReader(String fileName) throws IOException { File file = new File(fileName); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; System.out.println( "Reading text file using FileReader"); while ((line = br.readLine()) != null) { // process the line System.out.println(line); } br.close(); fr.close(); } // Method 2 // To read the file using Buffered Reader private static void readUsingBufferedReader(String fileName) throws IOException { File file = new File(fileName); FileReader fr = new FileReader(file); // read file line by line BufferedReader br = new BufferedReader(fr); String line; System.out.println( "Read text file using BufferedReader"); while ((line = br.readLine()) != null) { // process the line System.out.println(line); } // Closing resources to // release memory spaces br.close(); fr.close(); } // Method 3 // To read the file using Scanner private static void readUsingScanner(String fileName) throws IOException { Path path = Paths.get(fileName); Scanner scanner = new Scanner(path); System.out.println("Read text file using Scanner"); // read line by line while (scanner.hasNextLine()) { // process each line String line = scanner.nextLine(); System.out.println(line); } scanner.close(); } // Method 4 // To read the file using class private static void readUsingClass(String fileName) throws IOException { Path path = Paths.get(fileName); // read file to byte array byte[] bytes = Files.readAllBytes(path); System.out.println( "Read text file using Files class"); // read file to String list @SuppressWarnings("unused") List<String> allLines = Files.readAllLines( path, StandardCharsets.UTF_8); System.out.println(new String(bytes)); } // Method 5 // main driver method public static void main(String[] args) throws IOException { String fileName = "C:\\Users\\HP\\Desktop\\my_file.txt"; // using Java 7 Files class to // process small files, get complete file data readUsingClass(fileName); // using Scanner class for // large files, to read line by line readUsingScanner(fileName); // read using BufferedReader, to read line by line readUsingBufferedReader(fileName); // read using FileReader, no encoding support, not // efficient readUsingFileReader(fileName); }}
Example 2: Reading specific lines from a text file
Now If you want to read the specific lines from the given document then we use the BufferReader method. Depending on the file BufferReader() method is used so that our code works faster and efficiently. In this program, the Text file stored in BufferReader is a traverse through all the lines by using for loop, and when if the condition becomes true we will print that lines
Implementation:
“myfile.txt” is the demo file to be used.
This is the sample lines been contained in this file which is consisting of random arbitral words composed in lines
3D printing or additive manufacturing is a process of making three dimensional solid objects from a digital file.
The creation of a 3D printed object is achieved using additive processes. In an additive process an object is created by laying down successive layers of material until the object is created. Each of these layers can be seen as a thinly sliced cross-section of the object.
3D printing is the opposite of subtractive manufacturing which is cutting out / hollowing out a piece of metal or plastic with for instance a milling machine.
3D printing enables you to produce complex shapes.
It uses less material than traditional manufacturing methods.
Java
// Java program to Read Specific Lines from a Text File // Importing required librariesimport java.io.*;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Initially taking empty string String text = ""; // Declaring a variable to lookup for // number of lines in afile int lineNumber; // Try block to check for exceptions try { // Creating a FileReader object so as to // get the directory of file to be read FileReader readfile = new FileReader( "C:\\Users\\HP\\Desktop\\Exam.txt"); // Creating a BufferReader class object to // read file as passed above BufferedReader readbuffer = new BufferedReader(readfile); // Buffer reader declaration // Conditionality for specific line/s // Loop for the traversing line by line // into the text file for (lineNumber = 1; lineNumber < 10; lineNumber++) { // If spefic line/s is found if (lineNumber == 7) { // Store the content of this specific // line text = readbuffer.readLine(); } else { // Just keep on reading readbuffer.readLine(); } } } // Catching IOException exception catch (IOException e) { // Print the line number where exception occurred e.printStackTrace(); } // Print the specific line from the file read System.out.println(" The specific Line is: " + text); }}
Output: The specific Line is:
3D printing enables you to produce complex shapes.
arorakashish0911
Picked
How To
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install and Use NVM on Windows?
How to Install Jupyter Notebook on MacOS?
How to Permanently Disable Swap in Linux?
How to Import JSON Data into SQL Server?
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 204,
"s": 28,
"text": "There are several ways present in java to read the text file like BufferReader, FileReader, and Scanner. Each and every method provides a unique way of reading the text file."
},
{
"code": null,
"e": 213,
"s": 204,
"text": "Methods:"
},
{
"code": null,
"e": 296,
"s": 213,
"text": "Using Files classUsing FileReader classUsing BufferReader classUsing Scanner class"
},
{
"code": null,
"e": 314,
"s": 296,
"text": "Using Files class"
},
{
"code": null,
"e": 337,
"s": 314,
"text": "Using FileReader class"
},
{
"code": null,
"e": 362,
"s": 337,
"text": "Using BufferReader class"
},
{
"code": null,
"e": 382,
"s": 362,
"text": "Using Scanner class"
},
{
"code": null,
"e": 563,
"s": 382,
"text": "Let’s see each and every method in detail with an example to get a better understanding of the methods to, later on, implement the same to extract the content from a text document."
},
{
"code": null,
"e": 591,
"s": 563,
"text": "Method 1: Using Files class"
},
{
"code": null,
"e": 910,
"s": 591,
"text": "As Java provides java.nio.file. API we can use java.nio.file.Files class to read all the contents of a file into an array. To read a text file we can use the readAllBytes() method of Files class with which using this method, when you need all the file contents in memory as well as when you are working on small files."
},
{
"code": null,
"e": 919,
"s": 910,
"text": "Example:"
},
{
"code": null,
"e": 924,
"s": 919,
"text": "Java"
},
{
"code": "// Java Program to Extract Content From a Text Document// Using Files class // Importing java.nio package for network linkingimport java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;// Importing List class from java.util packageimport java.util.List; // Main classpublic class GFG { // Method 1 // To read the file using class private static void readUsingClass(String fileName) throws IOException { // Creating an object of Path class Path path = Paths.get(fileName); // To read file to byte array byte[] bytes = Files.readAllBytes(path); // Display message only System.out.println( \"Read text file using Files class\"); // Reading the file to String List @SuppressWarnings(\"unused\") // Creating a List class object of string type // as data in file to be read is words List<String> allLines = Files.readAllLines( path, StandardCharsets.UTF_8); System.out.println(new String(bytes)); } // Method 2 // Main driver method public static void main(String[] args) throws IOException { // Custom input directory passed where text String fileName = \"/Users/mayanksolanki/Desktop/file.txt\"; // read using FileReader, no encoding support, not // efficient readUsingClass(fileName); }}",
"e": 2393,
"s": 924,
"text": null
},
{
"code": null,
"e": 2401,
"s": 2393,
"text": "Output:"
},
{
"code": null,
"e": 2435,
"s": 2401,
"text": "Method 2: Using FileReader class "
},
{
"code": null,
"e": 2581,
"s": 2435,
"text": "We can use java.io.FileReader can be used to read data (in characters) from files. This is a very efficient method to read the file line by line."
},
{
"code": null,
"e": 2589,
"s": 2581,
"text": "Syntax:"
},
{
"code": null,
"e": 2637,
"s": 2589,
"text": "FileReader input = new FileReader(String name);"
},
{
"code": null,
"e": 2646,
"s": 2637,
"text": "Example:"
},
{
"code": null,
"e": 2651,
"s": 2646,
"text": "Java"
},
{
"code": "// Java Program to Extract Content From a Text Document// Using FileReader class // Importing required librariesimport java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException; // Main classpublic class GFG { // Method // To read the file using File Reader private static void readUsingFileReader(String fileName) throws IOException { File file = new File(fileName); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; System.out.println( \"Reading text file using FileReader\"); while ((line = br.readLine()) != null) { // process the line System.out.println(line); } br.close(); fr.close(); } // Method 2 // Main driver method public static void main(String[] args) throws IOException { String fileName = \"/Users/mayanksolanki/Desktop/file.txt\"; // read using FileReader, no encoding support, not // efficient readUsingFileReader(fileName); }}",
"e": 3758,
"s": 2651,
"text": null
},
{
"code": null,
"e": 3766,
"s": 3758,
"text": "Output:"
},
{
"code": null,
"e": 3804,
"s": 3766,
"text": "Method 3: Using BufferedReader class "
},
{
"code": null,
"e": 4054,
"s": 3804,
"text": "If you want to read the file line by line and If you want to process on that file then you have to use BufferedReader. It is also used for processing the large file, and it supports encoding also. Reading operation is very efficient on BufferReader."
},
{
"code": null,
"e": 4172,
"s": 4054,
"text": "Note: Either specify the size of the BufferReader or keep the size as a Default size of BufferReader which is 8KB. "
},
{
"code": null,
"e": 4180,
"s": 4172,
"text": "Syntax:"
},
{
"code": null,
"e": 4241,
"s": 4180,
"text": "BufferedReader in = new BufferedReader(Reader in, int size);"
},
{
"code": null,
"e": 4257,
"s": 4241,
"text": "Implementation:"
},
{
"code": null,
"e": 4381,
"s": 4257,
"text": "Hello I am learning web- development.\nI am writing article for GFG.\nI am cloud enthusiast.\nI am an open-source contributor."
},
{
"code": null,
"e": 4540,
"s": 4381,
"text": "Note: Before starting create a text file by using .txt extension on your local machine and use the path of that file whenever you necessary while practicing. "
},
{
"code": null,
"e": 4549,
"s": 4540,
"text": "Example:"
},
{
"code": null,
"e": 4554,
"s": 4549,
"text": "Java"
},
{
"code": "// Java Program to Extract Content From a Text Document// Using BufferedReader class // Importing required librariesimport java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException; // Main classpublic class GFG { // Method // To read the file using Buffered Reader private static void readUsingBufferedReader(String fileName) throws IOException { File file = new File(fileName); FileReader fr = new FileReader(file); // read file line by line BufferedReader br = new BufferedReader(fr); String line; System.out.println( \"Read text file using BufferedReader\"); while ((line = br.readLine()) != null) { // process the line System.out.println(line); } // close resources br.close(); fr.close(); } // Method 2 // Main driver method public static void main(String[] args) throws IOException { String fileName = \"/Users/mayanksolanki/Desktop/file.txt\"; // read using FileReader, no encoding support, not // efficient readUsingBufferedReader(fileName); }}",
"e": 5740,
"s": 4554,
"text": null
},
{
"code": null,
"e": 5749,
"s": 5740,
"text": " Output:"
},
{
"code": null,
"e": 5780,
"s": 5749,
"text": "Method 4: Using Scanner class "
},
{
"code": null,
"e": 5995,
"s": 5780,
"text": "If we want to read the document based on some expression & If you want to read the document line by line then we use Scanner class. A Scanner breaks the input into tokens, which by default matches the white space. "
},
{
"code": null,
"e": 6005,
"s": 5995,
"text": "Example :"
},
{
"code": null,
"e": 6010,
"s": 6005,
"text": "Java"
},
{
"code": "// Java Program to Extract Content From a Text Document// Using Scanner class // Importing required librariesimport java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths;import java.util.Scanner; // Main classpublic class GFG { // Method 1 // To read the file using Scanner private static void readUsingScanner(String fileName) throws IOException { // Again, creating Path class object in main() // method Path path = Paths.get(fileName); // Creating Scanner class object to take input Scanner scanner = new Scanner(path); // Display message for readability System.out.println(\"Read text file using Scanner\"); // Now reading file line by line // using hasNextLine() method while (scanner.hasNextLine()) { // Processing each line String line = scanner.nextLine(); // Printing processed lines System.out.println(line); } // close() method is used to close all the read // write connections scanner.close(); } // Method 2 // Main driver method public static void main(String[] args) throws IOException { // Custom input text document // present already on the machine String fileName = \"/Users/mayanksolanki/Desktop/file.txt\"; // Now lastly reading using FileReader // no encoding support, not efficient readUsingScanner(fileName); }}",
"e": 7513,
"s": 6010,
"text": null
},
{
"code": null,
"e": 7521,
"s": 7513,
"text": "Output:"
},
{
"code": null,
"e": 7538,
"s": 7521,
"text": "Implementation: "
},
{
"code": null,
"e": 7647,
"s": 7538,
"text": "Here “my_file.txt” is a demo file used for the program demonstrated below where sample lines are as follows:"
},
{
"code": null,
"e": 7770,
"s": 7647,
"text": "Hello I am learning web- development.\nI am writing article of GFG.\nI am cloud enthusiast.\nI am an open-source contributor."
},
{
"code": null,
"e": 7781,
"s": 7770,
"text": "Example 1:"
},
{
"code": null,
"e": 7786,
"s": 7781,
"text": "Java"
},
{
"code": "// Java Program to Implement Extraction of Content// From a Text Document // Importing required librariesimport java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileReader;import java.io.IOException;import java.io.InputStreamReader;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.util.List;import java.util.Scanner; // Main classpublic class read_file { // Method 1 // To read the file using File Reader private static void readUsingFileReader(String fileName) throws IOException { File file = new File(fileName); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; System.out.println( \"Reading text file using FileReader\"); while ((line = br.readLine()) != null) { // process the line System.out.println(line); } br.close(); fr.close(); } // Method 2 // To read the file using Buffered Reader private static void readUsingBufferedReader(String fileName) throws IOException { File file = new File(fileName); FileReader fr = new FileReader(file); // read file line by line BufferedReader br = new BufferedReader(fr); String line; System.out.println( \"Read text file using BufferedReader\"); while ((line = br.readLine()) != null) { // process the line System.out.println(line); } // Closing resources to // release memory spaces br.close(); fr.close(); } // Method 3 // To read the file using Scanner private static void readUsingScanner(String fileName) throws IOException { Path path = Paths.get(fileName); Scanner scanner = new Scanner(path); System.out.println(\"Read text file using Scanner\"); // read line by line while (scanner.hasNextLine()) { // process each line String line = scanner.nextLine(); System.out.println(line); } scanner.close(); } // Method 4 // To read the file using class private static void readUsingClass(String fileName) throws IOException { Path path = Paths.get(fileName); // read file to byte array byte[] bytes = Files.readAllBytes(path); System.out.println( \"Read text file using Files class\"); // read file to String list @SuppressWarnings(\"unused\") List<String> allLines = Files.readAllLines( path, StandardCharsets.UTF_8); System.out.println(new String(bytes)); } // Method 5 // main driver method public static void main(String[] args) throws IOException { String fileName = \"C:\\\\Users\\\\HP\\\\Desktop\\\\my_file.txt\"; // using Java 7 Files class to // process small files, get complete file data readUsingClass(fileName); // using Scanner class for // large files, to read line by line readUsingScanner(fileName); // read using BufferedReader, to read line by line readUsingBufferedReader(fileName); // read using FileReader, no encoding support, not // efficient readUsingFileReader(fileName); }}",
"e": 11205,
"s": 7786,
"text": null
},
{
"code": null,
"e": 11257,
"s": 11205,
"text": " Example 2: Reading specific lines from a text file"
},
{
"code": null,
"e": 11634,
"s": 11257,
"text": "Now If you want to read the specific lines from the given document then we use the BufferReader method. Depending on the file BufferReader() method is used so that our code works faster and efficiently. In this program, the Text file stored in BufferReader is a traverse through all the lines by using for loop, and when if the condition becomes true we will print that lines "
},
{
"code": null,
"e": 11651,
"s": 11634,
"text": "Implementation: "
},
{
"code": null,
"e": 11694,
"s": 11651,
"text": "“myfile.txt” is the demo file to be used. "
},
{
"code": null,
"e": 11811,
"s": 11694,
"text": "This is the sample lines been contained in this file which is consisting of random arbitral words composed in lines "
},
{
"code": null,
"e": 11925,
"s": 11811,
"text": "3D printing or additive manufacturing is a process of making three dimensional solid objects from a digital file."
},
{
"code": null,
"e": 12198,
"s": 11925,
"text": "The creation of a 3D printed object is achieved using additive processes. In an additive process an object is created by laying down successive layers of material until the object is created. Each of these layers can be seen as a thinly sliced cross-section of the object."
},
{
"code": null,
"e": 12357,
"s": 12198,
"text": "3D printing is the opposite of subtractive manufacturing which is cutting out / hollowing out a piece of metal or plastic with for instance a milling machine."
},
{
"code": null,
"e": 12408,
"s": 12357,
"text": "3D printing enables you to produce complex shapes."
},
{
"code": null,
"e": 12470,
"s": 12408,
"text": "It uses less material than traditional manufacturing methods."
},
{
"code": null,
"e": 12475,
"s": 12470,
"text": "Java"
},
{
"code": "// Java program to Read Specific Lines from a Text File // Importing required librariesimport java.io.*;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Initially taking empty string String text = \"\"; // Declaring a variable to lookup for // number of lines in afile int lineNumber; // Try block to check for exceptions try { // Creating a FileReader object so as to // get the directory of file to be read FileReader readfile = new FileReader( \"C:\\\\Users\\\\HP\\\\Desktop\\\\Exam.txt\"); // Creating a BufferReader class object to // read file as passed above BufferedReader readbuffer = new BufferedReader(readfile); // Buffer reader declaration // Conditionality for specific line/s // Loop for the traversing line by line // into the text file for (lineNumber = 1; lineNumber < 10; lineNumber++) { // If spefic line/s is found if (lineNumber == 7) { // Store the content of this specific // line text = readbuffer.readLine(); } else { // Just keep on reading readbuffer.readLine(); } } } // Catching IOException exception catch (IOException e) { // Print the line number where exception occurred e.printStackTrace(); } // Print the specific line from the file read System.out.println(\" The specific Line is: \" + text); }}",
"e": 14348,
"s": 12475,
"text": null
},
{
"code": null,
"e": 14379,
"s": 14348,
"text": " Output: The specific Line is:"
},
{
"code": null,
"e": 14430,
"s": 14379,
"text": "3D printing enables you to produce complex shapes."
},
{
"code": null,
"e": 14447,
"s": 14430,
"text": "arorakashish0911"
},
{
"code": null,
"e": 14454,
"s": 14447,
"text": "Picked"
},
{
"code": null,
"e": 14461,
"s": 14454,
"text": "How To"
},
{
"code": null,
"e": 14466,
"s": 14461,
"text": "Java"
},
{
"code": null,
"e": 14480,
"s": 14466,
"text": "Java Programs"
},
{
"code": null,
"e": 14485,
"s": 14480,
"text": "Java"
},
{
"code": null,
"e": 14583,
"s": 14485,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14632,
"s": 14583,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 14671,
"s": 14632,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 14713,
"s": 14671,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 14755,
"s": 14713,
"text": "How to Permanently Disable Swap in Linux?"
},
{
"code": null,
"e": 14796,
"s": 14755,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 14811,
"s": 14796,
"text": "Arrays in Java"
},
{
"code": null,
"e": 14855,
"s": 14811,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 14891,
"s": 14855,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 14942,
"s": 14891,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
How to change Screen Orientation programmatically using a Button in Android Kotlin?
|
This example demonstrates how to change Screen Orientation programmatically using a Button in Android Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<Button
android:id="@+id/buttonSetLandscape"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/text2"
android:layout_centerHorizontal="true"
android:layout_marginTop="62dp"
android:text="Landscape Orientation"
android:textColor="@color/colorPrimaryDark"
android:textStyle="bold" />
<Button
android:id="@+id/buttonSetPortrait"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginTop="62dp"
android:text="Portrait Orientation"
android:textColor="@color/colorPrimaryDark"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.pm.ActivityInfo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
class MainActivity : AppCompatActivity() {
lateinit var buttonLandscape: Button
lateinit var buttonPortrait: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
buttonLandscape = findViewById(R.id.buttonSetLandscape)
buttonPortrait = findViewById(R.id.buttonSetPortrait)
buttonLandscape.setOnClickListener {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
Toast.makeText(baseContext, "Landscape Orientation", Toast.LENGTH_SHORT).show()
}
buttonPortrait.setOnClickListener {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
Toast.makeText(baseContext, "Portrait Orientation", Toast.LENGTH_SHORT).show()
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
|
[
{
"code": null,
"e": 1172,
"s": 1062,
"text": "This example demonstrates how to change Screen Orientation programmatically using a Button in Android Kotlin."
},
{
"code": null,
"e": 1301,
"s": 1172,
"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": 1366,
"s": 1301,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2836,
"s": 1366,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/relativeLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/buttonSetLandscape\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/text2\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"62dp\"\n android:text=\"Landscape Orientation\"\n android:textColor=\"@color/colorPrimaryDark\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/buttonSetPortrait\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"62dp\"\n android:text=\"Portrait Orientation\"\n android:textColor=\"@color/colorPrimaryDark\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2891,
"s": 2836,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3904,
"s": 2891,
"text": "import android.content.pm.ActivityInfo\nimport androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.Toast\nclass MainActivity : AppCompatActivity() {\n lateinit var buttonLandscape: Button\n lateinit var buttonPortrait: Button\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n buttonLandscape = findViewById(R.id.buttonSetLandscape)\n buttonPortrait = findViewById(R.id.buttonSetPortrait)\n buttonLandscape.setOnClickListener {\n requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE\n Toast.makeText(baseContext, \"Landscape Orientation\", Toast.LENGTH_SHORT).show()\n }\n buttonPortrait.setOnClickListener {\n requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT\n Toast.makeText(baseContext, \"Portrait Orientation\", Toast.LENGTH_SHORT).show()\n }\n }\n}"
},
{
"code": null,
"e": 3959,
"s": 3904,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4633,
"s": 3959,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4982,
"s": 4633,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
}
] |
SQL Tryit Editor v1.6
|
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price < 20);
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
|
[
{
"code": null,
"e": 148,
"s": 35,
"text": "WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price < 20);"
},
{
"code": null,
"e": 150,
"s": 148,
"text": ""
},
{
"code": null,
"e": 213,
"s": 150,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 273,
"s": 213,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 341,
"s": 273,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 379,
"s": 341,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 464,
"s": 379,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 638,
"s": 464,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 689,
"s": 638,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 757,
"s": 689,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 928,
"s": 757,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 1028,
"s": 928,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 1088,
"s": 1028,
"text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)."
}
] |
How to take a screenshot programmatically in Android using Kotlin?
|
This example demonstrates how to take a screenshot programmatically in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
style="?attr/actionButtonStyle"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="Take screenshot" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:scaleType="fitCenter" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
private lateinit var main: View
private lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
main = findViewById(R.id.main)
imageView = findViewById(R.id.imageView)
val btn: Button = findViewById(R.id.button)
btn.setOnClickListener {
val b: Bitmap = Screenshot.takeScreenshotOfRootView(imageView)
imageView.setImageBitmap(b)
main.setBackgroundColor(Color.parseColor("#999999"))
}
}
companion object Screenshot {
private fun takeScreenshot(view: View): Bitmap {
view.isDrawingCacheEnabled = true
view.buildDrawingCache(true)
val b = Bitmap.createBitmap(view.drawingCache)
view.isDrawingCacheEnabled = false
return b
}
fun takeScreenshotOfRootView(v: View): Bitmap {
return takeScreenshot(v.rootView)
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activityv
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "This example demonstrates how to take a screenshot programmatically in Android using Kotlin."
},
{
"code": null,
"e": 1284,
"s": 1155,
"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": 1349,
"s": 1284,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2167,
"s": 1349,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/main\"\n style=\"?attr/actionButtonStyle\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"30dp\"\n android:text=\"Take screenshot\" />\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_below=\"@id/button\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"30dp\"\n android:scaleType=\"fitCenter\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2222,
"s": 2167,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3514,
"s": 2222,
"text": "import android.graphics.Bitmap\nimport android.graphics.Color\nimport android.os.Bundle\nimport android.view.View\nimport android.widget.Button\nimport android.widget.ImageView\nimport androidx.appcompat.app.AppCompatActivity\n@Suppress(\"DEPRECATION\")\nclass MainActivity : AppCompatActivity() {\n private lateinit var main: View\n private lateinit var imageView: ImageView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n main = findViewById(R.id.main)\n imageView = findViewById(R.id.imageView)\n val btn: Button = findViewById(R.id.button)\n btn.setOnClickListener {\n val b: Bitmap = Screenshot.takeScreenshotOfRootView(imageView)\n imageView.setImageBitmap(b)\n main.setBackgroundColor(Color.parseColor(\"#999999\"))\n }\n }\n companion object Screenshot {\n private fun takeScreenshot(view: View): Bitmap {\n view.isDrawingCacheEnabled = true\n view.buildDrawingCache(true)\n val b = Bitmap.createBitmap(view.drawingCache)\n view.isDrawingCacheEnabled = false\n return b\n }\n fun takeScreenshotOfRootView(v: View): Bitmap {\n return takeScreenshot(v.rootView)\n }\n }\n}"
},
{
"code": null,
"e": 3569,
"s": 3514,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4243,
"s": 3569,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activityv\n </application>\n</manifest>"
},
{
"code": null,
"e": 4592,
"s": 4243,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.